]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - samples/bpf/bpf_load.c
samples/bpf: Switch over to libbpf
[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         size_t insns_cnt = size / sizeof(struct bpf_insn);
70         enum bpf_prog_type prog_type;
71         char buf[256];
72         int fd, efd, err, id;
73         struct perf_event_attr attr = {};
74
75         attr.type = PERF_TYPE_TRACEPOINT;
76         attr.sample_type = PERF_SAMPLE_RAW;
77         attr.sample_period = 1;
78         attr.wakeup_events = 1;
79
80         if (is_socket) {
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;
86         } else if (is_xdp) {
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 {
95                 printf("Unknown event '%s'\n", event);
96                 return -1;
97         }
98
99         fd = bpf_load_program(prog_type, prog, insns_cnt, license, kern_version,
100                               bpf_log_buf, BPF_LOG_BUF_SIZE);
101         if (fd < 0) {
102                 printf("bpf_load_program() err=%d\n%s", errno, bpf_log_buf);
103                 return -1;
104         }
105
106         prog_fd[prog_cnt++] = fd;
107
108         if (is_xdp || is_perf_event || is_cgroup_skb || is_cgroup_sk)
109                 return 0;
110
111         if (is_socket) {
112                 event += 6;
113                 if (*event != '/')
114                         return 0;
115                 event++;
116                 if (!isdigit(*event)) {
117                         printf("invalid prog number\n");
118                         return -1;
119                 }
120                 return populate_prog_array(event, fd);
121         }
122
123         if (is_kprobe || is_kretprobe) {
124                 if (is_kprobe)
125                         event += 7;
126                 else
127                         event += 10;
128
129                 if (*event == 0) {
130                         printf("event name cannot be empty\n");
131                         return -1;
132                 }
133
134                 if (isdigit(*event))
135                         return populate_prog_array(event, fd);
136
137                 snprintf(buf, sizeof(buf),
138                          "echo '%c:%s %s' >> /sys/kernel/debug/tracing/kprobe_events",
139                          is_kprobe ? 'p' : 'r', event, event);
140                 err = system(buf);
141                 if (err < 0) {
142                         printf("failed to create kprobe '%s' error '%s'\n",
143                                event, strerror(errno));
144                         return -1;
145                 }
146
147                 strcpy(buf, DEBUGFS);
148                 strcat(buf, "events/kprobes/");
149                 strcat(buf, event);
150                 strcat(buf, "/id");
151         } else if (is_tracepoint) {
152                 event += 11;
153
154                 if (*event == 0) {
155                         printf("event name cannot be empty\n");
156                         return -1;
157                 }
158                 strcpy(buf, DEBUGFS);
159                 strcat(buf, "events/");
160                 strcat(buf, event);
161                 strcat(buf, "/id");
162         }
163
164         efd = open(buf, O_RDONLY, 0);
165         if (efd < 0) {
166                 printf("failed to open event %s\n", event);
167                 return -1;
168         }
169
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));
173                 return -1;
174         }
175
176         close(efd);
177
178         buf[err] = 0;
179         id = atoi(buf);
180         attr.config = id;
181
182         efd = perf_event_open(&attr, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
183         if (efd < 0) {
184                 printf("event %d fd %d err %s\n", id, efd, strerror(errno));
185                 return -1;
186         }
187         event_fd[prog_cnt - 1] = efd;
188         ioctl(efd, PERF_EVENT_IOC_ENABLE, 0);
189         ioctl(efd, PERF_EVENT_IOC_SET_BPF, fd);
190
191         return 0;
192 }
193
194 static int load_maps(struct bpf_map_def *maps, int len)
195 {
196         int i;
197
198         for (i = 0; i < len / sizeof(struct bpf_map_def); i++) {
199
200                 map_fd[i] = bpf_create_map(maps[i].type,
201                                            maps[i].key_size,
202                                            maps[i].value_size,
203                                            maps[i].max_entries,
204                                            maps[i].map_flags);
205                 if (map_fd[i] < 0) {
206                         printf("failed to create a map: %d %s\n",
207                                errno, strerror(errno));
208                         return 1;
209                 }
210
211                 if (maps[i].type == BPF_MAP_TYPE_PROG_ARRAY)
212                         prog_array_fd = map_fd[i];
213         }
214         return 0;
215 }
216
217 static int get_sec(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname,
218                    GElf_Shdr *shdr, Elf_Data **data)
219 {
220         Elf_Scn *scn;
221
222         scn = elf_getscn(elf, i);
223         if (!scn)
224                 return 1;
225
226         if (gelf_getshdr(scn, shdr) != shdr)
227                 return 2;
228
229         *shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
230         if (!*shname || !shdr->sh_size)
231                 return 3;
232
233         *data = elf_getdata(scn, 0);
234         if (!*data || elf_getdata(scn, *data) != NULL)
235                 return 4;
236
237         return 0;
238 }
239
240 static int parse_relo_and_apply(Elf_Data *data, Elf_Data *symbols,
241                                 GElf_Shdr *shdr, struct bpf_insn *insn)
242 {
243         int i, nrels;
244
245         nrels = shdr->sh_size / shdr->sh_entsize;
246
247         for (i = 0; i < nrels; i++) {
248                 GElf_Sym sym;
249                 GElf_Rel rel;
250                 unsigned int insn_idx;
251
252                 gelf_getrel(data, i, &rel);
253
254                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
255
256                 gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);
257
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);
261                         return 1;
262                 }
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)];
265         }
266
267         return 0;
268 }
269
270 int load_bpf_file(char *path)
271 {
272         int fd, i;
273         Elf *elf;
274         GElf_Ehdr ehdr;
275         GElf_Shdr shdr, shdr_prog;
276         Elf_Data *data, *data_prog, *symbols = NULL;
277         char *shname, *shname_prog;
278
279         if (elf_version(EV_CURRENT) == EV_NONE)
280                 return 1;
281
282         fd = open(path, O_RDONLY, 0);
283         if (fd < 0)
284                 return 1;
285
286         elf = elf_begin(fd, ELF_C_READ, NULL);
287
288         if (!elf)
289                 return 1;
290
291         if (gelf_getehdr(elf, &ehdr) != &ehdr)
292                 return 1;
293
294         /* clear all kprobes */
295         i = system("echo \"\" > /sys/kernel/debug/tracing/kprobe_events");
296
297         /* scan over all elf sections to get license and map info */
298         for (i = 1; i < ehdr.e_shnum; i++) {
299
300                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
301                         continue;
302
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);
307
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",
315                                        data->d_size);
316                                 return 1;
317                         }
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))
322                                 return 1;
323                 } else if (shdr.sh_type == SHT_SYMTAB) {
324                         symbols = data;
325                 }
326         }
327
328         /* load programs that need map fixup (relocations) */
329         for (i = 1; i < ehdr.e_shnum; i++) {
330
331                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
332                         continue;
333                 if (shdr.sh_type == SHT_REL) {
334                         struct bpf_insn *insns;
335
336                         if (get_sec(elf, shdr.sh_info, &ehdr, &shname_prog,
337                                     &shdr_prog, &data_prog))
338                                 continue;
339
340                         if (shdr_prog.sh_type != SHT_PROGBITS ||
341                             !(shdr_prog.sh_flags & SHF_EXECINSTR))
342                                 continue;
343
344                         insns = (struct bpf_insn *) data_prog->d_buf;
345
346                         processed_sec[shdr.sh_info] = true;
347                         processed_sec[i] = true;
348
349                         if (parse_relo_and_apply(data, symbols, &shdr, insns))
350                                 continue;
351
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);
360                 }
361         }
362
363         /* load programs that don't use maps */
364         for (i = 1; i < ehdr.e_shnum; i++) {
365
366                 if (processed_sec[i])
367                         continue;
368
369                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
370                         continue;
371
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);
380         }
381
382         close(fd);
383         return 0;
384 }
385
386 void read_trace_pipe(void)
387 {
388         int trace_fd;
389
390         trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
391         if (trace_fd < 0)
392                 return;
393
394         while (1) {
395                 static char buf[4096];
396                 ssize_t sz;
397
398                 sz = read(trace_fd, buf, sizeof(buf));
399                 if (sz > 0) {
400                         buf[sz] = 0;
401                         puts(buf);
402                 }
403         }
404 }
405
406 #define MAX_SYMS 300000
407 static struct ksym syms[MAX_SYMS];
408 static int sym_cnt;
409
410 static int ksym_cmp(const void *p1, const void *p2)
411 {
412         return ((struct ksym *)p1)->addr - ((struct ksym *)p2)->addr;
413 }
414
415 int load_kallsyms(void)
416 {
417         FILE *f = fopen("/proc/kallsyms", "r");
418         char func[256], buf[256];
419         char symbol;
420         void *addr;
421         int i = 0;
422
423         if (!f)
424                 return -ENOENT;
425
426         while (!feof(f)) {
427                 if (!fgets(buf, sizeof(buf), f))
428                         break;
429                 if (sscanf(buf, "%p %c %s", &addr, &symbol, func) != 3)
430                         break;
431                 if (!addr)
432                         continue;
433                 syms[i].addr = (long) addr;
434                 syms[i].name = strdup(func);
435                 i++;
436         }
437         sym_cnt = i;
438         qsort(syms, sym_cnt, sizeof(struct ksym), ksym_cmp);
439         return 0;
440 }
441
442 struct ksym *ksym_search(long key)
443 {
444         int start = 0, end = sym_cnt;
445         int result;
446
447         while (start < end) {
448                 size_t mid = start + (end - start) / 2;
449
450                 result = key - syms[mid].addr;
451                 if (result < 0)
452                         end = mid;
453                 else if (result > 0)
454                         start = mid + 1;
455                 else
456                         return &syms[mid];
457         }
458
459         if (start >= 1 && syms[start - 1].addr < key &&
460             key < syms[start].addr)
461                 /* valid ksym */
462                 return &syms[start - 1];
463
464         /* out of range. return _stext */
465         return &syms[0];
466 }
467
468 int set_link_xdp_fd(int ifindex, int fd)
469 {
470         struct sockaddr_nl sa;
471         int sock, seq = 0, len, ret = -1;
472         char buf[4096];
473         struct nlattr *nla, *nla_xdp;
474         struct {
475                 struct nlmsghdr  nh;
476                 struct ifinfomsg ifinfo;
477                 char             attrbuf[64];
478         } req;
479         struct nlmsghdr *nh;
480         struct nlmsgerr *err;
481
482         memset(&sa, 0, sizeof(sa));
483         sa.nl_family = AF_NETLINK;
484
485         sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
486         if (sock < 0) {
487                 printf("open netlink socket: %s\n", strerror(errno));
488                 return -1;
489         }
490
491         if (bind(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
492                 printf("bind to netlink: %s\n", strerror(errno));
493                 goto cleanup;
494         }
495
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*/;
507
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;
513
514         req.nh.nlmsg_len += NLA_ALIGN(nla->nla_len);
515
516         if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) {
517                 printf("send to netlink: %s\n", strerror(errno));
518                 goto cleanup;
519         }
520
521         len = recv(sock, buf, sizeof(buf), 0);
522         if (len < 0) {
523                 printf("recv from netlink: %s\n", strerror(errno));
524                 goto cleanup;
525         }
526
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());
532                         goto cleanup;
533                 }
534                 if (nh->nlmsg_seq != seq) {
535                         printf("Wrong seq %d, expected %d\n",
536                                nh->nlmsg_seq, seq);
537                         goto cleanup;
538                 }
539                 switch (nh->nlmsg_type) {
540                 case NLMSG_ERROR:
541                         err = (struct nlmsgerr *)NLMSG_DATA(nh);
542                         if (!err->error)
543                                 continue;
544                         printf("nlmsg error %s\n", strerror(-err->error));
545                         goto cleanup;
546                 case NLMSG_DONE:
547                         break;
548                 }
549         }
550
551         ret = 0;
552
553 cleanup:
554         close(sock);
555         return ret;
556 }