aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/instance/execprog.go
blob: a1dd9e8a5acc935c220ef7624098458a549f9cc9 (plain)
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
// Copyright 2022 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package instance

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"os"
	"path/filepath"
	"slices"
	"strconv"
	"time"

	"github.com/google/syzkaller/pkg/csource"
	"github.com/google/syzkaller/pkg/mgrconfig"
	"github.com/google/syzkaller/pkg/osutil"
	"github.com/google/syzkaller/pkg/report"
	"github.com/google/syzkaller/prog"
	"github.com/google/syzkaller/sys/targets"
	"github.com/google/syzkaller/vm"
)

type ExecutorLogger func(int, string, ...any)

type OptionalConfig struct {
	Logf               ExecutorLogger
	OldFlagsCompatMode bool
	BeforeContextLen   int
	StraceBin          string
}

type ExecProgInstance struct {
	execprogBin string
	executorBin string
	reporter    *report.Reporter
	mgrCfg      *mgrconfig.Config
	VMInstance  *vm.Instance
	OptionalConfig
}

type RunResult struct {
	Output   []byte
	Report   *report.Report
	Duration time.Duration
	Coverage [][]uint64
}

const (
	// It's reasonable to expect that tools/syz-execprog should not normally
	// return a non-zero exit code.
	SyzExitConditions = vm.ExitTimeout | vm.ExitNormal
	binExitConditions = vm.ExitTimeout | vm.ExitNormal | vm.ExitError
)

func SetupExecProg(vmInst *vm.Instance, mgrCfg *mgrconfig.Config, reporter *report.Reporter,
	opt *OptionalConfig) (*ExecProgInstance, error) {
	var err error
	execprogBin := mgrCfg.SysTarget.ExecprogBin
	if execprogBin == "" {
		execprogBin, err = vmInst.Copy(mgrCfg.ExecprogBin)
		if err != nil {
			return nil, &TestError{Title: fmt.Sprintf("failed to copy syz-execprog to VM: %v", err)}
		}
	}
	executorBin := mgrCfg.SysTarget.ExecutorBin
	if executorBin == "" {
		executorBin, err = vmInst.Copy(mgrCfg.ExecutorBin)
		if err != nil {
			return nil, &TestError{Title: fmt.Sprintf("failed to copy syz-executor to VM: %v", err)}
		}
	}
	ret := &ExecProgInstance{
		execprogBin: execprogBin,
		executorBin: executorBin,
		reporter:    reporter,
		mgrCfg:      mgrCfg,
		VMInstance:  vmInst,
	}
	if opt != nil {
		ret.OptionalConfig = *opt
		if !mgrCfg.StraceBinOnTarget && ret.StraceBin != "" {
			var err error
			ret.StraceBin, err = vmInst.Copy(ret.StraceBin)
			if err != nil {
				return nil, &TestError{Title: fmt.Sprintf("failed to copy strace bin: %v", err)}
			}
		}
	}
	if ret.Logf == nil {
		ret.Logf = func(int, string, ...any) {}
	}
	return ret, nil
}

func CreateExecProgInstance(vmPool *vm.Pool, vmIndex int, mgrCfg *mgrconfig.Config,
	reporter *report.Reporter, opt *OptionalConfig) (*ExecProgInstance, error) {
	vmInst, err := vmPool.Create(context.Background(), vmIndex)
	if err != nil {
		return nil, fmt.Errorf("failed to create VM: %w", err)
	}
	ret, err := SetupExecProg(vmInst, mgrCfg, reporter, opt)
	if err != nil {
		vmInst.Close()
		return nil, err
	}
	return ret, nil
}

func (inst *ExecProgInstance) runCommand(command string, duration time.Duration,
	exitCondition vm.ExitCondition) (*RunResult, error) {
	start := time.Now()

	var prefixOutput []byte
	if inst.StraceBin != "" {
		filterCalls := ""
		switch inst.mgrCfg.SysTarget.OS {
		case targets.Linux:
			// wait4 and nanosleep generate a lot of noise, especially when running syz-executor.
			// We cut them on the VM side in order to decrease load on the network and to use
			// the limited buffer size wisely.
			filterCalls = ` -e \!wait4,clock_nanosleep,nanosleep`
		}
		command = inst.StraceBin + filterCalls + ` -s 100 -x -f ` + command
		prefixOutput = []byte(fmt.Sprintf("%s\n\n<...>\n", command))
	}
	optionalBeforeContext := func(*vm.RunOptions) {}
	if inst.BeforeContextLen != 0 {
		optionalBeforeContext = vm.WithBeforeContext(inst.BeforeContextLen)
	}
	ctxTimeout, cancel := context.WithTimeout(context.Background(), duration)
	defer cancel()
	output, reps, err := inst.VMInstance.Run(ctxTimeout, inst.reporter, command,
		vm.WithExitCondition(exitCondition),
		optionalBeforeContext,
	)
	var rep *report.Report
	if len(reps) > 0 {
		rep = reps[0]
	}
	if err != nil {
		return nil, fmt.Errorf("failed to run command in VM: %w", err)
	}
	if rep == nil {
		inst.Logf(2, "program did not crash")
	} else {
		if err := inst.reporter.Symbolize(rep); err != nil {
			inst.Logf(0, "failed to symbolize report: %v", err)
		}
		inst.Logf(2, "program crashed: %v", rep.Title)
	}
	return &RunResult{
		Output:   append(prefixOutput, output...),
		Report:   rep,
		Duration: time.Since(start),
	}, nil
}

func (inst *ExecProgInstance) runBinary(bin string, duration time.Duration) (*RunResult, error) {
	bin, err := inst.VMInstance.Copy(bin)
	if err != nil {
		return nil, &TestError{Title: fmt.Sprintf("failed to copy binary to VM: %v", err)}
	}
	return inst.runCommand(bin, duration, binExitConditions)
}

type ExecParams struct {
	// Only one of these will be used, depending on the function.
	CProg   *prog.Prog
	SyzProg []byte

	Opts            csource.Options
	Duration        time.Duration
	CollectCoverage bool
	// If ExitConditions is empty, RunSyzProg() will assume instance.SyzExitConditions.
	// RunCProg() always runs with binExitConditions.
	ExitConditions vm.ExitCondition
}

func (inst *ExecProgInstance) RunCProg(params ExecParams) (*RunResult, error) {
	src, err := csource.Write(params.CProg, params.Opts)
	if err != nil {
		return nil, err
	}
	inst.Logf(2, "testing compiled C program (duration=%v, %+v): %s",
		params.Duration, params.Opts, params.CProg)
	return inst.RunCProgRaw(src, params.CProg.Target, params.Duration)
}

func (inst *ExecProgInstance) RunCProgRaw(src []byte, target *prog.Target,
	duration time.Duration) (*RunResult, error) {
	bin, err := csource.BuildNoWarn(target, src)
	if err != nil {
		return nil, err
	}
	defer os.Remove(bin)
	return inst.runBinary(bin, duration)
}

func (inst *ExecProgInstance) RunSyzProgFile(progFile string, duration time.Duration,
	opts csource.Options, collectCoverage bool, exitCondition vm.ExitCondition) (*RunResult, error) {
	coverFile := ""
	if collectCoverage {
		coverDir, err := os.MkdirTemp("", "syz-cover")
		if err != nil {
			return nil, err
		}
		defer osutil.RemoveAll(coverDir)
		coverFile = filepath.Join(coverDir, "cover")
	}
	vmProgFile, err := inst.VMInstance.Copy(progFile)
	if err != nil {
		return nil, &TestError{Title: fmt.Sprintf("failed to copy prog to VM: %v", err)}
	}
	command := ExecprogCmd(inst.execprogBin, inst.executorBin, inst.mgrCfg.TargetOS, inst.mgrCfg.TargetArch,
		inst.mgrCfg.Type, opts, !inst.OldFlagsCompatMode, inst.mgrCfg.Timeouts.Slowdown, coverFile, vmProgFile)
	res, err := inst.runCommand(command, duration, exitCondition)
	if err != nil {
		return nil, err
	}
	if coverFile != "" {
		files, err := filepath.Glob(coverFile + "*")
		if err != nil {
			return nil, fmt.Errorf("failed to glob cover files: %w", err)
		}
		slices.Sort(files)
		for _, f := range files {
			cover, err := parseCoverageFile(f)
			if err != nil {
				return nil, fmt.Errorf("failed to parse cover file: %w", err)
			}
			res.Coverage = append(res.Coverage, cover)
		}
	}
	return res, nil
}

func (inst *ExecProgInstance) RunSyzProg(params ExecParams) (*RunResult, error) {
	progFile, err := osutil.WriteTempFile(params.SyzProg)
	if err != nil {
		return nil, err
	}
	defer os.Remove(progFile)

	if params.ExitConditions == 0 {
		params.ExitConditions = SyzExitConditions
	}
	return inst.RunSyzProgFile(progFile, params.Duration, params.Opts,
		params.CollectCoverage, params.ExitConditions)
}

func parseCoverageFile(filename string) ([]uint64, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	var res []uint64
	for s := bufio.NewScanner(bytes.NewReader(data)); s.Scan(); {
		v, err := strconv.ParseUint(s.Text(), 16, 64)
		if err != nil {
			return nil, err
		}
		res = append(res, v)
	}
	return res, nil
}