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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
|
// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kvm
import (
"math/rand"
"reflect"
"sync/atomic"
"syscall"
"testing"
"time"
"gvisor.googlesource.com/gvisor/pkg/sentry/arch"
"gvisor.googlesource.com/gvisor/pkg/sentry/platform"
"gvisor.googlesource.com/gvisor/pkg/sentry/platform/kvm/testutil"
"gvisor.googlesource.com/gvisor/pkg/sentry/platform/ring0"
"gvisor.googlesource.com/gvisor/pkg/sentry/platform/ring0/pagetables"
"gvisor.googlesource.com/gvisor/pkg/sentry/usermem"
)
var dummyFPState = (*byte)(arch.NewFloatingPointData())
type testHarness interface {
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
}
func kvmTest(t testHarness, setup func(*KVM), fn func(*vCPU) bool) {
// Create the machine.
k, err := New()
if err != nil {
t.Fatalf("error creating KVM instance: %v", err)
}
defer k.machine.Destroy()
defer k.FileMem.Destroy()
// Call additional setup.
if setup != nil {
setup(k)
}
var c *vCPU // For recovery.
defer func() {
redpill()
if c != nil {
k.machine.Put(c)
}
}()
for {
c, err = k.machine.Get()
if err != nil {
t.Fatalf("error getting vCPU: %v", err)
}
if !fn(c) {
break
}
// We put the vCPU here and clear the value so that the
// deferred recovery will not re-put it above.
k.machine.Put(c)
c = nil
}
}
func bluepillTest(t testHarness, fn func(*vCPU)) {
kvmTest(t, nil, func(c *vCPU) bool {
bluepill(c)
fn(c)
return false
})
}
func TestKernelSyscall(t *testing.T) {
bluepillTest(t, func(c *vCPU) {
redpill() // Leave guest mode.
if got := atomic.LoadUint32(&c.state); got != vCPUUser {
t.Errorf("vCPU not in ready state: got %v", got)
}
})
}
func hostFault() {
defer func() {
recover()
}()
var foo *int
*foo = 0
}
func TestKernelFault(t *testing.T) {
hostFault() // Ensure recovery works.
bluepillTest(t, func(c *vCPU) {
hostFault()
if got := atomic.LoadUint32(&c.state); got != vCPUUser {
t.Errorf("vCPU not in ready state: got %v", got)
}
})
}
func TestKernelFloatingPoint(t *testing.T) {
bluepillTest(t, func(c *vCPU) {
if !testutil.FloatingPointWorks() {
t.Errorf("floating point does not work, and it should!")
}
})
}
func applicationTest(t testHarness, useHostMappings bool, target func(), fn func(*vCPU, *syscall.PtraceRegs, *pagetables.PageTables) bool) {
// Initialize registers & page tables.
var (
regs syscall.PtraceRegs
pt *pagetables.PageTables
)
testutil.SetTestTarget(®s, target)
defer func() {
if pt != nil {
pt.Release()
}
}()
kvmTest(t, func(k *KVM) {
// Create new page tables.
as, _, err := k.NewAddressSpace(nil /* invalidator */)
if err != nil {
t.Fatalf("can't create new address space: %v", err)
}
pt = as.(*addressSpace).pageTables
if useHostMappings {
// Apply the physical mappings to these page tables.
// (This is normally dangerous, since they point to
// physical pages that may not exist. This shouldn't be
// done for regular user code, but is fine for test
// purposes.)
applyPhysicalRegions(func(pr physicalRegion) bool {
pt.Map(usermem.Addr(pr.virtual), pr.length, true /* user */, usermem.AnyAccess, pr.physical)
return true // Keep iterating.
})
}
}, func(c *vCPU) bool {
// Invoke the function with the extra data.
return fn(c, ®s, pt)
})
}
func TestApplicationSyscall(t *testing.T) {
applicationTest(t, true, testutil.SyscallLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFull); err != nil {
t.Errorf("application syscall with full restore failed: %v", err)
}
return false
})
applicationTest(t, true, testutil.SyscallLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != nil {
t.Errorf("application syscall with partial restore failed: %v", err)
}
return false
})
}
func TestApplicationFault(t *testing.T) {
applicationTest(t, true, testutil.Touch, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
testutil.SetTouchTarget(regs, nil) // Cause fault.
if si, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFull); err != platform.ErrContextSignal || (si != nil && si.Signo != int32(syscall.SIGSEGV)) {
t.Errorf("application fault with full restore got (%v, %v), expected (%v, SIGSEGV)", err, si, platform.ErrContextSignal)
}
return false
})
applicationTest(t, true, testutil.Touch, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
testutil.SetTouchTarget(regs, nil) // Cause fault.
if si, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != platform.ErrContextSignal || (si != nil && si.Signo != int32(syscall.SIGSEGV)) {
t.Errorf("application fault with partial restore got (%v, %v), expected (%v, SIGSEGV)", err, si, platform.ErrContextSignal)
}
return false
})
}
func TestRegistersSyscall(t *testing.T) {
applicationTest(t, true, testutil.TwiddleRegsSyscall, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
testutil.SetTestRegs(regs) // Fill values for all registers.
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != nil {
t.Errorf("application register check with partial restore got unexpected error: %v", err)
}
if err := testutil.CheckTestRegs(regs, false); err != nil {
t.Errorf("application register check with partial restore failed: %v", err)
}
return false
})
}
func TestRegistersFault(t *testing.T) {
applicationTest(t, true, testutil.TwiddleRegsFault, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
testutil.SetTestRegs(regs) // Fill values for all registers.
if si, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFull); err != platform.ErrContextSignal || si.Signo != int32(syscall.SIGSEGV) {
t.Errorf("application register check with full restore got unexpected error: %v", err)
}
if err := testutil.CheckTestRegs(regs, true); err != nil {
t.Errorf("application register check with full restore failed: %v", err)
}
return false
})
}
func TestSegments(t *testing.T) {
applicationTest(t, true, testutil.TwiddleSegments, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
testutil.SetTestSegments(regs)
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFull); err != nil {
t.Errorf("application segment check with full restore got unexpected error: %v", err)
}
if err := testutil.CheckTestSegments(regs); err != nil {
t.Errorf("application segment check with full restore failed: %v", err)
}
return false
})
}
func TestBounce(t *testing.T) {
applicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
go func() {
time.Sleep(time.Millisecond)
c.BounceToKernel()
}()
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != platform.ErrContextInterrupt {
t.Errorf("application partial restore: got %v, wanted %v", err, platform.ErrContextInterrupt)
}
return false
})
applicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
go func() {
time.Sleep(time.Millisecond)
c.BounceToKernel()
}()
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFull); err != platform.ErrContextInterrupt {
t.Errorf("application full restore: got %v, wanted %v", err, platform.ErrContextInterrupt)
}
return false
})
}
func TestBounceStress(t *testing.T) {
applicationTest(t, true, testutil.SpinLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
randomSleep := func() {
// O(hundreds of microseconds) is appropriate to ensure
// different overlaps and different schedules.
if n := rand.Intn(1000); n > 100 {
time.Sleep(time.Duration(n) * time.Microsecond)
}
}
for i := 0; i < 1000; i++ {
// Start an asynchronously executing goroutine that
// calls Bounce at pseudo-random point in time.
// This should wind up calling Bounce when the
// kernel is in various stages of the switch.
go func() {
randomSleep()
c.BounceToKernel()
}()
randomSleep()
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != platform.ErrContextInterrupt {
t.Errorf("application partial restore: got %v, wanted %v", err, platform.ErrContextInterrupt)
}
c.unlock()
randomSleep()
c.lock()
}
return false
})
}
func TestInvalidate(t *testing.T) {
var data uintptr // Used below.
applicationTest(t, true, testutil.Touch, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
testutil.SetTouchTarget(regs, &data) // Read legitimate value.
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != nil {
t.Errorf("application partial restore: got %v, wanted nil", err)
}
// Unmap the page containing data & invalidate.
pt.Unmap(usermem.Addr(reflect.ValueOf(&data).Pointer() & ^uintptr(usermem.PageSize-1)), usermem.PageSize)
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFlush); err != platform.ErrContextSignal {
t.Errorf("application partial restore: got %v, wanted %v", err, platform.ErrContextSignal)
}
return false
})
}
// IsFault returns true iff the given signal represents a fault.
func IsFault(err error, si *arch.SignalInfo) bool {
return err == platform.ErrContextSignal && si.Signo == int32(syscall.SIGSEGV)
}
func TestEmptyAddressSpace(t *testing.T) {
applicationTest(t, false, testutil.SyscallLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
if si, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); !IsFault(err, si) {
t.Errorf("first fault with partial restore failed got %v", err)
t.Logf("registers: %#v", ®s)
}
return false
})
applicationTest(t, false, testutil.SyscallLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
if si, _, err := c.SwitchToUser(regs, dummyFPState, pt, ring0.FlagFull); !IsFault(err, si) {
t.Errorf("first fault with full restore failed got %v", err)
t.Logf("registers: %#v", ®s)
}
return false
})
}
func TestWrongVCPU(t *testing.T) {
kvmTest(t, nil, func(c1 *vCPU) bool {
kvmTest(t, nil, func(c2 *vCPU) bool {
// Basic test, one then the other.
bluepill(c1)
bluepill(c2)
if c2.switches == 0 {
// Don't allow the test to proceed if this fails.
t.Fatalf("wrong vCPU#2 switches: vCPU1=%+v,vCPU2=%+v", c1, c2)
}
// Alternate vCPUs; we expect to need to trigger the
// wrong vCPU path on each switch.
for i := 0; i < 100; i++ {
bluepill(c1)
bluepill(c2)
}
if count := c1.switches; count < 90 {
t.Errorf("wrong vCPU#1 switches: vCPU1=%+v,vCPU2=%+v", c1, c2)
}
if count := c2.switches; count < 90 {
t.Errorf("wrong vCPU#2 switches: vCPU1=%+v,vCPU2=%+v", c1, c2)
}
return false
})
return false
})
kvmTest(t, nil, func(c1 *vCPU) bool {
kvmTest(t, nil, func(c2 *vCPU) bool {
bluepill(c1)
bluepill(c2)
return false
})
return false
})
}
func BenchmarkApplicationSyscall(b *testing.B) {
var (
i int // Iteration includes machine.Get() / machine.Put().
a int // Count for ErrContextInterrupt.
)
applicationTest(b, true, testutil.SyscallLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != nil {
if err == platform.ErrContextInterrupt {
a++
return true // Ignore.
}
b.Fatalf("benchmark failed: %v", err)
}
i++
return i < b.N
})
if a != 0 {
b.Logf("ErrContextInterrupt occurred %d times (in %d iterations).", a, a+i)
}
}
func BenchmarkKernelSyscall(b *testing.B) {
// Note that the target passed here is irrelevant, we never execute SwitchToUser.
applicationTest(b, true, testutil.Getpid, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
// iteration does not include machine.Get() / machine.Put().
for i := 0; i < b.N; i++ {
testutil.Getpid()
}
return false
})
}
func BenchmarkWorldSwitchToUserRoundtrip(b *testing.B) {
// see BenchmarkApplicationSyscall.
var (
i int
a int
)
applicationTest(b, true, testutil.SyscallLoop, func(c *vCPU, regs *syscall.PtraceRegs, pt *pagetables.PageTables) bool {
if _, _, err := c.SwitchToUser(regs, dummyFPState, pt, 0); err != nil {
if err == platform.ErrContextInterrupt {
a++
return true // Ignore.
}
b.Fatalf("benchmark failed: %v", err)
}
// This will intentionally cause the world switch. By executing
// a host syscall here, we force the transition between guest
// and host mode.
testutil.Getpid()
i++
return i < b.N
})
if a != 0 {
b.Logf("EAGAIN occurred %d times (in %d iterations).", a, a+i)
}
}
|