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 <linux/types.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/syscall.h>
21 #include <sys/ioctl.h>
30 #define DEBUGFS "/sys/kernel/debug/tracing/"
32 static char license[128];
33 static int kern_version;
34 static bool processed_sec[128];
35 char bpf_log_buf[BPF_LOG_BUF_SIZE];
37 int prog_fd[MAX_PROGS];
38 int event_fd[MAX_PROGS];
40 int prog_array_fd = -1;
42 struct bpf_map_data map_data[MAX_MAPS];
43 int map_data_count = 0;
45 static int populate_prog_array(const char *event, int prog_fd)
47 int ind = atoi(event), err;
49 err = bpf_map_update_elem(prog_array_fd, &ind, &prog_fd, BPF_ANY);
51 printf("failed to store prog_fd in prog_array\n");
57 static int load_and_attach(const char *event, struct bpf_insn *prog, int size)
59 bool is_socket = strncmp(event, "socket", 6) == 0;
60 bool is_kprobe = strncmp(event, "kprobe/", 7) == 0;
61 bool is_kretprobe = strncmp(event, "kretprobe/", 10) == 0;
62 bool is_tracepoint = strncmp(event, "tracepoint/", 11) == 0;
63 bool is_xdp = strncmp(event, "xdp", 3) == 0;
64 bool is_perf_event = strncmp(event, "perf_event", 10) == 0;
65 bool is_cgroup_skb = strncmp(event, "cgroup/skb", 10) == 0;
66 bool is_cgroup_sk = strncmp(event, "cgroup/sock", 11) == 0;
67 bool is_sockops = strncmp(event, "sockops", 7) == 0;
68 bool is_sk_skb = strncmp(event, "sk_skb", 6) == 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;
94 } else if (is_sockops) {
95 prog_type = BPF_PROG_TYPE_SOCK_OPS;
96 } else if (is_sk_skb) {
97 prog_type = BPF_PROG_TYPE_SK_SKB;
99 printf("Unknown event '%s'\n", event);
103 fd = bpf_load_program(prog_type, prog, insns_cnt, license, kern_version,
104 bpf_log_buf, BPF_LOG_BUF_SIZE);
106 printf("bpf_load_program() err=%d\n%s", errno, bpf_log_buf);
110 prog_fd[prog_cnt++] = fd;
112 if (is_xdp || is_perf_event || is_cgroup_skb || is_cgroup_sk)
115 if (is_socket || is_sockops || is_sk_skb) {
123 if (!isdigit(*event)) {
124 printf("invalid prog number\n");
127 return populate_prog_array(event, fd);
130 if (is_kprobe || is_kretprobe) {
137 printf("event name cannot be empty\n");
142 return populate_prog_array(event, fd);
144 snprintf(buf, sizeof(buf),
145 "echo '%c:%s %s' >> /sys/kernel/debug/tracing/kprobe_events",
146 is_kprobe ? 'p' : 'r', event, event);
149 printf("failed to create kprobe '%s' error '%s'\n",
150 event, strerror(errno));
154 strcpy(buf, DEBUGFS);
155 strcat(buf, "events/kprobes/");
158 } else if (is_tracepoint) {
162 printf("event name cannot be empty\n");
165 strcpy(buf, DEBUGFS);
166 strcat(buf, "events/");
171 efd = open(buf, O_RDONLY, 0);
173 printf("failed to open event %s\n", event);
177 err = read(efd, buf, sizeof(buf));
178 if (err < 0 || err >= sizeof(buf)) {
179 printf("read from '%s' failed '%s'\n", event, strerror(errno));
189 efd = sys_perf_event_open(&attr, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
191 printf("event %d fd %d err %s\n", id, efd, strerror(errno));
194 event_fd[prog_cnt - 1] = efd;
195 ioctl(efd, PERF_EVENT_IOC_ENABLE, 0);
196 ioctl(efd, PERF_EVENT_IOC_SET_BPF, fd);
201 static int load_maps(struct bpf_map_data *maps, int nr_maps,
202 fixup_map_cb fixup_map)
206 for (i = 0; i < nr_maps; i++) {
208 fixup_map(&maps[i], i);
209 /* Allow userspace to assign map FD prior to creation */
210 if (maps[i].fd != -1) {
211 map_fd[i] = maps[i].fd;
216 numa_node = maps[i].def.map_flags & BPF_F_NUMA_NODE ?
217 maps[i].def.numa_node : -1;
219 if (maps[i].def.type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
220 maps[i].def.type == BPF_MAP_TYPE_HASH_OF_MAPS) {
221 int inner_map_fd = map_fd[maps[i].def.inner_map_idx];
223 map_fd[i] = bpf_create_map_in_map_node(maps[i].def.type,
224 maps[i].def.key_size,
226 maps[i].def.max_entries,
227 maps[i].def.map_flags,
230 map_fd[i] = bpf_create_map_node(maps[i].def.type,
231 maps[i].def.key_size,
232 maps[i].def.value_size,
233 maps[i].def.max_entries,
234 maps[i].def.map_flags,
238 printf("failed to create a map: %d %s\n",
239 errno, strerror(errno));
242 maps[i].fd = map_fd[i];
244 if (maps[i].def.type == BPF_MAP_TYPE_PROG_ARRAY)
245 prog_array_fd = map_fd[i];
250 static int get_sec(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname,
251 GElf_Shdr *shdr, Elf_Data **data)
255 scn = elf_getscn(elf, i);
259 if (gelf_getshdr(scn, shdr) != shdr)
262 *shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
263 if (!*shname || !shdr->sh_size)
266 *data = elf_getdata(scn, 0);
267 if (!*data || elf_getdata(scn, *data) != NULL)
273 static int parse_relo_and_apply(Elf_Data *data, Elf_Data *symbols,
274 GElf_Shdr *shdr, struct bpf_insn *insn,
275 struct bpf_map_data *maps, int nr_maps)
279 nrels = shdr->sh_size / shdr->sh_entsize;
281 for (i = 0; i < nrels; i++) {
284 unsigned int insn_idx;
288 gelf_getrel(data, i, &rel);
290 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
292 gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);
294 if (insn[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
295 printf("invalid relo for insn[%d].code 0x%x\n",
296 insn_idx, insn[insn_idx].code);
299 insn[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
301 /* Match FD relocation against recorded map_data[] offset */
302 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
303 if (maps[map_idx].elf_offset == sym.st_value) {
309 insn[insn_idx].imm = maps[map_idx].fd;
311 printf("invalid relo for insn[%d] no map_data match\n",
320 static int cmp_symbols(const void *l, const void *r)
322 const GElf_Sym *lsym = (const GElf_Sym *)l;
323 const GElf_Sym *rsym = (const GElf_Sym *)r;
325 if (lsym->st_value < rsym->st_value)
327 else if (lsym->st_value > rsym->st_value)
333 static int load_elf_maps_section(struct bpf_map_data *maps, int maps_shndx,
334 Elf *elf, Elf_Data *symbols, int strtabidx)
336 int map_sz_elf, map_sz_copy;
337 bool validate_zero = false;
349 /* Get data for maps section via elf index */
350 scn = elf_getscn(elf, maps_shndx);
352 data_maps = elf_getdata(scn, NULL);
353 if (!scn || !data_maps) {
354 printf("Failed to get Elf_Data from maps section %d\n",
359 /* For each map get corrosponding symbol table entry */
360 sym = calloc(MAX_MAPS+1, sizeof(GElf_Sym));
361 for (i = 0, nr_maps = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
362 assert(nr_maps < MAX_MAPS+1);
363 if (!gelf_getsym(symbols, i, &sym[nr_maps]))
365 if (sym[nr_maps].st_shndx != maps_shndx)
367 /* Only increment iif maps section */
371 /* Align to map_fd[] order, via sort on offset in sym.st_value */
372 qsort(sym, nr_maps, sizeof(GElf_Sym), cmp_symbols);
374 /* Keeping compatible with ELF maps section changes
375 * ------------------------------------------------
376 * The program size of struct bpf_map_def is known by loader
377 * code, but struct stored in ELF file can be different.
379 * Unfortunately sym[i].st_size is zero. To calculate the
380 * struct size stored in the ELF file, assume all struct have
381 * the same size, and simply divide with number of map
384 map_sz_elf = data_maps->d_size / nr_maps;
385 map_sz_copy = sizeof(struct bpf_map_def);
386 if (map_sz_elf < map_sz_copy) {
388 * Backward compat, loading older ELF file with
389 * smaller struct, keeping remaining bytes zero.
391 map_sz_copy = map_sz_elf;
392 } else if (map_sz_elf > map_sz_copy) {
394 * Forward compat, loading newer ELF file with larger
395 * struct with unknown features. Assume zero means
396 * feature not used. Thus, validate rest of struct
399 validate_zero = true;
402 /* Memcpy relevant part of ELF maps data to loader maps */
403 for (i = 0; i < nr_maps; i++) {
404 unsigned char *addr, *end;
405 struct bpf_map_def *def;
406 const char *map_name;
409 map_name = elf_strptr(elf, strtabidx, sym[i].st_name);
410 maps[i].name = strdup(map_name);
412 printf("strdup(%s): %s(%d)\n", map_name,
413 strerror(errno), errno);
418 /* Symbol value is offset into ELF maps section data area */
419 offset = sym[i].st_value;
420 def = (struct bpf_map_def *)(data_maps->d_buf + offset);
421 maps[i].elf_offset = offset;
422 memset(&maps[i].def, 0, sizeof(struct bpf_map_def));
423 memcpy(&maps[i].def, def, map_sz_copy);
425 /* Verify no newer features were requested */
427 addr = (unsigned char*) def + map_sz_copy;
428 end = (unsigned char*) def + map_sz_elf;
429 for (; addr < end; addr++) {
442 static int do_load_bpf_file(const char *path, fixup_map_cb fixup_map)
444 int fd, i, ret, maps_shndx = -1, strtabidx = -1;
447 GElf_Shdr shdr, shdr_prog;
448 Elf_Data *data, *data_prog, *data_maps = NULL, *symbols = NULL;
449 char *shname, *shname_prog;
452 /* reset global variables */
454 memset(license, 0, sizeof(license));
455 memset(processed_sec, 0, sizeof(processed_sec));
457 if (elf_version(EV_CURRENT) == EV_NONE)
460 fd = open(path, O_RDONLY, 0);
464 elf = elf_begin(fd, ELF_C_READ, NULL);
469 if (gelf_getehdr(elf, &ehdr) != &ehdr)
472 /* clear all kprobes */
473 i = system("echo \"\" > /sys/kernel/debug/tracing/kprobe_events");
475 /* scan over all elf sections to get license and map info */
476 for (i = 1; i < ehdr.e_shnum; i++) {
478 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
481 if (0) /* helpful for llvm debugging */
482 printf("section %d:%s data %p size %zd link %d flags %d\n",
483 i, shname, data->d_buf, data->d_size,
484 shdr.sh_link, (int) shdr.sh_flags);
486 if (strcmp(shname, "license") == 0) {
487 processed_sec[i] = true;
488 memcpy(license, data->d_buf, data->d_size);
489 } else if (strcmp(shname, "version") == 0) {
490 processed_sec[i] = true;
491 if (data->d_size != sizeof(int)) {
492 printf("invalid size of version section %zd\n",
496 memcpy(&kern_version, data->d_buf, sizeof(int));
497 } else if (strcmp(shname, "maps") == 0) {
502 for (j = 0; j < MAX_MAPS; j++)
504 } else if (shdr.sh_type == SHT_SYMTAB) {
505 strtabidx = shdr.sh_link;
513 printf("missing SHT_SYMTAB section\n");
518 nr_maps = load_elf_maps_section(map_data, maps_shndx,
519 elf, symbols, strtabidx);
521 printf("Error: Failed loading ELF maps (errno:%d):%s\n",
522 nr_maps, strerror(-nr_maps));
526 if (load_maps(map_data, nr_maps, fixup_map))
528 map_data_count = nr_maps;
530 processed_sec[maps_shndx] = true;
533 /* process all relo sections, and rewrite bpf insns for maps */
534 for (i = 1; i < ehdr.e_shnum; i++) {
535 if (processed_sec[i])
538 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
541 if (shdr.sh_type == SHT_REL) {
542 struct bpf_insn *insns;
544 /* locate prog sec that need map fixup (relocations) */
545 if (get_sec(elf, shdr.sh_info, &ehdr, &shname_prog,
546 &shdr_prog, &data_prog))
549 if (shdr_prog.sh_type != SHT_PROGBITS ||
550 !(shdr_prog.sh_flags & SHF_EXECINSTR))
553 insns = (struct bpf_insn *) data_prog->d_buf;
554 processed_sec[i] = true; /* relo section */
556 if (parse_relo_and_apply(data, symbols, &shdr, insns,
563 for (i = 1; i < ehdr.e_shnum; i++) {
565 if (processed_sec[i])
568 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
571 if (memcmp(shname, "kprobe/", 7) == 0 ||
572 memcmp(shname, "kretprobe/", 10) == 0 ||
573 memcmp(shname, "tracepoint/", 11) == 0 ||
574 memcmp(shname, "xdp", 3) == 0 ||
575 memcmp(shname, "perf_event", 10) == 0 ||
576 memcmp(shname, "socket", 6) == 0 ||
577 memcmp(shname, "cgroup/", 7) == 0 ||
578 memcmp(shname, "sockops", 7) == 0 ||
579 memcmp(shname, "sk_skb", 6) == 0) {
580 ret = load_and_attach(shname, data->d_buf,
593 int load_bpf_file(char *path)
595 return do_load_bpf_file(path, NULL);
598 int load_bpf_file_fixup_map(const char *path, fixup_map_cb fixup_map)
600 return do_load_bpf_file(path, fixup_map);
603 void read_trace_pipe(void)
607 trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
612 static char buf[4096];
615 sz = read(trace_fd, buf, sizeof(buf));
623 #define MAX_SYMS 300000
624 static struct ksym syms[MAX_SYMS];
627 static int ksym_cmp(const void *p1, const void *p2)
629 return ((struct ksym *)p1)->addr - ((struct ksym *)p2)->addr;
632 int load_kallsyms(void)
634 FILE *f = fopen("/proc/kallsyms", "r");
635 char func[256], buf[256];
644 if (!fgets(buf, sizeof(buf), f))
646 if (sscanf(buf, "%p %c %s", &addr, &symbol, func) != 3)
650 syms[i].addr = (long) addr;
651 syms[i].name = strdup(func);
655 qsort(syms, sym_cnt, sizeof(struct ksym), ksym_cmp);
659 struct ksym *ksym_search(long key)
661 int start = 0, end = sym_cnt;
664 while (start < end) {
665 size_t mid = start + (end - start) / 2;
667 result = key - syms[mid].addr;
676 if (start >= 1 && syms[start - 1].addr < key &&
677 key < syms[start].addr)
679 return &syms[start - 1];
681 /* out of range. return _stext */
685 int set_link_xdp_fd(int ifindex, int fd, __u32 flags)
687 struct sockaddr_nl sa;
688 int sock, seq = 0, len, ret = -1;
690 struct nlattr *nla, *nla_xdp;
693 struct ifinfomsg ifinfo;
697 struct nlmsgerr *err;
699 memset(&sa, 0, sizeof(sa));
700 sa.nl_family = AF_NETLINK;
702 sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
704 printf("open netlink socket: %s\n", strerror(errno));
708 if (bind(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
709 printf("bind to netlink: %s\n", strerror(errno));
713 memset(&req, 0, sizeof(req));
714 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
715 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
716 req.nh.nlmsg_type = RTM_SETLINK;
717 req.nh.nlmsg_pid = 0;
718 req.nh.nlmsg_seq = ++seq;
719 req.ifinfo.ifi_family = AF_UNSPEC;
720 req.ifinfo.ifi_index = ifindex;
722 /* started nested attribute for XDP */
723 nla = (struct nlattr *)(((char *)&req)
724 + NLMSG_ALIGN(req.nh.nlmsg_len));
725 nla->nla_type = NLA_F_NESTED | 43/*IFLA_XDP*/;
726 nla->nla_len = NLA_HDRLEN;
729 nla_xdp = (struct nlattr *)((char *)nla + nla->nla_len);
730 nla_xdp->nla_type = 1/*IFLA_XDP_FD*/;
731 nla_xdp->nla_len = NLA_HDRLEN + sizeof(int);
732 memcpy((char *)nla_xdp + NLA_HDRLEN, &fd, sizeof(fd));
733 nla->nla_len += nla_xdp->nla_len;
735 /* if user passed in any flags, add those too */
737 nla_xdp = (struct nlattr *)((char *)nla + nla->nla_len);
738 nla_xdp->nla_type = 3/*IFLA_XDP_FLAGS*/;
739 nla_xdp->nla_len = NLA_HDRLEN + sizeof(flags);
740 memcpy((char *)nla_xdp + NLA_HDRLEN, &flags, sizeof(flags));
741 nla->nla_len += nla_xdp->nla_len;
744 req.nh.nlmsg_len += NLA_ALIGN(nla->nla_len);
746 if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) {
747 printf("send to netlink: %s\n", strerror(errno));
751 len = recv(sock, buf, sizeof(buf), 0);
753 printf("recv from netlink: %s\n", strerror(errno));
757 for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len);
758 nh = NLMSG_NEXT(nh, len)) {
759 if (nh->nlmsg_pid != getpid()) {
760 printf("Wrong pid %d, expected %d\n",
761 nh->nlmsg_pid, getpid());
764 if (nh->nlmsg_seq != seq) {
765 printf("Wrong seq %d, expected %d\n",
769 switch (nh->nlmsg_type) {
771 err = (struct nlmsgerr *)NLMSG_DATA(nh);
774 printf("nlmsg error %s\n", strerror(-err->error));