1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2016 Sargun Dhillon <sargun@sargun.me>
9 #include <bpf/libbpf.h>
10 #include "cgroup_helpers.h"
12 #define CGROUP_PATH "/my-cgroup"
14 int main(int argc
, char **argv
)
16 pid_t remote_pid
, local_pid
= getpid();
17 int cg2
= -1, idx
= 0, rc
= 1;
18 struct bpf_link
*link
= NULL
;
19 struct bpf_program
*prog
;
20 struct bpf_object
*obj
;
24 snprintf(filename
, sizeof(filename
), "%s.bpf.o", argv
[0]);
25 obj
= bpf_object__open_file(filename
, NULL
);
26 if (libbpf_get_error(obj
)) {
27 fprintf(stderr
, "ERROR: opening BPF object file failed\n");
31 prog
= bpf_object__find_program_by_name(obj
, "bpf_prog1");
33 printf("finding a prog in obj file failed\n");
37 /* load BPF program */
38 if (bpf_object__load(obj
)) {
39 fprintf(stderr
, "ERROR: loading BPF object file failed\n");
43 map_fd
[0] = bpf_object__find_map_fd_by_name(obj
, "cgroup_map");
44 map_fd
[1] = bpf_object__find_map_fd_by_name(obj
, "perf_map");
45 if (map_fd
[0] < 0 || map_fd
[1] < 0) {
46 fprintf(stderr
, "ERROR: finding a map in obj file failed\n");
50 link
= bpf_program__attach(prog
);
51 if (libbpf_get_error(link
)) {
52 fprintf(stderr
, "ERROR: bpf_program__attach failed\n");
57 if (setup_cgroup_environment())
60 cg2
= create_and_get_cgroup(CGROUP_PATH
);
65 if (bpf_map_update_elem(map_fd
[0], &idx
, &cg2
, BPF_ANY
)) {
66 log_err("Adding target cgroup to map");
70 if (join_cgroup(CGROUP_PATH
))
74 * The installed helper program catched the sync call, and should
75 * write it to the map.
79 bpf_map_lookup_elem(map_fd
[1], &idx
, &remote_pid
);
81 if (local_pid
!= remote_pid
) {
83 "BPF Helper didn't write correct PID to map, but: %d\n",
88 /* Verify the negative scenario; leave the cgroup */
93 bpf_map_update_elem(map_fd
[1], &idx
, &remote_pid
, BPF_ANY
);
96 bpf_map_lookup_elem(map_fd
[1], &idx
, &remote_pid
);
98 if (local_pid
== remote_pid
) {
99 fprintf(stderr
, "BPF cgroup negative test did not work\n");
109 cleanup_cgroup_environment();
112 bpf_link__destroy(link
);
113 bpf_object__close(obj
);