]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/lib/bpf/libbpf.c
Merge tag 'sound-5.3-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/tiwai/sound
[linux.git] / tools / lib / bpf / libbpf.c
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <endian.h>
24 #include <fcntl.h>
25 #include <errno.h>
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <sys/epoll.h>
37 #include <sys/ioctl.h>
38 #include <sys/mman.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <sys/vfs.h>
42 #include <tools/libc_compat.h>
43 #include <libelf.h>
44 #include <gelf.h>
45
46 #include "libbpf.h"
47 #include "bpf.h"
48 #include "btf.h"
49 #include "str_error.h"
50 #include "libbpf_internal.h"
51
52 #ifndef EM_BPF
53 #define EM_BPF 247
54 #endif
55
56 #ifndef BPF_FS_MAGIC
57 #define BPF_FS_MAGIC            0xcafe4a11
58 #endif
59
60 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
61  * compilation if user enables corresponding warning. Disable it explicitly.
62  */
63 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
64
65 #define __printf(a, b)  __attribute__((format(printf, a, b)))
66
67 static int __base_pr(enum libbpf_print_level level, const char *format,
68                      va_list args)
69 {
70         if (level == LIBBPF_DEBUG)
71                 return 0;
72
73         return vfprintf(stderr, format, args);
74 }
75
76 static libbpf_print_fn_t __libbpf_pr = __base_pr;
77
78 void libbpf_set_print(libbpf_print_fn_t fn)
79 {
80         __libbpf_pr = fn;
81 }
82
83 __printf(2, 3)
84 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
85 {
86         va_list args;
87
88         if (!__libbpf_pr)
89                 return;
90
91         va_start(args, format);
92         __libbpf_pr(level, format, args);
93         va_end(args);
94 }
95
96 #define STRERR_BUFSIZE  128
97
98 #define CHECK_ERR(action, err, out) do {        \
99         err = action;                   \
100         if (err)                        \
101                 goto out;               \
102 } while(0)
103
104
105 /* Copied from tools/perf/util/util.h */
106 #ifndef zfree
107 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
108 #endif
109
110 #ifndef zclose
111 # define zclose(fd) ({                  \
112         int ___err = 0;                 \
113         if ((fd) >= 0)                  \
114                 ___err = close((fd));   \
115         fd = -1;                        \
116         ___err; })
117 #endif
118
119 #ifdef HAVE_LIBELF_MMAP_SUPPORT
120 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
121 #else
122 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
123 #endif
124
125 static inline __u64 ptr_to_u64(const void *ptr)
126 {
127         return (__u64) (unsigned long) ptr;
128 }
129
130 struct bpf_capabilities {
131         /* v4.14: kernel support for program & map names. */
132         __u32 name:1;
133         /* v5.2: kernel support for global data sections. */
134         __u32 global_data:1;
135         /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
136         __u32 btf_func:1;
137         /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
138         __u32 btf_datasec:1;
139 };
140
141 /*
142  * bpf_prog should be a better name but it has been used in
143  * linux/filter.h.
144  */
145 struct bpf_program {
146         /* Index in elf obj file, for relocation use. */
147         int idx;
148         char *name;
149         int prog_ifindex;
150         char *section_name;
151         /* section_name with / replaced by _; makes recursive pinning
152          * in bpf_object__pin_programs easier
153          */
154         char *pin_name;
155         struct bpf_insn *insns;
156         size_t insns_cnt, main_prog_cnt;
157         enum bpf_prog_type type;
158
159         struct reloc_desc {
160                 enum {
161                         RELO_LD64,
162                         RELO_CALL,
163                         RELO_DATA,
164                 } type;
165                 int insn_idx;
166                 union {
167                         int map_idx;
168                         int text_off;
169                 };
170         } *reloc_desc;
171         int nr_reloc;
172         int log_level;
173
174         struct {
175                 int nr;
176                 int *fds;
177         } instances;
178         bpf_program_prep_t preprocessor;
179
180         struct bpf_object *obj;
181         void *priv;
182         bpf_program_clear_priv_t clear_priv;
183
184         enum bpf_attach_type expected_attach_type;
185         int btf_fd;
186         void *func_info;
187         __u32 func_info_rec_size;
188         __u32 func_info_cnt;
189
190         struct bpf_capabilities *caps;
191
192         void *line_info;
193         __u32 line_info_rec_size;
194         __u32 line_info_cnt;
195         __u32 prog_flags;
196 };
197
198 enum libbpf_map_type {
199         LIBBPF_MAP_UNSPEC,
200         LIBBPF_MAP_DATA,
201         LIBBPF_MAP_BSS,
202         LIBBPF_MAP_RODATA,
203 };
204
205 static const char * const libbpf_type_to_btf_name[] = {
206         [LIBBPF_MAP_DATA]       = ".data",
207         [LIBBPF_MAP_BSS]        = ".bss",
208         [LIBBPF_MAP_RODATA]     = ".rodata",
209 };
210
211 struct bpf_map {
212         int fd;
213         char *name;
214         int sec_idx;
215         size_t sec_offset;
216         int map_ifindex;
217         int inner_map_fd;
218         struct bpf_map_def def;
219         __u32 btf_key_type_id;
220         __u32 btf_value_type_id;
221         void *priv;
222         bpf_map_clear_priv_t clear_priv;
223         enum libbpf_map_type libbpf_type;
224 };
225
226 struct bpf_secdata {
227         void *rodata;
228         void *data;
229 };
230
231 static LIST_HEAD(bpf_objects_list);
232
233 struct bpf_object {
234         char name[BPF_OBJ_NAME_LEN];
235         char license[64];
236         __u32 kern_version;
237
238         struct bpf_program *programs;
239         size_t nr_programs;
240         struct bpf_map *maps;
241         size_t nr_maps;
242         size_t maps_cap;
243         struct bpf_secdata sections;
244
245         bool loaded;
246         bool has_pseudo_calls;
247
248         /*
249          * Information when doing elf related work. Only valid if fd
250          * is valid.
251          */
252         struct {
253                 int fd;
254                 void *obj_buf;
255                 size_t obj_buf_sz;
256                 Elf *elf;
257                 GElf_Ehdr ehdr;
258                 Elf_Data *symbols;
259                 Elf_Data *data;
260                 Elf_Data *rodata;
261                 Elf_Data *bss;
262                 size_t strtabidx;
263                 struct {
264                         GElf_Shdr shdr;
265                         Elf_Data *data;
266                 } *reloc;
267                 int nr_reloc;
268                 int maps_shndx;
269                 int btf_maps_shndx;
270                 int text_shndx;
271                 int data_shndx;
272                 int rodata_shndx;
273                 int bss_shndx;
274         } efile;
275         /*
276          * All loaded bpf_object is linked in a list, which is
277          * hidden to caller. bpf_objects__<func> handlers deal with
278          * all objects.
279          */
280         struct list_head list;
281
282         struct btf *btf;
283         struct btf_ext *btf_ext;
284
285         void *priv;
286         bpf_object_clear_priv_t clear_priv;
287
288         struct bpf_capabilities caps;
289
290         char path[];
291 };
292 #define obj_elf_valid(o)        ((o)->efile.elf)
293
294 void bpf_program__unload(struct bpf_program *prog)
295 {
296         int i;
297
298         if (!prog)
299                 return;
300
301         /*
302          * If the object is opened but the program was never loaded,
303          * it is possible that prog->instances.nr == -1.
304          */
305         if (prog->instances.nr > 0) {
306                 for (i = 0; i < prog->instances.nr; i++)
307                         zclose(prog->instances.fds[i]);
308         } else if (prog->instances.nr != -1) {
309                 pr_warning("Internal error: instances.nr is %d\n",
310                            prog->instances.nr);
311         }
312
313         prog->instances.nr = -1;
314         zfree(&prog->instances.fds);
315
316         zclose(prog->btf_fd);
317         zfree(&prog->func_info);
318         zfree(&prog->line_info);
319 }
320
321 static void bpf_program__exit(struct bpf_program *prog)
322 {
323         if (!prog)
324                 return;
325
326         if (prog->clear_priv)
327                 prog->clear_priv(prog, prog->priv);
328
329         prog->priv = NULL;
330         prog->clear_priv = NULL;
331
332         bpf_program__unload(prog);
333         zfree(&prog->name);
334         zfree(&prog->section_name);
335         zfree(&prog->pin_name);
336         zfree(&prog->insns);
337         zfree(&prog->reloc_desc);
338
339         prog->nr_reloc = 0;
340         prog->insns_cnt = 0;
341         prog->idx = -1;
342 }
343
344 static char *__bpf_program__pin_name(struct bpf_program *prog)
345 {
346         char *name, *p;
347
348         name = p = strdup(prog->section_name);
349         while ((p = strchr(p, '/')))
350                 *p = '_';
351
352         return name;
353 }
354
355 static int
356 bpf_program__init(void *data, size_t size, char *section_name, int idx,
357                   struct bpf_program *prog)
358 {
359         const size_t bpf_insn_sz = sizeof(struct bpf_insn);
360
361         if (size == 0 || size % bpf_insn_sz) {
362                 pr_warning("corrupted section '%s', size: %zu\n",
363                            section_name, size);
364                 return -EINVAL;
365         }
366
367         memset(prog, 0, sizeof(*prog));
368
369         prog->section_name = strdup(section_name);
370         if (!prog->section_name) {
371                 pr_warning("failed to alloc name for prog under section(%d) %s\n",
372                            idx, section_name);
373                 goto errout;
374         }
375
376         prog->pin_name = __bpf_program__pin_name(prog);
377         if (!prog->pin_name) {
378                 pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
379                            idx, section_name);
380                 goto errout;
381         }
382
383         prog->insns = malloc(size);
384         if (!prog->insns) {
385                 pr_warning("failed to alloc insns for prog under section %s\n",
386                            section_name);
387                 goto errout;
388         }
389         prog->insns_cnt = size / bpf_insn_sz;
390         memcpy(prog->insns, data, size);
391         prog->idx = idx;
392         prog->instances.fds = NULL;
393         prog->instances.nr = -1;
394         prog->type = BPF_PROG_TYPE_UNSPEC;
395         prog->btf_fd = -1;
396
397         return 0;
398 errout:
399         bpf_program__exit(prog);
400         return -ENOMEM;
401 }
402
403 static int
404 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
405                         char *section_name, int idx)
406 {
407         struct bpf_program prog, *progs;
408         int nr_progs, err;
409
410         err = bpf_program__init(data, size, section_name, idx, &prog);
411         if (err)
412                 return err;
413
414         prog.caps = &obj->caps;
415         progs = obj->programs;
416         nr_progs = obj->nr_programs;
417
418         progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
419         if (!progs) {
420                 /*
421                  * In this case the original obj->programs
422                  * is still valid, so don't need special treat for
423                  * bpf_close_object().
424                  */
425                 pr_warning("failed to alloc a new program under section '%s'\n",
426                            section_name);
427                 bpf_program__exit(&prog);
428                 return -ENOMEM;
429         }
430
431         pr_debug("found program %s\n", prog.section_name);
432         obj->programs = progs;
433         obj->nr_programs = nr_progs + 1;
434         prog.obj = obj;
435         progs[nr_progs] = prog;
436         return 0;
437 }
438
439 static int
440 bpf_object__init_prog_names(struct bpf_object *obj)
441 {
442         Elf_Data *symbols = obj->efile.symbols;
443         struct bpf_program *prog;
444         size_t pi, si;
445
446         for (pi = 0; pi < obj->nr_programs; pi++) {
447                 const char *name = NULL;
448
449                 prog = &obj->programs[pi];
450
451                 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
452                      si++) {
453                         GElf_Sym sym;
454
455                         if (!gelf_getsym(symbols, si, &sym))
456                                 continue;
457                         if (sym.st_shndx != prog->idx)
458                                 continue;
459                         if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
460                                 continue;
461
462                         name = elf_strptr(obj->efile.elf,
463                                           obj->efile.strtabidx,
464                                           sym.st_name);
465                         if (!name) {
466                                 pr_warning("failed to get sym name string for prog %s\n",
467                                            prog->section_name);
468                                 return -LIBBPF_ERRNO__LIBELF;
469                         }
470                 }
471
472                 if (!name && prog->idx == obj->efile.text_shndx)
473                         name = ".text";
474
475                 if (!name) {
476                         pr_warning("failed to find sym for prog %s\n",
477                                    prog->section_name);
478                         return -EINVAL;
479                 }
480
481                 prog->name = strdup(name);
482                 if (!prog->name) {
483                         pr_warning("failed to allocate memory for prog sym %s\n",
484                                    name);
485                         return -ENOMEM;
486                 }
487         }
488
489         return 0;
490 }
491
492 static struct bpf_object *bpf_object__new(const char *path,
493                                           void *obj_buf,
494                                           size_t obj_buf_sz)
495 {
496         struct bpf_object *obj;
497         char *end;
498
499         obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
500         if (!obj) {
501                 pr_warning("alloc memory failed for %s\n", path);
502                 return ERR_PTR(-ENOMEM);
503         }
504
505         strcpy(obj->path, path);
506         /* Using basename() GNU version which doesn't modify arg. */
507         strncpy(obj->name, basename((void *)path), sizeof(obj->name) - 1);
508         end = strchr(obj->name, '.');
509         if (end)
510                 *end = 0;
511
512         obj->efile.fd = -1;
513         /*
514          * Caller of this function should also call
515          * bpf_object__elf_finish() after data collection to return
516          * obj_buf to user. If not, we should duplicate the buffer to
517          * avoid user freeing them before elf finish.
518          */
519         obj->efile.obj_buf = obj_buf;
520         obj->efile.obj_buf_sz = obj_buf_sz;
521         obj->efile.maps_shndx = -1;
522         obj->efile.btf_maps_shndx = -1;
523         obj->efile.data_shndx = -1;
524         obj->efile.rodata_shndx = -1;
525         obj->efile.bss_shndx = -1;
526
527         obj->loaded = false;
528
529         INIT_LIST_HEAD(&obj->list);
530         list_add(&obj->list, &bpf_objects_list);
531         return obj;
532 }
533
534 static void bpf_object__elf_finish(struct bpf_object *obj)
535 {
536         if (!obj_elf_valid(obj))
537                 return;
538
539         if (obj->efile.elf) {
540                 elf_end(obj->efile.elf);
541                 obj->efile.elf = NULL;
542         }
543         obj->efile.symbols = NULL;
544         obj->efile.data = NULL;
545         obj->efile.rodata = NULL;
546         obj->efile.bss = NULL;
547
548         zfree(&obj->efile.reloc);
549         obj->efile.nr_reloc = 0;
550         zclose(obj->efile.fd);
551         obj->efile.obj_buf = NULL;
552         obj->efile.obj_buf_sz = 0;
553 }
554
555 static int bpf_object__elf_init(struct bpf_object *obj)
556 {
557         int err = 0;
558         GElf_Ehdr *ep;
559
560         if (obj_elf_valid(obj)) {
561                 pr_warning("elf init: internal error\n");
562                 return -LIBBPF_ERRNO__LIBELF;
563         }
564
565         if (obj->efile.obj_buf_sz > 0) {
566                 /*
567                  * obj_buf should have been validated by
568                  * bpf_object__open_buffer().
569                  */
570                 obj->efile.elf = elf_memory(obj->efile.obj_buf,
571                                             obj->efile.obj_buf_sz);
572         } else {
573                 obj->efile.fd = open(obj->path, O_RDONLY);
574                 if (obj->efile.fd < 0) {
575                         char errmsg[STRERR_BUFSIZE], *cp;
576
577                         err = -errno;
578                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
579                         pr_warning("failed to open %s: %s\n", obj->path, cp);
580                         return err;
581                 }
582
583                 obj->efile.elf = elf_begin(obj->efile.fd,
584                                            LIBBPF_ELF_C_READ_MMAP, NULL);
585         }
586
587         if (!obj->efile.elf) {
588                 pr_warning("failed to open %s as ELF file\n", obj->path);
589                 err = -LIBBPF_ERRNO__LIBELF;
590                 goto errout;
591         }
592
593         if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
594                 pr_warning("failed to get EHDR from %s\n", obj->path);
595                 err = -LIBBPF_ERRNO__FORMAT;
596                 goto errout;
597         }
598         ep = &obj->efile.ehdr;
599
600         /* Old LLVM set e_machine to EM_NONE */
601         if (ep->e_type != ET_REL ||
602             (ep->e_machine && ep->e_machine != EM_BPF)) {
603                 pr_warning("%s is not an eBPF object file\n", obj->path);
604                 err = -LIBBPF_ERRNO__FORMAT;
605                 goto errout;
606         }
607
608         return 0;
609 errout:
610         bpf_object__elf_finish(obj);
611         return err;
612 }
613
614 static int bpf_object__check_endianness(struct bpf_object *obj)
615 {
616 #if __BYTE_ORDER == __LITTLE_ENDIAN
617         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
618                 return 0;
619 #elif __BYTE_ORDER == __BIG_ENDIAN
620         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
621                 return 0;
622 #else
623 # error "Unrecognized __BYTE_ORDER__"
624 #endif
625         pr_warning("endianness mismatch.\n");
626         return -LIBBPF_ERRNO__ENDIAN;
627 }
628
629 static int
630 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
631 {
632         memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
633         pr_debug("license of %s is %s\n", obj->path, obj->license);
634         return 0;
635 }
636
637 static int
638 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
639 {
640         __u32 kver;
641
642         if (size != sizeof(kver)) {
643                 pr_warning("invalid kver section in %s\n", obj->path);
644                 return -LIBBPF_ERRNO__FORMAT;
645         }
646         memcpy(&kver, data, sizeof(kver));
647         obj->kern_version = kver;
648         pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
649         return 0;
650 }
651
652 static int compare_bpf_map(const void *_a, const void *_b)
653 {
654         const struct bpf_map *a = _a;
655         const struct bpf_map *b = _b;
656
657         if (a->sec_idx != b->sec_idx)
658                 return a->sec_idx - b->sec_idx;
659         return a->sec_offset - b->sec_offset;
660 }
661
662 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
663 {
664         if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
665             type == BPF_MAP_TYPE_HASH_OF_MAPS)
666                 return true;
667         return false;
668 }
669
670 static int bpf_object_search_section_size(const struct bpf_object *obj,
671                                           const char *name, size_t *d_size)
672 {
673         const GElf_Ehdr *ep = &obj->efile.ehdr;
674         Elf *elf = obj->efile.elf;
675         Elf_Scn *scn = NULL;
676         int idx = 0;
677
678         while ((scn = elf_nextscn(elf, scn)) != NULL) {
679                 const char *sec_name;
680                 Elf_Data *data;
681                 GElf_Shdr sh;
682
683                 idx++;
684                 if (gelf_getshdr(scn, &sh) != &sh) {
685                         pr_warning("failed to get section(%d) header from %s\n",
686                                    idx, obj->path);
687                         return -EIO;
688                 }
689
690                 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
691                 if (!sec_name) {
692                         pr_warning("failed to get section(%d) name from %s\n",
693                                    idx, obj->path);
694                         return -EIO;
695                 }
696
697                 if (strcmp(name, sec_name))
698                         continue;
699
700                 data = elf_getdata(scn, 0);
701                 if (!data) {
702                         pr_warning("failed to get section(%d) data from %s(%s)\n",
703                                    idx, name, obj->path);
704                         return -EIO;
705                 }
706
707                 *d_size = data->d_size;
708                 return 0;
709         }
710
711         return -ENOENT;
712 }
713
714 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
715                              __u32 *size)
716 {
717         int ret = -ENOENT;
718         size_t d_size;
719
720         *size = 0;
721         if (!name) {
722                 return -EINVAL;
723         } else if (!strcmp(name, ".data")) {
724                 if (obj->efile.data)
725                         *size = obj->efile.data->d_size;
726         } else if (!strcmp(name, ".bss")) {
727                 if (obj->efile.bss)
728                         *size = obj->efile.bss->d_size;
729         } else if (!strcmp(name, ".rodata")) {
730                 if (obj->efile.rodata)
731                         *size = obj->efile.rodata->d_size;
732         } else {
733                 ret = bpf_object_search_section_size(obj, name, &d_size);
734                 if (!ret)
735                         *size = d_size;
736         }
737
738         return *size ? 0 : ret;
739 }
740
741 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
742                                 __u32 *off)
743 {
744         Elf_Data *symbols = obj->efile.symbols;
745         const char *sname;
746         size_t si;
747
748         if (!name || !off)
749                 return -EINVAL;
750
751         for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
752                 GElf_Sym sym;
753
754                 if (!gelf_getsym(symbols, si, &sym))
755                         continue;
756                 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
757                     GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
758                         continue;
759
760                 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
761                                    sym.st_name);
762                 if (!sname) {
763                         pr_warning("failed to get sym name string for var %s\n",
764                                    name);
765                         return -EIO;
766                 }
767                 if (strcmp(name, sname) == 0) {
768                         *off = sym.st_value;
769                         return 0;
770                 }
771         }
772
773         return -ENOENT;
774 }
775
776 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
777 {
778         struct bpf_map *new_maps;
779         size_t new_cap;
780         int i;
781
782         if (obj->nr_maps < obj->maps_cap)
783                 return &obj->maps[obj->nr_maps++];
784
785         new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
786         new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
787         if (!new_maps) {
788                 pr_warning("alloc maps for object failed\n");
789                 return ERR_PTR(-ENOMEM);
790         }
791
792         obj->maps_cap = new_cap;
793         obj->maps = new_maps;
794
795         /* zero out new maps */
796         memset(obj->maps + obj->nr_maps, 0,
797                (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
798         /*
799          * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
800          * when failure (zclose won't close negative fd)).
801          */
802         for (i = obj->nr_maps; i < obj->maps_cap; i++) {
803                 obj->maps[i].fd = -1;
804                 obj->maps[i].inner_map_fd = -1;
805         }
806
807         return &obj->maps[obj->nr_maps++];
808 }
809
810 static int
811 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
812                               int sec_idx, Elf_Data *data, void **data_buff)
813 {
814         char map_name[BPF_OBJ_NAME_LEN];
815         struct bpf_map_def *def;
816         struct bpf_map *map;
817
818         map = bpf_object__add_map(obj);
819         if (IS_ERR(map))
820                 return PTR_ERR(map);
821
822         map->libbpf_type = type;
823         map->sec_idx = sec_idx;
824         map->sec_offset = 0;
825         snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
826                  libbpf_type_to_btf_name[type]);
827         map->name = strdup(map_name);
828         if (!map->name) {
829                 pr_warning("failed to alloc map name\n");
830                 return -ENOMEM;
831         }
832         pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
833                  map_name, map->sec_idx, map->sec_offset);
834
835         def = &map->def;
836         def->type = BPF_MAP_TYPE_ARRAY;
837         def->key_size = sizeof(int);
838         def->value_size = data->d_size;
839         def->max_entries = 1;
840         def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
841         if (data_buff) {
842                 *data_buff = malloc(data->d_size);
843                 if (!*data_buff) {
844                         zfree(&map->name);
845                         pr_warning("failed to alloc map content buffer\n");
846                         return -ENOMEM;
847                 }
848                 memcpy(*data_buff, data->d_buf, data->d_size);
849         }
850
851         pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
852         return 0;
853 }
854
855 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
856 {
857         int err;
858
859         if (!obj->caps.global_data)
860                 return 0;
861         /*
862          * Populate obj->maps with libbpf internal maps.
863          */
864         if (obj->efile.data_shndx >= 0) {
865                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
866                                                     obj->efile.data_shndx,
867                                                     obj->efile.data,
868                                                     &obj->sections.data);
869                 if (err)
870                         return err;
871         }
872         if (obj->efile.rodata_shndx >= 0) {
873                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
874                                                     obj->efile.rodata_shndx,
875                                                     obj->efile.rodata,
876                                                     &obj->sections.rodata);
877                 if (err)
878                         return err;
879         }
880         if (obj->efile.bss_shndx >= 0) {
881                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
882                                                     obj->efile.bss_shndx,
883                                                     obj->efile.bss, NULL);
884                 if (err)
885                         return err;
886         }
887         return 0;
888 }
889
890 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
891 {
892         Elf_Data *symbols = obj->efile.symbols;
893         int i, map_def_sz = 0, nr_maps = 0, nr_syms;
894         Elf_Data *data = NULL;
895         Elf_Scn *scn;
896
897         if (obj->efile.maps_shndx < 0)
898                 return 0;
899
900         if (!symbols)
901                 return -EINVAL;
902
903         scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
904         if (scn)
905                 data = elf_getdata(scn, NULL);
906         if (!scn || !data) {
907                 pr_warning("failed to get Elf_Data from map section %d\n",
908                            obj->efile.maps_shndx);
909                 return -EINVAL;
910         }
911
912         /*
913          * Count number of maps. Each map has a name.
914          * Array of maps is not supported: only the first element is
915          * considered.
916          *
917          * TODO: Detect array of map and report error.
918          */
919         nr_syms = symbols->d_size / sizeof(GElf_Sym);
920         for (i = 0; i < nr_syms; i++) {
921                 GElf_Sym sym;
922
923                 if (!gelf_getsym(symbols, i, &sym))
924                         continue;
925                 if (sym.st_shndx != obj->efile.maps_shndx)
926                         continue;
927                 nr_maps++;
928         }
929         /* Assume equally sized map definitions */
930         pr_debug("maps in %s: %d maps in %zd bytes\n",
931                  obj->path, nr_maps, data->d_size);
932
933         map_def_sz = data->d_size / nr_maps;
934         if (!data->d_size || (data->d_size % nr_maps) != 0) {
935                 pr_warning("unable to determine map definition size "
936                            "section %s, %d maps in %zd bytes\n",
937                            obj->path, nr_maps, data->d_size);
938                 return -EINVAL;
939         }
940
941         /* Fill obj->maps using data in "maps" section.  */
942         for (i = 0; i < nr_syms; i++) {
943                 GElf_Sym sym;
944                 const char *map_name;
945                 struct bpf_map_def *def;
946                 struct bpf_map *map;
947
948                 if (!gelf_getsym(symbols, i, &sym))
949                         continue;
950                 if (sym.st_shndx != obj->efile.maps_shndx)
951                         continue;
952
953                 map = bpf_object__add_map(obj);
954                 if (IS_ERR(map))
955                         return PTR_ERR(map);
956
957                 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
958                                       sym.st_name);
959                 if (!map_name) {
960                         pr_warning("failed to get map #%d name sym string for obj %s\n",
961                                    i, obj->path);
962                         return -LIBBPF_ERRNO__FORMAT;
963                 }
964
965                 map->libbpf_type = LIBBPF_MAP_UNSPEC;
966                 map->sec_idx = sym.st_shndx;
967                 map->sec_offset = sym.st_value;
968                 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
969                          map_name, map->sec_idx, map->sec_offset);
970                 if (sym.st_value + map_def_sz > data->d_size) {
971                         pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
972                                    obj->path, map_name);
973                         return -EINVAL;
974                 }
975
976                 map->name = strdup(map_name);
977                 if (!map->name) {
978                         pr_warning("failed to alloc map name\n");
979                         return -ENOMEM;
980                 }
981                 pr_debug("map %d is \"%s\"\n", i, map->name);
982                 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
983                 /*
984                  * If the definition of the map in the object file fits in
985                  * bpf_map_def, copy it.  Any extra fields in our version
986                  * of bpf_map_def will default to zero as a result of the
987                  * calloc above.
988                  */
989                 if (map_def_sz <= sizeof(struct bpf_map_def)) {
990                         memcpy(&map->def, def, map_def_sz);
991                 } else {
992                         /*
993                          * Here the map structure being read is bigger than what
994                          * we expect, truncate if the excess bits are all zero.
995                          * If they are not zero, reject this map as
996                          * incompatible.
997                          */
998                         char *b;
999                         for (b = ((char *)def) + sizeof(struct bpf_map_def);
1000                              b < ((char *)def) + map_def_sz; b++) {
1001                                 if (*b != 0) {
1002                                         pr_warning("maps section in %s: \"%s\" "
1003                                                    "has unrecognized, non-zero "
1004                                                    "options\n",
1005                                                    obj->path, map_name);
1006                                         if (strict)
1007                                                 return -EINVAL;
1008                                 }
1009                         }
1010                         memcpy(&map->def, def, sizeof(struct bpf_map_def));
1011                 }
1012         }
1013         return 0;
1014 }
1015
1016 static const struct btf_type *skip_mods_and_typedefs(const struct btf *btf,
1017                                                      __u32 id)
1018 {
1019         const struct btf_type *t = btf__type_by_id(btf, id);
1020
1021         while (true) {
1022                 switch (BTF_INFO_KIND(t->info)) {
1023                 case BTF_KIND_VOLATILE:
1024                 case BTF_KIND_CONST:
1025                 case BTF_KIND_RESTRICT:
1026                 case BTF_KIND_TYPEDEF:
1027                         t = btf__type_by_id(btf, t->type);
1028                         break;
1029                 default:
1030                         return t;
1031                 }
1032         }
1033 }
1034
1035 /*
1036  * Fetch integer attribute of BTF map definition. Such attributes are
1037  * represented using a pointer to an array, in which dimensionality of array
1038  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1039  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1040  * type definition, while using only sizeof(void *) space in ELF data section.
1041  */
1042 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1043                               const struct btf_type *def,
1044                               const struct btf_member *m, __u32 *res) {
1045         const struct btf_type *t = skip_mods_and_typedefs(btf, m->type);
1046         const char *name = btf__name_by_offset(btf, m->name_off);
1047         const struct btf_array *arr_info;
1048         const struct btf_type *arr_t;
1049
1050         if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1051                 pr_warning("map '%s': attr '%s': expected PTR, got %u.\n",
1052                            map_name, name, BTF_INFO_KIND(t->info));
1053                 return false;
1054         }
1055
1056         arr_t = btf__type_by_id(btf, t->type);
1057         if (!arr_t) {
1058                 pr_warning("map '%s': attr '%s': type [%u] not found.\n",
1059                            map_name, name, t->type);
1060                 return false;
1061         }
1062         if (BTF_INFO_KIND(arr_t->info) != BTF_KIND_ARRAY) {
1063                 pr_warning("map '%s': attr '%s': expected ARRAY, got %u.\n",
1064                            map_name, name, BTF_INFO_KIND(arr_t->info));
1065                 return false;
1066         }
1067         arr_info = (const void *)(arr_t + 1);
1068         *res = arr_info->nelems;
1069         return true;
1070 }
1071
1072 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1073                                          const struct btf_type *sec,
1074                                          int var_idx, int sec_idx,
1075                                          const Elf_Data *data, bool strict)
1076 {
1077         const struct btf_type *var, *def, *t;
1078         const struct btf_var_secinfo *vi;
1079         const struct btf_var *var_extra;
1080         const struct btf_member *m;
1081         const char *map_name;
1082         struct bpf_map *map;
1083         int vlen, i;
1084
1085         vi = (const struct btf_var_secinfo *)(const void *)(sec + 1) + var_idx;
1086         var = btf__type_by_id(obj->btf, vi->type);
1087         var_extra = (const void *)(var + 1);
1088         map_name = btf__name_by_offset(obj->btf, var->name_off);
1089         vlen = BTF_INFO_VLEN(var->info);
1090
1091         if (map_name == NULL || map_name[0] == '\0') {
1092                 pr_warning("map #%d: empty name.\n", var_idx);
1093                 return -EINVAL;
1094         }
1095         if ((__u64)vi->offset + vi->size > data->d_size) {
1096                 pr_warning("map '%s' BTF data is corrupted.\n", map_name);
1097                 return -EINVAL;
1098         }
1099         if (BTF_INFO_KIND(var->info) != BTF_KIND_VAR) {
1100                 pr_warning("map '%s': unexpected var kind %u.\n",
1101                            map_name, BTF_INFO_KIND(var->info));
1102                 return -EINVAL;
1103         }
1104         if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1105             var_extra->linkage != BTF_VAR_STATIC) {
1106                 pr_warning("map '%s': unsupported var linkage %u.\n",
1107                            map_name, var_extra->linkage);
1108                 return -EOPNOTSUPP;
1109         }
1110
1111         def = skip_mods_and_typedefs(obj->btf, var->type);
1112         if (BTF_INFO_KIND(def->info) != BTF_KIND_STRUCT) {
1113                 pr_warning("map '%s': unexpected def kind %u.\n",
1114                            map_name, BTF_INFO_KIND(var->info));
1115                 return -EINVAL;
1116         }
1117         if (def->size > vi->size) {
1118                 pr_warning("map '%s': invalid def size.\n", map_name);
1119                 return -EINVAL;
1120         }
1121
1122         map = bpf_object__add_map(obj);
1123         if (IS_ERR(map))
1124                 return PTR_ERR(map);
1125         map->name = strdup(map_name);
1126         if (!map->name) {
1127                 pr_warning("map '%s': failed to alloc map name.\n", map_name);
1128                 return -ENOMEM;
1129         }
1130         map->libbpf_type = LIBBPF_MAP_UNSPEC;
1131         map->def.type = BPF_MAP_TYPE_UNSPEC;
1132         map->sec_idx = sec_idx;
1133         map->sec_offset = vi->offset;
1134         pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1135                  map_name, map->sec_idx, map->sec_offset);
1136
1137         vlen = BTF_INFO_VLEN(def->info);
1138         m = (const void *)(def + 1);
1139         for (i = 0; i < vlen; i++, m++) {
1140                 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1141
1142                 if (!name) {
1143                         pr_warning("map '%s': invalid field #%d.\n",
1144                                    map_name, i);
1145                         return -EINVAL;
1146                 }
1147                 if (strcmp(name, "type") == 0) {
1148                         if (!get_map_field_int(map_name, obj->btf, def, m,
1149                                                &map->def.type))
1150                                 return -EINVAL;
1151                         pr_debug("map '%s': found type = %u.\n",
1152                                  map_name, map->def.type);
1153                 } else if (strcmp(name, "max_entries") == 0) {
1154                         if (!get_map_field_int(map_name, obj->btf, def, m,
1155                                                &map->def.max_entries))
1156                                 return -EINVAL;
1157                         pr_debug("map '%s': found max_entries = %u.\n",
1158                                  map_name, map->def.max_entries);
1159                 } else if (strcmp(name, "map_flags") == 0) {
1160                         if (!get_map_field_int(map_name, obj->btf, def, m,
1161                                                &map->def.map_flags))
1162                                 return -EINVAL;
1163                         pr_debug("map '%s': found map_flags = %u.\n",
1164                                  map_name, map->def.map_flags);
1165                 } else if (strcmp(name, "key_size") == 0) {
1166                         __u32 sz;
1167
1168                         if (!get_map_field_int(map_name, obj->btf, def, m,
1169                                                &sz))
1170                                 return -EINVAL;
1171                         pr_debug("map '%s': found key_size = %u.\n",
1172                                  map_name, sz);
1173                         if (map->def.key_size && map->def.key_size != sz) {
1174                                 pr_warning("map '%s': conflicting key size %u != %u.\n",
1175                                            map_name, map->def.key_size, sz);
1176                                 return -EINVAL;
1177                         }
1178                         map->def.key_size = sz;
1179                 } else if (strcmp(name, "key") == 0) {
1180                         __s64 sz;
1181
1182                         t = btf__type_by_id(obj->btf, m->type);
1183                         if (!t) {
1184                                 pr_warning("map '%s': key type [%d] not found.\n",
1185                                            map_name, m->type);
1186                                 return -EINVAL;
1187                         }
1188                         if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1189                                 pr_warning("map '%s': key spec is not PTR: %u.\n",
1190                                            map_name, BTF_INFO_KIND(t->info));
1191                                 return -EINVAL;
1192                         }
1193                         sz = btf__resolve_size(obj->btf, t->type);
1194                         if (sz < 0) {
1195                                 pr_warning("map '%s': can't determine key size for type [%u]: %lld.\n",
1196                                            map_name, t->type, sz);
1197                                 return sz;
1198                         }
1199                         pr_debug("map '%s': found key [%u], sz = %lld.\n",
1200                                  map_name, t->type, sz);
1201                         if (map->def.key_size && map->def.key_size != sz) {
1202                                 pr_warning("map '%s': conflicting key size %u != %lld.\n",
1203                                            map_name, map->def.key_size, sz);
1204                                 return -EINVAL;
1205                         }
1206                         map->def.key_size = sz;
1207                         map->btf_key_type_id = t->type;
1208                 } else if (strcmp(name, "value_size") == 0) {
1209                         __u32 sz;
1210
1211                         if (!get_map_field_int(map_name, obj->btf, def, m,
1212                                                &sz))
1213                                 return -EINVAL;
1214                         pr_debug("map '%s': found value_size = %u.\n",
1215                                  map_name, sz);
1216                         if (map->def.value_size && map->def.value_size != sz) {
1217                                 pr_warning("map '%s': conflicting value size %u != %u.\n",
1218                                            map_name, map->def.value_size, sz);
1219                                 return -EINVAL;
1220                         }
1221                         map->def.value_size = sz;
1222                 } else if (strcmp(name, "value") == 0) {
1223                         __s64 sz;
1224
1225                         t = btf__type_by_id(obj->btf, m->type);
1226                         if (!t) {
1227                                 pr_warning("map '%s': value type [%d] not found.\n",
1228                                            map_name, m->type);
1229                                 return -EINVAL;
1230                         }
1231                         if (BTF_INFO_KIND(t->info) != BTF_KIND_PTR) {
1232                                 pr_warning("map '%s': value spec is not PTR: %u.\n",
1233                                            map_name, BTF_INFO_KIND(t->info));
1234                                 return -EINVAL;
1235                         }
1236                         sz = btf__resolve_size(obj->btf, t->type);
1237                         if (sz < 0) {
1238                                 pr_warning("map '%s': can't determine value size for type [%u]: %lld.\n",
1239                                            map_name, t->type, sz);
1240                                 return sz;
1241                         }
1242                         pr_debug("map '%s': found value [%u], sz = %lld.\n",
1243                                  map_name, t->type, sz);
1244                         if (map->def.value_size && map->def.value_size != sz) {
1245                                 pr_warning("map '%s': conflicting value size %u != %lld.\n",
1246                                            map_name, map->def.value_size, sz);
1247                                 return -EINVAL;
1248                         }
1249                         map->def.value_size = sz;
1250                         map->btf_value_type_id = t->type;
1251                 } else {
1252                         if (strict) {
1253                                 pr_warning("map '%s': unknown field '%s'.\n",
1254                                            map_name, name);
1255                                 return -ENOTSUP;
1256                         }
1257                         pr_debug("map '%s': ignoring unknown field '%s'.\n",
1258                                  map_name, name);
1259                 }
1260         }
1261
1262         if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1263                 pr_warning("map '%s': map type isn't specified.\n", map_name);
1264                 return -EINVAL;
1265         }
1266
1267         return 0;
1268 }
1269
1270 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict)
1271 {
1272         const struct btf_type *sec = NULL;
1273         int nr_types, i, vlen, err;
1274         const struct btf_type *t;
1275         const char *name;
1276         Elf_Data *data;
1277         Elf_Scn *scn;
1278
1279         if (obj->efile.btf_maps_shndx < 0)
1280                 return 0;
1281
1282         scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1283         if (scn)
1284                 data = elf_getdata(scn, NULL);
1285         if (!scn || !data) {
1286                 pr_warning("failed to get Elf_Data from map section %d (%s)\n",
1287                            obj->efile.maps_shndx, MAPS_ELF_SEC);
1288                 return -EINVAL;
1289         }
1290
1291         nr_types = btf__get_nr_types(obj->btf);
1292         for (i = 1; i <= nr_types; i++) {
1293                 t = btf__type_by_id(obj->btf, i);
1294                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
1295                         continue;
1296                 name = btf__name_by_offset(obj->btf, t->name_off);
1297                 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1298                         sec = t;
1299                         break;
1300                 }
1301         }
1302
1303         if (!sec) {
1304                 pr_warning("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1305                 return -ENOENT;
1306         }
1307
1308         vlen = BTF_INFO_VLEN(sec->info);
1309         for (i = 0; i < vlen; i++) {
1310                 err = bpf_object__init_user_btf_map(obj, sec, i,
1311                                                     obj->efile.btf_maps_shndx,
1312                                                     data, strict);
1313                 if (err)
1314                         return err;
1315         }
1316
1317         return 0;
1318 }
1319
1320 static int bpf_object__init_maps(struct bpf_object *obj, int flags)
1321 {
1322         bool strict = !(flags & MAPS_RELAX_COMPAT);
1323         int err;
1324
1325         err = bpf_object__init_user_maps(obj, strict);
1326         if (err)
1327                 return err;
1328
1329         err = bpf_object__init_user_btf_maps(obj, strict);
1330         if (err)
1331                 return err;
1332
1333         err = bpf_object__init_global_data_maps(obj);
1334         if (err)
1335                 return err;
1336
1337         if (obj->nr_maps) {
1338                 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1339                       compare_bpf_map);
1340         }
1341         return 0;
1342 }
1343
1344 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1345 {
1346         Elf_Scn *scn;
1347         GElf_Shdr sh;
1348
1349         scn = elf_getscn(obj->efile.elf, idx);
1350         if (!scn)
1351                 return false;
1352
1353         if (gelf_getshdr(scn, &sh) != &sh)
1354                 return false;
1355
1356         if (sh.sh_flags & SHF_EXECINSTR)
1357                 return true;
1358
1359         return false;
1360 }
1361
1362 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1363 {
1364         bool has_datasec = obj->caps.btf_datasec;
1365         bool has_func = obj->caps.btf_func;
1366         struct btf *btf = obj->btf;
1367         struct btf_type *t;
1368         int i, j, vlen;
1369         __u16 kind;
1370
1371         if (!obj->btf || (has_func && has_datasec))
1372                 return;
1373
1374         for (i = 1; i <= btf__get_nr_types(btf); i++) {
1375                 t = (struct btf_type *)btf__type_by_id(btf, i);
1376                 kind = BTF_INFO_KIND(t->info);
1377
1378                 if (!has_datasec && kind == BTF_KIND_VAR) {
1379                         /* replace VAR with INT */
1380                         t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1381                         /*
1382                          * using size = 1 is the safest choice, 4 will be too
1383                          * big and cause kernel BTF validation failure if
1384                          * original variable took less than 4 bytes
1385                          */
1386                         t->size = 1;
1387                         *(int *)(t+1) = BTF_INT_ENC(0, 0, 8);
1388                 } else if (!has_datasec && kind == BTF_KIND_DATASEC) {
1389                         /* replace DATASEC with STRUCT */
1390                         struct btf_var_secinfo *v = (void *)(t + 1);
1391                         struct btf_member *m = (void *)(t + 1);
1392                         struct btf_type *vt;
1393                         char *name;
1394
1395                         name = (char *)btf__name_by_offset(btf, t->name_off);
1396                         while (*name) {
1397                                 if (*name == '.')
1398                                         *name = '_';
1399                                 name++;
1400                         }
1401
1402                         vlen = BTF_INFO_VLEN(t->info);
1403                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1404                         for (j = 0; j < vlen; j++, v++, m++) {
1405                                 /* order of field assignments is important */
1406                                 m->offset = v->offset * 8;
1407                                 m->type = v->type;
1408                                 /* preserve variable name as member name */
1409                                 vt = (void *)btf__type_by_id(btf, v->type);
1410                                 m->name_off = vt->name_off;
1411                         }
1412                 } else if (!has_func && kind == BTF_KIND_FUNC_PROTO) {
1413                         /* replace FUNC_PROTO with ENUM */
1414                         vlen = BTF_INFO_VLEN(t->info);
1415                         t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1416                         t->size = sizeof(__u32); /* kernel enforced */
1417                 } else if (!has_func && kind == BTF_KIND_FUNC) {
1418                         /* replace FUNC with TYPEDEF */
1419                         t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1420                 }
1421         }
1422 }
1423
1424 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1425 {
1426         if (!obj->btf_ext)
1427                 return;
1428
1429         if (!obj->caps.btf_func) {
1430                 btf_ext__free(obj->btf_ext);
1431                 obj->btf_ext = NULL;
1432         }
1433 }
1434
1435 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1436 {
1437         return obj->efile.btf_maps_shndx >= 0;
1438 }
1439
1440 static int bpf_object__init_btf(struct bpf_object *obj,
1441                                 Elf_Data *btf_data,
1442                                 Elf_Data *btf_ext_data)
1443 {
1444         bool btf_required = bpf_object__is_btf_mandatory(obj);
1445         int err = 0;
1446
1447         if (btf_data) {
1448                 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1449                 if (IS_ERR(obj->btf)) {
1450                         pr_warning("Error loading ELF section %s: %d.\n",
1451                                    BTF_ELF_SEC, err);
1452                         goto out;
1453                 }
1454                 err = btf__finalize_data(obj, obj->btf);
1455                 if (err) {
1456                         pr_warning("Error finalizing %s: %d.\n",
1457                                    BTF_ELF_SEC, err);
1458                         goto out;
1459                 }
1460         }
1461         if (btf_ext_data) {
1462                 if (!obj->btf) {
1463                         pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1464                                  BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1465                         goto out;
1466                 }
1467                 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1468                                             btf_ext_data->d_size);
1469                 if (IS_ERR(obj->btf_ext)) {
1470                         pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1471                                    BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1472                         obj->btf_ext = NULL;
1473                         goto out;
1474                 }
1475         }
1476 out:
1477         if (err || IS_ERR(obj->btf)) {
1478                 if (btf_required)
1479                         err = err ? : PTR_ERR(obj->btf);
1480                 else
1481                         err = 0;
1482                 if (!IS_ERR_OR_NULL(obj->btf))
1483                         btf__free(obj->btf);
1484                 obj->btf = NULL;
1485         }
1486         if (btf_required && !obj->btf) {
1487                 pr_warning("BTF is required, but is missing or corrupted.\n");
1488                 return err == 0 ? -ENOENT : err;
1489         }
1490         return 0;
1491 }
1492
1493 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1494 {
1495         int err = 0;
1496
1497         if (!obj->btf)
1498                 return 0;
1499
1500         bpf_object__sanitize_btf(obj);
1501         bpf_object__sanitize_btf_ext(obj);
1502
1503         err = btf__load(obj->btf);
1504         if (err) {
1505                 pr_warning("Error loading %s into kernel: %d.\n",
1506                            BTF_ELF_SEC, err);
1507                 btf__free(obj->btf);
1508                 obj->btf = NULL;
1509                 /* btf_ext can't exist without btf, so free it as well */
1510                 if (obj->btf_ext) {
1511                         btf_ext__free(obj->btf_ext);
1512                         obj->btf_ext = NULL;
1513                 }
1514
1515                 if (bpf_object__is_btf_mandatory(obj))
1516                         return err;
1517         }
1518         return 0;
1519 }
1520
1521 static int bpf_object__elf_collect(struct bpf_object *obj, int flags)
1522 {
1523         Elf *elf = obj->efile.elf;
1524         GElf_Ehdr *ep = &obj->efile.ehdr;
1525         Elf_Data *btf_ext_data = NULL;
1526         Elf_Data *btf_data = NULL;
1527         Elf_Scn *scn = NULL;
1528         int idx = 0, err = 0;
1529
1530         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1531         if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1532                 pr_warning("failed to get e_shstrndx from %s\n", obj->path);
1533                 return -LIBBPF_ERRNO__FORMAT;
1534         }
1535
1536         while ((scn = elf_nextscn(elf, scn)) != NULL) {
1537                 char *name;
1538                 GElf_Shdr sh;
1539                 Elf_Data *data;
1540
1541                 idx++;
1542                 if (gelf_getshdr(scn, &sh) != &sh) {
1543                         pr_warning("failed to get section(%d) header from %s\n",
1544                                    idx, obj->path);
1545                         return -LIBBPF_ERRNO__FORMAT;
1546                 }
1547
1548                 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1549                 if (!name) {
1550                         pr_warning("failed to get section(%d) name from %s\n",
1551                                    idx, obj->path);
1552                         return -LIBBPF_ERRNO__FORMAT;
1553                 }
1554
1555                 data = elf_getdata(scn, 0);
1556                 if (!data) {
1557                         pr_warning("failed to get section(%d) data from %s(%s)\n",
1558                                    idx, name, obj->path);
1559                         return -LIBBPF_ERRNO__FORMAT;
1560                 }
1561                 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1562                          idx, name, (unsigned long)data->d_size,
1563                          (int)sh.sh_link, (unsigned long)sh.sh_flags,
1564                          (int)sh.sh_type);
1565
1566                 if (strcmp(name, "license") == 0) {
1567                         err = bpf_object__init_license(obj,
1568                                                        data->d_buf,
1569                                                        data->d_size);
1570                         if (err)
1571                                 return err;
1572                 } else if (strcmp(name, "version") == 0) {
1573                         err = bpf_object__init_kversion(obj,
1574                                                         data->d_buf,
1575                                                         data->d_size);
1576                         if (err)
1577                                 return err;
1578                 } else if (strcmp(name, "maps") == 0) {
1579                         obj->efile.maps_shndx = idx;
1580                 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1581                         obj->efile.btf_maps_shndx = idx;
1582                 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1583                         btf_data = data;
1584                 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1585                         btf_ext_data = data;
1586                 } else if (sh.sh_type == SHT_SYMTAB) {
1587                         if (obj->efile.symbols) {
1588                                 pr_warning("bpf: multiple SYMTAB in %s\n",
1589                                            obj->path);
1590                                 return -LIBBPF_ERRNO__FORMAT;
1591                         }
1592                         obj->efile.symbols = data;
1593                         obj->efile.strtabidx = sh.sh_link;
1594                 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1595                         if (sh.sh_flags & SHF_EXECINSTR) {
1596                                 if (strcmp(name, ".text") == 0)
1597                                         obj->efile.text_shndx = idx;
1598                                 err = bpf_object__add_program(obj, data->d_buf,
1599                                                               data->d_size, name, idx);
1600                                 if (err) {
1601                                         char errmsg[STRERR_BUFSIZE];
1602                                         char *cp = libbpf_strerror_r(-err, errmsg,
1603                                                                      sizeof(errmsg));
1604
1605                                         pr_warning("failed to alloc program %s (%s): %s",
1606                                                    name, obj->path, cp);
1607                                         return err;
1608                                 }
1609                         } else if (strcmp(name, ".data") == 0) {
1610                                 obj->efile.data = data;
1611                                 obj->efile.data_shndx = idx;
1612                         } else if (strcmp(name, ".rodata") == 0) {
1613                                 obj->efile.rodata = data;
1614                                 obj->efile.rodata_shndx = idx;
1615                         } else {
1616                                 pr_debug("skip section(%d) %s\n", idx, name);
1617                         }
1618                 } else if (sh.sh_type == SHT_REL) {
1619                         int nr_reloc = obj->efile.nr_reloc;
1620                         void *reloc = obj->efile.reloc;
1621                         int sec = sh.sh_info; /* points to other section */
1622
1623                         /* Only do relo for section with exec instructions */
1624                         if (!section_have_execinstr(obj, sec)) {
1625                                 pr_debug("skip relo %s(%d) for section(%d)\n",
1626                                          name, idx, sec);
1627                                 continue;
1628                         }
1629
1630                         reloc = reallocarray(reloc, nr_reloc + 1,
1631                                              sizeof(*obj->efile.reloc));
1632                         if (!reloc) {
1633                                 pr_warning("realloc failed\n");
1634                                 return -ENOMEM;
1635                         }
1636
1637                         obj->efile.reloc = reloc;
1638                         obj->efile.nr_reloc++;
1639
1640                         obj->efile.reloc[nr_reloc].shdr = sh;
1641                         obj->efile.reloc[nr_reloc].data = data;
1642                 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1643                         obj->efile.bss = data;
1644                         obj->efile.bss_shndx = idx;
1645                 } else {
1646                         pr_debug("skip section(%d) %s\n", idx, name);
1647                 }
1648         }
1649
1650         if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1651                 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1652                 return -LIBBPF_ERRNO__FORMAT;
1653         }
1654         err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1655         if (!err)
1656                 err = bpf_object__init_maps(obj, flags);
1657         if (!err)
1658                 err = bpf_object__sanitize_and_load_btf(obj);
1659         if (!err)
1660                 err = bpf_object__init_prog_names(obj);
1661         return err;
1662 }
1663
1664 static struct bpf_program *
1665 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1666 {
1667         struct bpf_program *prog;
1668         size_t i;
1669
1670         for (i = 0; i < obj->nr_programs; i++) {
1671                 prog = &obj->programs[i];
1672                 if (prog->idx == idx)
1673                         return prog;
1674         }
1675         return NULL;
1676 }
1677
1678 struct bpf_program *
1679 bpf_object__find_program_by_title(const struct bpf_object *obj,
1680                                   const char *title)
1681 {
1682         struct bpf_program *pos;
1683
1684         bpf_object__for_each_program(pos, obj) {
1685                 if (pos->section_name && !strcmp(pos->section_name, title))
1686                         return pos;
1687         }
1688         return NULL;
1689 }
1690
1691 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1692                                       int shndx)
1693 {
1694         return shndx == obj->efile.data_shndx ||
1695                shndx == obj->efile.bss_shndx ||
1696                shndx == obj->efile.rodata_shndx;
1697 }
1698
1699 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1700                                       int shndx)
1701 {
1702         return shndx == obj->efile.maps_shndx ||
1703                shndx == obj->efile.btf_maps_shndx;
1704 }
1705
1706 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1707                                               int shndx)
1708 {
1709         return shndx == obj->efile.text_shndx ||
1710                bpf_object__shndx_is_maps(obj, shndx) ||
1711                bpf_object__shndx_is_data(obj, shndx);
1712 }
1713
1714 static enum libbpf_map_type
1715 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1716 {
1717         if (shndx == obj->efile.data_shndx)
1718                 return LIBBPF_MAP_DATA;
1719         else if (shndx == obj->efile.bss_shndx)
1720                 return LIBBPF_MAP_BSS;
1721         else if (shndx == obj->efile.rodata_shndx)
1722                 return LIBBPF_MAP_RODATA;
1723         else
1724                 return LIBBPF_MAP_UNSPEC;
1725 }
1726
1727 static int
1728 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1729                            Elf_Data *data, struct bpf_object *obj)
1730 {
1731         Elf_Data *symbols = obj->efile.symbols;
1732         struct bpf_map *maps = obj->maps;
1733         size_t nr_maps = obj->nr_maps;
1734         int i, nrels;
1735
1736         pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1737         nrels = shdr->sh_size / shdr->sh_entsize;
1738
1739         prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1740         if (!prog->reloc_desc) {
1741                 pr_warning("failed to alloc memory in relocation\n");
1742                 return -ENOMEM;
1743         }
1744         prog->nr_reloc = nrels;
1745
1746         for (i = 0; i < nrels; i++) {
1747                 struct bpf_insn *insns = prog->insns;
1748                 enum libbpf_map_type type;
1749                 unsigned int insn_idx;
1750                 unsigned int shdr_idx;
1751                 const char *name;
1752                 size_t map_idx;
1753                 GElf_Sym sym;
1754                 GElf_Rel rel;
1755
1756                 if (!gelf_getrel(data, i, &rel)) {
1757                         pr_warning("relocation: failed to get %d reloc\n", i);
1758                         return -LIBBPF_ERRNO__FORMAT;
1759                 }
1760
1761                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1762                         pr_warning("relocation: symbol %"PRIx64" not found\n",
1763                                    GELF_R_SYM(rel.r_info));
1764                         return -LIBBPF_ERRNO__FORMAT;
1765                 }
1766
1767                 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1768                                   sym.st_name) ? : "<?>";
1769
1770                 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1771                          (long long) (rel.r_info >> 32),
1772                          (long long) sym.st_value, sym.st_name, name);
1773
1774                 shdr_idx = sym.st_shndx;
1775                 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1776                         pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1777                                    prog->section_name, shdr_idx);
1778                         return -LIBBPF_ERRNO__RELOC;
1779                 }
1780
1781                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1782                 pr_debug("relocation: insn_idx=%u\n", insn_idx);
1783
1784                 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1785                         if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1786                                 pr_warning("incorrect bpf_call opcode\n");
1787                                 return -LIBBPF_ERRNO__RELOC;
1788                         }
1789                         prog->reloc_desc[i].type = RELO_CALL;
1790                         prog->reloc_desc[i].insn_idx = insn_idx;
1791                         prog->reloc_desc[i].text_off = sym.st_value;
1792                         obj->has_pseudo_calls = true;
1793                         continue;
1794                 }
1795
1796                 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1797                         pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1798                                    insn_idx, insns[insn_idx].code);
1799                         return -LIBBPF_ERRNO__RELOC;
1800                 }
1801
1802                 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1803                     bpf_object__shndx_is_data(obj, shdr_idx)) {
1804                         type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1805                         if (type != LIBBPF_MAP_UNSPEC) {
1806                                 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1807                                         pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1808                                                    name, insn_idx, insns[insn_idx].code);
1809                                         return -LIBBPF_ERRNO__RELOC;
1810                                 }
1811                                 if (!obj->caps.global_data) {
1812                                         pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1813                                                    name, insn_idx);
1814                                         return -LIBBPF_ERRNO__RELOC;
1815                                 }
1816                         }
1817
1818                         for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1819                                 if (maps[map_idx].libbpf_type != type)
1820                                         continue;
1821                                 if (type != LIBBPF_MAP_UNSPEC ||
1822                                     (maps[map_idx].sec_idx == sym.st_shndx &&
1823                                      maps[map_idx].sec_offset == sym.st_value)) {
1824                                         pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1825                                                  map_idx, maps[map_idx].name,
1826                                                  maps[map_idx].sec_idx,
1827                                                  maps[map_idx].sec_offset,
1828                                                  insn_idx);
1829                                         break;
1830                                 }
1831                         }
1832
1833                         if (map_idx >= nr_maps) {
1834                                 pr_warning("bpf relocation: map_idx %d larger than %d\n",
1835                                            (int)map_idx, (int)nr_maps - 1);
1836                                 return -LIBBPF_ERRNO__RELOC;
1837                         }
1838
1839                         prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1840                                                    RELO_DATA : RELO_LD64;
1841                         prog->reloc_desc[i].insn_idx = insn_idx;
1842                         prog->reloc_desc[i].map_idx = map_idx;
1843                 }
1844         }
1845         return 0;
1846 }
1847
1848 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1849 {
1850         struct bpf_map_def *def = &map->def;
1851         __u32 key_type_id = 0, value_type_id = 0;
1852         int ret;
1853
1854         /* if it's BTF-defined map, we don't need to search for type IDs */
1855         if (map->sec_idx == obj->efile.btf_maps_shndx)
1856                 return 0;
1857
1858         if (!bpf_map__is_internal(map)) {
1859                 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1860                                            def->value_size, &key_type_id,
1861                                            &value_type_id);
1862         } else {
1863                 /*
1864                  * LLVM annotates global data differently in BTF, that is,
1865                  * only as '.data', '.bss' or '.rodata'.
1866                  */
1867                 ret = btf__find_by_name(obj->btf,
1868                                 libbpf_type_to_btf_name[map->libbpf_type]);
1869         }
1870         if (ret < 0)
1871                 return ret;
1872
1873         map->btf_key_type_id = key_type_id;
1874         map->btf_value_type_id = bpf_map__is_internal(map) ?
1875                                  ret : value_type_id;
1876         return 0;
1877 }
1878
1879 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1880 {
1881         struct bpf_map_info info = {};
1882         __u32 len = sizeof(info);
1883         int new_fd, err;
1884         char *new_name;
1885
1886         err = bpf_obj_get_info_by_fd(fd, &info, &len);
1887         if (err)
1888                 return err;
1889
1890         new_name = strdup(info.name);
1891         if (!new_name)
1892                 return -errno;
1893
1894         new_fd = open("/", O_RDONLY | O_CLOEXEC);
1895         if (new_fd < 0)
1896                 goto err_free_new_name;
1897
1898         new_fd = dup3(fd, new_fd, O_CLOEXEC);
1899         if (new_fd < 0)
1900                 goto err_close_new_fd;
1901
1902         err = zclose(map->fd);
1903         if (err)
1904                 goto err_close_new_fd;
1905         free(map->name);
1906
1907         map->fd = new_fd;
1908         map->name = new_name;
1909         map->def.type = info.type;
1910         map->def.key_size = info.key_size;
1911         map->def.value_size = info.value_size;
1912         map->def.max_entries = info.max_entries;
1913         map->def.map_flags = info.map_flags;
1914         map->btf_key_type_id = info.btf_key_type_id;
1915         map->btf_value_type_id = info.btf_value_type_id;
1916
1917         return 0;
1918
1919 err_close_new_fd:
1920         close(new_fd);
1921 err_free_new_name:
1922         free(new_name);
1923         return -errno;
1924 }
1925
1926 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1927 {
1928         if (!map || !max_entries)
1929                 return -EINVAL;
1930
1931         /* If map already created, its attributes can't be changed. */
1932         if (map->fd >= 0)
1933                 return -EBUSY;
1934
1935         map->def.max_entries = max_entries;
1936
1937         return 0;
1938 }
1939
1940 static int
1941 bpf_object__probe_name(struct bpf_object *obj)
1942 {
1943         struct bpf_load_program_attr attr;
1944         char *cp, errmsg[STRERR_BUFSIZE];
1945         struct bpf_insn insns[] = {
1946                 BPF_MOV64_IMM(BPF_REG_0, 0),
1947                 BPF_EXIT_INSN(),
1948         };
1949         int ret;
1950
1951         /* make sure basic loading works */
1952
1953         memset(&attr, 0, sizeof(attr));
1954         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1955         attr.insns = insns;
1956         attr.insns_cnt = ARRAY_SIZE(insns);
1957         attr.license = "GPL";
1958
1959         ret = bpf_load_program_xattr(&attr, NULL, 0);
1960         if (ret < 0) {
1961                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1962                 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1963                            __func__, cp, errno);
1964                 return -errno;
1965         }
1966         close(ret);
1967
1968         /* now try the same program, but with the name */
1969
1970         attr.name = "test";
1971         ret = bpf_load_program_xattr(&attr, NULL, 0);
1972         if (ret >= 0) {
1973                 obj->caps.name = 1;
1974                 close(ret);
1975         }
1976
1977         return 0;
1978 }
1979
1980 static int
1981 bpf_object__probe_global_data(struct bpf_object *obj)
1982 {
1983         struct bpf_load_program_attr prg_attr;
1984         struct bpf_create_map_attr map_attr;
1985         char *cp, errmsg[STRERR_BUFSIZE];
1986         struct bpf_insn insns[] = {
1987                 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1988                 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1989                 BPF_MOV64_IMM(BPF_REG_0, 0),
1990                 BPF_EXIT_INSN(),
1991         };
1992         int ret, map;
1993
1994         memset(&map_attr, 0, sizeof(map_attr));
1995         map_attr.map_type = BPF_MAP_TYPE_ARRAY;
1996         map_attr.key_size = sizeof(int);
1997         map_attr.value_size = 32;
1998         map_attr.max_entries = 1;
1999
2000         map = bpf_create_map_xattr(&map_attr);
2001         if (map < 0) {
2002                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2003                 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
2004                            __func__, cp, errno);
2005                 return -errno;
2006         }
2007
2008         insns[0].imm = map;
2009
2010         memset(&prg_attr, 0, sizeof(prg_attr));
2011         prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2012         prg_attr.insns = insns;
2013         prg_attr.insns_cnt = ARRAY_SIZE(insns);
2014         prg_attr.license = "GPL";
2015
2016         ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2017         if (ret >= 0) {
2018                 obj->caps.global_data = 1;
2019                 close(ret);
2020         }
2021
2022         close(map);
2023         return 0;
2024 }
2025
2026 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2027 {
2028         const char strs[] = "\0int\0x\0a";
2029         /* void x(int a) {} */
2030         __u32 types[] = {
2031                 /* int */
2032                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2033                 /* FUNC_PROTO */                                /* [2] */
2034                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2035                 BTF_PARAM_ENC(7, 1),
2036                 /* FUNC x */                                    /* [3] */
2037                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2038         };
2039         int btf_fd;
2040
2041         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2042                                       strs, sizeof(strs));
2043         if (btf_fd >= 0) {
2044                 obj->caps.btf_func = 1;
2045                 close(btf_fd);
2046                 return 1;
2047         }
2048
2049         return 0;
2050 }
2051
2052 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2053 {
2054         const char strs[] = "\0x\0.data";
2055         /* static int a; */
2056         __u32 types[] = {
2057                 /* int */
2058                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2059                 /* VAR x */                                     /* [2] */
2060                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2061                 BTF_VAR_STATIC,
2062                 /* DATASEC val */                               /* [3] */
2063                 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2064                 BTF_VAR_SECINFO_ENC(2, 0, 4),
2065         };
2066         int btf_fd;
2067
2068         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2069                                       strs, sizeof(strs));
2070         if (btf_fd >= 0) {
2071                 obj->caps.btf_datasec = 1;
2072                 close(btf_fd);
2073                 return 1;
2074         }
2075
2076         return 0;
2077 }
2078
2079 static int
2080 bpf_object__probe_caps(struct bpf_object *obj)
2081 {
2082         int (*probe_fn[])(struct bpf_object *obj) = {
2083                 bpf_object__probe_name,
2084                 bpf_object__probe_global_data,
2085                 bpf_object__probe_btf_func,
2086                 bpf_object__probe_btf_datasec,
2087         };
2088         int i, ret;
2089
2090         for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2091                 ret = probe_fn[i](obj);
2092                 if (ret < 0)
2093                         pr_debug("Probe #%d failed with %d.\n", i, ret);
2094         }
2095
2096         return 0;
2097 }
2098
2099 static int
2100 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2101 {
2102         char *cp, errmsg[STRERR_BUFSIZE];
2103         int err, zero = 0;
2104         __u8 *data;
2105
2106         /* Nothing to do here since kernel already zero-initializes .bss map. */
2107         if (map->libbpf_type == LIBBPF_MAP_BSS)
2108                 return 0;
2109
2110         data = map->libbpf_type == LIBBPF_MAP_DATA ?
2111                obj->sections.data : obj->sections.rodata;
2112
2113         err = bpf_map_update_elem(map->fd, &zero, data, 0);
2114         /* Freeze .rodata map as read-only from syscall side. */
2115         if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2116                 err = bpf_map_freeze(map->fd);
2117                 if (err) {
2118                         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2119                         pr_warning("Error freezing map(%s) as read-only: %s\n",
2120                                    map->name, cp);
2121                         err = 0;
2122                 }
2123         }
2124         return err;
2125 }
2126
2127 static int
2128 bpf_object__create_maps(struct bpf_object *obj)
2129 {
2130         struct bpf_create_map_attr create_attr = {};
2131         int nr_cpus = 0;
2132         unsigned int i;
2133         int err;
2134
2135         for (i = 0; i < obj->nr_maps; i++) {
2136                 struct bpf_map *map = &obj->maps[i];
2137                 struct bpf_map_def *def = &map->def;
2138                 char *cp, errmsg[STRERR_BUFSIZE];
2139                 int *pfd = &map->fd;
2140
2141                 if (map->fd >= 0) {
2142                         pr_debug("skip map create (preset) %s: fd=%d\n",
2143                                  map->name, map->fd);
2144                         continue;
2145                 }
2146
2147                 if (obj->caps.name)
2148                         create_attr.name = map->name;
2149                 create_attr.map_ifindex = map->map_ifindex;
2150                 create_attr.map_type = def->type;
2151                 create_attr.map_flags = def->map_flags;
2152                 create_attr.key_size = def->key_size;
2153                 create_attr.value_size = def->value_size;
2154                 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2155                     !def->max_entries) {
2156                         if (!nr_cpus)
2157                                 nr_cpus = libbpf_num_possible_cpus();
2158                         if (nr_cpus < 0) {
2159                                 pr_warning("failed to determine number of system CPUs: %d\n",
2160                                            nr_cpus);
2161                                 err = nr_cpus;
2162                                 goto err_out;
2163                         }
2164                         pr_debug("map '%s': setting size to %d\n",
2165                                  map->name, nr_cpus);
2166                         create_attr.max_entries = nr_cpus;
2167                 } else {
2168                         create_attr.max_entries = def->max_entries;
2169                 }
2170                 create_attr.btf_fd = 0;
2171                 create_attr.btf_key_type_id = 0;
2172                 create_attr.btf_value_type_id = 0;
2173                 if (bpf_map_type__is_map_in_map(def->type) &&
2174                     map->inner_map_fd >= 0)
2175                         create_attr.inner_map_fd = map->inner_map_fd;
2176
2177                 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2178                         create_attr.btf_fd = btf__fd(obj->btf);
2179                         create_attr.btf_key_type_id = map->btf_key_type_id;
2180                         create_attr.btf_value_type_id = map->btf_value_type_id;
2181                 }
2182
2183                 *pfd = bpf_create_map_xattr(&create_attr);
2184                 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2185                                  create_attr.btf_value_type_id)) {
2186                         err = -errno;
2187                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2188                         pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2189                                    map->name, cp, err);
2190                         create_attr.btf_fd = 0;
2191                         create_attr.btf_key_type_id = 0;
2192                         create_attr.btf_value_type_id = 0;
2193                         map->btf_key_type_id = 0;
2194                         map->btf_value_type_id = 0;
2195                         *pfd = bpf_create_map_xattr(&create_attr);
2196                 }
2197
2198                 if (*pfd < 0) {
2199                         size_t j;
2200
2201                         err = -errno;
2202 err_out:
2203                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2204                         pr_warning("failed to create map (name: '%s'): %s(%d)\n",
2205                                    map->name, cp, err);
2206                         for (j = 0; j < i; j++)
2207                                 zclose(obj->maps[j].fd);
2208                         return err;
2209                 }
2210
2211                 if (bpf_map__is_internal(map)) {
2212                         err = bpf_object__populate_internal_map(obj, map);
2213                         if (err < 0) {
2214                                 zclose(*pfd);
2215                                 goto err_out;
2216                         }
2217                 }
2218
2219                 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2220         }
2221
2222         return 0;
2223 }
2224
2225 static int
2226 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2227                         void *btf_prog_info, const char *info_name)
2228 {
2229         if (err != -ENOENT) {
2230                 pr_warning("Error in loading %s for sec %s.\n",
2231                            info_name, prog->section_name);
2232                 return err;
2233         }
2234
2235         /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2236
2237         if (btf_prog_info) {
2238                 /*
2239                  * Some info has already been found but has problem
2240                  * in the last btf_ext reloc. Must have to error out.
2241                  */
2242                 pr_warning("Error in relocating %s for sec %s.\n",
2243                            info_name, prog->section_name);
2244                 return err;
2245         }
2246
2247         /* Have problem loading the very first info. Ignore the rest. */
2248         pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
2249                    info_name, prog->section_name, info_name);
2250         return 0;
2251 }
2252
2253 static int
2254 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2255                           const char *section_name,  __u32 insn_offset)
2256 {
2257         int err;
2258
2259         if (!insn_offset || prog->func_info) {
2260                 /*
2261                  * !insn_offset => main program
2262                  *
2263                  * For sub prog, the main program's func_info has to
2264                  * be loaded first (i.e. prog->func_info != NULL)
2265                  */
2266                 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2267                                                section_name, insn_offset,
2268                                                &prog->func_info,
2269                                                &prog->func_info_cnt);
2270                 if (err)
2271                         return check_btf_ext_reloc_err(prog, err,
2272                                                        prog->func_info,
2273                                                        "bpf_func_info");
2274
2275                 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2276         }
2277
2278         if (!insn_offset || prog->line_info) {
2279                 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2280                                                section_name, insn_offset,
2281                                                &prog->line_info,
2282                                                &prog->line_info_cnt);
2283                 if (err)
2284                         return check_btf_ext_reloc_err(prog, err,
2285                                                        prog->line_info,
2286                                                        "bpf_line_info");
2287
2288                 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2289         }
2290
2291         if (!insn_offset)
2292                 prog->btf_fd = btf__fd(obj->btf);
2293
2294         return 0;
2295 }
2296
2297 static int
2298 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
2299                         struct reloc_desc *relo)
2300 {
2301         struct bpf_insn *insn, *new_insn;
2302         struct bpf_program *text;
2303         size_t new_cnt;
2304         int err;
2305
2306         if (relo->type != RELO_CALL)
2307                 return -LIBBPF_ERRNO__RELOC;
2308
2309         if (prog->idx == obj->efile.text_shndx) {
2310                 pr_warning("relo in .text insn %d into off %d\n",
2311                            relo->insn_idx, relo->text_off);
2312                 return -LIBBPF_ERRNO__RELOC;
2313         }
2314
2315         if (prog->main_prog_cnt == 0) {
2316                 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
2317                 if (!text) {
2318                         pr_warning("no .text section found yet relo into text exist\n");
2319                         return -LIBBPF_ERRNO__RELOC;
2320                 }
2321                 new_cnt = prog->insns_cnt + text->insns_cnt;
2322                 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
2323                 if (!new_insn) {
2324                         pr_warning("oom in prog realloc\n");
2325                         return -ENOMEM;
2326                 }
2327
2328                 if (obj->btf_ext) {
2329                         err = bpf_program_reloc_btf_ext(prog, obj,
2330                                                         text->section_name,
2331                                                         prog->insns_cnt);
2332                         if (err)
2333                                 return err;
2334                 }
2335
2336                 memcpy(new_insn + prog->insns_cnt, text->insns,
2337                        text->insns_cnt * sizeof(*insn));
2338                 prog->insns = new_insn;
2339                 prog->main_prog_cnt = prog->insns_cnt;
2340                 prog->insns_cnt = new_cnt;
2341                 pr_debug("added %zd insn from %s to prog %s\n",
2342                          text->insns_cnt, text->section_name,
2343                          prog->section_name);
2344         }
2345         insn = &prog->insns[relo->insn_idx];
2346         insn->imm += prog->main_prog_cnt - relo->insn_idx;
2347         return 0;
2348 }
2349
2350 static int
2351 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
2352 {
2353         int i, err;
2354
2355         if (!prog)
2356                 return 0;
2357
2358         if (obj->btf_ext) {
2359                 err = bpf_program_reloc_btf_ext(prog, obj,
2360                                                 prog->section_name, 0);
2361                 if (err)
2362                         return err;
2363         }
2364
2365         if (!prog->reloc_desc)
2366                 return 0;
2367
2368         for (i = 0; i < prog->nr_reloc; i++) {
2369                 if (prog->reloc_desc[i].type == RELO_LD64 ||
2370                     prog->reloc_desc[i].type == RELO_DATA) {
2371                         bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
2372                         struct bpf_insn *insns = prog->insns;
2373                         int insn_idx, map_idx;
2374
2375                         insn_idx = prog->reloc_desc[i].insn_idx;
2376                         map_idx = prog->reloc_desc[i].map_idx;
2377
2378                         if (insn_idx + 1 >= (int)prog->insns_cnt) {
2379                                 pr_warning("relocation out of range: '%s'\n",
2380                                            prog->section_name);
2381                                 return -LIBBPF_ERRNO__RELOC;
2382                         }
2383
2384                         if (!relo_data) {
2385                                 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
2386                         } else {
2387                                 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
2388                                 insns[insn_idx + 1].imm = insns[insn_idx].imm;
2389                         }
2390                         insns[insn_idx].imm = obj->maps[map_idx].fd;
2391                 } else if (prog->reloc_desc[i].type == RELO_CALL) {
2392                         err = bpf_program__reloc_text(prog, obj,
2393                                                       &prog->reloc_desc[i]);
2394                         if (err)
2395                                 return err;
2396                 }
2397         }
2398
2399         zfree(&prog->reloc_desc);
2400         prog->nr_reloc = 0;
2401         return 0;
2402 }
2403
2404
2405 static int
2406 bpf_object__relocate(struct bpf_object *obj)
2407 {
2408         struct bpf_program *prog;
2409         size_t i;
2410         int err;
2411
2412         for (i = 0; i < obj->nr_programs; i++) {
2413                 prog = &obj->programs[i];
2414
2415                 err = bpf_program__relocate(prog, obj);
2416                 if (err) {
2417                         pr_warning("failed to relocate '%s'\n",
2418                                    prog->section_name);
2419                         return err;
2420                 }
2421         }
2422         return 0;
2423 }
2424
2425 static int bpf_object__collect_reloc(struct bpf_object *obj)
2426 {
2427         int i, err;
2428
2429         if (!obj_elf_valid(obj)) {
2430                 pr_warning("Internal error: elf object is closed\n");
2431                 return -LIBBPF_ERRNO__INTERNAL;
2432         }
2433
2434         for (i = 0; i < obj->efile.nr_reloc; i++) {
2435                 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
2436                 Elf_Data *data = obj->efile.reloc[i].data;
2437                 int idx = shdr->sh_info;
2438                 struct bpf_program *prog;
2439
2440                 if (shdr->sh_type != SHT_REL) {
2441                         pr_warning("internal error at %d\n", __LINE__);
2442                         return -LIBBPF_ERRNO__INTERNAL;
2443                 }
2444
2445                 prog = bpf_object__find_prog_by_idx(obj, idx);
2446                 if (!prog) {
2447                         pr_warning("relocation failed: no section(%d)\n", idx);
2448                         return -LIBBPF_ERRNO__RELOC;
2449                 }
2450
2451                 err = bpf_program__collect_reloc(prog, shdr, data, obj);
2452                 if (err)
2453                         return err;
2454         }
2455         return 0;
2456 }
2457
2458 static int
2459 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
2460              char *license, __u32 kern_version, int *pfd)
2461 {
2462         struct bpf_load_program_attr load_attr;
2463         char *cp, errmsg[STRERR_BUFSIZE];
2464         int log_buf_size = BPF_LOG_BUF_SIZE;
2465         char *log_buf;
2466         int ret;
2467
2468         if (!insns || !insns_cnt)
2469                 return -EINVAL;
2470
2471         memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
2472         load_attr.prog_type = prog->type;
2473         load_attr.expected_attach_type = prog->expected_attach_type;
2474         if (prog->caps->name)
2475                 load_attr.name = prog->name;
2476         load_attr.insns = insns;
2477         load_attr.insns_cnt = insns_cnt;
2478         load_attr.license = license;
2479         load_attr.kern_version = kern_version;
2480         load_attr.prog_ifindex = prog->prog_ifindex;
2481         load_attr.prog_btf_fd = prog->btf_fd >= 0 ? prog->btf_fd : 0;
2482         load_attr.func_info = prog->func_info;
2483         load_attr.func_info_rec_size = prog->func_info_rec_size;
2484         load_attr.func_info_cnt = prog->func_info_cnt;
2485         load_attr.line_info = prog->line_info;
2486         load_attr.line_info_rec_size = prog->line_info_rec_size;
2487         load_attr.line_info_cnt = prog->line_info_cnt;
2488         load_attr.log_level = prog->log_level;
2489         load_attr.prog_flags = prog->prog_flags;
2490
2491 retry_load:
2492         log_buf = malloc(log_buf_size);
2493         if (!log_buf)
2494                 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
2495
2496         ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
2497
2498         if (ret >= 0) {
2499                 if (load_attr.log_level)
2500                         pr_debug("verifier log:\n%s", log_buf);
2501                 *pfd = ret;
2502                 ret = 0;
2503                 goto out;
2504         }
2505
2506         if (errno == ENOSPC) {
2507                 log_buf_size <<= 1;
2508                 free(log_buf);
2509                 goto retry_load;
2510         }
2511         ret = -LIBBPF_ERRNO__LOAD;
2512         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2513         pr_warning("load bpf program failed: %s\n", cp);
2514
2515         if (log_buf && log_buf[0] != '\0') {
2516                 ret = -LIBBPF_ERRNO__VERIFY;
2517                 pr_warning("-- BEGIN DUMP LOG ---\n");
2518                 pr_warning("\n%s\n", log_buf);
2519                 pr_warning("-- END LOG --\n");
2520         } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
2521                 pr_warning("Program too large (%zu insns), at most %d insns\n",
2522                            load_attr.insns_cnt, BPF_MAXINSNS);
2523                 ret = -LIBBPF_ERRNO__PROG2BIG;
2524         } else {
2525                 /* Wrong program type? */
2526                 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
2527                         int fd;
2528
2529                         load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
2530                         load_attr.expected_attach_type = 0;
2531                         fd = bpf_load_program_xattr(&load_attr, NULL, 0);
2532                         if (fd >= 0) {
2533                                 close(fd);
2534                                 ret = -LIBBPF_ERRNO__PROGTYPE;
2535                                 goto out;
2536                         }
2537                 }
2538
2539                 if (log_buf)
2540                         ret = -LIBBPF_ERRNO__KVER;
2541         }
2542
2543 out:
2544         free(log_buf);
2545         return ret;
2546 }
2547
2548 int
2549 bpf_program__load(struct bpf_program *prog,
2550                   char *license, __u32 kern_version)
2551 {
2552         int err = 0, fd, i;
2553
2554         if (prog->instances.nr < 0 || !prog->instances.fds) {
2555                 if (prog->preprocessor) {
2556                         pr_warning("Internal error: can't load program '%s'\n",
2557                                    prog->section_name);
2558                         return -LIBBPF_ERRNO__INTERNAL;
2559                 }
2560
2561                 prog->instances.fds = malloc(sizeof(int));
2562                 if (!prog->instances.fds) {
2563                         pr_warning("Not enough memory for BPF fds\n");
2564                         return -ENOMEM;
2565                 }
2566                 prog->instances.nr = 1;
2567                 prog->instances.fds[0] = -1;
2568         }
2569
2570         if (!prog->preprocessor) {
2571                 if (prog->instances.nr != 1) {
2572                         pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
2573                                    prog->section_name, prog->instances.nr);
2574                 }
2575                 err = load_program(prog, prog->insns, prog->insns_cnt,
2576                                    license, kern_version, &fd);
2577                 if (!err)
2578                         prog->instances.fds[0] = fd;
2579                 goto out;
2580         }
2581
2582         for (i = 0; i < prog->instances.nr; i++) {
2583                 struct bpf_prog_prep_result result;
2584                 bpf_program_prep_t preprocessor = prog->preprocessor;
2585
2586                 memset(&result, 0, sizeof(result));
2587                 err = preprocessor(prog, i, prog->insns,
2588                                    prog->insns_cnt, &result);
2589                 if (err) {
2590                         pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
2591                                    i, prog->section_name);
2592                         goto out;
2593                 }
2594
2595                 if (!result.new_insn_ptr || !result.new_insn_cnt) {
2596                         pr_debug("Skip loading the %dth instance of program '%s'\n",
2597                                  i, prog->section_name);
2598                         prog->instances.fds[i] = -1;
2599                         if (result.pfd)
2600                                 *result.pfd = -1;
2601                         continue;
2602                 }
2603
2604                 err = load_program(prog, result.new_insn_ptr,
2605                                    result.new_insn_cnt,
2606                                    license, kern_version, &fd);
2607
2608                 if (err) {
2609                         pr_warning("Loading the %dth instance of program '%s' failed\n",
2610                                         i, prog->section_name);
2611                         goto out;
2612                 }
2613
2614                 if (result.pfd)
2615                         *result.pfd = fd;
2616                 prog->instances.fds[i] = fd;
2617         }
2618 out:
2619         if (err)
2620                 pr_warning("failed to load program '%s'\n",
2621                            prog->section_name);
2622         zfree(&prog->insns);
2623         prog->insns_cnt = 0;
2624         return err;
2625 }
2626
2627 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
2628                                              const struct bpf_object *obj)
2629 {
2630         return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
2631 }
2632
2633 static int
2634 bpf_object__load_progs(struct bpf_object *obj, int log_level)
2635 {
2636         size_t i;
2637         int err;
2638
2639         for (i = 0; i < obj->nr_programs; i++) {
2640                 if (bpf_program__is_function_storage(&obj->programs[i], obj))
2641                         continue;
2642                 obj->programs[i].log_level |= log_level;
2643                 err = bpf_program__load(&obj->programs[i],
2644                                         obj->license,
2645                                         obj->kern_version);
2646                 if (err)
2647                         return err;
2648         }
2649         return 0;
2650 }
2651
2652 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
2653 {
2654         switch (type) {
2655         case BPF_PROG_TYPE_SOCKET_FILTER:
2656         case BPF_PROG_TYPE_SCHED_CLS:
2657         case BPF_PROG_TYPE_SCHED_ACT:
2658         case BPF_PROG_TYPE_XDP:
2659         case BPF_PROG_TYPE_CGROUP_SKB:
2660         case BPF_PROG_TYPE_CGROUP_SOCK:
2661         case BPF_PROG_TYPE_LWT_IN:
2662         case BPF_PROG_TYPE_LWT_OUT:
2663         case BPF_PROG_TYPE_LWT_XMIT:
2664         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2665         case BPF_PROG_TYPE_SOCK_OPS:
2666         case BPF_PROG_TYPE_SK_SKB:
2667         case BPF_PROG_TYPE_CGROUP_DEVICE:
2668         case BPF_PROG_TYPE_SK_MSG:
2669         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2670         case BPF_PROG_TYPE_LIRC_MODE2:
2671         case BPF_PROG_TYPE_SK_REUSEPORT:
2672         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2673         case BPF_PROG_TYPE_UNSPEC:
2674         case BPF_PROG_TYPE_TRACEPOINT:
2675         case BPF_PROG_TYPE_RAW_TRACEPOINT:
2676         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2677         case BPF_PROG_TYPE_PERF_EVENT:
2678         case BPF_PROG_TYPE_CGROUP_SYSCTL:
2679         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2680                 return false;
2681         case BPF_PROG_TYPE_KPROBE:
2682         default:
2683                 return true;
2684         }
2685 }
2686
2687 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
2688 {
2689         if (needs_kver && obj->kern_version == 0) {
2690                 pr_warning("%s doesn't provide kernel version\n",
2691                            obj->path);
2692                 return -LIBBPF_ERRNO__KVERSION;
2693         }
2694         return 0;
2695 }
2696
2697 static struct bpf_object *
2698 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
2699                    bool needs_kver, int flags)
2700 {
2701         struct bpf_object *obj;
2702         int err;
2703
2704         if (elf_version(EV_CURRENT) == EV_NONE) {
2705                 pr_warning("failed to init libelf for %s\n", path);
2706                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
2707         }
2708
2709         obj = bpf_object__new(path, obj_buf, obj_buf_sz);
2710         if (IS_ERR(obj))
2711                 return obj;
2712
2713         CHECK_ERR(bpf_object__elf_init(obj), err, out);
2714         CHECK_ERR(bpf_object__check_endianness(obj), err, out);
2715         CHECK_ERR(bpf_object__probe_caps(obj), err, out);
2716         CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
2717         CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
2718         CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
2719
2720         bpf_object__elf_finish(obj);
2721         return obj;
2722 out:
2723         bpf_object__close(obj);
2724         return ERR_PTR(err);
2725 }
2726
2727 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
2728                                             int flags)
2729 {
2730         /* param validation */
2731         if (!attr->file)
2732                 return NULL;
2733
2734         pr_debug("loading %s\n", attr->file);
2735
2736         return __bpf_object__open(attr->file, NULL, 0,
2737                                   bpf_prog_type__needs_kver(attr->prog_type),
2738                                   flags);
2739 }
2740
2741 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
2742 {
2743         return __bpf_object__open_xattr(attr, 0);
2744 }
2745
2746 struct bpf_object *bpf_object__open(const char *path)
2747 {
2748         struct bpf_object_open_attr attr = {
2749                 .file           = path,
2750                 .prog_type      = BPF_PROG_TYPE_UNSPEC,
2751         };
2752
2753         return bpf_object__open_xattr(&attr);
2754 }
2755
2756 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
2757                                            size_t obj_buf_sz,
2758                                            const char *name)
2759 {
2760         char tmp_name[64];
2761
2762         /* param validation */
2763         if (!obj_buf || obj_buf_sz <= 0)
2764                 return NULL;
2765
2766         if (!name) {
2767                 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
2768                          (unsigned long)obj_buf,
2769                          (unsigned long)obj_buf_sz);
2770                 name = tmp_name;
2771         }
2772         pr_debug("loading object '%s' from buffer\n", name);
2773
2774         return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
2775 }
2776
2777 int bpf_object__unload(struct bpf_object *obj)
2778 {
2779         size_t i;
2780
2781         if (!obj)
2782                 return -EINVAL;
2783
2784         for (i = 0; i < obj->nr_maps; i++)
2785                 zclose(obj->maps[i].fd);
2786
2787         for (i = 0; i < obj->nr_programs; i++)
2788                 bpf_program__unload(&obj->programs[i]);
2789
2790         return 0;
2791 }
2792
2793 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
2794 {
2795         struct bpf_object *obj;
2796         int err;
2797
2798         if (!attr)
2799                 return -EINVAL;
2800         obj = attr->obj;
2801         if (!obj)
2802                 return -EINVAL;
2803
2804         if (obj->loaded) {
2805                 pr_warning("object should not be loaded twice\n");
2806                 return -EINVAL;
2807         }
2808
2809         obj->loaded = true;
2810
2811         CHECK_ERR(bpf_object__create_maps(obj), err, out);
2812         CHECK_ERR(bpf_object__relocate(obj), err, out);
2813         CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
2814
2815         return 0;
2816 out:
2817         bpf_object__unload(obj);
2818         pr_warning("failed to load object '%s'\n", obj->path);
2819         return err;
2820 }
2821
2822 int bpf_object__load(struct bpf_object *obj)
2823 {
2824         struct bpf_object_load_attr attr = {
2825                 .obj = obj,
2826         };
2827
2828         return bpf_object__load_xattr(&attr);
2829 }
2830
2831 static int check_path(const char *path)
2832 {
2833         char *cp, errmsg[STRERR_BUFSIZE];
2834         struct statfs st_fs;
2835         char *dname, *dir;
2836         int err = 0;
2837
2838         if (path == NULL)
2839                 return -EINVAL;
2840
2841         dname = strdup(path);
2842         if (dname == NULL)
2843                 return -ENOMEM;
2844
2845         dir = dirname(dname);
2846         if (statfs(dir, &st_fs)) {
2847                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2848                 pr_warning("failed to statfs %s: %s\n", dir, cp);
2849                 err = -errno;
2850         }
2851         free(dname);
2852
2853         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
2854                 pr_warning("specified path %s is not on BPF FS\n", path);
2855                 err = -EINVAL;
2856         }
2857
2858         return err;
2859 }
2860
2861 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
2862                               int instance)
2863 {
2864         char *cp, errmsg[STRERR_BUFSIZE];
2865         int err;
2866
2867         err = check_path(path);
2868         if (err)
2869                 return err;
2870
2871         if (prog == NULL) {
2872                 pr_warning("invalid program pointer\n");
2873                 return -EINVAL;
2874         }
2875
2876         if (instance < 0 || instance >= prog->instances.nr) {
2877                 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2878                            instance, prog->section_name, prog->instances.nr);
2879                 return -EINVAL;
2880         }
2881
2882         if (bpf_obj_pin(prog->instances.fds[instance], path)) {
2883                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2884                 pr_warning("failed to pin program: %s\n", cp);
2885                 return -errno;
2886         }
2887         pr_debug("pinned program '%s'\n", path);
2888
2889         return 0;
2890 }
2891
2892 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
2893                                 int instance)
2894 {
2895         int err;
2896
2897         err = check_path(path);
2898         if (err)
2899                 return err;
2900
2901         if (prog == NULL) {
2902                 pr_warning("invalid program pointer\n");
2903                 return -EINVAL;
2904         }
2905
2906         if (instance < 0 || instance >= prog->instances.nr) {
2907                 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2908                            instance, prog->section_name, prog->instances.nr);
2909                 return -EINVAL;
2910         }
2911
2912         err = unlink(path);
2913         if (err != 0)
2914                 return -errno;
2915         pr_debug("unpinned program '%s'\n", path);
2916
2917         return 0;
2918 }
2919
2920 static int make_dir(const char *path)
2921 {
2922         char *cp, errmsg[STRERR_BUFSIZE];
2923         int err = 0;
2924
2925         if (mkdir(path, 0700) && errno != EEXIST)
2926                 err = -errno;
2927
2928         if (err) {
2929                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2930                 pr_warning("failed to mkdir %s: %s\n", path, cp);
2931         }
2932         return err;
2933 }
2934
2935 int bpf_program__pin(struct bpf_program *prog, const char *path)
2936 {
2937         int i, err;
2938
2939         err = check_path(path);
2940         if (err)
2941                 return err;
2942
2943         if (prog == NULL) {
2944                 pr_warning("invalid program pointer\n");
2945                 return -EINVAL;
2946         }
2947
2948         if (prog->instances.nr <= 0) {
2949                 pr_warning("no instances of prog %s to pin\n",
2950                            prog->section_name);
2951                 return -EINVAL;
2952         }
2953
2954         if (prog->instances.nr == 1) {
2955                 /* don't create subdirs when pinning single instance */
2956                 return bpf_program__pin_instance(prog, path, 0);
2957         }
2958
2959         err = make_dir(path);
2960         if (err)
2961                 return err;
2962
2963         for (i = 0; i < prog->instances.nr; i++) {
2964                 char buf[PATH_MAX];
2965                 int len;
2966
2967                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2968                 if (len < 0) {
2969                         err = -EINVAL;
2970                         goto err_unpin;
2971                 } else if (len >= PATH_MAX) {
2972                         err = -ENAMETOOLONG;
2973                         goto err_unpin;
2974                 }
2975
2976                 err = bpf_program__pin_instance(prog, buf, i);
2977                 if (err)
2978                         goto err_unpin;
2979         }
2980
2981         return 0;
2982
2983 err_unpin:
2984         for (i = i - 1; i >= 0; i--) {
2985                 char buf[PATH_MAX];
2986                 int len;
2987
2988                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2989                 if (len < 0)
2990                         continue;
2991                 else if (len >= PATH_MAX)
2992                         continue;
2993
2994                 bpf_program__unpin_instance(prog, buf, i);
2995         }
2996
2997         rmdir(path);
2998
2999         return err;
3000 }
3001
3002 int bpf_program__unpin(struct bpf_program *prog, const char *path)
3003 {
3004         int i, err;
3005
3006         err = check_path(path);
3007         if (err)
3008                 return err;
3009
3010         if (prog == NULL) {
3011                 pr_warning("invalid program pointer\n");
3012                 return -EINVAL;
3013         }
3014
3015         if (prog->instances.nr <= 0) {
3016                 pr_warning("no instances of prog %s to pin\n",
3017                            prog->section_name);
3018                 return -EINVAL;
3019         }
3020
3021         if (prog->instances.nr == 1) {
3022                 /* don't create subdirs when pinning single instance */
3023                 return bpf_program__unpin_instance(prog, path, 0);
3024         }
3025
3026         for (i = 0; i < prog->instances.nr; i++) {
3027                 char buf[PATH_MAX];
3028                 int len;
3029
3030                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
3031                 if (len < 0)
3032                         return -EINVAL;
3033                 else if (len >= PATH_MAX)
3034                         return -ENAMETOOLONG;
3035
3036                 err = bpf_program__unpin_instance(prog, buf, i);
3037                 if (err)
3038                         return err;
3039         }
3040
3041         err = rmdir(path);
3042         if (err)
3043                 return -errno;
3044
3045         return 0;
3046 }
3047
3048 int bpf_map__pin(struct bpf_map *map, const char *path)
3049 {
3050         char *cp, errmsg[STRERR_BUFSIZE];
3051         int err;
3052
3053         err = check_path(path);
3054         if (err)
3055                 return err;
3056
3057         if (map == NULL) {
3058                 pr_warning("invalid map pointer\n");
3059                 return -EINVAL;
3060         }
3061
3062         if (bpf_obj_pin(map->fd, path)) {
3063                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3064                 pr_warning("failed to pin map: %s\n", cp);
3065                 return -errno;
3066         }
3067
3068         pr_debug("pinned map '%s'\n", path);
3069
3070         return 0;
3071 }
3072
3073 int bpf_map__unpin(struct bpf_map *map, const char *path)
3074 {
3075         int err;
3076
3077         err = check_path(path);
3078         if (err)
3079                 return err;
3080
3081         if (map == NULL) {
3082                 pr_warning("invalid map pointer\n");
3083                 return -EINVAL;
3084         }
3085
3086         err = unlink(path);
3087         if (err != 0)
3088                 return -errno;
3089         pr_debug("unpinned map '%s'\n", path);
3090
3091         return 0;
3092 }
3093
3094 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
3095 {
3096         struct bpf_map *map;
3097         int err;
3098
3099         if (!obj)
3100                 return -ENOENT;
3101
3102         if (!obj->loaded) {
3103                 pr_warning("object not yet loaded; load it first\n");
3104                 return -ENOENT;
3105         }
3106
3107         err = make_dir(path);
3108         if (err)
3109                 return err;
3110
3111         bpf_object__for_each_map(map, obj) {
3112                 char buf[PATH_MAX];
3113                 int len;
3114
3115                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3116                                bpf_map__name(map));
3117                 if (len < 0) {
3118                         err = -EINVAL;
3119                         goto err_unpin_maps;
3120                 } else if (len >= PATH_MAX) {
3121                         err = -ENAMETOOLONG;
3122                         goto err_unpin_maps;
3123                 }
3124
3125                 err = bpf_map__pin(map, buf);
3126                 if (err)
3127                         goto err_unpin_maps;
3128         }
3129
3130         return 0;
3131
3132 err_unpin_maps:
3133         while ((map = bpf_map__prev(map, obj))) {
3134                 char buf[PATH_MAX];
3135                 int len;
3136
3137                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3138                                bpf_map__name(map));
3139                 if (len < 0)
3140                         continue;
3141                 else if (len >= PATH_MAX)
3142                         continue;
3143
3144                 bpf_map__unpin(map, buf);
3145         }
3146
3147         return err;
3148 }
3149
3150 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
3151 {
3152         struct bpf_map *map;
3153         int err;
3154
3155         if (!obj)
3156                 return -ENOENT;
3157
3158         bpf_object__for_each_map(map, obj) {
3159                 char buf[PATH_MAX];
3160                 int len;
3161
3162                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3163                                bpf_map__name(map));
3164                 if (len < 0)
3165                         return -EINVAL;
3166                 else if (len >= PATH_MAX)
3167                         return -ENAMETOOLONG;
3168
3169                 err = bpf_map__unpin(map, buf);
3170                 if (err)
3171                         return err;
3172         }
3173
3174         return 0;
3175 }
3176
3177 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
3178 {
3179         struct bpf_program *prog;
3180         int err;
3181
3182         if (!obj)
3183                 return -ENOENT;
3184
3185         if (!obj->loaded) {
3186                 pr_warning("object not yet loaded; load it first\n");
3187                 return -ENOENT;
3188         }
3189
3190         err = make_dir(path);
3191         if (err)
3192                 return err;
3193
3194         bpf_object__for_each_program(prog, obj) {
3195                 char buf[PATH_MAX];
3196                 int len;
3197
3198                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3199                                prog->pin_name);
3200                 if (len < 0) {
3201                         err = -EINVAL;
3202                         goto err_unpin_programs;
3203                 } else if (len >= PATH_MAX) {
3204                         err = -ENAMETOOLONG;
3205                         goto err_unpin_programs;
3206                 }
3207
3208                 err = bpf_program__pin(prog, buf);
3209                 if (err)
3210                         goto err_unpin_programs;
3211         }
3212
3213         return 0;
3214
3215 err_unpin_programs:
3216         while ((prog = bpf_program__prev(prog, obj))) {
3217                 char buf[PATH_MAX];
3218                 int len;
3219
3220                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3221                                prog->pin_name);
3222                 if (len < 0)
3223                         continue;
3224                 else if (len >= PATH_MAX)
3225                         continue;
3226
3227                 bpf_program__unpin(prog, buf);
3228         }
3229
3230         return err;
3231 }
3232
3233 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
3234 {
3235         struct bpf_program *prog;
3236         int err;
3237
3238         if (!obj)
3239                 return -ENOENT;
3240
3241         bpf_object__for_each_program(prog, obj) {
3242                 char buf[PATH_MAX];
3243                 int len;
3244
3245                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
3246                                prog->pin_name);
3247                 if (len < 0)
3248                         return -EINVAL;
3249                 else if (len >= PATH_MAX)
3250                         return -ENAMETOOLONG;
3251
3252                 err = bpf_program__unpin(prog, buf);
3253                 if (err)
3254                         return err;
3255         }
3256
3257         return 0;
3258 }
3259
3260 int bpf_object__pin(struct bpf_object *obj, const char *path)
3261 {
3262         int err;
3263
3264         err = bpf_object__pin_maps(obj, path);
3265         if (err)
3266                 return err;
3267
3268         err = bpf_object__pin_programs(obj, path);
3269         if (err) {
3270                 bpf_object__unpin_maps(obj, path);
3271                 return err;
3272         }
3273
3274         return 0;
3275 }
3276
3277 void bpf_object__close(struct bpf_object *obj)
3278 {
3279         size_t i;
3280
3281         if (!obj)
3282                 return;
3283
3284         if (obj->clear_priv)
3285                 obj->clear_priv(obj, obj->priv);
3286
3287         bpf_object__elf_finish(obj);
3288         bpf_object__unload(obj);
3289         btf__free(obj->btf);
3290         btf_ext__free(obj->btf_ext);
3291
3292         for (i = 0; i < obj->nr_maps; i++) {
3293                 zfree(&obj->maps[i].name);
3294                 if (obj->maps[i].clear_priv)
3295                         obj->maps[i].clear_priv(&obj->maps[i],
3296                                                 obj->maps[i].priv);
3297                 obj->maps[i].priv = NULL;
3298                 obj->maps[i].clear_priv = NULL;
3299         }
3300
3301         zfree(&obj->sections.rodata);
3302         zfree(&obj->sections.data);
3303         zfree(&obj->maps);
3304         obj->nr_maps = 0;
3305
3306         if (obj->programs && obj->nr_programs) {
3307                 for (i = 0; i < obj->nr_programs; i++)
3308                         bpf_program__exit(&obj->programs[i]);
3309         }
3310         zfree(&obj->programs);
3311
3312         list_del(&obj->list);
3313         free(obj);
3314 }
3315
3316 struct bpf_object *
3317 bpf_object__next(struct bpf_object *prev)
3318 {
3319         struct bpf_object *next;
3320
3321         if (!prev)
3322                 next = list_first_entry(&bpf_objects_list,
3323                                         struct bpf_object,
3324                                         list);
3325         else
3326                 next = list_next_entry(prev, list);
3327
3328         /* Empty list is noticed here so don't need checking on entry. */
3329         if (&next->list == &bpf_objects_list)
3330                 return NULL;
3331
3332         return next;
3333 }
3334
3335 const char *bpf_object__name(const struct bpf_object *obj)
3336 {
3337         return obj ? obj->path : ERR_PTR(-EINVAL);
3338 }
3339
3340 unsigned int bpf_object__kversion(const struct bpf_object *obj)
3341 {
3342         return obj ? obj->kern_version : 0;
3343 }
3344
3345 struct btf *bpf_object__btf(const struct bpf_object *obj)
3346 {
3347         return obj ? obj->btf : NULL;
3348 }
3349
3350 int bpf_object__btf_fd(const struct bpf_object *obj)
3351 {
3352         return obj->btf ? btf__fd(obj->btf) : -1;
3353 }
3354
3355 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
3356                          bpf_object_clear_priv_t clear_priv)
3357 {
3358         if (obj->priv && obj->clear_priv)
3359                 obj->clear_priv(obj, obj->priv);
3360
3361         obj->priv = priv;
3362         obj->clear_priv = clear_priv;
3363         return 0;
3364 }
3365
3366 void *bpf_object__priv(const struct bpf_object *obj)
3367 {
3368         return obj ? obj->priv : ERR_PTR(-EINVAL);
3369 }
3370
3371 static struct bpf_program *
3372 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
3373                     bool forward)
3374 {
3375         size_t nr_programs = obj->nr_programs;
3376         ssize_t idx;
3377
3378         if (!nr_programs)
3379                 return NULL;
3380
3381         if (!p)
3382                 /* Iter from the beginning */
3383                 return forward ? &obj->programs[0] :
3384                         &obj->programs[nr_programs - 1];
3385
3386         if (p->obj != obj) {
3387                 pr_warning("error: program handler doesn't match object\n");
3388                 return NULL;
3389         }
3390
3391         idx = (p - obj->programs) + (forward ? 1 : -1);
3392         if (idx >= obj->nr_programs || idx < 0)
3393                 return NULL;
3394         return &obj->programs[idx];
3395 }
3396
3397 struct bpf_program *
3398 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
3399 {
3400         struct bpf_program *prog = prev;
3401
3402         do {
3403                 prog = __bpf_program__iter(prog, obj, true);
3404         } while (prog && bpf_program__is_function_storage(prog, obj));
3405
3406         return prog;
3407 }
3408
3409 struct bpf_program *
3410 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
3411 {
3412         struct bpf_program *prog = next;
3413
3414         do {
3415                 prog = __bpf_program__iter(prog, obj, false);
3416         } while (prog && bpf_program__is_function_storage(prog, obj));
3417
3418         return prog;
3419 }
3420
3421 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
3422                           bpf_program_clear_priv_t clear_priv)
3423 {
3424         if (prog->priv && prog->clear_priv)
3425                 prog->clear_priv(prog, prog->priv);
3426
3427         prog->priv = priv;
3428         prog->clear_priv = clear_priv;
3429         return 0;
3430 }
3431
3432 void *bpf_program__priv(const struct bpf_program *prog)
3433 {
3434         return prog ? prog->priv : ERR_PTR(-EINVAL);
3435 }
3436
3437 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
3438 {
3439         prog->prog_ifindex = ifindex;
3440 }
3441
3442 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
3443 {
3444         const char *title;
3445
3446         title = prog->section_name;
3447         if (needs_copy) {
3448                 title = strdup(title);
3449                 if (!title) {
3450                         pr_warning("failed to strdup program title\n");
3451                         return ERR_PTR(-ENOMEM);
3452                 }
3453         }
3454
3455         return title;
3456 }
3457
3458 int bpf_program__fd(const struct bpf_program *prog)
3459 {
3460         return bpf_program__nth_fd(prog, 0);
3461 }
3462
3463 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
3464                           bpf_program_prep_t prep)
3465 {
3466         int *instances_fds;
3467
3468         if (nr_instances <= 0 || !prep)
3469                 return -EINVAL;
3470
3471         if (prog->instances.nr > 0 || prog->instances.fds) {
3472                 pr_warning("Can't set pre-processor after loading\n");
3473                 return -EINVAL;
3474         }
3475
3476         instances_fds = malloc(sizeof(int) * nr_instances);
3477         if (!instances_fds) {
3478                 pr_warning("alloc memory failed for fds\n");
3479                 return -ENOMEM;
3480         }
3481
3482         /* fill all fd with -1 */
3483         memset(instances_fds, -1, sizeof(int) * nr_instances);
3484
3485         prog->instances.nr = nr_instances;
3486         prog->instances.fds = instances_fds;
3487         prog->preprocessor = prep;
3488         return 0;
3489 }
3490
3491 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
3492 {
3493         int fd;
3494
3495         if (!prog)
3496                 return -EINVAL;
3497
3498         if (n >= prog->instances.nr || n < 0) {
3499                 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
3500                            n, prog->section_name, prog->instances.nr);
3501                 return -EINVAL;
3502         }
3503
3504         fd = prog->instances.fds[n];
3505         if (fd < 0) {
3506                 pr_warning("%dth instance of program '%s' is invalid\n",
3507                            n, prog->section_name);
3508                 return -ENOENT;
3509         }
3510
3511         return fd;
3512 }
3513
3514 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
3515 {
3516         prog->type = type;
3517 }
3518
3519 static bool bpf_program__is_type(const struct bpf_program *prog,
3520                                  enum bpf_prog_type type)
3521 {
3522         return prog ? (prog->type == type) : false;
3523 }
3524
3525 #define BPF_PROG_TYPE_FNS(NAME, TYPE)                           \
3526 int bpf_program__set_##NAME(struct bpf_program *prog)           \
3527 {                                                               \
3528         if (!prog)                                              \
3529                 return -EINVAL;                                 \
3530         bpf_program__set_type(prog, TYPE);                      \
3531         return 0;                                               \
3532 }                                                               \
3533                                                                 \
3534 bool bpf_program__is_##NAME(const struct bpf_program *prog)     \
3535 {                                                               \
3536         return bpf_program__is_type(prog, TYPE);                \
3537 }                                                               \
3538
3539 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
3540 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
3541 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
3542 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
3543 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
3544 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
3545 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
3546 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
3547
3548 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
3549                                            enum bpf_attach_type type)
3550 {
3551         prog->expected_attach_type = type;
3552 }
3553
3554 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
3555         { string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
3556
3557 /* Programs that can NOT be attached. */
3558 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
3559
3560 /* Programs that can be attached. */
3561 #define BPF_APROG_SEC(string, ptype, atype) \
3562         BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
3563
3564 /* Programs that must specify expected attach type at load time. */
3565 #define BPF_EAPROG_SEC(string, ptype, eatype) \
3566         BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
3567
3568 /* Programs that can be attached but attach type can't be identified by section
3569  * name. Kept for backward compatibility.
3570  */
3571 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
3572
3573 static const struct {
3574         const char *sec;
3575         size_t len;
3576         enum bpf_prog_type prog_type;
3577         enum bpf_attach_type expected_attach_type;
3578         int is_attachable;
3579         enum bpf_attach_type attach_type;
3580 } section_names[] = {
3581         BPF_PROG_SEC("socket",                  BPF_PROG_TYPE_SOCKET_FILTER),
3582         BPF_PROG_SEC("kprobe/",                 BPF_PROG_TYPE_KPROBE),
3583         BPF_PROG_SEC("kretprobe/",              BPF_PROG_TYPE_KPROBE),
3584         BPF_PROG_SEC("classifier",              BPF_PROG_TYPE_SCHED_CLS),
3585         BPF_PROG_SEC("action",                  BPF_PROG_TYPE_SCHED_ACT),
3586         BPF_PROG_SEC("tracepoint/",             BPF_PROG_TYPE_TRACEPOINT),
3587         BPF_PROG_SEC("raw_tracepoint/",         BPF_PROG_TYPE_RAW_TRACEPOINT),
3588         BPF_PROG_SEC("xdp",                     BPF_PROG_TYPE_XDP),
3589         BPF_PROG_SEC("perf_event",              BPF_PROG_TYPE_PERF_EVENT),
3590         BPF_PROG_SEC("lwt_in",                  BPF_PROG_TYPE_LWT_IN),
3591         BPF_PROG_SEC("lwt_out",                 BPF_PROG_TYPE_LWT_OUT),
3592         BPF_PROG_SEC("lwt_xmit",                BPF_PROG_TYPE_LWT_XMIT),
3593         BPF_PROG_SEC("lwt_seg6local",           BPF_PROG_TYPE_LWT_SEG6LOCAL),
3594         BPF_APROG_SEC("cgroup_skb/ingress",     BPF_PROG_TYPE_CGROUP_SKB,
3595                                                 BPF_CGROUP_INET_INGRESS),
3596         BPF_APROG_SEC("cgroup_skb/egress",      BPF_PROG_TYPE_CGROUP_SKB,
3597                                                 BPF_CGROUP_INET_EGRESS),
3598         BPF_APROG_COMPAT("cgroup/skb",          BPF_PROG_TYPE_CGROUP_SKB),
3599         BPF_APROG_SEC("cgroup/sock",            BPF_PROG_TYPE_CGROUP_SOCK,
3600                                                 BPF_CGROUP_INET_SOCK_CREATE),
3601         BPF_EAPROG_SEC("cgroup/post_bind4",     BPF_PROG_TYPE_CGROUP_SOCK,
3602                                                 BPF_CGROUP_INET4_POST_BIND),
3603         BPF_EAPROG_SEC("cgroup/post_bind6",     BPF_PROG_TYPE_CGROUP_SOCK,
3604                                                 BPF_CGROUP_INET6_POST_BIND),
3605         BPF_APROG_SEC("cgroup/dev",             BPF_PROG_TYPE_CGROUP_DEVICE,
3606                                                 BPF_CGROUP_DEVICE),
3607         BPF_APROG_SEC("sockops",                BPF_PROG_TYPE_SOCK_OPS,
3608                                                 BPF_CGROUP_SOCK_OPS),
3609         BPF_APROG_SEC("sk_skb/stream_parser",   BPF_PROG_TYPE_SK_SKB,
3610                                                 BPF_SK_SKB_STREAM_PARSER),
3611         BPF_APROG_SEC("sk_skb/stream_verdict",  BPF_PROG_TYPE_SK_SKB,
3612                                                 BPF_SK_SKB_STREAM_VERDICT),
3613         BPF_APROG_COMPAT("sk_skb",              BPF_PROG_TYPE_SK_SKB),
3614         BPF_APROG_SEC("sk_msg",                 BPF_PROG_TYPE_SK_MSG,
3615                                                 BPF_SK_MSG_VERDICT),
3616         BPF_APROG_SEC("lirc_mode2",             BPF_PROG_TYPE_LIRC_MODE2,
3617                                                 BPF_LIRC_MODE2),
3618         BPF_APROG_SEC("flow_dissector",         BPF_PROG_TYPE_FLOW_DISSECTOR,
3619                                                 BPF_FLOW_DISSECTOR),
3620         BPF_EAPROG_SEC("cgroup/bind4",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3621                                                 BPF_CGROUP_INET4_BIND),
3622         BPF_EAPROG_SEC("cgroup/bind6",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3623                                                 BPF_CGROUP_INET6_BIND),
3624         BPF_EAPROG_SEC("cgroup/connect4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3625                                                 BPF_CGROUP_INET4_CONNECT),
3626         BPF_EAPROG_SEC("cgroup/connect6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3627                                                 BPF_CGROUP_INET6_CONNECT),
3628         BPF_EAPROG_SEC("cgroup/sendmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3629                                                 BPF_CGROUP_UDP4_SENDMSG),
3630         BPF_EAPROG_SEC("cgroup/sendmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3631                                                 BPF_CGROUP_UDP6_SENDMSG),
3632         BPF_EAPROG_SEC("cgroup/recvmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3633                                                 BPF_CGROUP_UDP4_RECVMSG),
3634         BPF_EAPROG_SEC("cgroup/recvmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3635                                                 BPF_CGROUP_UDP6_RECVMSG),
3636         BPF_EAPROG_SEC("cgroup/sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,
3637                                                 BPF_CGROUP_SYSCTL),
3638         BPF_EAPROG_SEC("cgroup/getsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
3639                                                 BPF_CGROUP_GETSOCKOPT),
3640         BPF_EAPROG_SEC("cgroup/setsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
3641                                                 BPF_CGROUP_SETSOCKOPT),
3642 };
3643
3644 #undef BPF_PROG_SEC_IMPL
3645 #undef BPF_PROG_SEC
3646 #undef BPF_APROG_SEC
3647 #undef BPF_EAPROG_SEC
3648 #undef BPF_APROG_COMPAT
3649
3650 #define MAX_TYPE_NAME_SIZE 32
3651
3652 static char *libbpf_get_type_names(bool attach_type)
3653 {
3654         int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
3655         char *buf;
3656
3657         buf = malloc(len);
3658         if (!buf)
3659                 return NULL;
3660
3661         buf[0] = '\0';
3662         /* Forge string buf with all available names */
3663         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3664                 if (attach_type && !section_names[i].is_attachable)
3665                         continue;
3666
3667                 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
3668                         free(buf);
3669                         return NULL;
3670                 }
3671                 strcat(buf, " ");
3672                 strcat(buf, section_names[i].sec);
3673         }
3674
3675         return buf;
3676 }
3677
3678 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
3679                              enum bpf_attach_type *expected_attach_type)
3680 {
3681         char *type_names;
3682         int i;
3683
3684         if (!name)
3685                 return -EINVAL;
3686
3687         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3688                 if (strncmp(name, section_names[i].sec, section_names[i].len))
3689                         continue;
3690                 *prog_type = section_names[i].prog_type;
3691                 *expected_attach_type = section_names[i].expected_attach_type;
3692                 return 0;
3693         }
3694         pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
3695         type_names = libbpf_get_type_names(false);
3696         if (type_names != NULL) {
3697                 pr_info("supported section(type) names are:%s\n", type_names);
3698                 free(type_names);
3699         }
3700
3701         return -EINVAL;
3702 }
3703
3704 int libbpf_attach_type_by_name(const char *name,
3705                                enum bpf_attach_type *attach_type)
3706 {
3707         char *type_names;
3708         int i;
3709
3710         if (!name)
3711                 return -EINVAL;
3712
3713         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3714                 if (strncmp(name, section_names[i].sec, section_names[i].len))
3715                         continue;
3716                 if (!section_names[i].is_attachable)
3717                         return -EINVAL;
3718                 *attach_type = section_names[i].attach_type;
3719                 return 0;
3720         }
3721         pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
3722         type_names = libbpf_get_type_names(true);
3723         if (type_names != NULL) {
3724                 pr_info("attachable section(type) names are:%s\n", type_names);
3725                 free(type_names);
3726         }
3727
3728         return -EINVAL;
3729 }
3730
3731 static int
3732 bpf_program__identify_section(struct bpf_program *prog,
3733                               enum bpf_prog_type *prog_type,
3734                               enum bpf_attach_type *expected_attach_type)
3735 {
3736         return libbpf_prog_type_by_name(prog->section_name, prog_type,
3737                                         expected_attach_type);
3738 }
3739
3740 int bpf_map__fd(const struct bpf_map *map)
3741 {
3742         return map ? map->fd : -EINVAL;
3743 }
3744
3745 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
3746 {
3747         return map ? &map->def : ERR_PTR(-EINVAL);
3748 }
3749
3750 const char *bpf_map__name(const struct bpf_map *map)
3751 {
3752         return map ? map->name : NULL;
3753 }
3754
3755 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
3756 {
3757         return map ? map->btf_key_type_id : 0;
3758 }
3759
3760 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
3761 {
3762         return map ? map->btf_value_type_id : 0;
3763 }
3764
3765 int bpf_map__set_priv(struct bpf_map *map, void *priv,
3766                      bpf_map_clear_priv_t clear_priv)
3767 {
3768         if (!map)
3769                 return -EINVAL;
3770
3771         if (map->priv) {
3772                 if (map->clear_priv)
3773                         map->clear_priv(map, map->priv);
3774         }
3775
3776         map->priv = priv;
3777         map->clear_priv = clear_priv;
3778         return 0;
3779 }
3780
3781 void *bpf_map__priv(const struct bpf_map *map)
3782 {
3783         return map ? map->priv : ERR_PTR(-EINVAL);
3784 }
3785
3786 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
3787 {
3788         return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
3789 }
3790
3791 bool bpf_map__is_internal(const struct bpf_map *map)
3792 {
3793         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
3794 }
3795
3796 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
3797 {
3798         map->map_ifindex = ifindex;
3799 }
3800
3801 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
3802 {
3803         if (!bpf_map_type__is_map_in_map(map->def.type)) {
3804                 pr_warning("error: unsupported map type\n");
3805                 return -EINVAL;
3806         }
3807         if (map->inner_map_fd != -1) {
3808                 pr_warning("error: inner_map_fd already specified\n");
3809                 return -EINVAL;
3810         }
3811         map->inner_map_fd = fd;
3812         return 0;
3813 }
3814
3815 static struct bpf_map *
3816 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
3817 {
3818         ssize_t idx;
3819         struct bpf_map *s, *e;
3820
3821         if (!obj || !obj->maps)
3822                 return NULL;
3823
3824         s = obj->maps;
3825         e = obj->maps + obj->nr_maps;
3826
3827         if ((m < s) || (m >= e)) {
3828                 pr_warning("error in %s: map handler doesn't belong to object\n",
3829                            __func__);
3830                 return NULL;
3831         }
3832
3833         idx = (m - obj->maps) + i;
3834         if (idx >= obj->nr_maps || idx < 0)
3835                 return NULL;
3836         return &obj->maps[idx];
3837 }
3838
3839 struct bpf_map *
3840 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
3841 {
3842         if (prev == NULL)
3843                 return obj->maps;
3844
3845         return __bpf_map__iter(prev, obj, 1);
3846 }
3847
3848 struct bpf_map *
3849 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
3850 {
3851         if (next == NULL) {
3852                 if (!obj->nr_maps)
3853                         return NULL;
3854                 return obj->maps + obj->nr_maps - 1;
3855         }
3856
3857         return __bpf_map__iter(next, obj, -1);
3858 }
3859
3860 struct bpf_map *
3861 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
3862 {
3863         struct bpf_map *pos;
3864
3865         bpf_object__for_each_map(pos, obj) {
3866                 if (pos->name && !strcmp(pos->name, name))
3867                         return pos;
3868         }
3869         return NULL;
3870 }
3871
3872 int
3873 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
3874 {
3875         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
3876 }
3877
3878 struct bpf_map *
3879 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
3880 {
3881         return ERR_PTR(-ENOTSUP);
3882 }
3883
3884 long libbpf_get_error(const void *ptr)
3885 {
3886         return PTR_ERR_OR_ZERO(ptr);
3887 }
3888
3889 int bpf_prog_load(const char *file, enum bpf_prog_type type,
3890                   struct bpf_object **pobj, int *prog_fd)
3891 {
3892         struct bpf_prog_load_attr attr;
3893
3894         memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
3895         attr.file = file;
3896         attr.prog_type = type;
3897         attr.expected_attach_type = 0;
3898
3899         return bpf_prog_load_xattr(&attr, pobj, prog_fd);
3900 }
3901
3902 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
3903                         struct bpf_object **pobj, int *prog_fd)
3904 {
3905         struct bpf_object_open_attr open_attr = {};
3906         struct bpf_program *prog, *first_prog = NULL;
3907         enum bpf_attach_type expected_attach_type;
3908         enum bpf_prog_type prog_type;
3909         struct bpf_object *obj;
3910         struct bpf_map *map;
3911         int err;
3912
3913         if (!attr)
3914                 return -EINVAL;
3915         if (!attr->file)
3916                 return -EINVAL;
3917
3918         open_attr.file = attr->file;
3919         open_attr.prog_type = attr->prog_type;
3920
3921         obj = bpf_object__open_xattr(&open_attr);
3922         if (IS_ERR_OR_NULL(obj))
3923                 return -ENOENT;
3924
3925         bpf_object__for_each_program(prog, obj) {
3926                 /*
3927                  * If type is not specified, try to guess it based on
3928                  * section name.
3929                  */
3930                 prog_type = attr->prog_type;
3931                 prog->prog_ifindex = attr->ifindex;
3932                 expected_attach_type = attr->expected_attach_type;
3933                 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
3934                         err = bpf_program__identify_section(prog, &prog_type,
3935                                                             &expected_attach_type);
3936                         if (err < 0) {
3937                                 bpf_object__close(obj);
3938                                 return -EINVAL;
3939                         }
3940                 }
3941
3942                 bpf_program__set_type(prog, prog_type);
3943                 bpf_program__set_expected_attach_type(prog,
3944                                                       expected_attach_type);
3945
3946                 prog->log_level = attr->log_level;
3947                 prog->prog_flags = attr->prog_flags;
3948                 if (!first_prog)
3949                         first_prog = prog;
3950         }
3951
3952         bpf_object__for_each_map(map, obj) {
3953                 if (!bpf_map__is_offload_neutral(map))
3954                         map->map_ifindex = attr->ifindex;
3955         }
3956
3957         if (!first_prog) {
3958                 pr_warning("object file doesn't contain bpf program\n");
3959                 bpf_object__close(obj);
3960                 return -ENOENT;
3961         }
3962
3963         err = bpf_object__load(obj);
3964         if (err) {
3965                 bpf_object__close(obj);
3966                 return -EINVAL;
3967         }
3968
3969         *pobj = obj;
3970         *prog_fd = bpf_program__fd(first_prog);
3971         return 0;
3972 }
3973
3974 struct bpf_link {
3975         int (*destroy)(struct bpf_link *link);
3976 };
3977
3978 int bpf_link__destroy(struct bpf_link *link)
3979 {
3980         int err;
3981
3982         if (!link)
3983                 return 0;
3984
3985         err = link->destroy(link);
3986         free(link);
3987
3988         return err;
3989 }
3990
3991 struct bpf_link_fd {
3992         struct bpf_link link; /* has to be at the top of struct */
3993         int fd; /* hook FD */
3994 };
3995
3996 static int bpf_link__destroy_perf_event(struct bpf_link *link)
3997 {
3998         struct bpf_link_fd *l = (void *)link;
3999         int err;
4000
4001         err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
4002         if (err)
4003                 err = -errno;
4004
4005         close(l->fd);
4006         return err;
4007 }
4008
4009 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
4010                                                 int pfd)
4011 {
4012         char errmsg[STRERR_BUFSIZE];
4013         struct bpf_link_fd *link;
4014         int prog_fd, err;
4015
4016         if (pfd < 0) {
4017                 pr_warning("program '%s': invalid perf event FD %d\n",
4018                            bpf_program__title(prog, false), pfd);
4019                 return ERR_PTR(-EINVAL);
4020         }
4021         prog_fd = bpf_program__fd(prog);
4022         if (prog_fd < 0) {
4023                 pr_warning("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
4024                            bpf_program__title(prog, false));
4025                 return ERR_PTR(-EINVAL);
4026         }
4027
4028         link = malloc(sizeof(*link));
4029         if (!link)
4030                 return ERR_PTR(-ENOMEM);
4031         link->link.destroy = &bpf_link__destroy_perf_event;
4032         link->fd = pfd;
4033
4034         if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
4035                 err = -errno;
4036                 free(link);
4037                 pr_warning("program '%s': failed to attach to pfd %d: %s\n",
4038                            bpf_program__title(prog, false), pfd,
4039                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4040                 return ERR_PTR(err);
4041         }
4042         if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
4043                 err = -errno;
4044                 free(link);
4045                 pr_warning("program '%s': failed to enable pfd %d: %s\n",
4046                            bpf_program__title(prog, false), pfd,
4047                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4048                 return ERR_PTR(err);
4049         }
4050         return (struct bpf_link *)link;
4051 }
4052
4053 /*
4054  * this function is expected to parse integer in the range of [0, 2^31-1] from
4055  * given file using scanf format string fmt. If actual parsed value is
4056  * negative, the result might be indistinguishable from error
4057  */
4058 static int parse_uint_from_file(const char *file, const char *fmt)
4059 {
4060         char buf[STRERR_BUFSIZE];
4061         int err, ret;
4062         FILE *f;
4063
4064         f = fopen(file, "r");
4065         if (!f) {
4066                 err = -errno;
4067                 pr_debug("failed to open '%s': %s\n", file,
4068                          libbpf_strerror_r(err, buf, sizeof(buf)));
4069                 return err;
4070         }
4071         err = fscanf(f, fmt, &ret);
4072         if (err != 1) {
4073                 err = err == EOF ? -EIO : -errno;
4074                 pr_debug("failed to parse '%s': %s\n", file,
4075                         libbpf_strerror_r(err, buf, sizeof(buf)));
4076                 fclose(f);
4077                 return err;
4078         }
4079         fclose(f);
4080         return ret;
4081 }
4082
4083 static int determine_kprobe_perf_type(void)
4084 {
4085         const char *file = "/sys/bus/event_source/devices/kprobe/type";
4086
4087         return parse_uint_from_file(file, "%d\n");
4088 }
4089
4090 static int determine_uprobe_perf_type(void)
4091 {
4092         const char *file = "/sys/bus/event_source/devices/uprobe/type";
4093
4094         return parse_uint_from_file(file, "%d\n");
4095 }
4096
4097 static int determine_kprobe_retprobe_bit(void)
4098 {
4099         const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
4100
4101         return parse_uint_from_file(file, "config:%d\n");
4102 }
4103
4104 static int determine_uprobe_retprobe_bit(void)
4105 {
4106         const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
4107
4108         return parse_uint_from_file(file, "config:%d\n");
4109 }
4110
4111 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
4112                                  uint64_t offset, int pid)
4113 {
4114         struct perf_event_attr attr = {};
4115         char errmsg[STRERR_BUFSIZE];
4116         int type, pfd, err;
4117
4118         type = uprobe ? determine_uprobe_perf_type()
4119                       : determine_kprobe_perf_type();
4120         if (type < 0) {
4121                 pr_warning("failed to determine %s perf type: %s\n",
4122                            uprobe ? "uprobe" : "kprobe",
4123                            libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
4124                 return type;
4125         }
4126         if (retprobe) {
4127                 int bit = uprobe ? determine_uprobe_retprobe_bit()
4128                                  : determine_kprobe_retprobe_bit();
4129
4130                 if (bit < 0) {
4131                         pr_warning("failed to determine %s retprobe bit: %s\n",
4132                                    uprobe ? "uprobe" : "kprobe",
4133                                    libbpf_strerror_r(bit, errmsg,
4134                                                      sizeof(errmsg)));
4135                         return bit;
4136                 }
4137                 attr.config |= 1 << bit;
4138         }
4139         attr.size = sizeof(attr);
4140         attr.type = type;
4141         attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
4142         attr.config2 = offset;           /* kprobe_addr or probe_offset */
4143
4144         /* pid filter is meaningful only for uprobes */
4145         pfd = syscall(__NR_perf_event_open, &attr,
4146                       pid < 0 ? -1 : pid /* pid */,
4147                       pid == -1 ? 0 : -1 /* cpu */,
4148                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
4149         if (pfd < 0) {
4150                 err = -errno;
4151                 pr_warning("%s perf_event_open() failed: %s\n",
4152                            uprobe ? "uprobe" : "kprobe",
4153                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4154                 return err;
4155         }
4156         return pfd;
4157 }
4158
4159 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
4160                                             bool retprobe,
4161                                             const char *func_name)
4162 {
4163         char errmsg[STRERR_BUFSIZE];
4164         struct bpf_link *link;
4165         int pfd, err;
4166
4167         pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
4168                                     0 /* offset */, -1 /* pid */);
4169         if (pfd < 0) {
4170                 pr_warning("program '%s': failed to create %s '%s' perf event: %s\n",
4171                            bpf_program__title(prog, false),
4172                            retprobe ? "kretprobe" : "kprobe", func_name,
4173                            libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4174                 return ERR_PTR(pfd);
4175         }
4176         link = bpf_program__attach_perf_event(prog, pfd);
4177         if (IS_ERR(link)) {
4178                 close(pfd);
4179                 err = PTR_ERR(link);
4180                 pr_warning("program '%s': failed to attach to %s '%s': %s\n",
4181                            bpf_program__title(prog, false),
4182                            retprobe ? "kretprobe" : "kprobe", func_name,
4183                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4184                 return link;
4185         }
4186         return link;
4187 }
4188
4189 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
4190                                             bool retprobe, pid_t pid,
4191                                             const char *binary_path,
4192                                             size_t func_offset)
4193 {
4194         char errmsg[STRERR_BUFSIZE];
4195         struct bpf_link *link;
4196         int pfd, err;
4197
4198         pfd = perf_event_open_probe(true /* uprobe */, retprobe,
4199                                     binary_path, func_offset, pid);
4200         if (pfd < 0) {
4201                 pr_warning("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
4202                            bpf_program__title(prog, false),
4203                            retprobe ? "uretprobe" : "uprobe",
4204                            binary_path, func_offset,
4205                            libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4206                 return ERR_PTR(pfd);
4207         }
4208         link = bpf_program__attach_perf_event(prog, pfd);
4209         if (IS_ERR(link)) {
4210                 close(pfd);
4211                 err = PTR_ERR(link);
4212                 pr_warning("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
4213                            bpf_program__title(prog, false),
4214                            retprobe ? "uretprobe" : "uprobe",
4215                            binary_path, func_offset,
4216                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4217                 return link;
4218         }
4219         return link;
4220 }
4221
4222 static int determine_tracepoint_id(const char *tp_category,
4223                                    const char *tp_name)
4224 {
4225         char file[PATH_MAX];
4226         int ret;
4227
4228         ret = snprintf(file, sizeof(file),
4229                        "/sys/kernel/debug/tracing/events/%s/%s/id",
4230                        tp_category, tp_name);
4231         if (ret < 0)
4232                 return -errno;
4233         if (ret >= sizeof(file)) {
4234                 pr_debug("tracepoint %s/%s path is too long\n",
4235                          tp_category, tp_name);
4236                 return -E2BIG;
4237         }
4238         return parse_uint_from_file(file, "%d\n");
4239 }
4240
4241 static int perf_event_open_tracepoint(const char *tp_category,
4242                                       const char *tp_name)
4243 {
4244         struct perf_event_attr attr = {};
4245         char errmsg[STRERR_BUFSIZE];
4246         int tp_id, pfd, err;
4247
4248         tp_id = determine_tracepoint_id(tp_category, tp_name);
4249         if (tp_id < 0) {
4250                 pr_warning("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
4251                            tp_category, tp_name,
4252                            libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
4253                 return tp_id;
4254         }
4255
4256         attr.type = PERF_TYPE_TRACEPOINT;
4257         attr.size = sizeof(attr);
4258         attr.config = tp_id;
4259
4260         pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
4261                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
4262         if (pfd < 0) {
4263                 err = -errno;
4264                 pr_warning("tracepoint '%s/%s' perf_event_open() failed: %s\n",
4265                            tp_category, tp_name,
4266                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4267                 return err;
4268         }
4269         return pfd;
4270 }
4271
4272 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
4273                                                 const char *tp_category,
4274                                                 const char *tp_name)
4275 {
4276         char errmsg[STRERR_BUFSIZE];
4277         struct bpf_link *link;
4278         int pfd, err;
4279
4280         pfd = perf_event_open_tracepoint(tp_category, tp_name);
4281         if (pfd < 0) {
4282                 pr_warning("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
4283                            bpf_program__title(prog, false),
4284                            tp_category, tp_name,
4285                            libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4286                 return ERR_PTR(pfd);
4287         }
4288         link = bpf_program__attach_perf_event(prog, pfd);
4289         if (IS_ERR(link)) {
4290                 close(pfd);
4291                 err = PTR_ERR(link);
4292                 pr_warning("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
4293                            bpf_program__title(prog, false),
4294                            tp_category, tp_name,
4295                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
4296                 return link;
4297         }
4298         return link;
4299 }
4300
4301 static int bpf_link__destroy_fd(struct bpf_link *link)
4302 {
4303         struct bpf_link_fd *l = (void *)link;
4304
4305         return close(l->fd);
4306 }
4307
4308 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
4309                                                     const char *tp_name)
4310 {
4311         char errmsg[STRERR_BUFSIZE];
4312         struct bpf_link_fd *link;
4313         int prog_fd, pfd;
4314
4315         prog_fd = bpf_program__fd(prog);
4316         if (prog_fd < 0) {
4317                 pr_warning("program '%s': can't attach before loaded\n",
4318                            bpf_program__title(prog, false));
4319                 return ERR_PTR(-EINVAL);
4320         }
4321
4322         link = malloc(sizeof(*link));
4323         if (!link)
4324                 return ERR_PTR(-ENOMEM);
4325         link->link.destroy = &bpf_link__destroy_fd;
4326
4327         pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
4328         if (pfd < 0) {
4329                 pfd = -errno;
4330                 free(link);
4331                 pr_warning("program '%s': failed to attach to raw tracepoint '%s': %s\n",
4332                            bpf_program__title(prog, false), tp_name,
4333                            libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
4334                 return ERR_PTR(pfd);
4335         }
4336         link->fd = pfd;
4337         return (struct bpf_link *)link;
4338 }
4339
4340 enum bpf_perf_event_ret
4341 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
4342                            void **copy_mem, size_t *copy_size,
4343                            bpf_perf_event_print_t fn, void *private_data)
4344 {
4345         struct perf_event_mmap_page *header = mmap_mem;
4346         __u64 data_head = ring_buffer_read_head(header);
4347         __u64 data_tail = header->data_tail;
4348         void *base = ((__u8 *)header) + page_size;
4349         int ret = LIBBPF_PERF_EVENT_CONT;
4350         struct perf_event_header *ehdr;
4351         size_t ehdr_size;
4352
4353         while (data_head != data_tail) {
4354                 ehdr = base + (data_tail & (mmap_size - 1));
4355                 ehdr_size = ehdr->size;
4356
4357                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
4358                         void *copy_start = ehdr;
4359                         size_t len_first = base + mmap_size - copy_start;
4360                         size_t len_secnd = ehdr_size - len_first;
4361
4362                         if (*copy_size < ehdr_size) {
4363                                 free(*copy_mem);
4364                                 *copy_mem = malloc(ehdr_size);
4365                                 if (!*copy_mem) {
4366                                         *copy_size = 0;
4367                                         ret = LIBBPF_PERF_EVENT_ERROR;
4368                                         break;
4369                                 }
4370                                 *copy_size = ehdr_size;
4371                         }
4372
4373                         memcpy(*copy_mem, copy_start, len_first);
4374                         memcpy(*copy_mem + len_first, base, len_secnd);
4375                         ehdr = *copy_mem;
4376                 }
4377
4378                 ret = fn(ehdr, private_data);
4379                 data_tail += ehdr_size;
4380                 if (ret != LIBBPF_PERF_EVENT_CONT)
4381                         break;
4382         }
4383
4384         ring_buffer_write_tail(header, data_tail);
4385         return ret;
4386 }
4387
4388 struct perf_buffer;
4389
4390 struct perf_buffer_params {
4391         struct perf_event_attr *attr;
4392         /* if event_cb is specified, it takes precendence */
4393         perf_buffer_event_fn event_cb;
4394         /* sample_cb and lost_cb are higher-level common-case callbacks */
4395         perf_buffer_sample_fn sample_cb;
4396         perf_buffer_lost_fn lost_cb;
4397         void *ctx;
4398         int cpu_cnt;
4399         int *cpus;
4400         int *map_keys;
4401 };
4402
4403 struct perf_cpu_buf {
4404         struct perf_buffer *pb;
4405         void *base; /* mmap()'ed memory */
4406         void *buf; /* for reconstructing segmented data */
4407         size_t buf_size;
4408         int fd;
4409         int cpu;
4410         int map_key;
4411 };
4412
4413 struct perf_buffer {
4414         perf_buffer_event_fn event_cb;
4415         perf_buffer_sample_fn sample_cb;
4416         perf_buffer_lost_fn lost_cb;
4417         void *ctx; /* passed into callbacks */
4418
4419         size_t page_size;
4420         size_t mmap_size;
4421         struct perf_cpu_buf **cpu_bufs;
4422         struct epoll_event *events;
4423         int cpu_cnt;
4424         int epoll_fd; /* perf event FD */
4425         int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
4426 };
4427
4428 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
4429                                       struct perf_cpu_buf *cpu_buf)
4430 {
4431         if (!cpu_buf)
4432                 return;
4433         if (cpu_buf->base &&
4434             munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
4435                 pr_warning("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
4436         if (cpu_buf->fd >= 0) {
4437                 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
4438                 close(cpu_buf->fd);
4439         }
4440         free(cpu_buf->buf);
4441         free(cpu_buf);
4442 }
4443
4444 void perf_buffer__free(struct perf_buffer *pb)
4445 {
4446         int i;
4447
4448         if (!pb)
4449                 return;
4450         if (pb->cpu_bufs) {
4451                 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
4452                         struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
4453
4454                         bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
4455                         perf_buffer__free_cpu_buf(pb, cpu_buf);
4456                 }
4457                 free(pb->cpu_bufs);
4458         }
4459         if (pb->epoll_fd >= 0)
4460                 close(pb->epoll_fd);
4461         free(pb->events);
4462         free(pb);
4463 }
4464
4465 static struct perf_cpu_buf *
4466 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
4467                           int cpu, int map_key)
4468 {
4469         struct perf_cpu_buf *cpu_buf;
4470         char msg[STRERR_BUFSIZE];
4471         int err;
4472
4473         cpu_buf = calloc(1, sizeof(*cpu_buf));
4474         if (!cpu_buf)
4475                 return ERR_PTR(-ENOMEM);
4476
4477         cpu_buf->pb = pb;
4478         cpu_buf->cpu = cpu;
4479         cpu_buf->map_key = map_key;
4480
4481         cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
4482                               -1, PERF_FLAG_FD_CLOEXEC);
4483         if (cpu_buf->fd < 0) {
4484                 err = -errno;
4485                 pr_warning("failed to open perf buffer event on cpu #%d: %s\n",
4486                            cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4487                 goto error;
4488         }
4489
4490         cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
4491                              PROT_READ | PROT_WRITE, MAP_SHARED,
4492                              cpu_buf->fd, 0);
4493         if (cpu_buf->base == MAP_FAILED) {
4494                 cpu_buf->base = NULL;
4495                 err = -errno;
4496                 pr_warning("failed to mmap perf buffer on cpu #%d: %s\n",
4497                            cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4498                 goto error;
4499         }
4500
4501         if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
4502                 err = -errno;
4503                 pr_warning("failed to enable perf buffer event on cpu #%d: %s\n",
4504                            cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
4505                 goto error;
4506         }
4507
4508         return cpu_buf;
4509
4510 error:
4511         perf_buffer__free_cpu_buf(pb, cpu_buf);
4512         return (struct perf_cpu_buf *)ERR_PTR(err);
4513 }
4514
4515 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
4516                                               struct perf_buffer_params *p);
4517
4518 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
4519                                      const struct perf_buffer_opts *opts)
4520 {
4521         struct perf_buffer_params p = {};
4522         struct perf_event_attr attr = { 0, };
4523
4524         attr.config = PERF_COUNT_SW_BPF_OUTPUT,
4525         attr.type = PERF_TYPE_SOFTWARE;
4526         attr.sample_type = PERF_SAMPLE_RAW;
4527         attr.sample_period = 1;
4528         attr.wakeup_events = 1;
4529
4530         p.attr = &attr;
4531         p.sample_cb = opts ? opts->sample_cb : NULL;
4532         p.lost_cb = opts ? opts->lost_cb : NULL;
4533         p.ctx = opts ? opts->ctx : NULL;
4534
4535         return __perf_buffer__new(map_fd, page_cnt, &p);
4536 }
4537
4538 struct perf_buffer *
4539 perf_buffer__new_raw(int map_fd, size_t page_cnt,
4540                      const struct perf_buffer_raw_opts *opts)
4541 {
4542         struct perf_buffer_params p = {};
4543
4544         p.attr = opts->attr;
4545         p.event_cb = opts->event_cb;
4546         p.ctx = opts->ctx;
4547         p.cpu_cnt = opts->cpu_cnt;
4548         p.cpus = opts->cpus;
4549         p.map_keys = opts->map_keys;
4550
4551         return __perf_buffer__new(map_fd, page_cnt, &p);
4552 }
4553
4554 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
4555                                               struct perf_buffer_params *p)
4556 {
4557         struct bpf_map_info map = {};
4558         char msg[STRERR_BUFSIZE];
4559         struct perf_buffer *pb;
4560         __u32 map_info_len;
4561         int err, i;
4562
4563         if (page_cnt & (page_cnt - 1)) {
4564                 pr_warning("page count should be power of two, but is %zu\n",
4565                            page_cnt);
4566                 return ERR_PTR(-EINVAL);
4567         }
4568
4569         map_info_len = sizeof(map);
4570         err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
4571         if (err) {
4572                 err = -errno;
4573                 pr_warning("failed to get map info for map FD %d: %s\n",
4574                            map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
4575                 return ERR_PTR(err);
4576         }
4577
4578         if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
4579                 pr_warning("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
4580                            map.name);
4581                 return ERR_PTR(-EINVAL);
4582         }
4583
4584         pb = calloc(1, sizeof(*pb));
4585         if (!pb)
4586                 return ERR_PTR(-ENOMEM);
4587
4588         pb->event_cb = p->event_cb;
4589         pb->sample_cb = p->sample_cb;
4590         pb->lost_cb = p->lost_cb;
4591         pb->ctx = p->ctx;
4592
4593         pb->page_size = getpagesize();
4594         pb->mmap_size = pb->page_size * page_cnt;
4595         pb->map_fd = map_fd;
4596
4597         pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
4598         if (pb->epoll_fd < 0) {
4599                 err = -errno;
4600                 pr_warning("failed to create epoll instance: %s\n",
4601                            libbpf_strerror_r(err, msg, sizeof(msg)));
4602                 goto error;
4603         }
4604
4605         if (p->cpu_cnt > 0) {
4606                 pb->cpu_cnt = p->cpu_cnt;
4607         } else {
4608                 pb->cpu_cnt = libbpf_num_possible_cpus();
4609                 if (pb->cpu_cnt < 0) {
4610                         err = pb->cpu_cnt;
4611                         goto error;
4612                 }
4613                 if (map.max_entries < pb->cpu_cnt)
4614                         pb->cpu_cnt = map.max_entries;
4615         }
4616
4617         pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
4618         if (!pb->events) {
4619                 err = -ENOMEM;
4620                 pr_warning("failed to allocate events: out of memory\n");
4621                 goto error;
4622         }
4623         pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
4624         if (!pb->cpu_bufs) {
4625                 err = -ENOMEM;
4626                 pr_warning("failed to allocate buffers: out of memory\n");
4627                 goto error;
4628         }
4629
4630         for (i = 0; i < pb->cpu_cnt; i++) {
4631                 struct perf_cpu_buf *cpu_buf;
4632                 int cpu, map_key;
4633
4634                 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
4635                 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
4636
4637                 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
4638                 if (IS_ERR(cpu_buf)) {
4639                         err = PTR_ERR(cpu_buf);
4640                         goto error;
4641                 }
4642
4643                 pb->cpu_bufs[i] = cpu_buf;
4644
4645                 err = bpf_map_update_elem(pb->map_fd, &map_key,
4646                                           &cpu_buf->fd, 0);
4647                 if (err) {
4648                         err = -errno;
4649                         pr_warning("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
4650                                    cpu, map_key, cpu_buf->fd,
4651                                    libbpf_strerror_r(err, msg, sizeof(msg)));
4652                         goto error;
4653                 }
4654
4655                 pb->events[i].events = EPOLLIN;
4656                 pb->events[i].data.ptr = cpu_buf;
4657                 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
4658                               &pb->events[i]) < 0) {
4659                         err = -errno;
4660                         pr_warning("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
4661                                    cpu, cpu_buf->fd,
4662                                    libbpf_strerror_r(err, msg, sizeof(msg)));
4663                         goto error;
4664                 }
4665         }
4666
4667         return pb;
4668
4669 error:
4670         if (pb)
4671                 perf_buffer__free(pb);
4672         return ERR_PTR(err);
4673 }
4674
4675 struct perf_sample_raw {
4676         struct perf_event_header header;
4677         uint32_t size;
4678         char data[0];
4679 };
4680
4681 struct perf_sample_lost {
4682         struct perf_event_header header;
4683         uint64_t id;
4684         uint64_t lost;
4685         uint64_t sample_id;
4686 };
4687
4688 static enum bpf_perf_event_ret
4689 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
4690 {
4691         struct perf_cpu_buf *cpu_buf = ctx;
4692         struct perf_buffer *pb = cpu_buf->pb;
4693         void *data = e;
4694
4695         /* user wants full control over parsing perf event */
4696         if (pb->event_cb)
4697                 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
4698
4699         switch (e->type) {
4700         case PERF_RECORD_SAMPLE: {
4701                 struct perf_sample_raw *s = data;
4702
4703                 if (pb->sample_cb)
4704                         pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
4705                 break;
4706         }
4707         case PERF_RECORD_LOST: {
4708                 struct perf_sample_lost *s = data;
4709
4710                 if (pb->lost_cb)
4711                         pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
4712                 break;
4713         }
4714         default:
4715                 pr_warning("unknown perf sample type %d\n", e->type);
4716                 return LIBBPF_PERF_EVENT_ERROR;
4717         }
4718         return LIBBPF_PERF_EVENT_CONT;
4719 }
4720
4721 static int perf_buffer__process_records(struct perf_buffer *pb,
4722                                         struct perf_cpu_buf *cpu_buf)
4723 {
4724         enum bpf_perf_event_ret ret;
4725
4726         ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
4727                                          pb->page_size, &cpu_buf->buf,
4728                                          &cpu_buf->buf_size,
4729                                          perf_buffer__process_record, cpu_buf);
4730         if (ret != LIBBPF_PERF_EVENT_CONT)
4731                 return ret;
4732         return 0;
4733 }
4734
4735 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
4736 {
4737         int i, cnt, err;
4738
4739         cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
4740         for (i = 0; i < cnt; i++) {
4741                 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
4742
4743                 err = perf_buffer__process_records(pb, cpu_buf);
4744                 if (err) {
4745                         pr_warning("error while processing records: %d\n", err);
4746                         return err;
4747                 }
4748         }
4749         return cnt < 0 ? -errno : cnt;
4750 }
4751
4752 struct bpf_prog_info_array_desc {
4753         int     array_offset;   /* e.g. offset of jited_prog_insns */
4754         int     count_offset;   /* e.g. offset of jited_prog_len */
4755         int     size_offset;    /* > 0: offset of rec size,
4756                                  * < 0: fix size of -size_offset
4757                                  */
4758 };
4759
4760 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
4761         [BPF_PROG_INFO_JITED_INSNS] = {
4762                 offsetof(struct bpf_prog_info, jited_prog_insns),
4763                 offsetof(struct bpf_prog_info, jited_prog_len),
4764                 -1,
4765         },
4766         [BPF_PROG_INFO_XLATED_INSNS] = {
4767                 offsetof(struct bpf_prog_info, xlated_prog_insns),
4768                 offsetof(struct bpf_prog_info, xlated_prog_len),
4769                 -1,
4770         },
4771         [BPF_PROG_INFO_MAP_IDS] = {
4772                 offsetof(struct bpf_prog_info, map_ids),
4773                 offsetof(struct bpf_prog_info, nr_map_ids),
4774                 -(int)sizeof(__u32),
4775         },
4776         [BPF_PROG_INFO_JITED_KSYMS] = {
4777                 offsetof(struct bpf_prog_info, jited_ksyms),
4778                 offsetof(struct bpf_prog_info, nr_jited_ksyms),
4779                 -(int)sizeof(__u64),
4780         },
4781         [BPF_PROG_INFO_JITED_FUNC_LENS] = {
4782                 offsetof(struct bpf_prog_info, jited_func_lens),
4783                 offsetof(struct bpf_prog_info, nr_jited_func_lens),
4784                 -(int)sizeof(__u32),
4785         },
4786         [BPF_PROG_INFO_FUNC_INFO] = {
4787                 offsetof(struct bpf_prog_info, func_info),
4788                 offsetof(struct bpf_prog_info, nr_func_info),
4789                 offsetof(struct bpf_prog_info, func_info_rec_size),
4790         },
4791         [BPF_PROG_INFO_LINE_INFO] = {
4792                 offsetof(struct bpf_prog_info, line_info),
4793                 offsetof(struct bpf_prog_info, nr_line_info),
4794                 offsetof(struct bpf_prog_info, line_info_rec_size),
4795         },
4796         [BPF_PROG_INFO_JITED_LINE_INFO] = {
4797                 offsetof(struct bpf_prog_info, jited_line_info),
4798                 offsetof(struct bpf_prog_info, nr_jited_line_info),
4799                 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
4800         },
4801         [BPF_PROG_INFO_PROG_TAGS] = {
4802                 offsetof(struct bpf_prog_info, prog_tags),
4803                 offsetof(struct bpf_prog_info, nr_prog_tags),
4804                 -(int)sizeof(__u8) * BPF_TAG_SIZE,
4805         },
4806
4807 };
4808
4809 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
4810 {
4811         __u32 *array = (__u32 *)info;
4812
4813         if (offset >= 0)
4814                 return array[offset / sizeof(__u32)];
4815         return -(int)offset;
4816 }
4817
4818 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
4819 {
4820         __u64 *array = (__u64 *)info;
4821
4822         if (offset >= 0)
4823                 return array[offset / sizeof(__u64)];
4824         return -(int)offset;
4825 }
4826
4827 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
4828                                          __u32 val)
4829 {
4830         __u32 *array = (__u32 *)info;
4831
4832         if (offset >= 0)
4833                 array[offset / sizeof(__u32)] = val;
4834 }
4835
4836 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
4837                                          __u64 val)
4838 {
4839         __u64 *array = (__u64 *)info;
4840
4841         if (offset >= 0)
4842                 array[offset / sizeof(__u64)] = val;
4843 }
4844
4845 struct bpf_prog_info_linear *
4846 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
4847 {
4848         struct bpf_prog_info_linear *info_linear;
4849         struct bpf_prog_info info = {};
4850         __u32 info_len = sizeof(info);
4851         __u32 data_len = 0;
4852         int i, err;
4853         void *ptr;
4854
4855         if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
4856                 return ERR_PTR(-EINVAL);
4857
4858         /* step 1: get array dimensions */
4859         err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
4860         if (err) {
4861                 pr_debug("can't get prog info: %s", strerror(errno));
4862                 return ERR_PTR(-EFAULT);
4863         }
4864
4865         /* step 2: calculate total size of all arrays */
4866         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4867                 bool include_array = (arrays & (1UL << i)) > 0;
4868                 struct bpf_prog_info_array_desc *desc;
4869                 __u32 count, size;
4870
4871                 desc = bpf_prog_info_array_desc + i;
4872
4873                 /* kernel is too old to support this field */
4874                 if (info_len < desc->array_offset + sizeof(__u32) ||
4875                     info_len < desc->count_offset + sizeof(__u32) ||
4876                     (desc->size_offset > 0 && info_len < desc->size_offset))
4877                         include_array = false;
4878
4879                 if (!include_array) {
4880                         arrays &= ~(1UL << i);  /* clear the bit */
4881                         continue;
4882                 }
4883
4884                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4885                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4886
4887                 data_len += count * size;
4888         }
4889
4890         /* step 3: allocate continuous memory */
4891         data_len = roundup(data_len, sizeof(__u64));
4892         info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
4893         if (!info_linear)
4894                 return ERR_PTR(-ENOMEM);
4895
4896         /* step 4: fill data to info_linear->info */
4897         info_linear->arrays = arrays;
4898         memset(&info_linear->info, 0, sizeof(info));
4899         ptr = info_linear->data;
4900
4901         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4902                 struct bpf_prog_info_array_desc *desc;
4903                 __u32 count, size;
4904
4905                 if ((arrays & (1UL << i)) == 0)
4906                         continue;
4907
4908                 desc  = bpf_prog_info_array_desc + i;
4909                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4910                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4911                 bpf_prog_info_set_offset_u32(&info_linear->info,
4912                                              desc->count_offset, count);
4913                 bpf_prog_info_set_offset_u32(&info_linear->info,
4914                                              desc->size_offset, size);
4915                 bpf_prog_info_set_offset_u64(&info_linear->info,
4916                                              desc->array_offset,
4917                                              ptr_to_u64(ptr));
4918                 ptr += count * size;
4919         }
4920
4921         /* step 5: call syscall again to get required arrays */
4922         err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
4923         if (err) {
4924                 pr_debug("can't get prog info: %s", strerror(errno));
4925                 free(info_linear);
4926                 return ERR_PTR(-EFAULT);
4927         }
4928
4929         /* step 6: verify the data */
4930         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4931                 struct bpf_prog_info_array_desc *desc;
4932                 __u32 v1, v2;
4933
4934                 if ((arrays & (1UL << i)) == 0)
4935                         continue;
4936
4937                 desc = bpf_prog_info_array_desc + i;
4938                 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
4939                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4940                                                    desc->count_offset);
4941                 if (v1 != v2)
4942                         pr_warning("%s: mismatch in element count\n", __func__);
4943
4944                 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
4945                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
4946                                                    desc->size_offset);
4947                 if (v1 != v2)
4948                         pr_warning("%s: mismatch in rec size\n", __func__);
4949         }
4950
4951         /* step 7: update info_len and data_len */
4952         info_linear->info_len = sizeof(struct bpf_prog_info);
4953         info_linear->data_len = data_len;
4954
4955         return info_linear;
4956 }
4957
4958 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
4959 {
4960         int i;
4961
4962         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4963                 struct bpf_prog_info_array_desc *desc;
4964                 __u64 addr, offs;
4965
4966                 if ((info_linear->arrays & (1UL << i)) == 0)
4967                         continue;
4968
4969                 desc = bpf_prog_info_array_desc + i;
4970                 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
4971                                                      desc->array_offset);
4972                 offs = addr - ptr_to_u64(info_linear->data);
4973                 bpf_prog_info_set_offset_u64(&info_linear->info,
4974                                              desc->array_offset, offs);
4975         }
4976 }
4977
4978 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
4979 {
4980         int i;
4981
4982         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
4983                 struct bpf_prog_info_array_desc *desc;
4984                 __u64 addr, offs;
4985
4986                 if ((info_linear->arrays & (1UL << i)) == 0)
4987                         continue;
4988
4989                 desc = bpf_prog_info_array_desc + i;
4990                 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
4991                                                      desc->array_offset);
4992                 addr = offs + ptr_to_u64(info_linear->data);
4993                 bpf_prog_info_set_offset_u64(&info_linear->info,
4994                                              desc->array_offset, addr);
4995         }
4996 }
4997
4998 int libbpf_num_possible_cpus(void)
4999 {
5000         static const char *fcpu = "/sys/devices/system/cpu/possible";
5001         int len = 0, n = 0, il = 0, ir = 0;
5002         unsigned int start = 0, end = 0;
5003         static int cpus;
5004         char buf[128];
5005         int error = 0;
5006         int fd = -1;
5007
5008         if (cpus > 0)
5009                 return cpus;
5010
5011         fd = open(fcpu, O_RDONLY);
5012         if (fd < 0) {
5013                 error = errno;
5014                 pr_warning("Failed to open file %s: %s\n",
5015                            fcpu, strerror(error));
5016                 return -error;
5017         }
5018         len = read(fd, buf, sizeof(buf));
5019         close(fd);
5020         if (len <= 0) {
5021                 error = len ? errno : EINVAL;
5022                 pr_warning("Failed to read # of possible cpus from %s: %s\n",
5023                            fcpu, strerror(error));
5024                 return -error;
5025         }
5026         if (len == sizeof(buf)) {
5027                 pr_warning("File %s size overflow\n", fcpu);
5028                 return -EOVERFLOW;
5029         }
5030         buf[len] = '\0';
5031
5032         for (ir = 0, cpus = 0; ir <= len; ir++) {
5033                 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
5034                 if (buf[ir] == ',' || buf[ir] == '\0') {
5035                         buf[ir] = '\0';
5036                         n = sscanf(&buf[il], "%u-%u", &start, &end);
5037                         if (n <= 0) {
5038                                 pr_warning("Failed to get # CPUs from %s\n",
5039                                            &buf[il]);
5040                                 return -EINVAL;
5041                         } else if (n == 1) {
5042                                 end = start;
5043                         }
5044                         cpus += end - start + 1;
5045                         il = ir + 1;
5046                 }
5047         }
5048         if (cpus <= 0) {
5049                 pr_warning("Invalid #CPUs %d from %s\n", cpus, fcpu);
5050                 return -EINVAL;
5051         }
5052         return cpus;
5053 }