| 1 |
package ebpf |
| 2 |
|
| 3 |
import ( |
| 4 |
"io" |
| 5 |
"math" |
| 6 |
"os" |
| 7 |
"runtime" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/go-quicktest/qt" |
| 11 |
|
| 12 |
"github.com/cilium/ebpf/internal/sys" |
| 13 |
"github.com/cilium/ebpf/internal/testutils" |
| 14 |
) |
| 15 |
|
| 16 |
func mustMmapableArray(tb testing.TB, extraFlags uint32) *Map { |
| 17 |
tb.Helper() |
| 18 |
|
| 19 |
m, err := newMap(tb, &MapSpec{ |
| 20 |
Name: "ebpf_mmap", |
| 21 |
Type: Array, |
| 22 |
KeySize: 4, |
| 23 |
ValueSize: 8, |
| 24 |
MaxEntries: 8, |
| 25 |
Flags: sys.BPF_F_MMAPABLE | extraFlags, |
| 26 |
}, nil) |
| 27 |
testutils.SkipIfNotSupported(tb, err) |
| 28 |
qt.Assert(tb, qt.IsNil(err)) |
| 29 |
return m |
| 30 |
} |
| 31 |
|
| 32 |
func TestMemory(t *testing.T) { |
| 33 |
mm, err := mustMmapableArray(t, 0).Memory() |
| 34 |
qt.Assert(t, qt.IsNil(err)) |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
runtime.GC() |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
qt.Assert(t, qt.Equals(mm.Size(), uint32(os.Getpagesize()))) |
| 43 |
|
| 44 |
|
| 45 |
qt.Assert(t, qt.IsFalse(mm.ReadOnly())) |
| 46 |
|
| 47 |
want := []byte{1, 2, 3, 4, 4, 3, 2, 1} |
| 48 |
w := io.NewOffsetWriter(mm, 16) |
| 49 |
n, err := w.Write(want) |
| 50 |
qt.Assert(t, qt.IsNil(err)) |
| 51 |
qt.Assert(t, qt.Equals(n, 8)) |
| 52 |
|
| 53 |
r := io.NewSectionReader(mm, 16, int64(len(want))) |
| 54 |
got := make([]byte, len(want)) |
| 55 |
n, err = r.Read(got) |
| 56 |
qt.Assert(t, qt.IsNil(err)) |
| 57 |
qt.Assert(t, qt.Equals(n, len(want))) |
| 58 |
} |
| 59 |
|
| 60 |
func TestMemoryBounds(t *testing.T) { |
| 61 |
mm, err := mustMmapableArray(t, 0).Memory() |
| 62 |
qt.Assert(t, qt.IsNil(err)) |
| 63 |
|
| 64 |
end := mm.Size() |
| 65 |
|
| 66 |
qt.Assert(t, qt.IsTrue(mm.bounds(0, 0))) |
| 67 |
qt.Assert(t, qt.IsTrue(mm.bounds(end, 0))) |
| 68 |
qt.Assert(t, qt.IsTrue(mm.bounds(end-8, 8))) |
| 69 |
qt.Assert(t, qt.IsTrue(mm.bounds(0, end))) |
| 70 |
|
| 71 |
qt.Assert(t, qt.IsFalse(mm.bounds(end-8, 9))) |
| 72 |
qt.Assert(t, qt.IsFalse(mm.bounds(end, 1))) |
| 73 |
qt.Assert(t, qt.IsFalse(mm.bounds(math.MaxUint32, 1))) |
| 74 |
} |
| 75 |
|
| 76 |
func TestMemoryReadOnly(t *testing.T) { |
| 77 |
rd, err := mustMmapableArray(t, sys.BPF_F_RDONLY_PROG).Memory() |
| 78 |
qt.Assert(t, qt.IsNil(err)) |
| 79 |
|
| 80 |
|
| 81 |
qt.Assert(t, qt.IsTrue(rd.ReadOnly())) |
| 82 |
|
| 83 |
|
| 84 |
frozen := mustMmapableArray(t, 0) |
| 85 |
qt.Assert(t, qt.IsNil(frozen.Freeze())) |
| 86 |
fz, err := frozen.Memory() |
| 87 |
qt.Assert(t, qt.IsNil(err)) |
| 88 |
qt.Assert(t, qt.IsTrue(fz.ReadOnly())) |
| 89 |
} |
| 90 |
|
| 91 |
func TestMemoryClose(t *testing.T) { |
| 92 |
mm, err := mustMmapableArray(t, 0).Memory() |
| 93 |
qt.Assert(t, qt.IsNil(err)) |
| 94 |
|
| 95 |
|
| 96 |
mm.close() |
| 97 |
} |