• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package mypackagebeingfuzzed
16
17import (
18	"io/ioutil"
19	"os"
20	"runtime/pprof"
21	"testing"
22)
23
24func TestFuzzCorpus(t *testing.T) {
25	dir := os.Getenv("FUZZ_CORPUS_DIR")
26	if dir == "" {
27		t.Logf("No fuzzing corpus directory set")
28		return
29	}
30	infos, err := ioutil.ReadDir(dir)
31	if err != nil {
32		t.Logf("Not fuzzing corpus directory %s", err)
33		return
34	}
35	filename := ""
36	defer func() {
37		if r := recover(); r != nil {
38			t.Error("Fuzz panicked in "+filename, r)
39		}
40	}()
41	profname := os.Getenv("FUZZ_PROFILE_NAME")
42	if profname != "" {
43		f, err := os.Create(profname + ".cpu.prof")
44		if err != nil {
45			t.Logf("error creating profile file %s\n", err)
46		} else {
47			_ = pprof.StartCPUProfile(f)
48		}
49	}
50	for i := range infos {
51		filename = dir + infos[i].Name()
52		data, err := ioutil.ReadFile(filename)
53		if err != nil {
54			t.Error("Failed to read corpus file", err)
55		}
56		FuzzFunction(data)
57	}
58	if profname != "" {
59		pprof.StopCPUProfile()
60		f, err := os.Create(profname + ".heap.prof")
61		if err != nil {
62			t.Logf("error creating heap profile file %s\n", err)
63		}
64		if err = pprof.WriteHeapProfile(f); err != nil {
65			t.Logf("error writing heap profile file %s\n", err)
66		}
67		f.Close()
68	}
69}
70