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