1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Facebook
9 #include <linux/perf_event.h>
11 #include <sys/resource.h>
12 #include <bpf/libbpf.h>
15 /* This program verifies bpf attachment to tracepoint sys_enter_* and sys_exit_*.
16 * This requires kernel CONFIG_FTRACE_SYSCALLS to be set.
19 static void usage(const char *cmd)
21 printf("USAGE: %s [-i num_progs] [-h]\n", cmd);
22 printf(" -i num_progs # number of progs of the test\n");
23 printf(" -h # help\n");
26 static void verify_map(int map_id)
31 if (bpf_map_lookup_elem(map_id, &key, &val) != 0) {
32 fprintf(stderr, "map_lookup failed: %s\n", strerror(errno));
36 fprintf(stderr, "failed: map #%d returns value 0\n", map_id);
40 if (bpf_map_update_elem(map_id, &key, &val, BPF_ANY) != 0) {
41 fprintf(stderr, "map_update failed: %s\n", strerror(errno));
46 static int test(char *filename, int num_progs)
48 int map0_fds[num_progs], map1_fds[num_progs], fd, i, j = 0;
49 struct bpf_link *links[num_progs * 4];
50 struct bpf_object *objs[num_progs];
51 struct bpf_program *prog;
53 for (i = 0; i < num_progs; i++) {
54 objs[i] = bpf_object__open_file(filename, NULL);
55 if (libbpf_get_error(objs[i])) {
56 fprintf(stderr, "opening BPF object file failed\n");
61 /* load BPF program */
62 if (bpf_object__load(objs[i])) {
63 fprintf(stderr, "loading BPF object file failed\n");
67 map0_fds[i] = bpf_object__find_map_fd_by_name(objs[i],
69 map1_fds[i] = bpf_object__find_map_fd_by_name(objs[i],
71 if (map0_fds[i] < 0 || map1_fds[i] < 0) {
72 fprintf(stderr, "finding a map in obj file failed\n");
76 bpf_object__for_each_program(prog, objs[i]) {
77 links[j] = bpf_program__attach(prog);
78 if (libbpf_get_error(links[j])) {
79 fprintf(stderr, "bpf_program__attach failed\n");
85 printf("prog #%d: map ids %d %d\n", i, map0_fds[i], map1_fds[i]);
88 /* current load_bpf_file has perf_event_open default pid = -1
89 * and cpu = 0, which permits attached bpf execution on
90 * all cpus for all pid's. bpf program execution ignores
93 /* trigger some "open" operations */
94 fd = open(filename, O_RDONLY);
96 fprintf(stderr, "open failed: %s\n", strerror(errno));
102 for (i = 0; i < num_progs; i++) {
103 verify_map(map0_fds[i]);
104 verify_map(map1_fds[i]);
108 for (j--; j >= 0; j--)
109 bpf_link__destroy(links[j]);
111 for (i--; i >= 0; i--)
112 bpf_object__close(objs[i]);
116 int main(int argc, char **argv)
118 int opt, num_progs = 1;
121 while ((opt = getopt(argc, argv, "i:h")) != -1) {
124 num_progs = atoi(optarg);
133 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
135 return test(filename, num_progs);