Debian Codegraph @

psx/psx_test.go

raw
1 package psx
2
3 import (
4 "fmt"
5 "runtime"
6 "sync"
7 "syscall"
8 "testing"
9 )
10
11 func TestSyscall3(t *testing.T) {
12 want := syscall.Getpid()
13 if got, _, err := Syscall3(syscall.SYS_GETPID, 0, 0, 0); err != 0 {
14 t.Errorf("failed to get PID via libpsx: %v", err)
15 } else if int(got) != want {
16 t.Errorf("pid mismatch: got=%d want=%d", got, want)
17 }
18 if got, _, err := Syscall3(syscall.SYS_CAPGET, 0, 0, 0); err != 14 {
19 t.Errorf("malformed capget returned %d: %v (want 14: %v)", err, err, syscall.Errno(14))
20 } else if ^got != 0 {
21 t.Errorf("malformed capget did not return -1, got=%d", got)
22 }
23 }
24
25 func TestSyscall6(t *testing.T) {
26 want := syscall.Getpid()
27 if got, _, err := Syscall6(syscall.SYS_GETPID, 0, 0, 0, 0, 0, 0); err != 0 {
28 t.Errorf("failed to get PID via libpsx: %v", err)
29 } else if int(got) != want {
30 t.Errorf("pid mismatch: got=%d want=%d", got, want)
31 }
32 if got, _, err := Syscall6(syscall.SYS_CAPGET, 0, 0, 0, 0, 0, 0); err != 14 {
33 t.Errorf("malformed capget errno %d: %v (want 14: %v)", err, err, syscall.Errno(14))
34 } else if ^got != 0 {
35 t.Errorf("malformed capget did not return -1, got=%d", got)
36 }
37 }
38
39 // killAThread locks the goroutine to a thread and exits. This has the
40 // effect of making the go runtime terminate the thread.
41 func killAThread(c <-chan struct{}) {
42 runtime.LockOSThread()
43 <-c
44 }
45
46 // Test state is mirrored as expected.
47 func TestShared(t *testing.T) {
48 const prGetKeepCaps = 7
49 const prSetKeepCaps = 8
50
51 var wg sync.WaitGroup
52
53 newTracker := func() (chan<- uintptr, <-chan string) {
54 ch := make(chan uintptr)
55 ex := make(chan string)
56 go func() {
57 runtime.LockOSThread()
58 defer wg.Done()
59 defer close(ex)
60 tid := syscall.Gettid()
61 for {
62 if _, ok := <-ch; !ok {
63 break
64 }
65 val, ok := <-ch
66 if !ok {
67 break
68 }
69 got, _, e := Syscall3(syscall.SYS_PRCTL, prGetKeepCaps, 0, 0)
70 if e != 0 {
71 ex <- fmt.Sprintf("[%d] psx:prctl(GET_KEEPCAPS) ?= %d failed: %v", tid, val, syscall.Errno(e))
72 break
73 }
74 if got != val {
75 t.Errorf("[%d] bad keepcaps value: got=%d, want=%d", tid, got, val)
76 }
77 if _, ok := <-ch; !ok {
78 break
79 }
80 }
81 }()
82 return ch, ex
83 }
84
85 var tracked []chan<- uintptr
86 var exes []<-chan string
87 for i := 0; i <= 10; i++ {
88 val := uintptr(i & 1)
89 if _, _, e := Syscall3(syscall.SYS_PRCTL, prSetKeepCaps, val, 0); e != 0 {
90 t.Fatalf("[%d] psx:prctl(SET_KEEPCAPS, %d) failed: %v", i, i&1, syscall.Errno(e))
91 }
92 wg.Add(1)
93 tr, ex := newTracker()
94 tracked, exes = append(tracked, tr), append(exes, ex)
95 for i, ch := range tracked {
96 ch <- 2 // start serialization.
97 select {
98 case ferr := <-exes[i]:
99 t.Fatalf("%s", ferr)
100 case ch <- val: // definitely written after change.
101 }
102 ch <- 3 // end serialization.
103 }
104 }
105 for _, ch := range tracked {
106 close(ch)
107 }
108 wg.Wait()
109 }