File: kprobe_test.go

package info (click to toggle)
golang-github-cilium-ebpf 0.17.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,684 kB
  • sloc: ansic: 1,259; makefile: 127; python: 113; awk: 29; sh: 24
file content (84 lines) | stat: -rw-r--r-- 2,250 bytes parent folder | download
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
package tracefs

import (
	"fmt"
	"os"
	"strings"
	"testing"

	"github.com/go-quicktest/qt"

	"github.com/cilium/ebpf/internal/testutils"
)

// Global symbol, present on all tested kernels.
const ksym = "vprintk"

func TestKprobeTraceFSGroup(t *testing.T) {
	// Expect <prefix>_<16 random hex chars>.
	g, err := RandomGroup("ebpftest")
	qt.Assert(t, qt.IsNil(err))
	qt.Assert(t, qt.Matches(g, `ebpftest_[a-f0-9]{16}`))

	// Expect error when the generator's output exceeds 63 characters.
	p := make([]byte, 47) // 63 - 17 (length of the random suffix and underscore) + 1
	for i := range p {
		p[i] = byte('a')
	}
	_, err = RandomGroup(string(p))
	qt.Assert(t, qt.Not(qt.IsNil(err)))

	// Reject non-alphanumeric characters.
	_, err = RandomGroup("/")
	qt.Assert(t, qt.Not(qt.IsNil(err)))
}

func TestKprobeToken(t *testing.T) {
	tests := []struct {
		args     ProbeArgs
		expected string
	}{
		{ProbeArgs{Symbol: "symbol"}, "symbol"},
		{ProbeArgs{Symbol: "symbol", Offset: 1}, "symbol+0x1"},
		{ProbeArgs{Symbol: "symbol", Offset: 65535}, "symbol+0xffff"},
		{ProbeArgs{Symbol: "symbol", Offset: 65536}, "symbol+0x10000"},
	}

	for i, tt := range tests {
		t.Run(fmt.Sprint(i), func(t *testing.T) {
			po := KprobeToken(tt.args)
			if tt.expected != po {
				t.Errorf("Expected symbol+offset to be '%s', got '%s'", tt.expected, po)
			}
		})
	}
}

func TestNewEvent(t *testing.T) {
	for _, args := range []ProbeArgs{
		{Type: Kprobe, Symbol: ksym},
		{Type: Kprobe, Symbol: ksym, Ret: true},
		{Type: Uprobe, Path: "/bin/bash", Symbol: "main"},
		{Type: Uprobe, Path: "/bin/bash", Symbol: "main", Ret: true},
	} {
		name := fmt.Sprintf("%s ret=%v", args.Type, args.Ret)
		t.Run(name, func(t *testing.T) {
			args.Group, _ = RandomGroup("ebpftest")

			evt, err := NewEvent(args)
			testutils.SkipIfNotSupportedOnOS(t, err)
			if err != nil && strings.Contains(err.Error(), "permission denied") {
				t.Skipf("Skipping test: %v", err)
			}
			qt.Assert(t, qt.IsNil(err))
			defer evt.Close()

			_, err = NewEvent(args)
			qt.Assert(t, qt.ErrorIs(err, os.ErrExist),
				qt.Commentf("expected consecutive event creation to contain os.ErrExist"))

			qt.Assert(t, qt.IsNil(evt.Close()))
			qt.Assert(t, qt.ErrorIs(evt.Close(), os.ErrClosed))
		})
	}
}