-
Notifications
You must be signed in to change notification settings - Fork 706
/
memory_test.go
99 lines (79 loc) · 2.37 KB
/
memory_test.go
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
package ebpf
import (
"io"
"os"
"runtime"
"testing"
"github.com/go-quicktest/qt"
"github.com/cilium/ebpf/internal/sys"
"github.com/cilium/ebpf/internal/testutils"
)
func mustMmapableArray(tb testing.TB, extraFlags uint32) *Map {
tb.Helper()
m, err := NewMap(&MapSpec{
Name: "ebpf_mmap",
Type: Array,
KeySize: 4,
ValueSize: 8,
MaxEntries: 8,
Flags: sys.BPF_F_MMAPABLE | extraFlags,
})
testutils.SkipIfNotSupported(tb, err)
qt.Assert(tb, qt.IsNil(err))
tb.Cleanup(func() {
m.Close()
})
return m
}
func TestMemory(t *testing.T) {
mm, err := mustMmapableArray(t, 0).Memory()
qt.Assert(t, qt.IsNil(err))
// The mapping is always at least one page long, and the Map created here fits
// in a single page.
qt.Assert(t, qt.Equals(mm.Size(), os.Getpagesize()))
// No BPF_F_RDONLY_PROG flag, so the Memory should be read-write.
qt.Assert(t, qt.IsFalse(mm.ReadOnly()))
want := []byte{1, 2, 3, 4, 4, 3, 2, 1}
w := io.NewOffsetWriter(mm, 16)
n, err := w.Write(want)
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.Equals(n, 8))
r := io.NewSectionReader(mm, 16, int64(len(want)))
got := make([]byte, len(want))
n, err = r.Read(got)
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.Equals(n, len(want)))
}
func TestMemoryBounds(t *testing.T) {
mm, err := mustMmapableArray(t, 0).Memory()
qt.Assert(t, qt.IsNil(err))
size := uint64(mm.Size())
end := size - 1
qt.Assert(t, qt.IsTrue(mm.bounds(0, 0)))
qt.Assert(t, qt.IsTrue(mm.bounds(end, 0)))
qt.Assert(t, qt.IsTrue(mm.bounds(end-8, 8)))
qt.Assert(t, qt.IsTrue(mm.bounds(0, end)))
qt.Assert(t, qt.IsFalse(mm.bounds(end-8, 9)))
qt.Assert(t, qt.IsFalse(mm.bounds(end, 1)))
qt.Assert(t, qt.IsFalse(mm.bounds(0, size)))
}
func TestMemoryReadOnly(t *testing.T) {
rd, err := mustMmapableArray(t, sys.BPF_F_RDONLY_PROG).Memory()
qt.Assert(t, qt.IsNil(err))
// BPF_F_RDONLY_PROG flag, so the Memory should be read-only.
qt.Assert(t, qt.IsTrue(rd.ReadOnly()))
// Frozen maps can't be mapped rw either.
frozen := mustMmapableArray(t, 0)
qt.Assert(t, qt.IsNil(frozen.Freeze()))
fz, err := frozen.Memory()
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.IsTrue(fz.ReadOnly()))
}
func TestMemoryUnmap(t *testing.T) {
mm, err := mustMmapableArray(t, 0).Memory()
qt.Assert(t, qt.IsNil(err))
// Avoid unmap running twice.
runtime.SetFinalizer(mm, nil)
// unmap panics if the operation fails.
mm.close()
}