forked from dvyukov/go-fuzz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testee.go
306 lines (287 loc) · 7.22 KB
/
testee.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright 2015 Dmitry Vyukov. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package main
import (
"encoding/binary"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"sync/atomic"
"syscall"
"time"
"unsafe"
. "github.com/dvyukov/go-fuzz/go-fuzz-defs"
)
// Testee is a wrapper around one testee subprocess.
// It manages communication with the testee, timeouts and output collection.
type Testee struct {
coverRegion []byte
inputRegion []byte
sonarRegion []byte
cmd *exec.Cmd
inPipe *os.File
outPipe *os.File
stdoutPipe *os.File
execs int
startTime int64
outputC chan []byte
downC chan bool
down bool
}
// TestBinary handles communication with and restring of testee subprocesses.
type TestBinary struct {
fileName string
commFile string
comm *Mapping
periodicCheck func()
coverRegion []byte
inputRegion []byte
sonarRegion []byte
testee *Testee
stats *Stats
}
func init() {
if unsafe.Offsetof(Testee{}.startTime)%8 != 0 {
println(unsafe.Offsetof(Testee{}.startTime))
panic("bad atomic field offset")
}
}
func newTestBinary(fileName string, periodicCheck func(), stats *Stats) *TestBinary {
comm, err := ioutil.TempFile("", "go-fuzz-comm")
if err != nil {
log.Fatalf("failed to create comm file: %v", err)
}
comm.Truncate(CoverSize + MaxInputSize + SonarRegionSize)
comm.Close()
mapping, mem := createMapping(comm.Name(), CoverSize+MaxInputSize+SonarRegionSize)
return &TestBinary{
fileName: fileName,
commFile: comm.Name(),
comm: mapping,
periodicCheck: periodicCheck,
coverRegion: mem[:CoverSize],
inputRegion: mem[CoverSize : CoverSize+SonarRegionSize],
sonarRegion: mem[CoverSize+SonarRegionSize:],
stats: stats,
}
}
func (bin *TestBinary) close() {
if bin.testee != nil {
bin.testee.shutdown()
bin.testee = nil
}
bin.comm.destroy()
os.Remove(bin.commFile)
}
func (bin *TestBinary) test(data []byte) (res int, ns uint64, cover, sonar, output []byte, crashed, hanged bool) {
if len(data) > MaxInputSize {
panic("input is too large")
}
for {
// This is the only function that is executed regularly,
// so we tie some periodic checks to it.
bin.periodicCheck()
bin.stats.execs++
if bin.testee == nil {
bin.stats.restarts++
bin.testee = newTestee(bin.fileName, bin.comm, bin.coverRegion, bin.inputRegion, bin.sonarRegion)
}
var retry bool
res, ns, cover, sonar, crashed, hanged, retry = bin.testee.test(data)
if retry {
bin.testee.shutdown()
bin.testee = nil
continue
}
if crashed {
output = bin.testee.shutdown()
if hanged {
hdr := fmt.Sprintf("program hanged (timeout %v seconds)\n\n", *flagTimeout)
output = append([]byte(hdr), output...)
}
bin.testee = nil
return
}
return
}
}
func newTestee(bin string, comm *Mapping, coverRegion, inputRegion, sonarRegion []byte) *Testee {
retry:
rIn, wIn, err := os.Pipe()
if err != nil {
log.Fatalf("failed to pipe: %v", err)
}
rOut, wOut, err := os.Pipe()
if err != nil {
log.Fatalf("failed to pipe: %v", err)
}
rStdout, wStdout, err := os.Pipe()
if err != nil {
log.Fatalf("failed to pipe: %v", err)
}
cmd := exec.Command(bin)
if *flagTestOutput {
// For debugging of testee failures.
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
} else {
cmd.Stdout = wStdout
cmd.Stderr = wStdout
}
cmd.Env = append([]string{}, os.Environ()...)
cmd.Env = append(cmd.Env, "GOTRACEBACK=1")
setupCommMapping(cmd, comm, rOut, wIn)
if err = cmd.Start(); err != nil {
// This can be a transient failure like "cannot allocate memory" or "text file is busy".
log.Printf("failed to start test binary: %v", err)
rIn.Close()
wIn.Close()
rOut.Close()
wOut.Close()
rStdout.Close()
wStdout.Close()
time.Sleep(time.Second)
goto retry
}
rOut.Close()
wIn.Close()
wStdout.Close()
t := &Testee{
coverRegion: coverRegion,
inputRegion: inputRegion,
sonarRegion: sonarRegion,
cmd: cmd,
inPipe: rIn,
outPipe: wOut,
stdoutPipe: rStdout,
outputC: make(chan []byte),
downC: make(chan bool),
}
// Stdout reader goroutine.
go func() {
// The testee should not output unless it crashes.
// But there are still chances that it does. If so, it can overflow
// the stdout pipe during testing and deadlock. To prevent the
// deadlock we periodically read out stdout.
// This goroutine also collects crash output.
ticker := time.NewTicker(time.Second)
const N = 1 << 20
data := make([]byte, N)
filled := 0
for {
select {
case <-ticker.C:
case <-t.downC:
}
n, err := t.stdoutPipe.Read(data[filled:])
if err != nil {
break
}
if *flagV >= 3 {
log.Printf("testee: %v\n", string(data[filled:filled+n]))
}
filled += n
if filled > N/4*3 {
copy(data, data[N/2:filled])
filled -= N / 2
}
}
ticker.Stop()
trimmed := make([]byte, filled)
copy(trimmed, data)
t.outputC <- trimmed
}()
// Hang watcher goroutine.
go func() {
timeout := time.Duration(*flagTimeout) * time.Second
ticker := time.NewTicker(timeout / 2)
for {
select {
case <-ticker.C:
start := atomic.LoadInt64(&t.startTime)
if start != 0 && time.Now().UnixNano()-start > int64(timeout) {
atomic.StoreInt64(&t.startTime, -1)
t.cmd.Process.Signal(syscall.SIGABRT)
time.Sleep(time.Second)
t.cmd.Process.Signal(syscall.SIGKILL)
ticker.Stop()
return
}
case <-t.downC:
ticker.Stop()
return
}
}
}()
// Shutdown watcher goroutine.
go func() {
select {
case <-t.downC:
case <-shutdownC:
t.cmd.Process.Signal(syscall.SIGKILL)
}
}()
return t
}
// test passes data for testing.
func (t *Testee) test(data []byte) (res int, ns uint64, cover, sonar []byte, crashed, hanged, retry bool) {
if t.down {
log.Fatalf("cannot test: testee is already shutdown")
}
// The test binary can accumulate significant amount of memory,
// so we recreate it periodically.
t.execs++
if t.execs > 10000 {
t.cmd.Process.Signal(syscall.SIGKILL)
retry = true
return
}
copy(t.inputRegion[:], data)
atomic.StoreInt64(&t.startTime, time.Now().UnixNano())
if err := binary.Write(t.outPipe, binary.LittleEndian, uint64(len(data))); err != nil {
if *flagV >= 1 {
log.Printf("write to testee failed: %v", err)
}
retry = true
return
}
// Once we do the write, the test is running.
// Once we read the reply below, the test is done.
type Reply struct {
Res uint64
Ns uint64
Sonar uint64
}
var r Reply
err := binary.Read(t.inPipe, binary.LittleEndian, &r)
hanged = atomic.LoadInt64(&t.startTime) == -1
atomic.StoreInt64(&t.startTime, 0)
if err != nil || hanged {
// Should have been crashed.
crashed = true
return
}
res = int(r.Res)
ns = r.Ns
cover = t.coverRegion
sonar = t.sonarRegion[:r.Sonar]
return
}
func (t *Testee) shutdown() (output []byte) {
if t.down {
log.Fatalf("cannot shutdown: testee is already shutdown")
}
t.down = true
t.cmd.Process.Kill() // it is probably already dead, but kill it again to be sure
close(t.downC) // wakeup stdout reader
out := <-t.outputC
if err := t.cmd.Wait(); err != nil {
out = append(out, err.Error()...)
}
t.inPipe.Close()
t.outPipe.Close()
t.stdoutPipe.Close()
return out
}