]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - samples/bpf/bpf_load.c
Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/pmladek...
[mirror_ubuntu-artful-kernel.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 <linux/types.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/syscall.h>
21 #include <sys/ioctl.h>
22 #include <sys/mman.h>
23 #include <poll.h>
24 #include <ctype.h>
25 #include <assert.h>
26 #include "libbpf.h"
27 #include "bpf_load.h"
28 #include "perf-sys.h"
29
30 #define DEBUGFS "/sys/kernel/debug/tracing/"
31
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];
36 int map_fd[MAX_MAPS];
37 int prog_fd[MAX_PROGS];
38 int event_fd[MAX_PROGS];
39 int prog_cnt;
40 int prog_array_fd = -1;
41
42 static int populate_prog_array(const char *event, int prog_fd)
43 {
44 int ind = atoi(event), err;
45
46 err = bpf_map_update_elem(prog_array_fd, &ind, &prog_fd, BPF_ANY);
47 if (err < 0) {
48 printf("failed to store prog_fd in prog_array\n");
49 return -1;
50 }
51 return 0;
52 }
53
54 static int load_and_attach(const char *event, struct bpf_insn *prog, int size)
55 {
56 bool is_socket = strncmp(event, "socket", 6) == 0;
57 bool is_kprobe = strncmp(event, "kprobe/", 7) == 0;
58 bool is_kretprobe = strncmp(event, "kretprobe/", 10) == 0;
59 bool is_tracepoint = strncmp(event, "tracepoint/", 11) == 0;
60 bool is_xdp = strncmp(event, "xdp", 3) == 0;
61 bool is_perf_event = strncmp(event, "perf_event", 10) == 0;
62 bool is_cgroup_skb = strncmp(event, "cgroup/skb", 10) == 0;
63 bool is_cgroup_sk = strncmp(event, "cgroup/sock", 11) == 0;
64 size_t insns_cnt = size / sizeof(struct bpf_insn);
65 enum bpf_prog_type prog_type;
66 char buf[256];
67 int fd, efd, err, id;
68 struct perf_event_attr attr = {};
69
70 attr.type = PERF_TYPE_TRACEPOINT;
71 attr.sample_type = PERF_SAMPLE_RAW;
72 attr.sample_period = 1;
73 attr.wakeup_events = 1;
74
75 if (is_socket) {
76 prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
77 } else if (is_kprobe || is_kretprobe) {
78 prog_type = BPF_PROG_TYPE_KPROBE;
79 } else if (is_tracepoint) {
80 prog_type = BPF_PROG_TYPE_TRACEPOINT;
81 } else if (is_xdp) {
82 prog_type = BPF_PROG_TYPE_XDP;
83 } else if (is_perf_event) {
84 prog_type = BPF_PROG_TYPE_PERF_EVENT;
85 } else if (is_cgroup_skb) {
86 prog_type = BPF_PROG_TYPE_CGROUP_SKB;
87 } else if (is_cgroup_sk) {
88 prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
89 } else {
90 printf("Unknown event '%s'\n", event);
91 return -1;
92 }
93
94 fd = bpf_load_program(prog_type, prog, insns_cnt, license, kern_version,
95 bpf_log_buf, BPF_LOG_BUF_SIZE);
96 if (fd < 0) {
97 printf("bpf_load_program() err=%d\n%s", errno, bpf_log_buf);
98 return -1;
99 }
100
101 prog_fd[prog_cnt++] = fd;
102
103 if (is_xdp || is_perf_event || is_cgroup_skb || is_cgroup_sk)
104 return 0;
105
106 if (is_socket) {
107 event += 6;
108 if (*event != '/')
109 return 0;
110 event++;
111 if (!isdigit(*event)) {
112 printf("invalid prog number\n");
113 return -1;
114 }
115 return populate_prog_array(event, fd);
116 }
117
118 if (is_kprobe || is_kretprobe) {
119 if (is_kprobe)
120 event += 7;
121 else
122 event += 10;
123
124 if (*event == 0) {
125 printf("event name cannot be empty\n");
126 return -1;
127 }
128
129 if (isdigit(*event))
130 return populate_prog_array(event, fd);
131
132 snprintf(buf, sizeof(buf),
133 "echo '%c:%s %s' >> /sys/kernel/debug/tracing/kprobe_events",
134 is_kprobe ? 'p' : 'r', event, event);
135 err = system(buf);
136 if (err < 0) {
137 printf("failed to create kprobe '%s' error '%s'\n",
138 event, strerror(errno));
139 return -1;
140 }
141
142 strcpy(buf, DEBUGFS);
143 strcat(buf, "events/kprobes/");
144 strcat(buf, event);
145 strcat(buf, "/id");
146 } else if (is_tracepoint) {
147 event += 11;
148
149 if (*event == 0) {
150 printf("event name cannot be empty\n");
151 return -1;
152 }
153 strcpy(buf, DEBUGFS);
154 strcat(buf, "events/");
155 strcat(buf, event);
156 strcat(buf, "/id");
157 }
158
159 efd = open(buf, O_RDONLY, 0);
160 if (efd < 0) {
161 printf("failed to open event %s\n", event);
162 return -1;
163 }
164
165 err = read(efd, buf, sizeof(buf));
166 if (err < 0 || err >= sizeof(buf)) {
167 printf("read from '%s' failed '%s'\n", event, strerror(errno));
168 return -1;
169 }
170
171 close(efd);
172
173 buf[err] = 0;
174 id = atoi(buf);
175 attr.config = id;
176
177 efd = sys_perf_event_open(&attr, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
178 if (efd < 0) {
179 printf("event %d fd %d err %s\n", id, efd, strerror(errno));
180 return -1;
181 }
182 event_fd[prog_cnt - 1] = efd;
183 ioctl(efd, PERF_EVENT_IOC_ENABLE, 0);
184 ioctl(efd, PERF_EVENT_IOC_SET_BPF, fd);
185
186 return 0;
187 }
188
189 static int load_maps(struct bpf_map_def *maps, int nr_maps,
190 const char **map_names, fixup_map_cb fixup_map)
191 {
192 int i;
193 /*
194 * Warning: Using "maps" pointing to ELF data_maps->d_buf as
195 * an array of struct bpf_map_def is a wrong assumption about
196 * the ELF maps section format.
197 */
198 for (i = 0; i < nr_maps; i++) {
199 if (fixup_map)
200 fixup_map(&maps[i], map_names[i], i);
201
202 if (maps[i].type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
203 maps[i].type == BPF_MAP_TYPE_HASH_OF_MAPS) {
204 int inner_map_fd = map_fd[maps[i].inner_map_idx];
205
206 map_fd[i] = bpf_create_map_in_map(maps[i].type,
207 maps[i].key_size,
208 inner_map_fd,
209 maps[i].max_entries,
210 maps[i].map_flags);
211 } else {
212 map_fd[i] = bpf_create_map(maps[i].type,
213 maps[i].key_size,
214 maps[i].value_size,
215 maps[i].max_entries,
216 maps[i].map_flags);
217 }
218 if (map_fd[i] < 0) {
219 printf("failed to create a map: %d %s\n",
220 errno, strerror(errno));
221 return 1;
222 }
223
224 if (maps[i].type == BPF_MAP_TYPE_PROG_ARRAY)
225 prog_array_fd = map_fd[i];
226 }
227 return 0;
228 }
229
230 static int get_sec(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname,
231 GElf_Shdr *shdr, Elf_Data **data)
232 {
233 Elf_Scn *scn;
234
235 scn = elf_getscn(elf, i);
236 if (!scn)
237 return 1;
238
239 if (gelf_getshdr(scn, shdr) != shdr)
240 return 2;
241
242 *shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
243 if (!*shname || !shdr->sh_size)
244 return 3;
245
246 *data = elf_getdata(scn, 0);
247 if (!*data || elf_getdata(scn, *data) != NULL)
248 return 4;
249
250 return 0;
251 }
252
253 static int parse_relo_and_apply(Elf_Data *data, Elf_Data *symbols,
254 GElf_Shdr *shdr, struct bpf_insn *insn)
255 {
256 int i, nrels;
257
258 nrels = shdr->sh_size / shdr->sh_entsize;
259
260 for (i = 0; i < nrels; i++) {
261 GElf_Sym sym;
262 GElf_Rel rel;
263 unsigned int insn_idx;
264
265 gelf_getrel(data, i, &rel);
266
267 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
268
269 gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);
270
271 if (insn[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
272 printf("invalid relo for insn[%d].code 0x%x\n",
273 insn_idx, insn[insn_idx].code);
274 return 1;
275 }
276 insn[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
277 /*
278 * Warning: Using sizeof(struct bpf_map_def) here is a
279 * wrong assumption about ELF maps section format
280 */
281 insn[insn_idx].imm = map_fd[sym.st_value / sizeof(struct bpf_map_def)];
282 }
283
284 return 0;
285 }
286
287 static int cmp_symbols(const void *l, const void *r)
288 {
289 const GElf_Sym *lsym = (const GElf_Sym *)l;
290 const GElf_Sym *rsym = (const GElf_Sym *)r;
291
292 if (lsym->st_value < rsym->st_value)
293 return -1;
294 else if (lsym->st_value > rsym->st_value)
295 return 1;
296 else
297 return 0;
298 }
299
300 static int get_sorted_map_names(Elf *elf, Elf_Data *symbols, int maps_shndx,
301 int strtabidx, char **map_names)
302 {
303 GElf_Sym map_symbols[MAX_MAPS];
304 int i, nr_maps = 0;
305
306 for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
307 assert(nr_maps < MAX_MAPS);
308 if (!gelf_getsym(symbols, i, &map_symbols[nr_maps]))
309 continue;
310 if (map_symbols[nr_maps].st_shndx != maps_shndx)
311 continue;
312 nr_maps++;
313 }
314
315 qsort(map_symbols, nr_maps, sizeof(GElf_Sym), cmp_symbols);
316
317 for (i = 0; i < nr_maps; i++) {
318 char *map_name;
319
320 map_name = elf_strptr(elf, strtabidx, map_symbols[i].st_name);
321 if (!map_name) {
322 printf("cannot get map symbol\n");
323 return -1;
324 }
325
326 map_names[i] = strdup(map_name);
327 if (!map_names[i]) {
328 printf("strdup(%s): %s(%d)\n", map_name,
329 strerror(errno), errno);
330 return -1;
331 }
332 }
333
334 return nr_maps;
335 }
336
337 static int do_load_bpf_file(const char *path, fixup_map_cb fixup_map)
338 {
339 int fd, i, ret, maps_shndx = -1, strtabidx = -1;
340 Elf *elf;
341 GElf_Ehdr ehdr;
342 GElf_Shdr shdr, shdr_prog;
343 Elf_Data *data, *data_prog, *data_maps = NULL, *symbols = NULL;
344 char *shname, *shname_prog, *map_names[MAX_MAPS] = { NULL };
345
346 /* reset global variables */
347 kern_version = 0;
348 memset(license, 0, sizeof(license));
349 memset(processed_sec, 0, sizeof(processed_sec));
350
351 if (elf_version(EV_CURRENT) == EV_NONE)
352 return 1;
353
354 fd = open(path, O_RDONLY, 0);
355 if (fd < 0)
356 return 1;
357
358 elf = elf_begin(fd, ELF_C_READ, NULL);
359
360 if (!elf)
361 return 1;
362
363 if (gelf_getehdr(elf, &ehdr) != &ehdr)
364 return 1;
365
366 /* clear all kprobes */
367 i = system("echo \"\" > /sys/kernel/debug/tracing/kprobe_events");
368
369 /* scan over all elf sections to get license and map info */
370 for (i = 1; i < ehdr.e_shnum; i++) {
371
372 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
373 continue;
374
375 if (0) /* helpful for llvm debugging */
376 printf("section %d:%s data %p size %zd link %d flags %d\n",
377 i, shname, data->d_buf, data->d_size,
378 shdr.sh_link, (int) shdr.sh_flags);
379
380 if (strcmp(shname, "license") == 0) {
381 processed_sec[i] = true;
382 memcpy(license, data->d_buf, data->d_size);
383 } else if (strcmp(shname, "version") == 0) {
384 processed_sec[i] = true;
385 if (data->d_size != sizeof(int)) {
386 printf("invalid size of version section %zd\n",
387 data->d_size);
388 return 1;
389 }
390 memcpy(&kern_version, data->d_buf, sizeof(int));
391 } else if (strcmp(shname, "maps") == 0) {
392 maps_shndx = i;
393 data_maps = data;
394 } else if (shdr.sh_type == SHT_SYMTAB) {
395 strtabidx = shdr.sh_link;
396 symbols = data;
397 }
398 }
399
400 ret = 1;
401
402 if (!symbols) {
403 printf("missing SHT_SYMTAB section\n");
404 goto done;
405 }
406
407 if (data_maps) {
408 int nr_maps;
409 int prog_elf_map_sz;
410
411 nr_maps = get_sorted_map_names(elf, symbols, maps_shndx,
412 strtabidx, map_names);
413 if (nr_maps < 0)
414 goto done;
415
416 /* Deduce map struct size stored in ELF maps section */
417 prog_elf_map_sz = data_maps->d_size / nr_maps;
418 if (prog_elf_map_sz != sizeof(struct bpf_map_def)) {
419 printf("Error: ELF maps sec wrong size (%d/%lu),"
420 " old kern.o file?\n",
421 prog_elf_map_sz, sizeof(struct bpf_map_def));
422 ret = 1;
423 goto done;
424 }
425
426 if (load_maps(data_maps->d_buf, nr_maps,
427 (const char **)map_names, fixup_map))
428 goto done;
429
430 processed_sec[maps_shndx] = true;
431 }
432
433 /* load programs that need map fixup (relocations) */
434 for (i = 1; i < ehdr.e_shnum; i++) {
435 if (processed_sec[i])
436 continue;
437
438 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
439 continue;
440 if (shdr.sh_type == SHT_REL) {
441 struct bpf_insn *insns;
442
443 if (get_sec(elf, shdr.sh_info, &ehdr, &shname_prog,
444 &shdr_prog, &data_prog))
445 continue;
446
447 if (shdr_prog.sh_type != SHT_PROGBITS ||
448 !(shdr_prog.sh_flags & SHF_EXECINSTR))
449 continue;
450
451 insns = (struct bpf_insn *) data_prog->d_buf;
452
453 processed_sec[shdr.sh_info] = true;
454 processed_sec[i] = true;
455
456 if (parse_relo_and_apply(data, symbols, &shdr, insns))
457 continue;
458
459 if (memcmp(shname_prog, "kprobe/", 7) == 0 ||
460 memcmp(shname_prog, "kretprobe/", 10) == 0 ||
461 memcmp(shname_prog, "tracepoint/", 11) == 0 ||
462 memcmp(shname_prog, "xdp", 3) == 0 ||
463 memcmp(shname_prog, "perf_event", 10) == 0 ||
464 memcmp(shname_prog, "socket", 6) == 0 ||
465 memcmp(shname_prog, "cgroup/", 7) == 0)
466 load_and_attach(shname_prog, insns, data_prog->d_size);
467 }
468 }
469
470 /* load programs that don't use maps */
471 for (i = 1; i < ehdr.e_shnum; i++) {
472
473 if (processed_sec[i])
474 continue;
475
476 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
477 continue;
478
479 if (memcmp(shname, "kprobe/", 7) == 0 ||
480 memcmp(shname, "kretprobe/", 10) == 0 ||
481 memcmp(shname, "tracepoint/", 11) == 0 ||
482 memcmp(shname, "xdp", 3) == 0 ||
483 memcmp(shname, "perf_event", 10) == 0 ||
484 memcmp(shname, "socket", 6) == 0 ||
485 memcmp(shname, "cgroup/", 7) == 0)
486 load_and_attach(shname, data->d_buf, data->d_size);
487 }
488
489 ret = 0;
490 done:
491 for (i = 0; i < MAX_MAPS; i++)
492 free(map_names[i]);
493 close(fd);
494 return ret;
495 }
496
497 int load_bpf_file(char *path)
498 {
499 return do_load_bpf_file(path, NULL);
500 }
501
502 int load_bpf_file_fixup_map(const char *path, fixup_map_cb fixup_map)
503 {
504 return do_load_bpf_file(path, fixup_map);
505 }
506
507 void read_trace_pipe(void)
508 {
509 int trace_fd;
510
511 trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
512 if (trace_fd < 0)
513 return;
514
515 while (1) {
516 static char buf[4096];
517 ssize_t sz;
518
519 sz = read(trace_fd, buf, sizeof(buf));
520 if (sz > 0) {
521 buf[sz] = 0;
522 puts(buf);
523 }
524 }
525 }
526
527 #define MAX_SYMS 300000
528 static struct ksym syms[MAX_SYMS];
529 static int sym_cnt;
530
531 static int ksym_cmp(const void *p1, const void *p2)
532 {
533 return ((struct ksym *)p1)->addr - ((struct ksym *)p2)->addr;
534 }
535
536 int load_kallsyms(void)
537 {
538 FILE *f = fopen("/proc/kallsyms", "r");
539 char func[256], buf[256];
540 char symbol;
541 void *addr;
542 int i = 0;
543
544 if (!f)
545 return -ENOENT;
546
547 while (!feof(f)) {
548 if (!fgets(buf, sizeof(buf), f))
549 break;
550 if (sscanf(buf, "%p %c %s", &addr, &symbol, func) != 3)
551 break;
552 if (!addr)
553 continue;
554 syms[i].addr = (long) addr;
555 syms[i].name = strdup(func);
556 i++;
557 }
558 sym_cnt = i;
559 qsort(syms, sym_cnt, sizeof(struct ksym), ksym_cmp);
560 return 0;
561 }
562
563 struct ksym *ksym_search(long key)
564 {
565 int start = 0, end = sym_cnt;
566 int result;
567
568 while (start < end) {
569 size_t mid = start + (end - start) / 2;
570
571 result = key - syms[mid].addr;
572 if (result < 0)
573 end = mid;
574 else if (result > 0)
575 start = mid + 1;
576 else
577 return &syms[mid];
578 }
579
580 if (start >= 1 && syms[start - 1].addr < key &&
581 key < syms[start].addr)
582 /* valid ksym */
583 return &syms[start - 1];
584
585 /* out of range. return _stext */
586 return &syms[0];
587 }
588
589 int set_link_xdp_fd(int ifindex, int fd, __u32 flags)
590 {
591 struct sockaddr_nl sa;
592 int sock, seq = 0, len, ret = -1;
593 char buf[4096];
594 struct nlattr *nla, *nla_xdp;
595 struct {
596 struct nlmsghdr nh;
597 struct ifinfomsg ifinfo;
598 char attrbuf[64];
599 } req;
600 struct nlmsghdr *nh;
601 struct nlmsgerr *err;
602
603 memset(&sa, 0, sizeof(sa));
604 sa.nl_family = AF_NETLINK;
605
606 sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
607 if (sock < 0) {
608 printf("open netlink socket: %s\n", strerror(errno));
609 return -1;
610 }
611
612 if (bind(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
613 printf("bind to netlink: %s\n", strerror(errno));
614 goto cleanup;
615 }
616
617 memset(&req, 0, sizeof(req));
618 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
619 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
620 req.nh.nlmsg_type = RTM_SETLINK;
621 req.nh.nlmsg_pid = 0;
622 req.nh.nlmsg_seq = ++seq;
623 req.ifinfo.ifi_family = AF_UNSPEC;
624 req.ifinfo.ifi_index = ifindex;
625
626 /* started nested attribute for XDP */
627 nla = (struct nlattr *)(((char *)&req)
628 + NLMSG_ALIGN(req.nh.nlmsg_len));
629 nla->nla_type = NLA_F_NESTED | 43/*IFLA_XDP*/;
630 nla->nla_len = NLA_HDRLEN;
631
632 /* add XDP fd */
633 nla_xdp = (struct nlattr *)((char *)nla + nla->nla_len);
634 nla_xdp->nla_type = 1/*IFLA_XDP_FD*/;
635 nla_xdp->nla_len = NLA_HDRLEN + sizeof(int);
636 memcpy((char *)nla_xdp + NLA_HDRLEN, &fd, sizeof(fd));
637 nla->nla_len += nla_xdp->nla_len;
638
639 /* if user passed in any flags, add those too */
640 if (flags) {
641 nla_xdp = (struct nlattr *)((char *)nla + nla->nla_len);
642 nla_xdp->nla_type = 3/*IFLA_XDP_FLAGS*/;
643 nla_xdp->nla_len = NLA_HDRLEN + sizeof(flags);
644 memcpy((char *)nla_xdp + NLA_HDRLEN, &flags, sizeof(flags));
645 nla->nla_len += nla_xdp->nla_len;
646 }
647
648 req.nh.nlmsg_len += NLA_ALIGN(nla->nla_len);
649
650 if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) {
651 printf("send to netlink: %s\n", strerror(errno));
652 goto cleanup;
653 }
654
655 len = recv(sock, buf, sizeof(buf), 0);
656 if (len < 0) {
657 printf("recv from netlink: %s\n", strerror(errno));
658 goto cleanup;
659 }
660
661 for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len);
662 nh = NLMSG_NEXT(nh, len)) {
663 if (nh->nlmsg_pid != getpid()) {
664 printf("Wrong pid %d, expected %d\n",
665 nh->nlmsg_pid, getpid());
666 goto cleanup;
667 }
668 if (nh->nlmsg_seq != seq) {
669 printf("Wrong seq %d, expected %d\n",
670 nh->nlmsg_seq, seq);
671 goto cleanup;
672 }
673 switch (nh->nlmsg_type) {
674 case NLMSG_ERROR:
675 err = (struct nlmsgerr *)NLMSG_DATA(nh);
676 if (!err->error)
677 continue;
678 printf("nlmsg error %s\n", strerror(-err->error));
679 goto cleanup;
680 case NLMSG_DONE:
681 break;
682 }
683 }
684
685 ret = 0;
686
687 cleanup:
688 close(sock);
689 return ret;
690 }