aboutsummaryrefslogtreecommitdiffstats
path: root/vm/kvm/kvm.go
blob: e63e128e9261707de2039b087c2cb09e04fbcf9a (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
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
// Copyright 2015 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 kvm provides VMs based on lkvm (kvmtool) virtualization.
// It is not well tested.
package kvm

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"sync"
	"time"

	"github.com/google/syzkaller/pkg/config"
	"github.com/google/syzkaller/pkg/log"
	"github.com/google/syzkaller/pkg/osutil"
	"github.com/google/syzkaller/pkg/report"
	"github.com/google/syzkaller/vm/vmimpl"
)

const (
	hostAddr = "192.168.33.1"
)

func init() {
	vmimpl.Register("kvm", ctor, true)
}

type Config struct {
	Count   int    // number of VMs to use
	Lkvm    string // lkvm binary name
	Kernel  string // e.g. arch/x86/boot/bzImage
	Cmdline string // kernel command line
	CPU     int    // number of VM CPUs
	Mem     int    // amount of VM memory in MBs
}

type Pool struct {
	env *vmimpl.Env
	cfg *Config
}

type instance struct {
	cfg         *Config
	sandbox     string
	sandboxPath string
	lkvm        *exec.Cmd
	readerC     chan error
	waiterC     chan error
	debug       bool

	mu      sync.Mutex
	outputB []byte
	outputC chan []byte
}

func ctor(env *vmimpl.Env) (vmimpl.Pool, error) {
	cfg := &Config{
		Count: 1,
		Lkvm:  "lkvm",
	}
	if err := config.LoadData(env.Config, cfg); err != nil {
		return nil, fmt.Errorf("failed to parse kvm vm config: %v", err)
	}
	if cfg.Count < 1 || cfg.Count > 128 {
		return nil, fmt.Errorf("invalid config param count: %v, want [1, 128]", cfg.Count)
	}
	if env.Debug && cfg.Count > 1 {
		log.Logf(0, "limiting number of VMs from %v to 1 in debug mode", cfg.Count)
		cfg.Count = 1
	}
	if env.Image != "" {
		return nil, fmt.Errorf("lkvm does not support custom images")
	}
	if _, err := exec.LookPath(cfg.Lkvm); err != nil {
		return nil, err
	}
	if !osutil.IsExist(cfg.Kernel) {
		return nil, fmt.Errorf("kernel file '%v' does not exist", cfg.Kernel)
	}
	if cfg.CPU < 1 || cfg.CPU > 1024 {
		return nil, fmt.Errorf("invalid config param cpu: %v, want [1-1024]", cfg.CPU)
	}
	if cfg.Mem < 128 || cfg.Mem > 1048576 {
		return nil, fmt.Errorf("invalid config param mem: %v, want [128-1048576]", cfg.Mem)
	}
	cfg.Kernel = osutil.Abs(cfg.Kernel)
	pool := &Pool{
		cfg: cfg,
		env: env,
	}
	return pool, nil
}

func (pool *Pool) Count() int {
	return pool.cfg.Count
}

func (pool *Pool) Create(workdir string, index int) (vmimpl.Instance, error) {
	sandbox := fmt.Sprintf("syz-%v", index)
	inst := &instance{
		cfg:         pool.cfg,
		sandbox:     sandbox,
		sandboxPath: filepath.Join(os.Getenv("HOME"), ".lkvm", sandbox),
		debug:       pool.env.Debug,
	}
	closeInst := inst
	defer func() {
		if closeInst != nil {
			closeInst.Close()
		}
	}()

	os.RemoveAll(inst.sandboxPath)
	os.Remove(inst.sandboxPath + ".sock")
	out, err := osutil.Command(inst.cfg.Lkvm, "setup", sandbox).CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("failed to lkvm setup: %v\n%s", err, out)
	}
	scriptPath := filepath.Join(workdir, "script.sh")
	if err := osutil.WriteExecFile(scriptPath, []byte(script)); err != nil {
		return nil, fmt.Errorf("failed to create temp file: %v", err)
	}

	rpipe, wpipe, err := osutil.LongPipe()
	if err != nil {
		return nil, fmt.Errorf("failed to create pipe: %v", err)
	}

	inst.lkvm = osutil.Command("taskset", "-c", strconv.Itoa(index%runtime.NumCPU()),
		inst.cfg.Lkvm, "sandbox",
		"--disk", inst.sandbox,
		"--kernel", inst.cfg.Kernel,
		"--params", "slub_debug=UZ "+inst.cfg.Cmdline,
		"--mem", strconv.Itoa(inst.cfg.Mem),
		"--cpus", strconv.Itoa(inst.cfg.CPU),
		"--network", "mode=user",
		"--sandbox", scriptPath,
	)
	inst.lkvm.Stdout = wpipe
	inst.lkvm.Stderr = wpipe
	if err := inst.lkvm.Start(); err != nil {
		rpipe.Close()
		wpipe.Close()
		return nil, fmt.Errorf("failed to start lkvm: %v", err)
	}

	// Start output reading goroutine.
	inst.readerC = make(chan error)
	go func() {
		var buf [64 << 10]byte
		for {
			n, err := rpipe.Read(buf[:])
			if n != 0 {
				if inst.debug {
					os.Stdout.Write(buf[:n])
					os.Stdout.Write([]byte{'\n'})
				}
				inst.mu.Lock()
				inst.outputB = append(inst.outputB, buf[:n]...)
				if inst.outputC != nil {
					select {
					case inst.outputC <- inst.outputB:
						inst.outputB = nil
					default:
					}
				}
				inst.mu.Unlock()
				time.Sleep(time.Millisecond)
			}
			if err != nil {
				rpipe.Close()
				inst.readerC <- err
				return
			}
		}
	}()

	// Wait for the lkvm asynchronously.
	inst.waiterC = make(chan error, 1)
	go func() {
		err := inst.lkvm.Wait()
		wpipe.Close()
		inst.waiterC <- err
	}()

	// Wait for the script to start serving.
	_, errc, err := inst.Run(10*time.Minute, nil, "mount -t debugfs none /sys/kernel/debug/")
	if err == nil {
		err = <-errc
	}
	if err != nil {
		return nil, fmt.Errorf("failed to run script: %v", err)
	}

	closeInst = nil
	return inst, nil
}

func (inst *instance) Close() {
	if inst.lkvm != nil {
		inst.lkvm.Process.Kill()
		err := <-inst.waiterC
		inst.waiterC <- err // repost it for waiting goroutines
		<-inst.readerC
	}
	os.RemoveAll(inst.sandboxPath)
	os.Remove(inst.sandboxPath + ".sock")
}

func (inst *instance) Forward(port int) (string, error) {
	return fmt.Sprintf("%v:%v", hostAddr, port), nil
}

func (inst *instance) Copy(hostSrc string) (string, error) {
	vmDst := filepath.Join("/", filepath.Base(hostSrc))
	dst := filepath.Join(inst.sandboxPath, vmDst)
	if err := osutil.CopyFile(hostSrc, dst); err != nil {
		return "", err
	}
	if err := os.Chmod(dst, 0777); err != nil {
		return "", err
	}
	return vmDst, nil
}

func (inst *instance) Run(timeout time.Duration, stop <-chan bool, command string) (
	<-chan []byte, <-chan error, error) {
	outputC := make(chan []byte, 10)
	errorC := make(chan error, 1)
	inst.mu.Lock()
	inst.outputB = nil
	inst.outputC = outputC
	inst.mu.Unlock()

	cmdFile := filepath.Join(inst.sandboxPath, "/syz-cmd")
	tmpFile := cmdFile + "-tmp"
	if err := osutil.WriteExecFile(tmpFile, []byte(command)); err != nil {
		return nil, nil, err
	}
	if err := osutil.Rename(tmpFile, cmdFile); err != nil {
		return nil, nil, err
	}

	signal := func(err error) {
		inst.mu.Lock()
		if inst.outputC == outputC {
			inst.outputB = nil
			inst.outputC = nil
		}
		inst.mu.Unlock()
		errorC <- err
	}

	go func() {
		timeoutTicker := time.NewTicker(timeout)
		secondTicker := time.NewTicker(time.Second)
		var resultErr error
	loop:
		for {
			select {
			case <-timeoutTicker.C:
				resultErr = vmimpl.ErrTimeout
				break loop
			case <-stop:
				resultErr = vmimpl.ErrTimeout
				break loop
			case <-secondTicker.C:
				if !osutil.IsExist(cmdFile) {
					resultErr = nil
					break loop
				}
			case err := <-inst.waiterC:
				inst.waiterC <- err // repost it for Close
				resultErr = fmt.Errorf("lkvm exited")
				break loop
			}
		}
		signal(resultErr)
		timeoutTicker.Stop()
		secondTicker.Stop()
	}()

	return outputC, errorC, nil
}

func (inst *instance) Diagnose(rep *report.Report) ([]byte, bool) {
	return nil, false
}

const script = `#! /bin/bash
while true; do
	if [ -e "/syz-cmd" ]; then
		/syz-cmd
		rm -f /syz-cmd
	else
		sleep 1
	fi
done
`