-
Notifications
You must be signed in to change notification settings - Fork 49
/
editor_test.go
123 lines (100 loc) · 2.54 KB
/
editor_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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package manager
import (
"fmt"
"github.com/cilium/ebpf/rlimit"
"math"
"testing"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/asm"
)
// ExampleEditor_rewriteConstant shows how to change constants in
// compiled eBPF byte code.
//
// The C should look something like this:
//
// #define LOAD_CONSTANT(param, var) asm("%0 = " param " ll" : "=r"(var))
//
// int xdp() {
// bool my_constant;
// LOAD_CONSTANT("SYMBOL_NAME", my_constant);
//
// if (my_constant) ...
func ExampleEditor_rewriteConstant() {
// This assembly is roughly equivalent to what clang
// would emit for the C above.
insns := asm.Instructions{
asm.LoadImm(asm.R0, 0, asm.DWord).WithReference("my_ret"),
asm.Return(),
}
editor := Edit(&insns)
if err := editor.RewriteConstant("my_ret", 42); err != nil {
panic(err)
}
fmt.Printf("%0.0s", insns)
// Output: 0: LdImmDW dst: r0 imm: 42 <my_ret>
// 2: Exit
}
func TestEditorRewriteConstant(t *testing.T) {
if err := rlimit.RemoveMemlock(); err != nil {
t.Fatal(err)
}
spec, err := ebpf.LoadCollectionSpec("testdata/rewrite.elf")
if err != nil {
t.Fatal(err)
}
progSpec := spec.Programs["rewrite"]
editor := Edit(&progSpec.Instructions)
if err := editor.RewriteConstant("constant", 0x01); err != nil {
t.Fatal(err)
}
if err := editor.RewriteConstant("bogus", 0x01); !IsUnreferencedSymbol(err) {
t.Error("Rewriting unreferenced symbol doesn't return appropriate error")
}
t.Log(progSpec.Instructions)
prog, err := ebpf.NewProgram(progSpec)
if err != nil {
t.Fatal(err)
}
defer prog.Close()
ret, _, err := prog.Test(make([]byte, 15))
if err != nil {
t.Fatal(err)
}
const N = 1 // number of rewrites
if expected := uint32(1<<N) - 1; ret != expected {
t.Errorf("Expected return value %d, got %d", expected, ret)
}
}
func TestEditorIssue59(t *testing.T) {
max := uint64(math.MaxUint64)
insns := asm.Instructions{
asm.LoadImm(asm.R1, 0, asm.DWord).WithReference("my_ret"),
asm.RSh.Imm(asm.R1, 63),
asm.Mov.Imm(asm.R0, 1),
asm.JGT.Imm(asm.R1, 0, "exit"),
asm.Mov.Imm(asm.R0, 0),
asm.Return().WithSymbol("exit"),
}
editor := Edit(&insns)
if err := editor.RewriteConstant("my_ret", max); err != nil {
t.Fatal(err)
}
if err := rlimit.RemoveMemlock(); err != nil {
t.Fatal(err)
}
prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{
Type: ebpf.XDP,
License: "MIT",
Instructions: insns,
})
if err != nil {
t.Fatal(err)
}
ret, _, err := prog.Test(make([]byte, 14))
if err != nil {
t.Fatal(err)
}
if ret != 1 {
t.Errorf("Expected return of 1, got %d", ret)
}
}