12 #include <linux/bpf.h>
13 #include <linux/filter.h>
14 #include <linux/perf_event.h>
15 #include <linux/netlink.h>
16 #include <linux/rtnetlink.h>
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/syscall.h>
20 #include <sys/ioctl.h>
27 #define DEBUGFS "/sys/kernel/debug/tracing/"
29 static char license[128];
30 static int kern_version;
31 static bool processed_sec[128];
32 char bpf_log_buf[BPF_LOG_BUF_SIZE];
34 int prog_fd[MAX_PROGS];
35 int event_fd[MAX_PROGS];
37 int prog_array_fd = -1;
41 unsigned int key_size;
42 unsigned int value_size;
43 unsigned int max_entries;
44 unsigned int map_flags;
47 static int populate_prog_array(const char *event, int prog_fd)
49 int ind = atoi(event), err;
51 err = bpf_map_update_elem(prog_array_fd, &ind, &prog_fd, BPF_ANY);
53 printf("failed to store prog_fd in prog_array\n");
59 static int load_and_attach(const char *event, struct bpf_insn *prog, int size)
61 bool is_socket = strncmp(event, "socket", 6) == 0;
62 bool is_kprobe = strncmp(event, "kprobe/", 7) == 0;
63 bool is_kretprobe = strncmp(event, "kretprobe/", 10) == 0;
64 bool is_tracepoint = strncmp(event, "tracepoint/", 11) == 0;
65 bool is_xdp = strncmp(event, "xdp", 3) == 0;
66 bool is_perf_event = strncmp(event, "perf_event", 10) == 0;
67 bool is_cgroup_skb = strncmp(event, "cgroup/skb", 10) == 0;
68 bool is_cgroup_sk = strncmp(event, "cgroup/sock", 11) == 0;
69 size_t insns_cnt = size / sizeof(struct bpf_insn);
70 enum bpf_prog_type prog_type;
73 struct perf_event_attr attr = {};
75 attr.type = PERF_TYPE_TRACEPOINT;
76 attr.sample_type = PERF_SAMPLE_RAW;
77 attr.sample_period = 1;
78 attr.wakeup_events = 1;
81 prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
82 } else if (is_kprobe || is_kretprobe) {
83 prog_type = BPF_PROG_TYPE_KPROBE;
84 } else if (is_tracepoint) {
85 prog_type = BPF_PROG_TYPE_TRACEPOINT;
87 prog_type = BPF_PROG_TYPE_XDP;
88 } else if (is_perf_event) {
89 prog_type = BPF_PROG_TYPE_PERF_EVENT;
90 } else if (is_cgroup_skb) {
91 prog_type = BPF_PROG_TYPE_CGROUP_SKB;
92 } else if (is_cgroup_sk) {
93 prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
95 printf("Unknown event '%s'\n", event);
99 fd = bpf_load_program(prog_type, prog, insns_cnt, license, kern_version,
100 bpf_log_buf, BPF_LOG_BUF_SIZE);
102 printf("bpf_load_program() err=%d\n%s", errno, bpf_log_buf);
106 prog_fd[prog_cnt++] = fd;
108 if (is_xdp || is_perf_event || is_cgroup_skb || is_cgroup_sk)
116 if (!isdigit(*event)) {
117 printf("invalid prog number\n");
120 return populate_prog_array(event, fd);
123 if (is_kprobe || is_kretprobe) {
130 printf("event name cannot be empty\n");
135 return populate_prog_array(event, fd);
137 snprintf(buf, sizeof(buf),
138 "echo '%c:%s %s' >> /sys/kernel/debug/tracing/kprobe_events",
139 is_kprobe ? 'p' : 'r', event, event);
142 printf("failed to create kprobe '%s' error '%s'\n",
143 event, strerror(errno));
147 strcpy(buf, DEBUGFS);
148 strcat(buf, "events/kprobes/");
151 } else if (is_tracepoint) {
155 printf("event name cannot be empty\n");
158 strcpy(buf, DEBUGFS);
159 strcat(buf, "events/");
164 efd = open(buf, O_RDONLY, 0);
166 printf("failed to open event %s\n", event);
170 err = read(efd, buf, sizeof(buf));
171 if (err < 0 || err >= sizeof(buf)) {
172 printf("read from '%s' failed '%s'\n", event, strerror(errno));
182 efd = perf_event_open(&attr, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
184 printf("event %d fd %d err %s\n", id, efd, strerror(errno));
187 event_fd[prog_cnt - 1] = efd;
188 ioctl(efd, PERF_EVENT_IOC_ENABLE, 0);
189 ioctl(efd, PERF_EVENT_IOC_SET_BPF, fd);
194 static int load_maps(struct bpf_map_def *maps, int len)
198 for (i = 0; i < len / sizeof(struct bpf_map_def); i++) {
200 map_fd[i] = bpf_create_map(maps[i].type,
206 printf("failed to create a map: %d %s\n",
207 errno, strerror(errno));
211 if (maps[i].type == BPF_MAP_TYPE_PROG_ARRAY)
212 prog_array_fd = map_fd[i];
217 static int get_sec(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname,
218 GElf_Shdr *shdr, Elf_Data **data)
222 scn = elf_getscn(elf, i);
226 if (gelf_getshdr(scn, shdr) != shdr)
229 *shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
230 if (!*shname || !shdr->sh_size)
233 *data = elf_getdata(scn, 0);
234 if (!*data || elf_getdata(scn, *data) != NULL)
240 static int parse_relo_and_apply(Elf_Data *data, Elf_Data *symbols,
241 GElf_Shdr *shdr, struct bpf_insn *insn)
245 nrels = shdr->sh_size / shdr->sh_entsize;
247 for (i = 0; i < nrels; i++) {
250 unsigned int insn_idx;
252 gelf_getrel(data, i, &rel);
254 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
256 gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);
258 if (insn[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
259 printf("invalid relo for insn[%d].code 0x%x\n",
260 insn_idx, insn[insn_idx].code);
263 insn[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
264 insn[insn_idx].imm = map_fd[sym.st_value / sizeof(struct bpf_map_def)];
270 int load_bpf_file(char *path)
275 GElf_Shdr shdr, shdr_prog;
276 Elf_Data *data, *data_prog, *symbols = NULL;
277 char *shname, *shname_prog;
279 if (elf_version(EV_CURRENT) == EV_NONE)
282 fd = open(path, O_RDONLY, 0);
286 elf = elf_begin(fd, ELF_C_READ, NULL);
291 if (gelf_getehdr(elf, &ehdr) != &ehdr)
294 /* clear all kprobes */
295 i = system("echo \"\" > /sys/kernel/debug/tracing/kprobe_events");
297 /* scan over all elf sections to get license and map info */
298 for (i = 1; i < ehdr.e_shnum; i++) {
300 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
303 if (0) /* helpful for llvm debugging */
304 printf("section %d:%s data %p size %zd link %d flags %d\n",
305 i, shname, data->d_buf, data->d_size,
306 shdr.sh_link, (int) shdr.sh_flags);
308 if (strcmp(shname, "license") == 0) {
309 processed_sec[i] = true;
310 memcpy(license, data->d_buf, data->d_size);
311 } else if (strcmp(shname, "version") == 0) {
312 processed_sec[i] = true;
313 if (data->d_size != sizeof(int)) {
314 printf("invalid size of version section %zd\n",
318 memcpy(&kern_version, data->d_buf, sizeof(int));
319 } else if (strcmp(shname, "maps") == 0) {
320 processed_sec[i] = true;
321 if (load_maps(data->d_buf, data->d_size))
323 } else if (shdr.sh_type == SHT_SYMTAB) {
328 /* load programs that need map fixup (relocations) */
329 for (i = 1; i < ehdr.e_shnum; i++) {
331 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
333 if (shdr.sh_type == SHT_REL) {
334 struct bpf_insn *insns;
336 if (get_sec(elf, shdr.sh_info, &ehdr, &shname_prog,
337 &shdr_prog, &data_prog))
340 if (shdr_prog.sh_type != SHT_PROGBITS ||
341 !(shdr_prog.sh_flags & SHF_EXECINSTR))
344 insns = (struct bpf_insn *) data_prog->d_buf;
346 processed_sec[shdr.sh_info] = true;
347 processed_sec[i] = true;
349 if (parse_relo_and_apply(data, symbols, &shdr, insns))
352 if (memcmp(shname_prog, "kprobe/", 7) == 0 ||
353 memcmp(shname_prog, "kretprobe/", 10) == 0 ||
354 memcmp(shname_prog, "tracepoint/", 11) == 0 ||
355 memcmp(shname_prog, "xdp", 3) == 0 ||
356 memcmp(shname_prog, "perf_event", 10) == 0 ||
357 memcmp(shname_prog, "socket", 6) == 0 ||
358 memcmp(shname_prog, "cgroup/", 7) == 0)
359 load_and_attach(shname_prog, insns, data_prog->d_size);
363 /* load programs that don't use maps */
364 for (i = 1; i < ehdr.e_shnum; i++) {
366 if (processed_sec[i])
369 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
372 if (memcmp(shname, "kprobe/", 7) == 0 ||
373 memcmp(shname, "kretprobe/", 10) == 0 ||
374 memcmp(shname, "tracepoint/", 11) == 0 ||
375 memcmp(shname, "xdp", 3) == 0 ||
376 memcmp(shname, "perf_event", 10) == 0 ||
377 memcmp(shname, "socket", 6) == 0 ||
378 memcmp(shname, "cgroup/", 7) == 0)
379 load_and_attach(shname, data->d_buf, data->d_size);
386 void read_trace_pipe(void)
390 trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
395 static char buf[4096];
398 sz = read(trace_fd, buf, sizeof(buf));
406 #define MAX_SYMS 300000
407 static struct ksym syms[MAX_SYMS];
410 static int ksym_cmp(const void *p1, const void *p2)
412 return ((struct ksym *)p1)->addr - ((struct ksym *)p2)->addr;
415 int load_kallsyms(void)
417 FILE *f = fopen("/proc/kallsyms", "r");
418 char func[256], buf[256];
427 if (!fgets(buf, sizeof(buf), f))
429 if (sscanf(buf, "%p %c %s", &addr, &symbol, func) != 3)
433 syms[i].addr = (long) addr;
434 syms[i].name = strdup(func);
438 qsort(syms, sym_cnt, sizeof(struct ksym), ksym_cmp);
442 struct ksym *ksym_search(long key)
444 int start = 0, end = sym_cnt;
447 while (start < end) {
448 size_t mid = start + (end - start) / 2;
450 result = key - syms[mid].addr;
459 if (start >= 1 && syms[start - 1].addr < key &&
460 key < syms[start].addr)
462 return &syms[start - 1];
464 /* out of range. return _stext */
468 int set_link_xdp_fd(int ifindex, int fd)
470 struct sockaddr_nl sa;
471 int sock, seq = 0, len, ret = -1;
473 struct nlattr *nla, *nla_xdp;
476 struct ifinfomsg ifinfo;
480 struct nlmsgerr *err;
482 memset(&sa, 0, sizeof(sa));
483 sa.nl_family = AF_NETLINK;
485 sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
487 printf("open netlink socket: %s\n", strerror(errno));
491 if (bind(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
492 printf("bind to netlink: %s\n", strerror(errno));
496 memset(&req, 0, sizeof(req));
497 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
498 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
499 req.nh.nlmsg_type = RTM_SETLINK;
500 req.nh.nlmsg_pid = 0;
501 req.nh.nlmsg_seq = ++seq;
502 req.ifinfo.ifi_family = AF_UNSPEC;
503 req.ifinfo.ifi_index = ifindex;
504 nla = (struct nlattr *)(((char *)&req)
505 + NLMSG_ALIGN(req.nh.nlmsg_len));
506 nla->nla_type = NLA_F_NESTED | 43/*IFLA_XDP*/;
508 nla_xdp = (struct nlattr *)((char *)nla + NLA_HDRLEN);
509 nla_xdp->nla_type = 1/*IFLA_XDP_FD*/;
510 nla_xdp->nla_len = NLA_HDRLEN + sizeof(int);
511 memcpy((char *)nla_xdp + NLA_HDRLEN, &fd, sizeof(fd));
512 nla->nla_len = NLA_HDRLEN + nla_xdp->nla_len;
514 req.nh.nlmsg_len += NLA_ALIGN(nla->nla_len);
516 if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) {
517 printf("send to netlink: %s\n", strerror(errno));
521 len = recv(sock, buf, sizeof(buf), 0);
523 printf("recv from netlink: %s\n", strerror(errno));
527 for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len);
528 nh = NLMSG_NEXT(nh, len)) {
529 if (nh->nlmsg_pid != getpid()) {
530 printf("Wrong pid %d, expected %d\n",
531 nh->nlmsg_pid, getpid());
534 if (nh->nlmsg_seq != seq) {
535 printf("Wrong seq %d, expected %d\n",
539 switch (nh->nlmsg_type) {
541 err = (struct nlmsgerr *)NLMSG_DATA(nh);
544 printf("nlmsg error %s\n", strerror(-err->error));