]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - samples/bpf/bpf_load.c
f5b186c46b7cf4c41c2927571432538f7ee0e5b2
[karo-tx-linux.git] / samples / bpf / bpf_load.c
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include <libelf.h>
6 #include <gelf.h>
7 #include <errno.h>
8 #include <unistd.h>
9 #include <string.h>
10 #include <stdbool.h>
11 #include <stdlib.h>
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>
21 #include <sys/mman.h>
22 #include <poll.h>
23 #include <ctype.h>
24 #include "libbpf.h"
25 #include "bpf_load.h"
26
27 #define DEBUGFS "/sys/kernel/debug/tracing/"
28
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];
33 int map_fd[MAX_MAPS];
34 int prog_fd[MAX_PROGS];
35 int event_fd[MAX_PROGS];
36 int prog_cnt;
37 int prog_array_fd = -1;
38
39 struct bpf_map_def {
40         unsigned int type;
41         unsigned int key_size;
42         unsigned int value_size;
43         unsigned int max_entries;
44         unsigned int map_flags;
45 };
46
47 static int populate_prog_array(const char *event, int prog_fd)
48 {
49         int ind = atoi(event), err;
50
51         err = bpf_map_update_elem(prog_array_fd, &ind, &prog_fd, BPF_ANY);
52         if (err < 0) {
53                 printf("failed to store prog_fd in prog_array\n");
54                 return -1;
55         }
56         return 0;
57 }
58
59 static int load_and_attach(const char *event, struct bpf_insn *prog, int size)
60 {
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         enum bpf_prog_type prog_type;
70         char buf[256];
71         int fd, efd, err, id;
72         struct perf_event_attr attr = {};
73
74         attr.type = PERF_TYPE_TRACEPOINT;
75         attr.sample_type = PERF_SAMPLE_RAW;
76         attr.sample_period = 1;
77         attr.wakeup_events = 1;
78
79         if (is_socket) {
80                 prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
81         } else if (is_kprobe || is_kretprobe) {
82                 prog_type = BPF_PROG_TYPE_KPROBE;
83         } else if (is_tracepoint) {
84                 prog_type = BPF_PROG_TYPE_TRACEPOINT;
85         } else if (is_xdp) {
86                 prog_type = BPF_PROG_TYPE_XDP;
87         } else if (is_perf_event) {
88                 prog_type = BPF_PROG_TYPE_PERF_EVENT;
89         } else if (is_cgroup_skb) {
90                 prog_type = BPF_PROG_TYPE_CGROUP_SKB;
91         } else if (is_cgroup_sk) {
92                 prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
93         } else {
94                 printf("Unknown event '%s'\n", event);
95                 return -1;
96         }
97
98         fd = bpf_load_program(prog_type, prog, size, license, kern_version,
99                               bpf_log_buf, BPF_LOG_BUF_SIZE);
100         if (fd < 0) {
101                 printf("bpf_load_program() err=%d\n%s", errno, bpf_log_buf);
102                 return -1;
103         }
104
105         prog_fd[prog_cnt++] = fd;
106
107         if (is_xdp || is_perf_event || is_cgroup_skb || is_cgroup_sk)
108                 return 0;
109
110         if (is_socket) {
111                 event += 6;
112                 if (*event != '/')
113                         return 0;
114                 event++;
115                 if (!isdigit(*event)) {
116                         printf("invalid prog number\n");
117                         return -1;
118                 }
119                 return populate_prog_array(event, fd);
120         }
121
122         if (is_kprobe || is_kretprobe) {
123                 if (is_kprobe)
124                         event += 7;
125                 else
126                         event += 10;
127
128                 if (*event == 0) {
129                         printf("event name cannot be empty\n");
130                         return -1;
131                 }
132
133                 if (isdigit(*event))
134                         return populate_prog_array(event, fd);
135
136                 snprintf(buf, sizeof(buf),
137                          "echo '%c:%s %s' >> /sys/kernel/debug/tracing/kprobe_events",
138                          is_kprobe ? 'p' : 'r', event, event);
139                 err = system(buf);
140                 if (err < 0) {
141                         printf("failed to create kprobe '%s' error '%s'\n",
142                                event, strerror(errno));
143                         return -1;
144                 }
145
146                 strcpy(buf, DEBUGFS);
147                 strcat(buf, "events/kprobes/");
148                 strcat(buf, event);
149                 strcat(buf, "/id");
150         } else if (is_tracepoint) {
151                 event += 11;
152
153                 if (*event == 0) {
154                         printf("event name cannot be empty\n");
155                         return -1;
156                 }
157                 strcpy(buf, DEBUGFS);
158                 strcat(buf, "events/");
159                 strcat(buf, event);
160                 strcat(buf, "/id");
161         }
162
163         efd = open(buf, O_RDONLY, 0);
164         if (efd < 0) {
165                 printf("failed to open event %s\n", event);
166                 return -1;
167         }
168
169         err = read(efd, buf, sizeof(buf));
170         if (err < 0 || err >= sizeof(buf)) {
171                 printf("read from '%s' failed '%s'\n", event, strerror(errno));
172                 return -1;
173         }
174
175         close(efd);
176
177         buf[err] = 0;
178         id = atoi(buf);
179         attr.config = id;
180
181         efd = perf_event_open(&attr, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
182         if (efd < 0) {
183                 printf("event %d fd %d err %s\n", id, efd, strerror(errno));
184                 return -1;
185         }
186         event_fd[prog_cnt - 1] = efd;
187         ioctl(efd, PERF_EVENT_IOC_ENABLE, 0);
188         ioctl(efd, PERF_EVENT_IOC_SET_BPF, fd);
189
190         return 0;
191 }
192
193 static int load_maps(struct bpf_map_def *maps, int len)
194 {
195         int i;
196
197         for (i = 0; i < len / sizeof(struct bpf_map_def); i++) {
198
199                 map_fd[i] = bpf_create_map(maps[i].type,
200                                            maps[i].key_size,
201                                            maps[i].value_size,
202                                            maps[i].max_entries,
203                                            maps[i].map_flags);
204                 if (map_fd[i] < 0) {
205                         printf("failed to create a map: %d %s\n",
206                                errno, strerror(errno));
207                         return 1;
208                 }
209
210                 if (maps[i].type == BPF_MAP_TYPE_PROG_ARRAY)
211                         prog_array_fd = map_fd[i];
212         }
213         return 0;
214 }
215
216 static int get_sec(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname,
217                    GElf_Shdr *shdr, Elf_Data **data)
218 {
219         Elf_Scn *scn;
220
221         scn = elf_getscn(elf, i);
222         if (!scn)
223                 return 1;
224
225         if (gelf_getshdr(scn, shdr) != shdr)
226                 return 2;
227
228         *shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
229         if (!*shname || !shdr->sh_size)
230                 return 3;
231
232         *data = elf_getdata(scn, 0);
233         if (!*data || elf_getdata(scn, *data) != NULL)
234                 return 4;
235
236         return 0;
237 }
238
239 static int parse_relo_and_apply(Elf_Data *data, Elf_Data *symbols,
240                                 GElf_Shdr *shdr, struct bpf_insn *insn)
241 {
242         int i, nrels;
243
244         nrels = shdr->sh_size / shdr->sh_entsize;
245
246         for (i = 0; i < nrels; i++) {
247                 GElf_Sym sym;
248                 GElf_Rel rel;
249                 unsigned int insn_idx;
250
251                 gelf_getrel(data, i, &rel);
252
253                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
254
255                 gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);
256
257                 if (insn[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
258                         printf("invalid relo for insn[%d].code 0x%x\n",
259                                insn_idx, insn[insn_idx].code);
260                         return 1;
261                 }
262                 insn[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
263                 insn[insn_idx].imm = map_fd[sym.st_value / sizeof(struct bpf_map_def)];
264         }
265
266         return 0;
267 }
268
269 int load_bpf_file(char *path)
270 {
271         int fd, i;
272         Elf *elf;
273         GElf_Ehdr ehdr;
274         GElf_Shdr shdr, shdr_prog;
275         Elf_Data *data, *data_prog, *symbols = NULL;
276         char *shname, *shname_prog;
277
278         if (elf_version(EV_CURRENT) == EV_NONE)
279                 return 1;
280
281         fd = open(path, O_RDONLY, 0);
282         if (fd < 0)
283                 return 1;
284
285         elf = elf_begin(fd, ELF_C_READ, NULL);
286
287         if (!elf)
288                 return 1;
289
290         if (gelf_getehdr(elf, &ehdr) != &ehdr)
291                 return 1;
292
293         /* clear all kprobes */
294         i = system("echo \"\" > /sys/kernel/debug/tracing/kprobe_events");
295
296         /* scan over all elf sections to get license and map info */
297         for (i = 1; i < ehdr.e_shnum; i++) {
298
299                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
300                         continue;
301
302                 if (0) /* helpful for llvm debugging */
303                         printf("section %d:%s data %p size %zd link %d flags %d\n",
304                                i, shname, data->d_buf, data->d_size,
305                                shdr.sh_link, (int) shdr.sh_flags);
306
307                 if (strcmp(shname, "license") == 0) {
308                         processed_sec[i] = true;
309                         memcpy(license, data->d_buf, data->d_size);
310                 } else if (strcmp(shname, "version") == 0) {
311                         processed_sec[i] = true;
312                         if (data->d_size != sizeof(int)) {
313                                 printf("invalid size of version section %zd\n",
314                                        data->d_size);
315                                 return 1;
316                         }
317                         memcpy(&kern_version, data->d_buf, sizeof(int));
318                 } else if (strcmp(shname, "maps") == 0) {
319                         processed_sec[i] = true;
320                         if (load_maps(data->d_buf, data->d_size))
321                                 return 1;
322                 } else if (shdr.sh_type == SHT_SYMTAB) {
323                         symbols = data;
324                 }
325         }
326
327         /* load programs that need map fixup (relocations) */
328         for (i = 1; i < ehdr.e_shnum; i++) {
329
330                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
331                         continue;
332                 if (shdr.sh_type == SHT_REL) {
333                         struct bpf_insn *insns;
334
335                         if (get_sec(elf, shdr.sh_info, &ehdr, &shname_prog,
336                                     &shdr_prog, &data_prog))
337                                 continue;
338
339                         if (shdr_prog.sh_type != SHT_PROGBITS ||
340                             !(shdr_prog.sh_flags & SHF_EXECINSTR))
341                                 continue;
342
343                         insns = (struct bpf_insn *) data_prog->d_buf;
344
345                         processed_sec[shdr.sh_info] = true;
346                         processed_sec[i] = true;
347
348                         if (parse_relo_and_apply(data, symbols, &shdr, insns))
349                                 continue;
350
351                         if (memcmp(shname_prog, "kprobe/", 7) == 0 ||
352                             memcmp(shname_prog, "kretprobe/", 10) == 0 ||
353                             memcmp(shname_prog, "tracepoint/", 11) == 0 ||
354                             memcmp(shname_prog, "xdp", 3) == 0 ||
355                             memcmp(shname_prog, "perf_event", 10) == 0 ||
356                             memcmp(shname_prog, "socket", 6) == 0 ||
357                             memcmp(shname_prog, "cgroup/", 7) == 0)
358                                 load_and_attach(shname_prog, insns, data_prog->d_size);
359                 }
360         }
361
362         /* load programs that don't use maps */
363         for (i = 1; i < ehdr.e_shnum; i++) {
364
365                 if (processed_sec[i])
366                         continue;
367
368                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
369                         continue;
370
371                 if (memcmp(shname, "kprobe/", 7) == 0 ||
372                     memcmp(shname, "kretprobe/", 10) == 0 ||
373                     memcmp(shname, "tracepoint/", 11) == 0 ||
374                     memcmp(shname, "xdp", 3) == 0 ||
375                     memcmp(shname, "perf_event", 10) == 0 ||
376                     memcmp(shname, "socket", 6) == 0 ||
377                     memcmp(shname, "cgroup/", 7) == 0)
378                         load_and_attach(shname, data->d_buf, data->d_size);
379         }
380
381         close(fd);
382         return 0;
383 }
384
385 void read_trace_pipe(void)
386 {
387         int trace_fd;
388
389         trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
390         if (trace_fd < 0)
391                 return;
392
393         while (1) {
394                 static char buf[4096];
395                 ssize_t sz;
396
397                 sz = read(trace_fd, buf, sizeof(buf));
398                 if (sz > 0) {
399                         buf[sz] = 0;
400                         puts(buf);
401                 }
402         }
403 }
404
405 #define MAX_SYMS 300000
406 static struct ksym syms[MAX_SYMS];
407 static int sym_cnt;
408
409 static int ksym_cmp(const void *p1, const void *p2)
410 {
411         return ((struct ksym *)p1)->addr - ((struct ksym *)p2)->addr;
412 }
413
414 int load_kallsyms(void)
415 {
416         FILE *f = fopen("/proc/kallsyms", "r");
417         char func[256], buf[256];
418         char symbol;
419         void *addr;
420         int i = 0;
421
422         if (!f)
423                 return -ENOENT;
424
425         while (!feof(f)) {
426                 if (!fgets(buf, sizeof(buf), f))
427                         break;
428                 if (sscanf(buf, "%p %c %s", &addr, &symbol, func) != 3)
429                         break;
430                 if (!addr)
431                         continue;
432                 syms[i].addr = (long) addr;
433                 syms[i].name = strdup(func);
434                 i++;
435         }
436         sym_cnt = i;
437         qsort(syms, sym_cnt, sizeof(struct ksym), ksym_cmp);
438         return 0;
439 }
440
441 struct ksym *ksym_search(long key)
442 {
443         int start = 0, end = sym_cnt;
444         int result;
445
446         while (start < end) {
447                 size_t mid = start + (end - start) / 2;
448
449                 result = key - syms[mid].addr;
450                 if (result < 0)
451                         end = mid;
452                 else if (result > 0)
453                         start = mid + 1;
454                 else
455                         return &syms[mid];
456         }
457
458         if (start >= 1 && syms[start - 1].addr < key &&
459             key < syms[start].addr)
460                 /* valid ksym */
461                 return &syms[start - 1];
462
463         /* out of range. return _stext */
464         return &syms[0];
465 }
466
467 int set_link_xdp_fd(int ifindex, int fd)
468 {
469         struct sockaddr_nl sa;
470         int sock, seq = 0, len, ret = -1;
471         char buf[4096];
472         struct nlattr *nla, *nla_xdp;
473         struct {
474                 struct nlmsghdr  nh;
475                 struct ifinfomsg ifinfo;
476                 char             attrbuf[64];
477         } req;
478         struct nlmsghdr *nh;
479         struct nlmsgerr *err;
480
481         memset(&sa, 0, sizeof(sa));
482         sa.nl_family = AF_NETLINK;
483
484         sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
485         if (sock < 0) {
486                 printf("open netlink socket: %s\n", strerror(errno));
487                 return -1;
488         }
489
490         if (bind(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
491                 printf("bind to netlink: %s\n", strerror(errno));
492                 goto cleanup;
493         }
494
495         memset(&req, 0, sizeof(req));
496         req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
497         req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
498         req.nh.nlmsg_type = RTM_SETLINK;
499         req.nh.nlmsg_pid = 0;
500         req.nh.nlmsg_seq = ++seq;
501         req.ifinfo.ifi_family = AF_UNSPEC;
502         req.ifinfo.ifi_index = ifindex;
503         nla = (struct nlattr *)(((char *)&req)
504                                 + NLMSG_ALIGN(req.nh.nlmsg_len));
505         nla->nla_type = NLA_F_NESTED | 43/*IFLA_XDP*/;
506
507         nla_xdp = (struct nlattr *)((char *)nla + NLA_HDRLEN);
508         nla_xdp->nla_type = 1/*IFLA_XDP_FD*/;
509         nla_xdp->nla_len = NLA_HDRLEN + sizeof(int);
510         memcpy((char *)nla_xdp + NLA_HDRLEN, &fd, sizeof(fd));
511         nla->nla_len = NLA_HDRLEN + nla_xdp->nla_len;
512
513         req.nh.nlmsg_len += NLA_ALIGN(nla->nla_len);
514
515         if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) {
516                 printf("send to netlink: %s\n", strerror(errno));
517                 goto cleanup;
518         }
519
520         len = recv(sock, buf, sizeof(buf), 0);
521         if (len < 0) {
522                 printf("recv from netlink: %s\n", strerror(errno));
523                 goto cleanup;
524         }
525
526         for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len);
527              nh = NLMSG_NEXT(nh, len)) {
528                 if (nh->nlmsg_pid != getpid()) {
529                         printf("Wrong pid %d, expected %d\n",
530                                nh->nlmsg_pid, getpid());
531                         goto cleanup;
532                 }
533                 if (nh->nlmsg_seq != seq) {
534                         printf("Wrong seq %d, expected %d\n",
535                                nh->nlmsg_seq, seq);
536                         goto cleanup;
537                 }
538                 switch (nh->nlmsg_type) {
539                 case NLMSG_ERROR:
540                         err = (struct nlmsgerr *)NLMSG_DATA(nh);
541                         if (!err->error)
542                                 continue;
543                         printf("nlmsg error %s\n", strerror(-err->error));
544                         goto cleanup;
545                 case NLMSG_DONE:
546                         break;
547                 }
548         }
549
550         ret = 0;
551
552 cleanup:
553         close(sock);
554         return ret;
555 }