|
1 | 1 | # Ported from Linux tools/testing/selftests/bpf/progs/get_cgroup_id_kern.c |
2 | 2 | # |
3 | 3 | # Upstream records the cgroup id of a process whose pid matches one the |
4 | | -# userspace half of the test set beforehand. |
| 4 | +# userspace half of the test set beforehand: |
5 | 5 | # |
6 | | -# WORKAROUND(globals): upstream uses the file-scope variables `cg_id` and |
7 | | -# `expected_pid` to pass values in and out. PythonBPF has no global variable |
8 | | -# support yet, so each becomes a one-entry HashMap keyed by 0. Replace these |
9 | | -# with real globals once they land; grep for WORKAROUND(globals). |
| 6 | +# __u64 cg_id; |
| 7 | +# __u64 expected_pid; |
| 8 | +# |
| 9 | +# SEC("tracepoint/syscalls/sys_enter_nanosleep") |
| 10 | +# int trace(void *ctx) |
| 11 | +# { |
| 12 | +# __u32 pid = bpf_get_current_pid_tgid(); |
| 13 | +# |
| 14 | +# if (expected_pid == pid) |
| 15 | +# cg_id = bpf_get_current_cgroup_id(); |
| 16 | +# |
| 17 | +# return 0; |
| 18 | +# } |
| 19 | +# |
| 20 | +# Both file-scope variables are @bpfglobal scalars, so the userspace half reads |
| 21 | +# `cg_id` back out of the object's .bss exactly as the kernel's driver does. |
10 | 22 |
|
11 | | -from pythonbpf import bpf, map, section, bpfglobal, compile |
12 | | -from pythonbpf.maps import HashMap |
| 23 | +from pythonbpf import bpf, section, bpfglobal, compile |
13 | 24 | from pythonbpf.helper import pid, get_current_cgroup_id |
14 | | -from ctypes import c_void_p, c_int64, c_int32, c_uint64 |
| 25 | +from ctypes import c_void_p, c_int64, c_uint64 |
15 | 26 |
|
16 | 27 |
|
17 | | -# WORKAROUND(globals): stands in for `__u64 expected_pid;` |
18 | 28 | @bpf |
19 | | -@map |
20 | | -def expected_pid() -> HashMap: |
21 | | - return HashMap(key=c_int32, value=c_uint64, max_entries=1) |
| 29 | +@bpfglobal |
| 30 | +def cg_id() -> c_uint64: |
| 31 | + return c_uint64(0) |
22 | 32 |
|
23 | 33 |
|
24 | | -# WORKAROUND(globals): stands in for `__u64 cg_id;` |
25 | 34 | @bpf |
26 | | -@map |
27 | | -def cg_id() -> HashMap: |
28 | | - return HashMap(key=c_int32, value=c_uint64, max_entries=1) |
| 35 | +@bpfglobal |
| 36 | +def expected_pid() -> c_uint64: |
| 37 | + return c_uint64(0) |
29 | 38 |
|
30 | 39 |
|
31 | 40 | @bpf |
32 | 41 | @section("tracepoint/syscalls/sys_enter_nanosleep") |
33 | 42 | def trace(ctx: c_void_p) -> c_int64: |
34 | | - process_id = pid() |
35 | | - want = expected_pid.lookup(0) |
36 | | - if want == process_id: |
37 | | - cg_id.update(0, get_current_cgroup_id()) |
| 43 | + global cg_id |
| 44 | + if expected_pid == pid(): |
| 45 | + cg_id = get_current_cgroup_id() |
38 | 46 | return c_int64(0) |
39 | 47 |
|
40 | 48 |
|
|
0 commit comments