1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2016 Sargun Dhillon <sargun@sargun.me>
3 */
4
5 #define _GNU_SOURCE
6 #include <stdio.h>
7 #include <linux/bpf.h>
8 #include <unistd.h>
9 #include <bpf/bpf.h>
10 #include "bpf_load.h"
11 #include "cgroup_helpers.h"
12
13 #define CGROUP_PATH "/my-cgroup"
14
main(int argc,char ** argv)15 int main(int argc, char **argv)
16 {
17 pid_t remote_pid, local_pid = getpid();
18 int cg2, idx = 0, rc = 0;
19 char filename[256];
20
21 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
22 if (load_bpf_file(filename)) {
23 printf("%s", bpf_log_buf);
24 return 1;
25 }
26
27 if (setup_cgroup_environment())
28 goto err;
29
30 cg2 = create_and_get_cgroup(CGROUP_PATH);
31
32 if (cg2 < 0)
33 goto err;
34
35 if (bpf_map_update_elem(map_fd[0], &idx, &cg2, BPF_ANY)) {
36 log_err("Adding target cgroup to map");
37 goto err;
38 }
39
40 if (join_cgroup(CGROUP_PATH))
41 goto err;
42
43 /*
44 * The installed helper program catched the sync call, and should
45 * write it to the map.
46 */
47
48 sync();
49 bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
50
51 if (local_pid != remote_pid) {
52 fprintf(stderr,
53 "BPF Helper didn't write correct PID to map, but: %d\n",
54 remote_pid);
55 goto err;
56 }
57
58 /* Verify the negative scenario; leave the cgroup */
59 if (join_cgroup("/"))
60 goto err;
61
62 remote_pid = 0;
63 bpf_map_update_elem(map_fd[1], &idx, &remote_pid, BPF_ANY);
64
65 sync();
66 bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
67
68 if (local_pid == remote_pid) {
69 fprintf(stderr, "BPF cgroup negative test did not work\n");
70 goto err;
71 }
72
73 goto out;
74 err:
75 rc = 1;
76
77 out:
78 close(cg2);
79 cleanup_cgroup_environment();
80 return rc;
81 }
82