1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Facebook
9 #include <linux/perf_event.h>
11 #include <bpf/libbpf.h>
14 /* This program verifies bpf attachment to tracepoint sys_enter_* and sys_exit_*.
15 * This requires kernel CONFIG_FTRACE_SYSCALLS to be set.
18 static void usage(const char *cmd)
20 printf("USAGE: %s [-i nr_tests] [-h]\n", cmd);
21 printf(" -i nr_tests # rounds of test to run\n");
22 printf(" -h # help\n");
25 static void verify_map(int map_id)
30 if (bpf_map_lookup_elem(map_id, &key, &val) != 0) {
31 fprintf(stderr, "map_lookup failed: %s\n", strerror(errno));
35 fprintf(stderr, "failed: map #%d returns value 0\n", map_id);
39 printf("verify map:%d val: %d\n", map_id, val);
42 if (bpf_map_update_elem(map_id, &key, &val, BPF_ANY) != 0) {
43 fprintf(stderr, "map_update failed: %s\n", strerror(errno));
48 static int test(char *filename, int nr_tests)
50 int map0_fds[nr_tests], map1_fds[nr_tests], fd, i, j = 0;
51 struct bpf_link **links = NULL;
52 struct bpf_object *objs[nr_tests];
53 struct bpf_program *prog;
55 for (i = 0; i < nr_tests; i++) {
56 objs[i] = bpf_object__open_file(filename, NULL);
57 if (libbpf_get_error(objs[i])) {
58 fprintf(stderr, "opening BPF object file failed\n");
63 /* One-time initialization */
67 bpf_object__for_each_program(prog, objs[i])
70 links = calloc(nr_progs * nr_tests, sizeof(struct bpf_link *));
76 /* load BPF program */
77 if (bpf_object__load(objs[i])) {
78 fprintf(stderr, "loading BPF object file failed\n");
82 map0_fds[i] = bpf_object__find_map_fd_by_name(objs[i],
84 map1_fds[i] = bpf_object__find_map_fd_by_name(objs[i],
86 if (map0_fds[i] < 0 || map1_fds[i] < 0) {
87 fprintf(stderr, "finding a map in obj file failed\n");
91 bpf_object__for_each_program(prog, objs[i]) {
92 links[j] = bpf_program__attach(prog);
93 if (libbpf_get_error(links[j])) {
94 fprintf(stderr, "bpf_program__attach failed\n");
100 printf("prog #%d: map ids %d %d\n", i, map0_fds[i], map1_fds[i]);
103 /* current load_bpf_file has perf_event_open default pid = -1
104 * and cpu = 0, which permits attached bpf execution on
105 * all cpus for all pid's. bpf program execution ignores
108 /* trigger some "open" operations */
109 fd = open(filename, O_RDONLY);
111 fprintf(stderr, "open failed: %s\n", strerror(errno));
117 for (i = 0; i < nr_tests; i++) {
118 verify_map(map0_fds[i]);
119 verify_map(map1_fds[i]);
124 for (j--; j >= 0; j--)
125 bpf_link__destroy(links[j]);
130 for (i--; i >= 0; i--)
131 bpf_object__close(objs[i]);
135 int main(int argc, char **argv)
137 int opt, nr_tests = 1;
140 while ((opt = getopt(argc, argv, "i:h")) != -1) {
143 nr_tests = atoi(optarg);
152 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
154 return test(filename, nr_tests);