forked from tw4452852/zbpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterator.zig
58 lines (49 loc) · 1.74 KB
/
iterator.zig
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
const std = @import("std");
const root = @import("root.zig");
const print = std.debug.print;
const testing = std.testing;
const allocator = root.allocator;
const libbpf = root.libbpf;
test "iterator" {
const obj_bytes = @embedFile("@iterator");
const bytes = try allocator.dupe(u8, obj_bytes);
defer allocator.free(bytes);
_ = libbpf.libbpf_set_print(root.dbg_printf);
const obj = libbpf.bpf_object__open_mem(bytes.ptr, bytes.len, null);
if (obj == null) {
print("failed to open bpf object: {}\n", .{std.os.errno(-1)});
return error.OPEN;
}
defer libbpf.bpf_object__close(obj);
var ret = libbpf.bpf_object__load(obj);
if (ret != 0) {
print("failed to load bpf object: {}\n", .{std.os.errno(-1)});
return error.LOAD;
}
if (libbpf.bpf_object__next_program(obj, null)) |prog| {
const link = libbpf.bpf_program__attach_iter(prog, null).?;
defer _ = libbpf.bpf_link__destroy(link);
const fd = libbpf.bpf_iter_create(libbpf.bpf_link__fd(link));
const f = std.fs.File{ .handle = fd };
defer f.close();
var r = f.reader();
const expect = blk: {
var n: u64 = 0;
var id: u32 = 0;
while (true) : (n += 1) {
ret = libbpf.bpf_map_get_next_id(id, &id);
if (ret != 0) break;
}
break :blk n;
};
var got: u64 = undefined;
const native_endian = @import("builtin").target.cpu.arch.endian();
while (true) {
got = r.readInt(u64, native_endian) catch |e| switch (e) {
error.EndOfStream => break,
else => return e,
};
}
try testing.expectEqual(expect, got);
}
}