aboutsummaryrefslogtreecommitdiffstats
path: root/tools/syz-testbed/instance.go
blob: 5c7718c4f627e12ed785872e13f54e213f752379 (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
// Copyright 2021 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 main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/google/syzkaller/pkg/config"
	"github.com/google/syzkaller/pkg/osutil"
)

type Instance interface {
	Run() error
	Stop()
	FetchResult() (RunResult, error)
	Uptime() time.Duration
}

// The essential information about an active instance.
type InstanceCommon struct {
	Name            string
	LogFile         string
	ExecCommand     string
	ExecCommandArgs []string
	StartedAt       time.Time
	StoppedAt       time.Time
	stopChannel     chan bool
}

func (inst *InstanceCommon) Run() error {
	const stopDelay = time.Minute

	log.Printf("[%s] starting", inst.Name)
	cmd := osutil.GraciousCommand(inst.ExecCommand, inst.ExecCommandArgs...)

	if inst.LogFile != "" {
		logfile, err := os.Create(inst.LogFile)
		if err != nil {
			return fmt.Errorf("[%s] failed to create logfile: %s", inst.Name, err)
		}
		cmd.Stdout = logfile
		cmd.Stderr = logfile
	}

	complete := make(chan error)
	inst.StartedAt = time.Now()
	cmd.Start()
	go func() {
		complete <- cmd.Wait()
	}()

	select {
	case err := <-complete:
		return err
	case <-inst.stopChannel:
		// TODO: handle other OSes?
		cmd.Process.Signal(os.Interrupt)
		select {
		case <-complete:
			// The manager has exited.
		case <-time.After(stopDelay):
			// The manager did not exit - kill it.
			log.Printf("[%s] instance did not exit itself, killing it", inst.Name)
			cmd.Process.Kill()
			<-complete
		}
	}
	inst.StoppedAt = time.Now()
	return nil
}

func (inst *InstanceCommon) Stop() {
	select {
	case inst.stopChannel <- true:
	default:
	}
}

func (inst *InstanceCommon) Uptime() time.Duration {
	if !inst.StartedAt.IsZero() && inst.StoppedAt.IsZero() {
		return time.Since(inst.StartedAt)
	}
	return inst.StoppedAt.Sub(inst.StartedAt)
}

type SyzManagerInstance struct {
	InstanceCommon
	SyzkallerInfo
	RunTime time.Duration
}

func (inst *SyzManagerInstance) FetchResult() (RunResult, error) {
	bugs, err := collectBugs(inst.Workdir)
	if err != nil {
		return nil, err
	}
	records, err := readBenches(inst.BenchFile)
	if err != nil {
		return nil, err
	}
	return &SyzManagerResult{
		Bugs:        bugs,
		StatRecords: records,
	}, nil
}

func (inst *SyzManagerInstance) Run() error {
	ret := make(chan error, 1)
	go func() {
		ret <- inst.InstanceCommon.Run()
	}()

	select {
	case err := <-ret:
		// Syz-managers are not supposed to stop themselves under normal circumstances.
		// If one of them did stop, there must have been a very good reason to do so.
		return fmt.Errorf("[%s] stopped: %v", inst.Name, err)
	case <-time.After(inst.RunTime):
		inst.Stop()
		<-ret
		return nil
	}
}

type SyzkallerInfo struct {
	Workdir   string
	CfgFile   string
	BenchFile string
}

func SetupSyzkallerInstance(mgrName, folder string, checkout *Checkout) (*SyzkallerInfo, error) {
	workdir := filepath.Join(folder, "workdir")
	log.Printf("[%s] Generating workdir", mgrName)
	err := osutil.MkdirAll(workdir)
	if err != nil {
		return nil, fmt.Errorf("failed to create workdir %s", workdir)
	}
	log.Printf("[%s] Generating syz-manager config", mgrName)
	cfgFile := filepath.Join(folder, "manager.cfg")
	managerCfg, err := config.PatchJSON(checkout.ManagerConfig, map[string]interface{}{
		"name":      mgrName,
		"workdir":   workdir,
		"syzkaller": checkout.Path,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to patch mgr config")
	}
	err = osutil.WriteFile(cfgFile, managerCfg)
	if err != nil {
		return nil, fmt.Errorf("failed to save manager config to %s: %s", cfgFile, err)
	}
	return &SyzkallerInfo{
		Workdir:   workdir,
		CfgFile:   cfgFile,
		BenchFile: filepath.Join(folder, "bench.txt"),
	}, nil
}

func (t *SyzManagerTarget) newSyzManagerInstance(slotName, uniqName string, checkout *Checkout) (Instance, error) {
	folder := filepath.Join(checkout.Path, fmt.Sprintf("run-%s", uniqName))
	common, err := SetupSyzkallerInstance(slotName, folder, checkout)
	if err != nil {
		return nil, err
	}
	if t.config.Corpus != "" {
		log.Printf("[%s] Copying corpus", uniqName)
		corpusPath := filepath.Join(common.Workdir, "corpus.db")
		err = osutil.CopyFile(t.config.Corpus, corpusPath)
		if err != nil {
			return nil, fmt.Errorf("failed to copy corpus from %s: %s", t.config.Corpus, err)
		}
	}
	return &SyzManagerInstance{
		InstanceCommon: InstanceCommon{
			Name:            uniqName,
			LogFile:         filepath.Join(folder, "log.txt"),
			ExecCommand:     filepath.Join(checkout.Path, "bin", "syz-manager"),
			ExecCommandArgs: []string{"-config", common.CfgFile, "-bench", common.BenchFile},
			stopChannel:     make(chan bool, 1),
		},
		SyzkallerInfo: *common,
		RunTime:       t.config.RunTime.Duration,
	}, nil
}

type SyzReproInstance struct {
	InstanceCommon
	SyzkallerInfo
	Input      *SyzReproInput
	ReproFile  string
	CReproFile string
	TitleFile  string
}

func (inst *SyzReproInstance) FetchResult() (RunResult, error) {
	result := &SyzReproResult{
		Input:       inst.Input,
		ReproFound:  osutil.IsExist(inst.ReproFile),
		CReproFound: osutil.IsExist(inst.CReproFile),
		Duration:    inst.Uptime(),
	}
	outTitle, _ := ioutil.ReadFile(inst.TitleFile)
	if outTitle != nil {
		result.ReproTitle = strings.TrimSpace(string(outTitle))
		if result.ReproTitle != inst.Input.origTitle {
			// If we found a different bug, treat the reproduction as unsuccessful.
			result.ReproFound = false
			result.CReproFound = false
		}
	}
	return result, nil
}

func (t *SyzReproTarget) newSyzReproInstance(slotName, uniqName string, input *SyzReproInput,
	checkout *Checkout) (Instance, error) {
	folder := filepath.Join(checkout.Path, fmt.Sprintf("run-%s", uniqName))
	common, err := SetupSyzkallerInstance(slotName, folder, checkout)
	if err != nil {
		return nil, err
	}

	reproFile := filepath.Join(folder, "repro.txt")
	cReproFile := filepath.Join(folder, "crepro.txt")
	titleFile := filepath.Join(folder, "title.txt")
	newExecLog := filepath.Join(folder, "execution-log.txt")
	err = osutil.CopyFile(input.Path, newExecLog)
	if err != nil {
		return nil, err
	}
	return &SyzReproInstance{
		InstanceCommon: InstanceCommon{
			Name:        uniqName,
			LogFile:     filepath.Join(folder, "log.txt"),
			ExecCommand: filepath.Join(checkout.Path, "bin", "syz-repro"),
			ExecCommandArgs: []string{
				"-config", common.CfgFile,
				"-output", reproFile,
				"-crepro", cReproFile,
				"-title", titleFile,
				newExecLog,
			},
			stopChannel: make(chan bool, 1),
		},
		SyzkallerInfo: *common,
		Input:         input,
		ReproFile:     reproFile,
		CReproFile:    cReproFile,
		TitleFile:     titleFile,
	}, nil
}