forked from cilium/ebpf
-
Notifications
You must be signed in to change notification settings - Fork 1
/
elf_reader_test.go
319 lines (278 loc) · 7.38 KB
/
elf_reader_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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package ebpf
import (
"errors"
"flag"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/cilium/ebpf/internal"
"github.com/cilium/ebpf/internal/btf"
"github.com/cilium/ebpf/internal/testutils"
"github.com/cilium/ebpf/internal/unix"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
func TestLoadCollectionSpec(t *testing.T) {
coll := &CollectionSpec{
Maps: map[string]*MapSpec{
"hash_map": {
Name: "hash_map",
Type: Hash,
KeySize: 4,
ValueSize: 8,
MaxEntries: 1,
Flags: unix.BPF_F_NO_PREALLOC,
},
"hash_map2": {
Name: "hash_map2",
Type: Hash,
KeySize: 4,
ValueSize: 8,
MaxEntries: 2,
},
"array_of_hash_map": {
Name: "array_of_hash_map",
Type: ArrayOfMaps,
KeySize: 4,
MaxEntries: 2,
},
"btf_pin": {
Name: "btf_pin",
Type: Hash,
KeySize: 4,
ValueSize: 8,
MaxEntries: 1,
Pinning: PinByName,
},
},
Programs: map[string]*ProgramSpec{
"xdp_prog": {
Name: "xdp_prog",
Type: XDP,
License: "MIT",
},
"no_relocation": {
Name: "no_relocation",
Type: SocketFilter,
License: "MIT",
},
},
}
defaultOpts := cmp.Options{
cmpopts.IgnoreTypes(new(btf.Map), new(btf.Program)),
cmpopts.IgnoreFields(ProgramSpec{}, "Instructions", "ByteOrder"),
cmpopts.IgnoreMapEntries(func(key string, _ *MapSpec) bool {
switch key {
case ".bss", ".data", ".rodata":
return true
default:
return false
}
}),
}
ignoreBTFOpts := append(defaultOpts,
cmpopts.IgnoreMapEntries(func(key string, _ *MapSpec) bool {
return strings.HasPrefix(key, "btf_")
}),
)
testutils.TestFiles(t, "testdata/loader-*.elf", func(t *testing.T, file string) {
have, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
opts := defaultOpts
if have.Maps[".rodata"] != nil {
err := have.RewriteConstants(map[string]interface{}{
"arg": uint32(1),
})
if err != nil {
t.Fatal("Can't rewrite constant:", err)
}
err = have.RewriteConstants(map[string]interface{}{
"totallyBogus": uint32(1),
})
if err == nil {
t.Error("Rewriting a bogus constant doesn't fail")
}
} else {
opts = ignoreBTFOpts
}
if diff := cmp.Diff(coll, have, opts...); diff != "" {
t.Errorf("MapSpec mismatch (-want +got):\n%s", diff)
}
if have.Programs["xdp_prog"].ByteOrder != internal.NativeEndian {
return
}
have.Maps["array_of_hash_map"].InnerMap = have.Maps["hash_map"]
coll, err := NewCollectionWithOptions(have, CollectionOptions{
Maps: MapOptions{
PinPath: tempBPFFS(t),
},
Programs: ProgramOptions{
LogLevel: 1,
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer coll.Close()
ret, _, err := coll.Programs["xdp_prog"].Test(make([]byte, 14))
if err != nil {
t.Fatal("Can't run program:", err)
}
if ret != 5 {
t.Error("Expected return value to be 5, got", ret)
}
})
}
func TestCollectionSpecDetach(t *testing.T) {
coll := Collection{
Maps: map[string]*Map{
"foo": new(Map),
},
Programs: map[string]*Program{
"bar": new(Program),
},
}
foo := coll.DetachMap("foo")
if foo == nil {
t.Error("Program not returned from DetachMap")
}
if _, ok := coll.Programs["foo"]; ok {
t.Error("DetachMap doesn't remove map from Maps")
}
bar := coll.DetachProgram("bar")
if bar == nil {
t.Fatal("Program not returned from DetachProgram")
}
if _, ok := coll.Programs["bar"]; ok {
t.Error("DetachProgram doesn't remove program from Programs")
}
}
func TestLoadInvalidMap(t *testing.T) {
testutils.TestFiles(t, "testdata/invalid_map-*.elf", func(t *testing.T, file string) {
_, err := LoadCollectionSpec(file)
t.Log(err)
if err == nil {
t.Fatal("Loading an invalid map should fail")
}
})
}
func TestLoadInvalidMapMissingSymbol(t *testing.T) {
testutils.TestFiles(t, "testdata/invalid_map_static-el.elf", func(t *testing.T, file string) {
_, err := LoadCollectionSpec(file)
t.Log(err)
if err == nil {
t.Fatal("Loading a map with static qualifier should fail")
}
})
}
func TestLoadInitializedBTFMap(t *testing.T) {
testutils.TestFiles(t, "testdata/initialized_btf_map-*.elf", func(t *testing.T, file string) {
_, err := LoadCollectionSpec(file)
t.Log(err)
if !errors.Is(err, internal.ErrNotSupported) {
t.Fatal("Loading an initialized BTF map should be unsupported")
}
})
}
func TestStringSection(t *testing.T) {
testutils.TestFiles(t, "testdata/strings-*.elf", func(t *testing.T, file string) {
_, err := LoadCollectionSpec(file)
t.Log(err)
if !errors.Is(err, ErrNotSupported) {
t.Error("References to a string section should be unsupported")
}
})
}
func TestLoadRawTracepoint(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.17", "BPF_RAW_TRACEPOINT API")
testutils.TestFiles(t, "testdata/raw_tracepoint-*.elf", func(t *testing.T, file string) {
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
if spec.Programs["sched_process_exec"].ByteOrder != internal.NativeEndian {
return
}
coll, err := NewCollectionWithOptions(spec, CollectionOptions{
Programs: ProgramOptions{
LogLevel: 1,
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't create collection:", err)
}
coll.Close()
})
}
var (
elfPath = flag.String("elfs", "", "`Path` containing libbpf-compatible ELFs")
elfPattern = flag.String("elf-pattern", "*.o", "Glob `pattern` for object files that should be tested")
)
func TestLibBPFCompat(t *testing.T) {
if *elfPath == "" {
// Specify the path to the directory containing the eBPF for
// the kernel's selftests if you want to run this test.
// As of 5.2 that is tools/testing/selftests/bpf/
t.Skip("No path specified")
}
testutils.TestFiles(t, filepath.Join(*elfPath, *elfPattern), func(t *testing.T, path string) {
file := filepath.Base(path)
switch file {
case "test_ksyms.o":
// Issue #114
t.Skip("Kernel symbols not supported")
case "test_sk_assign.o":
t.Skip("Incompatible struct bpf_map_def")
case "test_ringbuf_multi.o", "map_ptr_kern.o", "test_btf_map_in_map.o":
// Issue #155
t.Skip("BTF .values not supported")
}
t.Parallel()
_, err := LoadCollectionSpec(path)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatalf("Can't read %s: %s", file, err)
}
})
}
func TestGetProgType(t *testing.T) {
testcases := []struct {
section string
pt ProgramType
at AttachType
to string
}{
{"socket/garbage", SocketFilter, AttachNone, ""},
{"kprobe/func", Kprobe, AttachNone, "func"},
{"xdp/foo", XDP, AttachNone, ""},
{"cgroup_skb/ingress", CGroupSKB, AttachCGroupInetIngress, ""},
{"iter/bpf_map", Tracing, AttachTraceIter, "bpf_map"},
}
for _, tc := range testcases {
pt, at, to := getProgType(tc.section)
if pt != tc.pt {
t.Errorf("section %s: expected type %s, got %s", tc.section, tc.pt, pt)
}
if at != tc.at {
t.Errorf("section %s: expected attach type %s, got %s", tc.section, tc.at, at)
}
if to != tc.to {
t.Errorf("section %s: expected attachment to be %q, got %q", tc.section, tc.to, to)
}
}
}
func tempBPFFS(tb testing.TB) string {
tb.Helper()
tmp, err := ioutil.TempDir("/sys/fs/bpf", "ebpf-test")
if err != nil {
tb.Fatal(err)
}
tb.Cleanup(func() { os.RemoveAll(tmp) })
return tmp
}