GNU Linux-libre 4.19.264-gnu1
[releases.git] / samples / bpf / bpf_load.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <libelf.h>
7 #include <gelf.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include <string.h>
11 #include <stdbool.h>
12 #include <stdlib.h>
13 #include <linux/bpf.h>
14 #include <linux/filter.h>
15 #include <linux/perf_event.h>
16 #include <linux/netlink.h>
17 #include <linux/rtnetlink.h>
18 #include <linux/types.h>
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/syscall.h>
22 #include <sys/ioctl.h>
23 #include <sys/mman.h>
24 #include <poll.h>
25 #include <ctype.h>
26 #include <assert.h>
27 #include <bpf/bpf.h>
28 #include "bpf_load.h"
29 #include "perf-sys.h"
30
31 #define DEBUGFS "/sys/kernel/debug/tracing/"
32
33 static char license[128];
34 static int kern_version;
35 static bool processed_sec[128];
36 char bpf_log_buf[BPF_LOG_BUF_SIZE];
37 int map_fd[MAX_MAPS];
38 int prog_fd[MAX_PROGS];
39 int event_fd[MAX_PROGS];
40 int prog_cnt;
41 int prog_array_fd = -1;
42
43 struct bpf_map_data map_data[MAX_MAPS];
44 int map_data_count = 0;
45
46 static int populate_prog_array(const char *event, int prog_fd)
47 {
48         int ind = atoi(event), err;
49
50         err = bpf_map_update_elem(prog_array_fd, &ind, &prog_fd, BPF_ANY);
51         if (err < 0) {
52                 printf("failed to store prog_fd in prog_array\n");
53                 return -1;
54         }
55         return 0;
56 }
57
58 static int write_kprobe_events(const char *val)
59 {
60         int fd, ret, flags;
61
62         if (val == NULL)
63                 return -1;
64         else if (val[0] == '\0')
65                 flags = O_WRONLY | O_TRUNC;
66         else
67                 flags = O_WRONLY | O_APPEND;
68
69         fd = open("/sys/kernel/debug/tracing/kprobe_events", flags);
70
71         ret = write(fd, val, strlen(val));
72         close(fd);
73
74         return ret;
75 }
76
77 static int load_and_attach(const char *event, struct bpf_insn *prog, int size)
78 {
79         bool is_socket = strncmp(event, "socket", 6) == 0;
80         bool is_kprobe = strncmp(event, "kprobe/", 7) == 0;
81         bool is_kretprobe = strncmp(event, "kretprobe/", 10) == 0;
82         bool is_tracepoint = strncmp(event, "tracepoint/", 11) == 0;
83         bool is_raw_tracepoint = strncmp(event, "raw_tracepoint/", 15) == 0;
84         bool is_xdp = strncmp(event, "xdp", 3) == 0;
85         bool is_perf_event = strncmp(event, "perf_event", 10) == 0;
86         bool is_cgroup_skb = strncmp(event, "cgroup/skb", 10) == 0;
87         bool is_cgroup_sk = strncmp(event, "cgroup/sock", 11) == 0;
88         bool is_sockops = strncmp(event, "sockops", 7) == 0;
89         bool is_sk_skb = strncmp(event, "sk_skb", 6) == 0;
90         bool is_sk_msg = strncmp(event, "sk_msg", 6) == 0;
91         size_t insns_cnt = size / sizeof(struct bpf_insn);
92         enum bpf_prog_type prog_type;
93         char buf[256];
94         int fd, efd, err, id;
95         struct perf_event_attr attr = {};
96
97         attr.type = PERF_TYPE_TRACEPOINT;
98         attr.sample_type = PERF_SAMPLE_RAW;
99         attr.sample_period = 1;
100         attr.wakeup_events = 1;
101
102         if (is_socket) {
103                 prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
104         } else if (is_kprobe || is_kretprobe) {
105                 prog_type = BPF_PROG_TYPE_KPROBE;
106         } else if (is_tracepoint) {
107                 prog_type = BPF_PROG_TYPE_TRACEPOINT;
108         } else if (is_raw_tracepoint) {
109                 prog_type = BPF_PROG_TYPE_RAW_TRACEPOINT;
110         } else if (is_xdp) {
111                 prog_type = BPF_PROG_TYPE_XDP;
112         } else if (is_perf_event) {
113                 prog_type = BPF_PROG_TYPE_PERF_EVENT;
114         } else if (is_cgroup_skb) {
115                 prog_type = BPF_PROG_TYPE_CGROUP_SKB;
116         } else if (is_cgroup_sk) {
117                 prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
118         } else if (is_sockops) {
119                 prog_type = BPF_PROG_TYPE_SOCK_OPS;
120         } else if (is_sk_skb) {
121                 prog_type = BPF_PROG_TYPE_SK_SKB;
122         } else if (is_sk_msg) {
123                 prog_type = BPF_PROG_TYPE_SK_MSG;
124         } else {
125                 printf("Unknown event '%s'\n", event);
126                 return -1;
127         }
128
129         if (prog_cnt == MAX_PROGS)
130                 return -1;
131
132         fd = bpf_load_program(prog_type, prog, insns_cnt, license, kern_version,
133                               bpf_log_buf, BPF_LOG_BUF_SIZE);
134         if (fd < 0) {
135                 printf("bpf_load_program() err=%d\n%s", errno, bpf_log_buf);
136                 return -1;
137         }
138
139         prog_fd[prog_cnt++] = fd;
140
141         if (is_xdp || is_perf_event || is_cgroup_skb || is_cgroup_sk)
142                 return 0;
143
144         if (is_socket || is_sockops || is_sk_skb || is_sk_msg) {
145                 if (is_socket)
146                         event += 6;
147                 else
148                         event += 7;
149                 if (*event != '/')
150                         return 0;
151                 event++;
152                 if (!isdigit(*event)) {
153                         printf("invalid prog number\n");
154                         return -1;
155                 }
156                 return populate_prog_array(event, fd);
157         }
158
159         if (is_raw_tracepoint) {
160                 efd = bpf_raw_tracepoint_open(event + 15, fd);
161                 if (efd < 0) {
162                         printf("tracepoint %s %s\n", event + 15, strerror(errno));
163                         return -1;
164                 }
165                 event_fd[prog_cnt - 1] = efd;
166                 return 0;
167         }
168
169         if (is_kprobe || is_kretprobe) {
170                 bool need_normal_check = true;
171                 const char *event_prefix = "";
172
173                 if (is_kprobe)
174                         event += 7;
175                 else
176                         event += 10;
177
178                 if (*event == 0) {
179                         printf("event name cannot be empty\n");
180                         return -1;
181                 }
182
183                 if (isdigit(*event))
184                         return populate_prog_array(event, fd);
185
186 #ifdef __x86_64__
187                 if (strncmp(event, "sys_", 4) == 0) {
188                         snprintf(buf, sizeof(buf), "%c:__x64_%s __x64_%s",
189                                 is_kprobe ? 'p' : 'r', event, event);
190                         err = write_kprobe_events(buf);
191                         if (err >= 0) {
192                                 need_normal_check = false;
193                                 event_prefix = "__x64_";
194                         }
195                 }
196 #endif
197                 if (need_normal_check) {
198                         snprintf(buf, sizeof(buf), "%c:%s %s",
199                                 is_kprobe ? 'p' : 'r', event, event);
200                         err = write_kprobe_events(buf);
201                         if (err < 0) {
202                                 printf("failed to create kprobe '%s' error '%s'\n",
203                                        event, strerror(errno));
204                                 return -1;
205                         }
206                 }
207
208                 strcpy(buf, DEBUGFS);
209                 strcat(buf, "events/kprobes/");
210                 strcat(buf, event_prefix);
211                 strcat(buf, event);
212                 strcat(buf, "/id");
213         } else if (is_tracepoint) {
214                 event += 11;
215
216                 if (*event == 0) {
217                         printf("event name cannot be empty\n");
218                         return -1;
219                 }
220                 strcpy(buf, DEBUGFS);
221                 strcat(buf, "events/");
222                 strcat(buf, event);
223                 strcat(buf, "/id");
224         }
225
226         efd = open(buf, O_RDONLY, 0);
227         if (efd < 0) {
228                 printf("failed to open event %s\n", event);
229                 return -1;
230         }
231
232         err = read(efd, buf, sizeof(buf));
233         if (err < 0 || err >= sizeof(buf)) {
234                 printf("read from '%s' failed '%s'\n", event, strerror(errno));
235                 return -1;
236         }
237
238         close(efd);
239
240         buf[err] = 0;
241         id = atoi(buf);
242         attr.config = id;
243
244         efd = sys_perf_event_open(&attr, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
245         if (efd < 0) {
246                 printf("event %d fd %d err %s\n", id, efd, strerror(errno));
247                 return -1;
248         }
249         event_fd[prog_cnt - 1] = efd;
250         err = ioctl(efd, PERF_EVENT_IOC_ENABLE, 0);
251         if (err < 0) {
252                 printf("ioctl PERF_EVENT_IOC_ENABLE failed err %s\n",
253                        strerror(errno));
254                 return -1;
255         }
256         err = ioctl(efd, PERF_EVENT_IOC_SET_BPF, fd);
257         if (err < 0) {
258                 printf("ioctl PERF_EVENT_IOC_SET_BPF failed err %s\n",
259                        strerror(errno));
260                 return -1;
261         }
262
263         return 0;
264 }
265
266 static int load_maps(struct bpf_map_data *maps, int nr_maps,
267                      fixup_map_cb fixup_map)
268 {
269         int i, numa_node;
270
271         for (i = 0; i < nr_maps; i++) {
272                 if (fixup_map) {
273                         fixup_map(&maps[i], i);
274                         /* Allow userspace to assign map FD prior to creation */
275                         if (maps[i].fd != -1) {
276                                 map_fd[i] = maps[i].fd;
277                                 continue;
278                         }
279                 }
280
281                 numa_node = maps[i].def.map_flags & BPF_F_NUMA_NODE ?
282                         maps[i].def.numa_node : -1;
283
284                 if (maps[i].def.type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
285                     maps[i].def.type == BPF_MAP_TYPE_HASH_OF_MAPS) {
286                         int inner_map_fd = map_fd[maps[i].def.inner_map_idx];
287
288                         map_fd[i] = bpf_create_map_in_map_node(maps[i].def.type,
289                                                         maps[i].name,
290                                                         maps[i].def.key_size,
291                                                         inner_map_fd,
292                                                         maps[i].def.max_entries,
293                                                         maps[i].def.map_flags,
294                                                         numa_node);
295                 } else {
296                         map_fd[i] = bpf_create_map_node(maps[i].def.type,
297                                                         maps[i].name,
298                                                         maps[i].def.key_size,
299                                                         maps[i].def.value_size,
300                                                         maps[i].def.max_entries,
301                                                         maps[i].def.map_flags,
302                                                         numa_node);
303                 }
304                 if (map_fd[i] < 0) {
305                         printf("failed to create a map: %d %s\n",
306                                errno, strerror(errno));
307                         return 1;
308                 }
309                 maps[i].fd = map_fd[i];
310
311                 if (maps[i].def.type == BPF_MAP_TYPE_PROG_ARRAY)
312                         prog_array_fd = map_fd[i];
313         }
314         return 0;
315 }
316
317 static int get_sec(Elf *elf, int i, GElf_Ehdr *ehdr, char **shname,
318                    GElf_Shdr *shdr, Elf_Data **data)
319 {
320         Elf_Scn *scn;
321
322         scn = elf_getscn(elf, i);
323         if (!scn)
324                 return 1;
325
326         if (gelf_getshdr(scn, shdr) != shdr)
327                 return 2;
328
329         *shname = elf_strptr(elf, ehdr->e_shstrndx, shdr->sh_name);
330         if (!*shname || !shdr->sh_size)
331                 return 3;
332
333         *data = elf_getdata(scn, 0);
334         if (!*data || elf_getdata(scn, *data) != NULL)
335                 return 4;
336
337         return 0;
338 }
339
340 static int parse_relo_and_apply(Elf_Data *data, Elf_Data *symbols,
341                                 GElf_Shdr *shdr, struct bpf_insn *insn,
342                                 struct bpf_map_data *maps, int nr_maps)
343 {
344         int i, nrels;
345
346         nrels = shdr->sh_size / shdr->sh_entsize;
347
348         for (i = 0; i < nrels; i++) {
349                 GElf_Sym sym;
350                 GElf_Rel rel;
351                 unsigned int insn_idx;
352                 bool match = false;
353                 int j, map_idx;
354
355                 gelf_getrel(data, i, &rel);
356
357                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
358
359                 gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym);
360
361                 if (insn[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
362                         printf("invalid relo for insn[%d].code 0x%x\n",
363                                insn_idx, insn[insn_idx].code);
364                         return 1;
365                 }
366                 insn[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
367
368                 /* Match FD relocation against recorded map_data[] offset */
369                 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
370                         if (maps[map_idx].elf_offset == sym.st_value) {
371                                 match = true;
372                                 break;
373                         }
374                 }
375                 if (match) {
376                         insn[insn_idx].imm = maps[map_idx].fd;
377                 } else {
378                         printf("invalid relo for insn[%d] no map_data match\n",
379                                insn_idx);
380                         return 1;
381                 }
382         }
383
384         return 0;
385 }
386
387 static int cmp_symbols(const void *l, const void *r)
388 {
389         const GElf_Sym *lsym = (const GElf_Sym *)l;
390         const GElf_Sym *rsym = (const GElf_Sym *)r;
391
392         if (lsym->st_value < rsym->st_value)
393                 return -1;
394         else if (lsym->st_value > rsym->st_value)
395                 return 1;
396         else
397                 return 0;
398 }
399
400 static int load_elf_maps_section(struct bpf_map_data *maps, int maps_shndx,
401                                  Elf *elf, Elf_Data *symbols, int strtabidx)
402 {
403         int map_sz_elf, map_sz_copy;
404         bool validate_zero = false;
405         Elf_Data *data_maps;
406         int i, nr_maps;
407         GElf_Sym *sym;
408         Elf_Scn *scn;
409         int copy_sz;
410
411         if (maps_shndx < 0)
412                 return -EINVAL;
413         if (!symbols)
414                 return -EINVAL;
415
416         /* Get data for maps section via elf index */
417         scn = elf_getscn(elf, maps_shndx);
418         if (scn)
419                 data_maps = elf_getdata(scn, NULL);
420         if (!scn || !data_maps) {
421                 printf("Failed to get Elf_Data from maps section %d\n",
422                        maps_shndx);
423                 return -EINVAL;
424         }
425
426         /* For each map get corrosponding symbol table entry */
427         sym = calloc(MAX_MAPS+1, sizeof(GElf_Sym));
428         for (i = 0, nr_maps = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
429                 assert(nr_maps < MAX_MAPS+1);
430                 if (!gelf_getsym(symbols, i, &sym[nr_maps]))
431                         continue;
432                 if (sym[nr_maps].st_shndx != maps_shndx)
433                         continue;
434                 /* Only increment iif maps section */
435                 nr_maps++;
436         }
437
438         /* Align to map_fd[] order, via sort on offset in sym.st_value */
439         qsort(sym, nr_maps, sizeof(GElf_Sym), cmp_symbols);
440
441         /* Keeping compatible with ELF maps section changes
442          * ------------------------------------------------
443          * The program size of struct bpf_load_map_def is known by loader
444          * code, but struct stored in ELF file can be different.
445          *
446          * Unfortunately sym[i].st_size is zero.  To calculate the
447          * struct size stored in the ELF file, assume all struct have
448          * the same size, and simply divide with number of map
449          * symbols.
450          */
451         map_sz_elf = data_maps->d_size / nr_maps;
452         map_sz_copy = sizeof(struct bpf_load_map_def);
453         if (map_sz_elf < map_sz_copy) {
454                 /*
455                  * Backward compat, loading older ELF file with
456                  * smaller struct, keeping remaining bytes zero.
457                  */
458                 map_sz_copy = map_sz_elf;
459         } else if (map_sz_elf > map_sz_copy) {
460                 /*
461                  * Forward compat, loading newer ELF file with larger
462                  * struct with unknown features. Assume zero means
463                  * feature not used.  Thus, validate rest of struct
464                  * data is zero.
465                  */
466                 validate_zero = true;
467         }
468
469         /* Memcpy relevant part of ELF maps data to loader maps */
470         for (i = 0; i < nr_maps; i++) {
471                 struct bpf_load_map_def *def;
472                 unsigned char *addr, *end;
473                 const char *map_name;
474                 size_t offset;
475
476                 map_name = elf_strptr(elf, strtabidx, sym[i].st_name);
477                 maps[i].name = strdup(map_name);
478                 if (!maps[i].name) {
479                         printf("strdup(%s): %s(%d)\n", map_name,
480                                strerror(errno), errno);
481                         free(sym);
482                         return -errno;
483                 }
484
485                 /* Symbol value is offset into ELF maps section data area */
486                 offset = sym[i].st_value;
487                 def = (struct bpf_load_map_def *)(data_maps->d_buf + offset);
488                 maps[i].elf_offset = offset;
489                 memset(&maps[i].def, 0, sizeof(struct bpf_load_map_def));
490                 memcpy(&maps[i].def, def, map_sz_copy);
491
492                 /* Verify no newer features were requested */
493                 if (validate_zero) {
494                         addr = (unsigned char*) def + map_sz_copy;
495                         end  = (unsigned char*) def + map_sz_elf;
496                         for (; addr < end; addr++) {
497                                 if (*addr != 0) {
498                                         free(sym);
499                                         return -EFBIG;
500                                 }
501                         }
502                 }
503         }
504
505         free(sym);
506         return nr_maps;
507 }
508
509 static int do_load_bpf_file(const char *path, fixup_map_cb fixup_map)
510 {
511         int fd, i, ret, maps_shndx = -1, strtabidx = -1;
512         Elf *elf;
513         GElf_Ehdr ehdr;
514         GElf_Shdr shdr, shdr_prog;
515         Elf_Data *data, *data_prog, *data_maps = NULL, *symbols = NULL;
516         char *shname, *shname_prog;
517         int nr_maps = 0;
518
519         /* reset global variables */
520         kern_version = 0;
521         memset(license, 0, sizeof(license));
522         memset(processed_sec, 0, sizeof(processed_sec));
523
524         if (elf_version(EV_CURRENT) == EV_NONE)
525                 return 1;
526
527         fd = open(path, O_RDONLY, 0);
528         if (fd < 0)
529                 return 1;
530
531         elf = elf_begin(fd, ELF_C_READ, NULL);
532
533         if (!elf)
534                 return 1;
535
536         if (gelf_getehdr(elf, &ehdr) != &ehdr)
537                 return 1;
538
539         /* clear all kprobes */
540         i = write_kprobe_events("");
541
542         /* scan over all elf sections to get license and map info */
543         for (i = 1; i < ehdr.e_shnum; i++) {
544
545                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
546                         continue;
547
548                 if (0) /* helpful for llvm debugging */
549                         printf("section %d:%s data %p size %zd link %d flags %d\n",
550                                i, shname, data->d_buf, data->d_size,
551                                shdr.sh_link, (int) shdr.sh_flags);
552
553                 if (strcmp(shname, "license") == 0) {
554                         processed_sec[i] = true;
555                         memcpy(license, data->d_buf, data->d_size);
556                 } else if (strcmp(shname, "version") == 0) {
557                         processed_sec[i] = true;
558                         if (data->d_size != sizeof(int)) {
559                                 printf("invalid size of version section %zd\n",
560                                        data->d_size);
561                                 return 1;
562                         }
563                         memcpy(&kern_version, data->d_buf, sizeof(int));
564                 } else if (strcmp(shname, "maps") == 0) {
565                         int j;
566
567                         maps_shndx = i;
568                         data_maps = data;
569                         for (j = 0; j < MAX_MAPS; j++)
570                                 map_data[j].fd = -1;
571                 } else if (shdr.sh_type == SHT_SYMTAB) {
572                         strtabidx = shdr.sh_link;
573                         symbols = data;
574                 }
575         }
576
577         ret = 1;
578
579         if (!symbols) {
580                 printf("missing SHT_SYMTAB section\n");
581                 goto done;
582         }
583
584         if (data_maps) {
585                 nr_maps = load_elf_maps_section(map_data, maps_shndx,
586                                                 elf, symbols, strtabidx);
587                 if (nr_maps < 0) {
588                         printf("Error: Failed loading ELF maps (errno:%d):%s\n",
589                                nr_maps, strerror(-nr_maps));
590                         goto done;
591                 }
592                 if (load_maps(map_data, nr_maps, fixup_map))
593                         goto done;
594                 map_data_count = nr_maps;
595
596                 processed_sec[maps_shndx] = true;
597         }
598
599         /* process all relo sections, and rewrite bpf insns for maps */
600         for (i = 1; i < ehdr.e_shnum; i++) {
601                 if (processed_sec[i])
602                         continue;
603
604                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
605                         continue;
606
607                 if (shdr.sh_type == SHT_REL) {
608                         struct bpf_insn *insns;
609
610                         /* locate prog sec that need map fixup (relocations) */
611                         if (get_sec(elf, shdr.sh_info, &ehdr, &shname_prog,
612                                     &shdr_prog, &data_prog))
613                                 continue;
614
615                         if (shdr_prog.sh_type != SHT_PROGBITS ||
616                             !(shdr_prog.sh_flags & SHF_EXECINSTR))
617                                 continue;
618
619                         insns = (struct bpf_insn *) data_prog->d_buf;
620                         processed_sec[i] = true; /* relo section */
621
622                         if (parse_relo_and_apply(data, symbols, &shdr, insns,
623                                                  map_data, nr_maps))
624                                 continue;
625                 }
626         }
627
628         /* load programs */
629         for (i = 1; i < ehdr.e_shnum; i++) {
630
631                 if (processed_sec[i])
632                         continue;
633
634                 if (get_sec(elf, i, &ehdr, &shname, &shdr, &data))
635                         continue;
636
637                 if (memcmp(shname, "kprobe/", 7) == 0 ||
638                     memcmp(shname, "kretprobe/", 10) == 0 ||
639                     memcmp(shname, "tracepoint/", 11) == 0 ||
640                     memcmp(shname, "raw_tracepoint/", 15) == 0 ||
641                     memcmp(shname, "xdp", 3) == 0 ||
642                     memcmp(shname, "perf_event", 10) == 0 ||
643                     memcmp(shname, "socket", 6) == 0 ||
644                     memcmp(shname, "cgroup/", 7) == 0 ||
645                     memcmp(shname, "sockops", 7) == 0 ||
646                     memcmp(shname, "sk_skb", 6) == 0 ||
647                     memcmp(shname, "sk_msg", 6) == 0) {
648                         ret = load_and_attach(shname, data->d_buf,
649                                               data->d_size);
650                         if (ret != 0)
651                                 goto done;
652                 }
653         }
654
655 done:
656         close(fd);
657         return ret;
658 }
659
660 int load_bpf_file(char *path)
661 {
662         return do_load_bpf_file(path, NULL);
663 }
664
665 int load_bpf_file_fixup_map(const char *path, fixup_map_cb fixup_map)
666 {
667         return do_load_bpf_file(path, fixup_map);
668 }
669
670 void read_trace_pipe(void)
671 {
672         int trace_fd;
673
674         trace_fd = open(DEBUGFS "trace_pipe", O_RDONLY, 0);
675         if (trace_fd < 0)
676                 return;
677
678         while (1) {
679                 static char buf[4096];
680                 ssize_t sz;
681
682                 sz = read(trace_fd, buf, sizeof(buf) - 1);
683                 if (sz > 0) {
684                         buf[sz] = 0;
685                         puts(buf);
686                 }
687         }
688 }