hc
2024-05-14 bedbef8ad3e75a304af6361af235302bcc61d06b
kernel/samples/bpf/test_current_task_under_cgroup_user.c
....@@ -1,17 +1,12 @@
1
+// SPDX-License-Identifier: GPL-2.0-only
12 /* 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.
63 */
74
85 #define _GNU_SOURCE
96 #include <stdio.h>
10
-#include <linux/bpf.h>
117 #include <unistd.h>
128 #include <bpf/bpf.h>
13
-#include "bpf_load.h"
14
-#include <linux/bpf.h>
9
+#include <bpf/libbpf.h>
1510 #include "cgroup_helpers.h"
1611
1712 #define CGROUP_PATH "/my-cgroup"
....@@ -19,13 +14,44 @@
1914 int main(int argc, char **argv)
2015 {
2116 pid_t remote_pid, local_pid = getpid();
22
- int cg2, idx = 0, rc = 0;
17
+ struct bpf_link *link = NULL;
18
+ struct bpf_program *prog;
19
+ int cg2, idx = 0, rc = 1;
20
+ struct bpf_object *obj;
2321 char filename[256];
22
+ int map_fd[2];
2423
2524 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
26
- if (load_bpf_file(filename)) {
27
- printf("%s", bpf_log_buf);
28
- return 1;
25
+ obj = bpf_object__open_file(filename, NULL);
26
+ if (libbpf_get_error(obj)) {
27
+ fprintf(stderr, "ERROR: opening BPF object file failed\n");
28
+ return 0;
29
+ }
30
+
31
+ prog = bpf_object__find_program_by_name(obj, "bpf_prog1");
32
+ if (!prog) {
33
+ printf("finding a prog in obj file failed\n");
34
+ goto cleanup;
35
+ }
36
+
37
+ /* load BPF program */
38
+ if (bpf_object__load(obj)) {
39
+ fprintf(stderr, "ERROR: loading BPF object file failed\n");
40
+ goto cleanup;
41
+ }
42
+
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");
47
+ goto cleanup;
48
+ }
49
+
50
+ link = bpf_program__attach(prog);
51
+ if (libbpf_get_error(link)) {
52
+ fprintf(stderr, "ERROR: bpf_program__attach failed\n");
53
+ link = NULL;
54
+ goto cleanup;
2955 }
3056
3157 if (setup_cgroup_environment())
....@@ -33,7 +59,7 @@
3359
3460 cg2 = create_and_get_cgroup(CGROUP_PATH);
3561
36
- if (!cg2)
62
+ if (cg2 < 0)
3763 goto err;
3864
3965 if (bpf_map_update_elem(map_fd[0], &idx, &cg2, BPF_ANY)) {
....@@ -74,12 +100,14 @@
74100 goto err;
75101 }
76102
77
- goto out;
78
-err:
79
- rc = 1;
103
+ rc = 0;
80104
81
-out:
105
+err:
82106 close(cg2);
83107 cleanup_cgroup_environment();
108
+
109
+cleanup:
110
+ bpf_link__destroy(link);
111
+ bpf_object__close(obj);
84112 return rc;
85113 }