aboutsummaryrefslogtreecommitdiffhomepage
path: root/container/seccomp/std_test.go
blob: 93b5613c2f0de0040e8de1a890e3f5661310e9d5 (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
package seccomp

import (
	"reflect"
	"testing"
	"unsafe"

	"hakurei.app/container/std"
	"hakurei.app/ext"
)

func TestSyscallResolveName(t *testing.T) {
	t.Parallel()

	for name, want := range ext.Syscalls() {
		t.Run(name, func(t *testing.T) {
			t.Parallel()

			// this checks the std implementation against libseccomp.
			if got, ok := syscallResolveName(name); !ok || got != want {
				t.Errorf("syscallResolveName(%q) = %d, want %d", name, got, want)
			}
		})
	}
}

func TestRuleType(t *testing.T) {
	assertKind[ext.Uint, scmpUint](t)
	assertOverflow(t, ext.Uint(ext.MaxUint))
	assertKind[ext.Int, scmpInt](t)
	assertOverflow(t, ext.Int(ext.MaxInt))

	assertSize[std.NativeRule, syscallRule](t)
	assertKind[std.ScmpDatum, scmpDatum](t)
	assertKind[std.ScmpCompare, scmpCompare](t)
	assertSize[std.ScmpArgCmp, scmpArgCmp](t)
}

// assertSize asserts that native and equivalent are of the same size.
func assertSize[native, equivalent any](t *testing.T) {
	t.Helper()

	got, want := unsafe.Sizeof(*new(native)), unsafe.Sizeof(*new(equivalent))
	if got != want {
		t.Fatalf("%s: %d, want %d", reflect.TypeFor[native]().Name(), got, want)
	}
}

// assertKind asserts that native and equivalent are of the same kind.
func assertKind[native, equivalent any](t *testing.T) {
	t.Helper()

	assertSize[native, equivalent](t)
	nativeType, equivalentType := reflect.TypeFor[native](), reflect.TypeFor[equivalent]()
	got, want := nativeType.Kind(), equivalentType.Kind()

	if got == reflect.Invalid || want == reflect.Invalid {
		t.Fatalf("%s: invalid call to assertKind", nativeType.Name())
	}
	if got == reflect.Struct {
		t.Fatalf("%s: struct is unsupported by assertKind", nativeType.Name())
	}
	if got != want {
		t.Fatalf("%s: %s, want %s", nativeType.Name(), nativeType.Kind(), equivalentType.Kind())
	}
}

// assertOverflow asserts that incrementing m overflows.
func assertOverflow[T ~int32 | ~uint32](t *testing.T, m T) {
	t.Helper()

	old := m
	m++
	if m > old {
		t.Fatalf("unexpected value %#x", m)
	}
}