libbpf: Add bpf_link__disconnect() API to preserve underlying BPF resource
[linux-2.6-microblaze.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 <linux/version.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <tools/libc_compat.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "str_error.h"
54 #include "libbpf_internal.h"
55 #include "hashmap.h"
56
57 #ifndef EM_BPF
58 #define EM_BPF 247
59 #endif
60
61 #ifndef BPF_FS_MAGIC
62 #define BPF_FS_MAGIC            0xcafe4a11
63 #endif
64
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66  * compilation if user enables corresponding warning. Disable it explicitly.
67  */
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
69
70 #define __printf(a, b)  __attribute__((format(printf, a, b)))
71
72 static int __base_pr(enum libbpf_print_level level, const char *format,
73                      va_list args)
74 {
75         if (level == LIBBPF_DEBUG)
76                 return 0;
77
78         return vfprintf(stderr, format, args);
79 }
80
81 static libbpf_print_fn_t __libbpf_pr = __base_pr;
82
83 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
84 {
85         libbpf_print_fn_t old_print_fn = __libbpf_pr;
86
87         __libbpf_pr = fn;
88         return old_print_fn;
89 }
90
91 __printf(2, 3)
92 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
93 {
94         va_list args;
95
96         if (!__libbpf_pr)
97                 return;
98
99         va_start(args, format);
100         __libbpf_pr(level, format, args);
101         va_end(args);
102 }
103
104 static void pr_perm_msg(int err)
105 {
106         struct rlimit limit;
107         char buf[100];
108
109         if (err != -EPERM || geteuid() != 0)
110                 return;
111
112         err = getrlimit(RLIMIT_MEMLOCK, &limit);
113         if (err)
114                 return;
115
116         if (limit.rlim_cur == RLIM_INFINITY)
117                 return;
118
119         if (limit.rlim_cur < 1024)
120                 snprintf(buf, sizeof(buf), "%lu bytes", limit.rlim_cur);
121         else if (limit.rlim_cur < 1024*1024)
122                 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
123         else
124                 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
125
126         pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
127                 buf);
128 }
129
130 #define STRERR_BUFSIZE  128
131
132 /* Copied from tools/perf/util/util.h */
133 #ifndef zfree
134 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
135 #endif
136
137 #ifndef zclose
138 # define zclose(fd) ({                  \
139         int ___err = 0;                 \
140         if ((fd) >= 0)                  \
141                 ___err = close((fd));   \
142         fd = -1;                        \
143         ___err; })
144 #endif
145
146 #ifdef HAVE_LIBELF_MMAP_SUPPORT
147 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
148 #else
149 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
150 #endif
151
152 static inline __u64 ptr_to_u64(const void *ptr)
153 {
154         return (__u64) (unsigned long) ptr;
155 }
156
157 struct bpf_capabilities {
158         /* v4.14: kernel support for program & map names. */
159         __u32 name:1;
160         /* v5.2: kernel support for global data sections. */
161         __u32 global_data:1;
162         /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
163         __u32 btf_func:1;
164         /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
165         __u32 btf_datasec:1;
166         /* BPF_F_MMAPABLE is supported for arrays */
167         __u32 array_mmap:1;
168 };
169
170 enum reloc_type {
171         RELO_LD64,
172         RELO_CALL,
173         RELO_DATA,
174         RELO_EXTERN,
175 };
176
177 struct reloc_desc {
178         enum reloc_type type;
179         int insn_idx;
180         int map_idx;
181         int sym_off;
182 };
183
184 /*
185  * bpf_prog should be a better name but it has been used in
186  * linux/filter.h.
187  */
188 struct bpf_program {
189         /* Index in elf obj file, for relocation use. */
190         int idx;
191         char *name;
192         int prog_ifindex;
193         char *section_name;
194         /* section_name with / replaced by _; makes recursive pinning
195          * in bpf_object__pin_programs easier
196          */
197         char *pin_name;
198         struct bpf_insn *insns;
199         size_t insns_cnt, main_prog_cnt;
200         enum bpf_prog_type type;
201
202         struct reloc_desc *reloc_desc;
203         int nr_reloc;
204         int log_level;
205
206         struct {
207                 int nr;
208                 int *fds;
209         } instances;
210         bpf_program_prep_t preprocessor;
211
212         struct bpf_object *obj;
213         void *priv;
214         bpf_program_clear_priv_t clear_priv;
215
216         enum bpf_attach_type expected_attach_type;
217         __u32 attach_btf_id;
218         __u32 attach_prog_fd;
219         void *func_info;
220         __u32 func_info_rec_size;
221         __u32 func_info_cnt;
222
223         struct bpf_capabilities *caps;
224
225         void *line_info;
226         __u32 line_info_rec_size;
227         __u32 line_info_cnt;
228         __u32 prog_flags;
229 };
230
231 #define DATA_SEC ".data"
232 #define BSS_SEC ".bss"
233 #define RODATA_SEC ".rodata"
234 #define EXTERN_SEC ".extern"
235
236 enum libbpf_map_type {
237         LIBBPF_MAP_UNSPEC,
238         LIBBPF_MAP_DATA,
239         LIBBPF_MAP_BSS,
240         LIBBPF_MAP_RODATA,
241         LIBBPF_MAP_EXTERN,
242 };
243
244 static const char * const libbpf_type_to_btf_name[] = {
245         [LIBBPF_MAP_DATA]       = DATA_SEC,
246         [LIBBPF_MAP_BSS]        = BSS_SEC,
247         [LIBBPF_MAP_RODATA]     = RODATA_SEC,
248         [LIBBPF_MAP_EXTERN]     = EXTERN_SEC,
249 };
250
251 struct bpf_map {
252         char *name;
253         int fd;
254         int sec_idx;
255         size_t sec_offset;
256         int map_ifindex;
257         int inner_map_fd;
258         struct bpf_map_def def;
259         __u32 btf_key_type_id;
260         __u32 btf_value_type_id;
261         void *priv;
262         bpf_map_clear_priv_t clear_priv;
263         enum libbpf_map_type libbpf_type;
264         void *mmaped;
265         char *pin_path;
266         bool pinned;
267         bool reused;
268 };
269
270 enum extern_type {
271         EXT_UNKNOWN,
272         EXT_CHAR,
273         EXT_BOOL,
274         EXT_INT,
275         EXT_TRISTATE,
276         EXT_CHAR_ARR,
277 };
278
279 struct extern_desc {
280         const char *name;
281         int sym_idx;
282         int btf_id;
283         enum extern_type type;
284         int sz;
285         int align;
286         int data_off;
287         bool is_signed;
288         bool is_weak;
289         bool is_set;
290 };
291
292 static LIST_HEAD(bpf_objects_list);
293
294 struct bpf_object {
295         char name[BPF_OBJ_NAME_LEN];
296         char license[64];
297         __u32 kern_version;
298
299         struct bpf_program *programs;
300         size_t nr_programs;
301         struct bpf_map *maps;
302         size_t nr_maps;
303         size_t maps_cap;
304
305         char *kconfig_path;
306         struct extern_desc *externs;
307         int nr_extern;
308         int extern_map_idx;
309
310         bool loaded;
311         bool has_pseudo_calls;
312         bool relaxed_core_relocs;
313
314         /*
315          * Information when doing elf related work. Only valid if fd
316          * is valid.
317          */
318         struct {
319                 int fd;
320                 const void *obj_buf;
321                 size_t obj_buf_sz;
322                 Elf *elf;
323                 GElf_Ehdr ehdr;
324                 Elf_Data *symbols;
325                 Elf_Data *data;
326                 Elf_Data *rodata;
327                 Elf_Data *bss;
328                 size_t strtabidx;
329                 struct {
330                         GElf_Shdr shdr;
331                         Elf_Data *data;
332                 } *reloc_sects;
333                 int nr_reloc_sects;
334                 int maps_shndx;
335                 int btf_maps_shndx;
336                 int text_shndx;
337                 int symbols_shndx;
338                 int data_shndx;
339                 int rodata_shndx;
340                 int bss_shndx;
341         } efile;
342         /*
343          * All loaded bpf_object is linked in a list, which is
344          * hidden to caller. bpf_objects__<func> handlers deal with
345          * all objects.
346          */
347         struct list_head list;
348
349         struct btf *btf;
350         struct btf_ext *btf_ext;
351
352         void *priv;
353         bpf_object_clear_priv_t clear_priv;
354
355         struct bpf_capabilities caps;
356
357         char path[];
358 };
359 #define obj_elf_valid(o)        ((o)->efile.elf)
360
361 void bpf_program__unload(struct bpf_program *prog)
362 {
363         int i;
364
365         if (!prog)
366                 return;
367
368         /*
369          * If the object is opened but the program was never loaded,
370          * it is possible that prog->instances.nr == -1.
371          */
372         if (prog->instances.nr > 0) {
373                 for (i = 0; i < prog->instances.nr; i++)
374                         zclose(prog->instances.fds[i]);
375         } else if (prog->instances.nr != -1) {
376                 pr_warn("Internal error: instances.nr is %d\n",
377                         prog->instances.nr);
378         }
379
380         prog->instances.nr = -1;
381         zfree(&prog->instances.fds);
382
383         zfree(&prog->func_info);
384         zfree(&prog->line_info);
385 }
386
387 static void bpf_program__exit(struct bpf_program *prog)
388 {
389         if (!prog)
390                 return;
391
392         if (prog->clear_priv)
393                 prog->clear_priv(prog, prog->priv);
394
395         prog->priv = NULL;
396         prog->clear_priv = NULL;
397
398         bpf_program__unload(prog);
399         zfree(&prog->name);
400         zfree(&prog->section_name);
401         zfree(&prog->pin_name);
402         zfree(&prog->insns);
403         zfree(&prog->reloc_desc);
404
405         prog->nr_reloc = 0;
406         prog->insns_cnt = 0;
407         prog->idx = -1;
408 }
409
410 static char *__bpf_program__pin_name(struct bpf_program *prog)
411 {
412         char *name, *p;
413
414         name = p = strdup(prog->section_name);
415         while ((p = strchr(p, '/')))
416                 *p = '_';
417
418         return name;
419 }
420
421 static int
422 bpf_program__init(void *data, size_t size, char *section_name, int idx,
423                   struct bpf_program *prog)
424 {
425         const size_t bpf_insn_sz = sizeof(struct bpf_insn);
426
427         if (size == 0 || size % bpf_insn_sz) {
428                 pr_warn("corrupted section '%s', size: %zu\n",
429                         section_name, size);
430                 return -EINVAL;
431         }
432
433         memset(prog, 0, sizeof(*prog));
434
435         prog->section_name = strdup(section_name);
436         if (!prog->section_name) {
437                 pr_warn("failed to alloc name for prog under section(%d) %s\n",
438                         idx, section_name);
439                 goto errout;
440         }
441
442         prog->pin_name = __bpf_program__pin_name(prog);
443         if (!prog->pin_name) {
444                 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
445                         idx, section_name);
446                 goto errout;
447         }
448
449         prog->insns = malloc(size);
450         if (!prog->insns) {
451                 pr_warn("failed to alloc insns for prog under section %s\n",
452                         section_name);
453                 goto errout;
454         }
455         prog->insns_cnt = size / bpf_insn_sz;
456         memcpy(prog->insns, data, size);
457         prog->idx = idx;
458         prog->instances.fds = NULL;
459         prog->instances.nr = -1;
460         prog->type = BPF_PROG_TYPE_UNSPEC;
461
462         return 0;
463 errout:
464         bpf_program__exit(prog);
465         return -ENOMEM;
466 }
467
468 static int
469 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
470                         char *section_name, int idx)
471 {
472         struct bpf_program prog, *progs;
473         int nr_progs, err;
474
475         err = bpf_program__init(data, size, section_name, idx, &prog);
476         if (err)
477                 return err;
478
479         prog.caps = &obj->caps;
480         progs = obj->programs;
481         nr_progs = obj->nr_programs;
482
483         progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
484         if (!progs) {
485                 /*
486                  * In this case the original obj->programs
487                  * is still valid, so don't need special treat for
488                  * bpf_close_object().
489                  */
490                 pr_warn("failed to alloc a new program under section '%s'\n",
491                         section_name);
492                 bpf_program__exit(&prog);
493                 return -ENOMEM;
494         }
495
496         pr_debug("found program %s\n", prog.section_name);
497         obj->programs = progs;
498         obj->nr_programs = nr_progs + 1;
499         prog.obj = obj;
500         progs[nr_progs] = prog;
501         return 0;
502 }
503
504 static int
505 bpf_object__init_prog_names(struct bpf_object *obj)
506 {
507         Elf_Data *symbols = obj->efile.symbols;
508         struct bpf_program *prog;
509         size_t pi, si;
510
511         for (pi = 0; pi < obj->nr_programs; pi++) {
512                 const char *name = NULL;
513
514                 prog = &obj->programs[pi];
515
516                 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
517                      si++) {
518                         GElf_Sym sym;
519
520                         if (!gelf_getsym(symbols, si, &sym))
521                                 continue;
522                         if (sym.st_shndx != prog->idx)
523                                 continue;
524                         if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
525                                 continue;
526
527                         name = elf_strptr(obj->efile.elf,
528                                           obj->efile.strtabidx,
529                                           sym.st_name);
530                         if (!name) {
531                                 pr_warn("failed to get sym name string for prog %s\n",
532                                         prog->section_name);
533                                 return -LIBBPF_ERRNO__LIBELF;
534                         }
535                 }
536
537                 if (!name && prog->idx == obj->efile.text_shndx)
538                         name = ".text";
539
540                 if (!name) {
541                         pr_warn("failed to find sym for prog %s\n",
542                                 prog->section_name);
543                         return -EINVAL;
544                 }
545
546                 prog->name = strdup(name);
547                 if (!prog->name) {
548                         pr_warn("failed to allocate memory for prog sym %s\n",
549                                 name);
550                         return -ENOMEM;
551                 }
552         }
553
554         return 0;
555 }
556
557 static __u32 get_kernel_version(void)
558 {
559         __u32 major, minor, patch;
560         struct utsname info;
561
562         uname(&info);
563         if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
564                 return 0;
565         return KERNEL_VERSION(major, minor, patch);
566 }
567
568 static struct bpf_object *bpf_object__new(const char *path,
569                                           const void *obj_buf,
570                                           size_t obj_buf_sz,
571                                           const char *obj_name)
572 {
573         struct bpf_object *obj;
574         char *end;
575
576         obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
577         if (!obj) {
578                 pr_warn("alloc memory failed for %s\n", path);
579                 return ERR_PTR(-ENOMEM);
580         }
581
582         strcpy(obj->path, path);
583         if (obj_name) {
584                 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
585                 obj->name[sizeof(obj->name) - 1] = 0;
586         } else {
587                 /* Using basename() GNU version which doesn't modify arg. */
588                 strncpy(obj->name, basename((void *)path),
589                         sizeof(obj->name) - 1);
590                 end = strchr(obj->name, '.');
591                 if (end)
592                         *end = 0;
593         }
594
595         obj->efile.fd = -1;
596         /*
597          * Caller of this function should also call
598          * bpf_object__elf_finish() after data collection to return
599          * obj_buf to user. If not, we should duplicate the buffer to
600          * avoid user freeing them before elf finish.
601          */
602         obj->efile.obj_buf = obj_buf;
603         obj->efile.obj_buf_sz = obj_buf_sz;
604         obj->efile.maps_shndx = -1;
605         obj->efile.btf_maps_shndx = -1;
606         obj->efile.data_shndx = -1;
607         obj->efile.rodata_shndx = -1;
608         obj->efile.bss_shndx = -1;
609         obj->extern_map_idx = -1;
610
611         obj->kern_version = get_kernel_version();
612         obj->loaded = false;
613
614         INIT_LIST_HEAD(&obj->list);
615         list_add(&obj->list, &bpf_objects_list);
616         return obj;
617 }
618
619 static void bpf_object__elf_finish(struct bpf_object *obj)
620 {
621         if (!obj_elf_valid(obj))
622                 return;
623
624         if (obj->efile.elf) {
625                 elf_end(obj->efile.elf);
626                 obj->efile.elf = NULL;
627         }
628         obj->efile.symbols = NULL;
629         obj->efile.data = NULL;
630         obj->efile.rodata = NULL;
631         obj->efile.bss = NULL;
632
633         zfree(&obj->efile.reloc_sects);
634         obj->efile.nr_reloc_sects = 0;
635         zclose(obj->efile.fd);
636         obj->efile.obj_buf = NULL;
637         obj->efile.obj_buf_sz = 0;
638 }
639
640 static int bpf_object__elf_init(struct bpf_object *obj)
641 {
642         int err = 0;
643         GElf_Ehdr *ep;
644
645         if (obj_elf_valid(obj)) {
646                 pr_warn("elf init: internal error\n");
647                 return -LIBBPF_ERRNO__LIBELF;
648         }
649
650         if (obj->efile.obj_buf_sz > 0) {
651                 /*
652                  * obj_buf should have been validated by
653                  * bpf_object__open_buffer().
654                  */
655                 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
656                                             obj->efile.obj_buf_sz);
657         } else {
658                 obj->efile.fd = open(obj->path, O_RDONLY);
659                 if (obj->efile.fd < 0) {
660                         char errmsg[STRERR_BUFSIZE], *cp;
661
662                         err = -errno;
663                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
664                         pr_warn("failed to open %s: %s\n", obj->path, cp);
665                         return err;
666                 }
667
668                 obj->efile.elf = elf_begin(obj->efile.fd,
669                                            LIBBPF_ELF_C_READ_MMAP, NULL);
670         }
671
672         if (!obj->efile.elf) {
673                 pr_warn("failed to open %s as ELF file\n", obj->path);
674                 err = -LIBBPF_ERRNO__LIBELF;
675                 goto errout;
676         }
677
678         if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
679                 pr_warn("failed to get EHDR from %s\n", obj->path);
680                 err = -LIBBPF_ERRNO__FORMAT;
681                 goto errout;
682         }
683         ep = &obj->efile.ehdr;
684
685         /* Old LLVM set e_machine to EM_NONE */
686         if (ep->e_type != ET_REL ||
687             (ep->e_machine && ep->e_machine != EM_BPF)) {
688                 pr_warn("%s is not an eBPF object file\n", obj->path);
689                 err = -LIBBPF_ERRNO__FORMAT;
690                 goto errout;
691         }
692
693         return 0;
694 errout:
695         bpf_object__elf_finish(obj);
696         return err;
697 }
698
699 static int bpf_object__check_endianness(struct bpf_object *obj)
700 {
701 #if __BYTE_ORDER == __LITTLE_ENDIAN
702         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
703                 return 0;
704 #elif __BYTE_ORDER == __BIG_ENDIAN
705         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
706                 return 0;
707 #else
708 # error "Unrecognized __BYTE_ORDER__"
709 #endif
710         pr_warn("endianness mismatch.\n");
711         return -LIBBPF_ERRNO__ENDIAN;
712 }
713
714 static int
715 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
716 {
717         memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
718         pr_debug("license of %s is %s\n", obj->path, obj->license);
719         return 0;
720 }
721
722 static int
723 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
724 {
725         __u32 kver;
726
727         if (size != sizeof(kver)) {
728                 pr_warn("invalid kver section in %s\n", obj->path);
729                 return -LIBBPF_ERRNO__FORMAT;
730         }
731         memcpy(&kver, data, sizeof(kver));
732         obj->kern_version = kver;
733         pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
734         return 0;
735 }
736
737 static int compare_bpf_map(const void *_a, const void *_b)
738 {
739         const struct bpf_map *a = _a;
740         const struct bpf_map *b = _b;
741
742         if (a->sec_idx != b->sec_idx)
743                 return a->sec_idx - b->sec_idx;
744         return a->sec_offset - b->sec_offset;
745 }
746
747 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
748 {
749         if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
750             type == BPF_MAP_TYPE_HASH_OF_MAPS)
751                 return true;
752         return false;
753 }
754
755 static int bpf_object_search_section_size(const struct bpf_object *obj,
756                                           const char *name, size_t *d_size)
757 {
758         const GElf_Ehdr *ep = &obj->efile.ehdr;
759         Elf *elf = obj->efile.elf;
760         Elf_Scn *scn = NULL;
761         int idx = 0;
762
763         while ((scn = elf_nextscn(elf, scn)) != NULL) {
764                 const char *sec_name;
765                 Elf_Data *data;
766                 GElf_Shdr sh;
767
768                 idx++;
769                 if (gelf_getshdr(scn, &sh) != &sh) {
770                         pr_warn("failed to get section(%d) header from %s\n",
771                                 idx, obj->path);
772                         return -EIO;
773                 }
774
775                 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
776                 if (!sec_name) {
777                         pr_warn("failed to get section(%d) name from %s\n",
778                                 idx, obj->path);
779                         return -EIO;
780                 }
781
782                 if (strcmp(name, sec_name))
783                         continue;
784
785                 data = elf_getdata(scn, 0);
786                 if (!data) {
787                         pr_warn("failed to get section(%d) data from %s(%s)\n",
788                                 idx, name, obj->path);
789                         return -EIO;
790                 }
791
792                 *d_size = data->d_size;
793                 return 0;
794         }
795
796         return -ENOENT;
797 }
798
799 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
800                              __u32 *size)
801 {
802         int ret = -ENOENT;
803         size_t d_size;
804
805         *size = 0;
806         if (!name) {
807                 return -EINVAL;
808         } else if (!strcmp(name, DATA_SEC)) {
809                 if (obj->efile.data)
810                         *size = obj->efile.data->d_size;
811         } else if (!strcmp(name, BSS_SEC)) {
812                 if (obj->efile.bss)
813                         *size = obj->efile.bss->d_size;
814         } else if (!strcmp(name, RODATA_SEC)) {
815                 if (obj->efile.rodata)
816                         *size = obj->efile.rodata->d_size;
817         } else {
818                 ret = bpf_object_search_section_size(obj, name, &d_size);
819                 if (!ret)
820                         *size = d_size;
821         }
822
823         return *size ? 0 : ret;
824 }
825
826 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
827                                 __u32 *off)
828 {
829         Elf_Data *symbols = obj->efile.symbols;
830         const char *sname;
831         size_t si;
832
833         if (!name || !off)
834                 return -EINVAL;
835
836         for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
837                 GElf_Sym sym;
838
839                 if (!gelf_getsym(symbols, si, &sym))
840                         continue;
841                 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
842                     GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
843                         continue;
844
845                 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
846                                    sym.st_name);
847                 if (!sname) {
848                         pr_warn("failed to get sym name string for var %s\n",
849                                 name);
850                         return -EIO;
851                 }
852                 if (strcmp(name, sname) == 0) {
853                         *off = sym.st_value;
854                         return 0;
855                 }
856         }
857
858         return -ENOENT;
859 }
860
861 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
862 {
863         struct bpf_map *new_maps;
864         size_t new_cap;
865         int i;
866
867         if (obj->nr_maps < obj->maps_cap)
868                 return &obj->maps[obj->nr_maps++];
869
870         new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
871         new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
872         if (!new_maps) {
873                 pr_warn("alloc maps for object failed\n");
874                 return ERR_PTR(-ENOMEM);
875         }
876
877         obj->maps_cap = new_cap;
878         obj->maps = new_maps;
879
880         /* zero out new maps */
881         memset(obj->maps + obj->nr_maps, 0,
882                (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
883         /*
884          * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
885          * when failure (zclose won't close negative fd)).
886          */
887         for (i = obj->nr_maps; i < obj->maps_cap; i++) {
888                 obj->maps[i].fd = -1;
889                 obj->maps[i].inner_map_fd = -1;
890         }
891
892         return &obj->maps[obj->nr_maps++];
893 }
894
895 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
896 {
897         long page_sz = sysconf(_SC_PAGE_SIZE);
898         size_t map_sz;
899
900         map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
901         map_sz = roundup(map_sz, page_sz);
902         return map_sz;
903 }
904
905 static int
906 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
907                               int sec_idx, void *data, size_t data_sz)
908 {
909         char map_name[BPF_OBJ_NAME_LEN];
910         struct bpf_map_def *def;
911         struct bpf_map *map;
912         int err;
913
914         map = bpf_object__add_map(obj);
915         if (IS_ERR(map))
916                 return PTR_ERR(map);
917
918         map->libbpf_type = type;
919         map->sec_idx = sec_idx;
920         map->sec_offset = 0;
921         snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
922                  libbpf_type_to_btf_name[type]);
923         map->name = strdup(map_name);
924         if (!map->name) {
925                 pr_warn("failed to alloc map name\n");
926                 return -ENOMEM;
927         }
928
929         def = &map->def;
930         def->type = BPF_MAP_TYPE_ARRAY;
931         def->key_size = sizeof(int);
932         def->value_size = data_sz;
933         def->max_entries = 1;
934         def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_EXTERN
935                          ? BPF_F_RDONLY_PROG : 0;
936         def->map_flags |= BPF_F_MMAPABLE;
937
938         pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
939                  map_name, map->sec_idx, map->sec_offset, def->map_flags);
940
941         map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
942                            MAP_SHARED | MAP_ANONYMOUS, -1, 0);
943         if (map->mmaped == MAP_FAILED) {
944                 err = -errno;
945                 map->mmaped = NULL;
946                 pr_warn("failed to alloc map '%s' content buffer: %d\n",
947                         map->name, err);
948                 zfree(&map->name);
949                 return err;
950         }
951
952         if (data)
953                 memcpy(map->mmaped, data, data_sz);
954
955         pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
956         return 0;
957 }
958
959 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
960 {
961         int err;
962
963         /*
964          * Populate obj->maps with libbpf internal maps.
965          */
966         if (obj->efile.data_shndx >= 0) {
967                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
968                                                     obj->efile.data_shndx,
969                                                     obj->efile.data->d_buf,
970                                                     obj->efile.data->d_size);
971                 if (err)
972                         return err;
973         }
974         if (obj->efile.rodata_shndx >= 0) {
975                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
976                                                     obj->efile.rodata_shndx,
977                                                     obj->efile.rodata->d_buf,
978                                                     obj->efile.rodata->d_size);
979                 if (err)
980                         return err;
981         }
982         if (obj->efile.bss_shndx >= 0) {
983                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
984                                                     obj->efile.bss_shndx,
985                                                     NULL,
986                                                     obj->efile.bss->d_size);
987                 if (err)
988                         return err;
989         }
990         return 0;
991 }
992
993
994 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
995                                                const void *name)
996 {
997         int i;
998
999         for (i = 0; i < obj->nr_extern; i++) {
1000                 if (strcmp(obj->externs[i].name, name) == 0)
1001                         return &obj->externs[i];
1002         }
1003         return NULL;
1004 }
1005
1006 static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1007                              char value)
1008 {
1009         switch (ext->type) {
1010         case EXT_BOOL:
1011                 if (value == 'm') {
1012                         pr_warn("extern %s=%c should be tristate or char\n",
1013                                 ext->name, value);
1014                         return -EINVAL;
1015                 }
1016                 *(bool *)ext_val = value == 'y' ? true : false;
1017                 break;
1018         case EXT_TRISTATE:
1019                 if (value == 'y')
1020                         *(enum libbpf_tristate *)ext_val = TRI_YES;
1021                 else if (value == 'm')
1022                         *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1023                 else /* value == 'n' */
1024                         *(enum libbpf_tristate *)ext_val = TRI_NO;
1025                 break;
1026         case EXT_CHAR:
1027                 *(char *)ext_val = value;
1028                 break;
1029         case EXT_UNKNOWN:
1030         case EXT_INT:
1031         case EXT_CHAR_ARR:
1032         default:
1033                 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1034                         ext->name, value);
1035                 return -EINVAL;
1036         }
1037         ext->is_set = true;
1038         return 0;
1039 }
1040
1041 static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1042                              const char *value)
1043 {
1044         size_t len;
1045
1046         if (ext->type != EXT_CHAR_ARR) {
1047                 pr_warn("extern %s=%s should char array\n", ext->name, value);
1048                 return -EINVAL;
1049         }
1050
1051         len = strlen(value);
1052         if (value[len - 1] != '"') {
1053                 pr_warn("extern '%s': invalid string config '%s'\n",
1054                         ext->name, value);
1055                 return -EINVAL;
1056         }
1057
1058         /* strip quotes */
1059         len -= 2;
1060         if (len >= ext->sz) {
1061                 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1062                         ext->name, value, len, ext->sz - 1);
1063                 len = ext->sz - 1;
1064         }
1065         memcpy(ext_val, value + 1, len);
1066         ext_val[len] = '\0';
1067         ext->is_set = true;
1068         return 0;
1069 }
1070
1071 static int parse_u64(const char *value, __u64 *res)
1072 {
1073         char *value_end;
1074         int err;
1075
1076         errno = 0;
1077         *res = strtoull(value, &value_end, 0);
1078         if (errno) {
1079                 err = -errno;
1080                 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1081                 return err;
1082         }
1083         if (*value_end) {
1084                 pr_warn("failed to parse '%s' as integer completely\n", value);
1085                 return -EINVAL;
1086         }
1087         return 0;
1088 }
1089
1090 static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1091 {
1092         int bit_sz = ext->sz * 8;
1093
1094         if (ext->sz == 8)
1095                 return true;
1096
1097         /* Validate that value stored in u64 fits in integer of `ext->sz`
1098          * bytes size without any loss of information. If the target integer
1099          * is signed, we rely on the following limits of integer type of
1100          * Y bits and subsequent transformation:
1101          *
1102          *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1103          *            0 <= X + 2^(Y-1) <= 2^Y - 1
1104          *            0 <= X + 2^(Y-1) <  2^Y
1105          *
1106          *  For unsigned target integer, check that all the (64 - Y) bits are
1107          *  zero.
1108          */
1109         if (ext->is_signed)
1110                 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1111         else
1112                 return (v >> bit_sz) == 0;
1113 }
1114
1115 static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1116                              __u64 value)
1117 {
1118         if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1119                 pr_warn("extern %s=%llu should be integer\n",
1120                         ext->name, value);
1121                 return -EINVAL;
1122         }
1123         if (!is_ext_value_in_range(ext, value)) {
1124                 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1125                         ext->name, value, ext->sz);
1126                 return -ERANGE;
1127         }
1128         switch (ext->sz) {
1129                 case 1: *(__u8 *)ext_val = value; break;
1130                 case 2: *(__u16 *)ext_val = value; break;
1131                 case 4: *(__u32 *)ext_val = value; break;
1132                 case 8: *(__u64 *)ext_val = value; break;
1133                 default:
1134                         return -EINVAL;
1135         }
1136         ext->is_set = true;
1137         return 0;
1138 }
1139
1140 static int bpf_object__read_kernel_config(struct bpf_object *obj,
1141                                           const char *config_path,
1142                                           void *data)
1143 {
1144         char buf[PATH_MAX], *sep, *value;
1145         struct extern_desc *ext;
1146         int len, err = 0;
1147         void *ext_val;
1148         __u64 num;
1149         gzFile file;
1150
1151         if (config_path) {
1152                 file = gzopen(config_path, "r");
1153         } else {
1154                 struct utsname uts;
1155
1156                 uname(&uts);
1157                 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1158                 if (len < 0)
1159                         return -EINVAL;
1160                 else if (len >= PATH_MAX)
1161                         return -ENAMETOOLONG;
1162                 /* gzopen also accepts uncompressed files. */
1163                 file = gzopen(buf, "r");
1164                 if (!file)
1165                         file = gzopen("/proc/config.gz", "r");
1166         }
1167         if (!file) {
1168                 pr_warn("failed to read kernel config at '%s'\n", config_path);
1169                 return -ENOENT;
1170         }
1171
1172         while (gzgets(file, buf, sizeof(buf))) {
1173                 if (strncmp(buf, "CONFIG_", 7))
1174                         continue;
1175
1176                 sep = strchr(buf, '=');
1177                 if (!sep) {
1178                         err = -EINVAL;
1179                         pr_warn("failed to parse '%s': no separator\n", buf);
1180                         goto out;
1181                 }
1182                 /* Trim ending '\n' */
1183                 len = strlen(buf);
1184                 if (buf[len - 1] == '\n')
1185                         buf[len - 1] = '\0';
1186                 /* Split on '=' and ensure that a value is present. */
1187                 *sep = '\0';
1188                 if (!sep[1]) {
1189                         err = -EINVAL;
1190                         *sep = '=';
1191                         pr_warn("failed to parse '%s': no value\n", buf);
1192                         goto out;
1193                 }
1194
1195                 ext = find_extern_by_name(obj, buf);
1196                 if (!ext)
1197                         continue;
1198                 if (ext->is_set) {
1199                         err = -EINVAL;
1200                         pr_warn("re-defining extern '%s' not allowed\n", buf);
1201                         goto out;
1202                 }
1203
1204                 ext_val = data + ext->data_off;
1205                 value = sep + 1;
1206
1207                 switch (*value) {
1208                 case 'y': case 'n': case 'm':
1209                         err = set_ext_value_tri(ext, ext_val, *value);
1210                         break;
1211                 case '"':
1212                         err = set_ext_value_str(ext, ext_val, value);
1213                         break;
1214                 default:
1215                         /* assume integer */
1216                         err = parse_u64(value, &num);
1217                         if (err) {
1218                                 pr_warn("extern %s=%s should be integer\n",
1219                                         ext->name, value);
1220                                 goto out;
1221                         }
1222                         err = set_ext_value_num(ext, ext_val, num);
1223                         break;
1224                 }
1225                 if (err)
1226                         goto out;
1227                 pr_debug("extern %s=%s\n", ext->name, value);
1228         }
1229
1230 out:
1231         gzclose(file);
1232         return err;
1233 }
1234
1235 static int bpf_object__init_extern_map(struct bpf_object *obj)
1236 {
1237         struct extern_desc *last_ext;
1238         size_t map_sz;
1239         int err;
1240
1241         if (obj->nr_extern == 0)
1242                 return 0;
1243
1244         last_ext = &obj->externs[obj->nr_extern - 1];
1245         map_sz = last_ext->data_off + last_ext->sz;
1246
1247         err = bpf_object__init_internal_map(obj, LIBBPF_MAP_EXTERN,
1248                                             obj->efile.symbols_shndx,
1249                                             NULL, map_sz);
1250         if (err)
1251                 return err;
1252
1253         obj->extern_map_idx = obj->nr_maps - 1;
1254
1255         return 0;
1256 }
1257
1258 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1259 {
1260         Elf_Data *symbols = obj->efile.symbols;
1261         int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1262         Elf_Data *data = NULL;
1263         Elf_Scn *scn;
1264
1265         if (obj->efile.maps_shndx < 0)
1266                 return 0;
1267
1268         if (!symbols)
1269                 return -EINVAL;
1270
1271         scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1272         if (scn)
1273                 data = elf_getdata(scn, NULL);
1274         if (!scn || !data) {
1275                 pr_warn("failed to get Elf_Data from map section %d\n",
1276                         obj->efile.maps_shndx);
1277                 return -EINVAL;
1278         }
1279
1280         /*
1281          * Count number of maps. Each map has a name.
1282          * Array of maps is not supported: only the first element is
1283          * considered.
1284          *
1285          * TODO: Detect array of map and report error.
1286          */
1287         nr_syms = symbols->d_size / sizeof(GElf_Sym);
1288         for (i = 0; i < nr_syms; i++) {
1289                 GElf_Sym sym;
1290
1291                 if (!gelf_getsym(symbols, i, &sym))
1292                         continue;
1293                 if (sym.st_shndx != obj->efile.maps_shndx)
1294                         continue;
1295                 nr_maps++;
1296         }
1297         /* Assume equally sized map definitions */
1298         pr_debug("maps in %s: %d maps in %zd bytes\n",
1299                  obj->path, nr_maps, data->d_size);
1300
1301         if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1302                 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1303                         obj->path, nr_maps, data->d_size);
1304                 return -EINVAL;
1305         }
1306         map_def_sz = data->d_size / nr_maps;
1307
1308         /* Fill obj->maps using data in "maps" section.  */
1309         for (i = 0; i < nr_syms; i++) {
1310                 GElf_Sym sym;
1311                 const char *map_name;
1312                 struct bpf_map_def *def;
1313                 struct bpf_map *map;
1314
1315                 if (!gelf_getsym(symbols, i, &sym))
1316                         continue;
1317                 if (sym.st_shndx != obj->efile.maps_shndx)
1318                         continue;
1319
1320                 map = bpf_object__add_map(obj);
1321                 if (IS_ERR(map))
1322                         return PTR_ERR(map);
1323
1324                 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1325                                       sym.st_name);
1326                 if (!map_name) {
1327                         pr_warn("failed to get map #%d name sym string for obj %s\n",
1328                                 i, obj->path);
1329                         return -LIBBPF_ERRNO__FORMAT;
1330                 }
1331
1332                 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1333                 map->sec_idx = sym.st_shndx;
1334                 map->sec_offset = sym.st_value;
1335                 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1336                          map_name, map->sec_idx, map->sec_offset);
1337                 if (sym.st_value + map_def_sz > data->d_size) {
1338                         pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1339                                 obj->path, map_name);
1340                         return -EINVAL;
1341                 }
1342
1343                 map->name = strdup(map_name);
1344                 if (!map->name) {
1345                         pr_warn("failed to alloc map name\n");
1346                         return -ENOMEM;
1347                 }
1348                 pr_debug("map %d is \"%s\"\n", i, map->name);
1349                 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1350                 /*
1351                  * If the definition of the map in the object file fits in
1352                  * bpf_map_def, copy it.  Any extra fields in our version
1353                  * of bpf_map_def will default to zero as a result of the
1354                  * calloc above.
1355                  */
1356                 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1357                         memcpy(&map->def, def, map_def_sz);
1358                 } else {
1359                         /*
1360                          * Here the map structure being read is bigger than what
1361                          * we expect, truncate if the excess bits are all zero.
1362                          * If they are not zero, reject this map as
1363                          * incompatible.
1364                          */
1365                         char *b;
1366
1367                         for (b = ((char *)def) + sizeof(struct bpf_map_def);
1368                              b < ((char *)def) + map_def_sz; b++) {
1369                                 if (*b != 0) {
1370                                         pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1371                                                 obj->path, map_name);
1372                                         if (strict)
1373                                                 return -EINVAL;
1374                                 }
1375                         }
1376                         memcpy(&map->def, def, sizeof(struct bpf_map_def));
1377                 }
1378         }
1379         return 0;
1380 }
1381
1382 static const struct btf_type *
1383 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1384 {
1385         const struct btf_type *t = btf__type_by_id(btf, id);
1386
1387         if (res_id)
1388                 *res_id = id;
1389
1390         while (btf_is_mod(t) || btf_is_typedef(t)) {
1391                 if (res_id)
1392                         *res_id = t->type;
1393                 t = btf__type_by_id(btf, t->type);
1394         }
1395
1396         return t;
1397 }
1398
1399 /*
1400  * Fetch integer attribute of BTF map definition. Such attributes are
1401  * represented using a pointer to an array, in which dimensionality of array
1402  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1403  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1404  * type definition, while using only sizeof(void *) space in ELF data section.
1405  */
1406 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1407                               const struct btf_type *def,
1408                               const struct btf_member *m, __u32 *res)
1409 {
1410         const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1411         const char *name = btf__name_by_offset(btf, m->name_off);
1412         const struct btf_array *arr_info;
1413         const struct btf_type *arr_t;
1414
1415         if (!btf_is_ptr(t)) {
1416                 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1417                         map_name, name, btf_kind(t));
1418                 return false;
1419         }
1420
1421         arr_t = btf__type_by_id(btf, t->type);
1422         if (!arr_t) {
1423                 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1424                         map_name, name, t->type);
1425                 return false;
1426         }
1427         if (!btf_is_array(arr_t)) {
1428                 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1429                         map_name, name, btf_kind(arr_t));
1430                 return false;
1431         }
1432         arr_info = btf_array(arr_t);
1433         *res = arr_info->nelems;
1434         return true;
1435 }
1436
1437 static int build_map_pin_path(struct bpf_map *map, const char *path)
1438 {
1439         char buf[PATH_MAX];
1440         int err, len;
1441
1442         if (!path)
1443                 path = "/sys/fs/bpf";
1444
1445         len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1446         if (len < 0)
1447                 return -EINVAL;
1448         else if (len >= PATH_MAX)
1449                 return -ENAMETOOLONG;
1450
1451         err = bpf_map__set_pin_path(map, buf);
1452         if (err)
1453                 return err;
1454
1455         return 0;
1456 }
1457
1458 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1459                                          const struct btf_type *sec,
1460                                          int var_idx, int sec_idx,
1461                                          const Elf_Data *data, bool strict,
1462                                          const char *pin_root_path)
1463 {
1464         const struct btf_type *var, *def, *t;
1465         const struct btf_var_secinfo *vi;
1466         const struct btf_var *var_extra;
1467         const struct btf_member *m;
1468         const char *map_name;
1469         struct bpf_map *map;
1470         int vlen, i;
1471
1472         vi = btf_var_secinfos(sec) + var_idx;
1473         var = btf__type_by_id(obj->btf, vi->type);
1474         var_extra = btf_var(var);
1475         map_name = btf__name_by_offset(obj->btf, var->name_off);
1476         vlen = btf_vlen(var);
1477
1478         if (map_name == NULL || map_name[0] == '\0') {
1479                 pr_warn("map #%d: empty name.\n", var_idx);
1480                 return -EINVAL;
1481         }
1482         if ((__u64)vi->offset + vi->size > data->d_size) {
1483                 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1484                 return -EINVAL;
1485         }
1486         if (!btf_is_var(var)) {
1487                 pr_warn("map '%s': unexpected var kind %u.\n",
1488                         map_name, btf_kind(var));
1489                 return -EINVAL;
1490         }
1491         if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1492             var_extra->linkage != BTF_VAR_STATIC) {
1493                 pr_warn("map '%s': unsupported var linkage %u.\n",
1494                         map_name, var_extra->linkage);
1495                 return -EOPNOTSUPP;
1496         }
1497
1498         def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1499         if (!btf_is_struct(def)) {
1500                 pr_warn("map '%s': unexpected def kind %u.\n",
1501                         map_name, btf_kind(var));
1502                 return -EINVAL;
1503         }
1504         if (def->size > vi->size) {
1505                 pr_warn("map '%s': invalid def size.\n", map_name);
1506                 return -EINVAL;
1507         }
1508
1509         map = bpf_object__add_map(obj);
1510         if (IS_ERR(map))
1511                 return PTR_ERR(map);
1512         map->name = strdup(map_name);
1513         if (!map->name) {
1514                 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1515                 return -ENOMEM;
1516         }
1517         map->libbpf_type = LIBBPF_MAP_UNSPEC;
1518         map->def.type = BPF_MAP_TYPE_UNSPEC;
1519         map->sec_idx = sec_idx;
1520         map->sec_offset = vi->offset;
1521         pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1522                  map_name, map->sec_idx, map->sec_offset);
1523
1524         vlen = btf_vlen(def);
1525         m = btf_members(def);
1526         for (i = 0; i < vlen; i++, m++) {
1527                 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1528
1529                 if (!name) {
1530                         pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1531                         return -EINVAL;
1532                 }
1533                 if (strcmp(name, "type") == 0) {
1534                         if (!get_map_field_int(map_name, obj->btf, def, m,
1535                                                &map->def.type))
1536                                 return -EINVAL;
1537                         pr_debug("map '%s': found type = %u.\n",
1538                                  map_name, map->def.type);
1539                 } else if (strcmp(name, "max_entries") == 0) {
1540                         if (!get_map_field_int(map_name, obj->btf, def, m,
1541                                                &map->def.max_entries))
1542                                 return -EINVAL;
1543                         pr_debug("map '%s': found max_entries = %u.\n",
1544                                  map_name, map->def.max_entries);
1545                 } else if (strcmp(name, "map_flags") == 0) {
1546                         if (!get_map_field_int(map_name, obj->btf, def, m,
1547                                                &map->def.map_flags))
1548                                 return -EINVAL;
1549                         pr_debug("map '%s': found map_flags = %u.\n",
1550                                  map_name, map->def.map_flags);
1551                 } else if (strcmp(name, "key_size") == 0) {
1552                         __u32 sz;
1553
1554                         if (!get_map_field_int(map_name, obj->btf, def, m,
1555                                                &sz))
1556                                 return -EINVAL;
1557                         pr_debug("map '%s': found key_size = %u.\n",
1558                                  map_name, sz);
1559                         if (map->def.key_size && map->def.key_size != sz) {
1560                                 pr_warn("map '%s': conflicting key size %u != %u.\n",
1561                                         map_name, map->def.key_size, sz);
1562                                 return -EINVAL;
1563                         }
1564                         map->def.key_size = sz;
1565                 } else if (strcmp(name, "key") == 0) {
1566                         __s64 sz;
1567
1568                         t = btf__type_by_id(obj->btf, m->type);
1569                         if (!t) {
1570                                 pr_warn("map '%s': key type [%d] not found.\n",
1571                                         map_name, m->type);
1572                                 return -EINVAL;
1573                         }
1574                         if (!btf_is_ptr(t)) {
1575                                 pr_warn("map '%s': key spec is not PTR: %u.\n",
1576                                         map_name, btf_kind(t));
1577                                 return -EINVAL;
1578                         }
1579                         sz = btf__resolve_size(obj->btf, t->type);
1580                         if (sz < 0) {
1581                                 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1582                                         map_name, t->type, (ssize_t)sz);
1583                                 return sz;
1584                         }
1585                         pr_debug("map '%s': found key [%u], sz = %zd.\n",
1586                                  map_name, t->type, (ssize_t)sz);
1587                         if (map->def.key_size && map->def.key_size != sz) {
1588                                 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1589                                         map_name, map->def.key_size, (ssize_t)sz);
1590                                 return -EINVAL;
1591                         }
1592                         map->def.key_size = sz;
1593                         map->btf_key_type_id = t->type;
1594                 } else if (strcmp(name, "value_size") == 0) {
1595                         __u32 sz;
1596
1597                         if (!get_map_field_int(map_name, obj->btf, def, m,
1598                                                &sz))
1599                                 return -EINVAL;
1600                         pr_debug("map '%s': found value_size = %u.\n",
1601                                  map_name, sz);
1602                         if (map->def.value_size && map->def.value_size != sz) {
1603                                 pr_warn("map '%s': conflicting value size %u != %u.\n",
1604                                         map_name, map->def.value_size, sz);
1605                                 return -EINVAL;
1606                         }
1607                         map->def.value_size = sz;
1608                 } else if (strcmp(name, "value") == 0) {
1609                         __s64 sz;
1610
1611                         t = btf__type_by_id(obj->btf, m->type);
1612                         if (!t) {
1613                                 pr_warn("map '%s': value type [%d] not found.\n",
1614                                         map_name, m->type);
1615                                 return -EINVAL;
1616                         }
1617                         if (!btf_is_ptr(t)) {
1618                                 pr_warn("map '%s': value spec is not PTR: %u.\n",
1619                                         map_name, btf_kind(t));
1620                                 return -EINVAL;
1621                         }
1622                         sz = btf__resolve_size(obj->btf, t->type);
1623                         if (sz < 0) {
1624                                 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
1625                                         map_name, t->type, (ssize_t)sz);
1626                                 return sz;
1627                         }
1628                         pr_debug("map '%s': found value [%u], sz = %zd.\n",
1629                                  map_name, t->type, (ssize_t)sz);
1630                         if (map->def.value_size && map->def.value_size != sz) {
1631                                 pr_warn("map '%s': conflicting value size %u != %zd.\n",
1632                                         map_name, map->def.value_size, (ssize_t)sz);
1633                                 return -EINVAL;
1634                         }
1635                         map->def.value_size = sz;
1636                         map->btf_value_type_id = t->type;
1637                 } else if (strcmp(name, "pinning") == 0) {
1638                         __u32 val;
1639                         int err;
1640
1641                         if (!get_map_field_int(map_name, obj->btf, def, m,
1642                                                &val))
1643                                 return -EINVAL;
1644                         pr_debug("map '%s': found pinning = %u.\n",
1645                                  map_name, val);
1646
1647                         if (val != LIBBPF_PIN_NONE &&
1648                             val != LIBBPF_PIN_BY_NAME) {
1649                                 pr_warn("map '%s': invalid pinning value %u.\n",
1650                                         map_name, val);
1651                                 return -EINVAL;
1652                         }
1653                         if (val == LIBBPF_PIN_BY_NAME) {
1654                                 err = build_map_pin_path(map, pin_root_path);
1655                                 if (err) {
1656                                         pr_warn("map '%s': couldn't build pin path.\n",
1657                                                 map_name);
1658                                         return err;
1659                                 }
1660                         }
1661                 } else {
1662                         if (strict) {
1663                                 pr_warn("map '%s': unknown field '%s'.\n",
1664                                         map_name, name);
1665                                 return -ENOTSUP;
1666                         }
1667                         pr_debug("map '%s': ignoring unknown field '%s'.\n",
1668                                  map_name, name);
1669                 }
1670         }
1671
1672         if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1673                 pr_warn("map '%s': map type isn't specified.\n", map_name);
1674                 return -EINVAL;
1675         }
1676
1677         return 0;
1678 }
1679
1680 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1681                                           const char *pin_root_path)
1682 {
1683         const struct btf_type *sec = NULL;
1684         int nr_types, i, vlen, err;
1685         const struct btf_type *t;
1686         const char *name;
1687         Elf_Data *data;
1688         Elf_Scn *scn;
1689
1690         if (obj->efile.btf_maps_shndx < 0)
1691                 return 0;
1692
1693         scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1694         if (scn)
1695                 data = elf_getdata(scn, NULL);
1696         if (!scn || !data) {
1697                 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1698                         obj->efile.maps_shndx, MAPS_ELF_SEC);
1699                 return -EINVAL;
1700         }
1701
1702         nr_types = btf__get_nr_types(obj->btf);
1703         for (i = 1; i <= nr_types; i++) {
1704                 t = btf__type_by_id(obj->btf, i);
1705                 if (!btf_is_datasec(t))
1706                         continue;
1707                 name = btf__name_by_offset(obj->btf, t->name_off);
1708                 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1709                         sec = t;
1710                         break;
1711                 }
1712         }
1713
1714         if (!sec) {
1715                 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1716                 return -ENOENT;
1717         }
1718
1719         vlen = btf_vlen(sec);
1720         for (i = 0; i < vlen; i++) {
1721                 err = bpf_object__init_user_btf_map(obj, sec, i,
1722                                                     obj->efile.btf_maps_shndx,
1723                                                     data, strict,
1724                                                     pin_root_path);
1725                 if (err)
1726                         return err;
1727         }
1728
1729         return 0;
1730 }
1731
1732 static int bpf_object__init_maps(struct bpf_object *obj,
1733                                  const struct bpf_object_open_opts *opts)
1734 {
1735         const char *pin_root_path;
1736         bool strict;
1737         int err;
1738
1739         strict = !OPTS_GET(opts, relaxed_maps, false);
1740         pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
1741
1742         err = bpf_object__init_user_maps(obj, strict);
1743         err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1744         err = err ?: bpf_object__init_global_data_maps(obj);
1745         err = err ?: bpf_object__init_extern_map(obj);
1746         if (err)
1747                 return err;
1748
1749         if (obj->nr_maps) {
1750                 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1751                       compare_bpf_map);
1752         }
1753         return 0;
1754 }
1755
1756 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1757 {
1758         Elf_Scn *scn;
1759         GElf_Shdr sh;
1760
1761         scn = elf_getscn(obj->efile.elf, idx);
1762         if (!scn)
1763                 return false;
1764
1765         if (gelf_getshdr(scn, &sh) != &sh)
1766                 return false;
1767
1768         if (sh.sh_flags & SHF_EXECINSTR)
1769                 return true;
1770
1771         return false;
1772 }
1773
1774 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1775 {
1776         bool has_datasec = obj->caps.btf_datasec;
1777         bool has_func = obj->caps.btf_func;
1778         struct btf *btf = obj->btf;
1779         struct btf_type *t;
1780         int i, j, vlen;
1781
1782         if (!obj->btf || (has_func && has_datasec))
1783                 return;
1784
1785         for (i = 1; i <= btf__get_nr_types(btf); i++) {
1786                 t = (struct btf_type *)btf__type_by_id(btf, i);
1787
1788                 if (!has_datasec && btf_is_var(t)) {
1789                         /* replace VAR with INT */
1790                         t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1791                         /*
1792                          * using size = 1 is the safest choice, 4 will be too
1793                          * big and cause kernel BTF validation failure if
1794                          * original variable took less than 4 bytes
1795                          */
1796                         t->size = 1;
1797                         *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1798                 } else if (!has_datasec && btf_is_datasec(t)) {
1799                         /* replace DATASEC with STRUCT */
1800                         const struct btf_var_secinfo *v = btf_var_secinfos(t);
1801                         struct btf_member *m = btf_members(t);
1802                         struct btf_type *vt;
1803                         char *name;
1804
1805                         name = (char *)btf__name_by_offset(btf, t->name_off);
1806                         while (*name) {
1807                                 if (*name == '.')
1808                                         *name = '_';
1809                                 name++;
1810                         }
1811
1812                         vlen = btf_vlen(t);
1813                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1814                         for (j = 0; j < vlen; j++, v++, m++) {
1815                                 /* order of field assignments is important */
1816                                 m->offset = v->offset * 8;
1817                                 m->type = v->type;
1818                                 /* preserve variable name as member name */
1819                                 vt = (void *)btf__type_by_id(btf, v->type);
1820                                 m->name_off = vt->name_off;
1821                         }
1822                 } else if (!has_func && btf_is_func_proto(t)) {
1823                         /* replace FUNC_PROTO with ENUM */
1824                         vlen = btf_vlen(t);
1825                         t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1826                         t->size = sizeof(__u32); /* kernel enforced */
1827                 } else if (!has_func && btf_is_func(t)) {
1828                         /* replace FUNC with TYPEDEF */
1829                         t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1830                 }
1831         }
1832 }
1833
1834 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1835 {
1836         if (!obj->btf_ext)
1837                 return;
1838
1839         if (!obj->caps.btf_func) {
1840                 btf_ext__free(obj->btf_ext);
1841                 obj->btf_ext = NULL;
1842         }
1843 }
1844
1845 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1846 {
1847         return obj->efile.btf_maps_shndx >= 0;
1848 }
1849
1850 static int bpf_object__init_btf(struct bpf_object *obj,
1851                                 Elf_Data *btf_data,
1852                                 Elf_Data *btf_ext_data)
1853 {
1854         bool btf_required = bpf_object__is_btf_mandatory(obj);
1855         int err = 0;
1856
1857         if (btf_data) {
1858                 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1859                 if (IS_ERR(obj->btf)) {
1860                         pr_warn("Error loading ELF section %s: %d.\n",
1861                                 BTF_ELF_SEC, err);
1862                         goto out;
1863                 }
1864         }
1865         if (btf_ext_data) {
1866                 if (!obj->btf) {
1867                         pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1868                                  BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1869                         goto out;
1870                 }
1871                 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1872                                             btf_ext_data->d_size);
1873                 if (IS_ERR(obj->btf_ext)) {
1874                         pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1875                                 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1876                         obj->btf_ext = NULL;
1877                         goto out;
1878                 }
1879         }
1880 out:
1881         if (err || IS_ERR(obj->btf)) {
1882                 if (btf_required)
1883                         err = err ? : PTR_ERR(obj->btf);
1884                 else
1885                         err = 0;
1886                 if (!IS_ERR_OR_NULL(obj->btf))
1887                         btf__free(obj->btf);
1888                 obj->btf = NULL;
1889         }
1890         if (btf_required && !obj->btf) {
1891                 pr_warn("BTF is required, but is missing or corrupted.\n");
1892                 return err == 0 ? -ENOENT : err;
1893         }
1894         return 0;
1895 }
1896
1897 static int bpf_object__finalize_btf(struct bpf_object *obj)
1898 {
1899         int err;
1900
1901         if (!obj->btf)
1902                 return 0;
1903
1904         err = btf__finalize_data(obj, obj->btf);
1905         if (!err)
1906                 return 0;
1907
1908         pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1909         btf__free(obj->btf);
1910         obj->btf = NULL;
1911         btf_ext__free(obj->btf_ext);
1912         obj->btf_ext = NULL;
1913
1914         if (bpf_object__is_btf_mandatory(obj)) {
1915                 pr_warn("BTF is required, but is missing or corrupted.\n");
1916                 return -ENOENT;
1917         }
1918         return 0;
1919 }
1920
1921 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1922 {
1923         int err = 0;
1924
1925         if (!obj->btf)
1926                 return 0;
1927
1928         bpf_object__sanitize_btf(obj);
1929         bpf_object__sanitize_btf_ext(obj);
1930
1931         err = btf__load(obj->btf);
1932         if (err) {
1933                 pr_warn("Error loading %s into kernel: %d.\n",
1934                         BTF_ELF_SEC, err);
1935                 btf__free(obj->btf);
1936                 obj->btf = NULL;
1937                 /* btf_ext can't exist without btf, so free it as well */
1938                 if (obj->btf_ext) {
1939                         btf_ext__free(obj->btf_ext);
1940                         obj->btf_ext = NULL;
1941                 }
1942
1943                 if (bpf_object__is_btf_mandatory(obj))
1944                         return err;
1945         }
1946         return 0;
1947 }
1948
1949 static int bpf_object__elf_collect(struct bpf_object *obj)
1950 {
1951         Elf *elf = obj->efile.elf;
1952         GElf_Ehdr *ep = &obj->efile.ehdr;
1953         Elf_Data *btf_ext_data = NULL;
1954         Elf_Data *btf_data = NULL;
1955         Elf_Scn *scn = NULL;
1956         int idx = 0, err = 0;
1957
1958         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1959         if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1960                 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
1961                 return -LIBBPF_ERRNO__FORMAT;
1962         }
1963
1964         while ((scn = elf_nextscn(elf, scn)) != NULL) {
1965                 char *name;
1966                 GElf_Shdr sh;
1967                 Elf_Data *data;
1968
1969                 idx++;
1970                 if (gelf_getshdr(scn, &sh) != &sh) {
1971                         pr_warn("failed to get section(%d) header from %s\n",
1972                                 idx, obj->path);
1973                         return -LIBBPF_ERRNO__FORMAT;
1974                 }
1975
1976                 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1977                 if (!name) {
1978                         pr_warn("failed to get section(%d) name from %s\n",
1979                                 idx, obj->path);
1980                         return -LIBBPF_ERRNO__FORMAT;
1981                 }
1982
1983                 data = elf_getdata(scn, 0);
1984                 if (!data) {
1985                         pr_warn("failed to get section(%d) data from %s(%s)\n",
1986                                 idx, name, obj->path);
1987                         return -LIBBPF_ERRNO__FORMAT;
1988                 }
1989                 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1990                          idx, name, (unsigned long)data->d_size,
1991                          (int)sh.sh_link, (unsigned long)sh.sh_flags,
1992                          (int)sh.sh_type);
1993
1994                 if (strcmp(name, "license") == 0) {
1995                         err = bpf_object__init_license(obj,
1996                                                        data->d_buf,
1997                                                        data->d_size);
1998                         if (err)
1999                                 return err;
2000                 } else if (strcmp(name, "version") == 0) {
2001                         err = bpf_object__init_kversion(obj,
2002                                                         data->d_buf,
2003                                                         data->d_size);
2004                         if (err)
2005                                 return err;
2006                 } else if (strcmp(name, "maps") == 0) {
2007                         obj->efile.maps_shndx = idx;
2008                 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2009                         obj->efile.btf_maps_shndx = idx;
2010                 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2011                         btf_data = data;
2012                 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2013                         btf_ext_data = data;
2014                 } else if (sh.sh_type == SHT_SYMTAB) {
2015                         if (obj->efile.symbols) {
2016                                 pr_warn("bpf: multiple SYMTAB in %s\n",
2017                                         obj->path);
2018                                 return -LIBBPF_ERRNO__FORMAT;
2019                         }
2020                         obj->efile.symbols = data;
2021                         obj->efile.symbols_shndx = idx;
2022                         obj->efile.strtabidx = sh.sh_link;
2023                 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2024                         if (sh.sh_flags & SHF_EXECINSTR) {
2025                                 if (strcmp(name, ".text") == 0)
2026                                         obj->efile.text_shndx = idx;
2027                                 err = bpf_object__add_program(obj, data->d_buf,
2028                                                               data->d_size,
2029                                                               name, idx);
2030                                 if (err) {
2031                                         char errmsg[STRERR_BUFSIZE];
2032                                         char *cp;
2033
2034                                         cp = libbpf_strerror_r(-err, errmsg,
2035                                                                sizeof(errmsg));
2036                                         pr_warn("failed to alloc program %s (%s): %s",
2037                                                 name, obj->path, cp);
2038                                         return err;
2039                                 }
2040                         } else if (strcmp(name, DATA_SEC) == 0) {
2041                                 obj->efile.data = data;
2042                                 obj->efile.data_shndx = idx;
2043                         } else if (strcmp(name, RODATA_SEC) == 0) {
2044                                 obj->efile.rodata = data;
2045                                 obj->efile.rodata_shndx = idx;
2046                         } else {
2047                                 pr_debug("skip section(%d) %s\n", idx, name);
2048                         }
2049                 } else if (sh.sh_type == SHT_REL) {
2050                         int nr_sects = obj->efile.nr_reloc_sects;
2051                         void *sects = obj->efile.reloc_sects;
2052                         int sec = sh.sh_info; /* points to other section */
2053
2054                         /* Only do relo for section with exec instructions */
2055                         if (!section_have_execinstr(obj, sec)) {
2056                                 pr_debug("skip relo %s(%d) for section(%d)\n",
2057                                          name, idx, sec);
2058                                 continue;
2059                         }
2060
2061                         sects = reallocarray(sects, nr_sects + 1,
2062                                              sizeof(*obj->efile.reloc_sects));
2063                         if (!sects) {
2064                                 pr_warn("reloc_sects realloc failed\n");
2065                                 return -ENOMEM;
2066                         }
2067
2068                         obj->efile.reloc_sects = sects;
2069                         obj->efile.nr_reloc_sects++;
2070
2071                         obj->efile.reloc_sects[nr_sects].shdr = sh;
2072                         obj->efile.reloc_sects[nr_sects].data = data;
2073                 } else if (sh.sh_type == SHT_NOBITS &&
2074                            strcmp(name, BSS_SEC) == 0) {
2075                         obj->efile.bss = data;
2076                         obj->efile.bss_shndx = idx;
2077                 } else {
2078                         pr_debug("skip section(%d) %s\n", idx, name);
2079                 }
2080         }
2081
2082         if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2083                 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2084                 return -LIBBPF_ERRNO__FORMAT;
2085         }
2086         return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2087 }
2088
2089 static bool sym_is_extern(const GElf_Sym *sym)
2090 {
2091         int bind = GELF_ST_BIND(sym->st_info);
2092         /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2093         return sym->st_shndx == SHN_UNDEF &&
2094                (bind == STB_GLOBAL || bind == STB_WEAK) &&
2095                GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2096 }
2097
2098 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2099 {
2100         const struct btf_type *t;
2101         const char *var_name;
2102         int i, n;
2103
2104         if (!btf)
2105                 return -ESRCH;
2106
2107         n = btf__get_nr_types(btf);
2108         for (i = 1; i <= n; i++) {
2109                 t = btf__type_by_id(btf, i);
2110
2111                 if (!btf_is_var(t))
2112                         continue;
2113
2114                 var_name = btf__name_by_offset(btf, t->name_off);
2115                 if (strcmp(var_name, ext_name))
2116                         continue;
2117
2118                 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2119                         return -EINVAL;
2120
2121                 return i;
2122         }
2123
2124         return -ENOENT;
2125 }
2126
2127 static enum extern_type find_extern_type(const struct btf *btf, int id,
2128                                          bool *is_signed)
2129 {
2130         const struct btf_type *t;
2131         const char *name;
2132
2133         t = skip_mods_and_typedefs(btf, id, NULL);
2134         name = btf__name_by_offset(btf, t->name_off);
2135
2136         if (is_signed)
2137                 *is_signed = false;
2138         switch (btf_kind(t)) {
2139         case BTF_KIND_INT: {
2140                 int enc = btf_int_encoding(t);
2141
2142                 if (enc & BTF_INT_BOOL)
2143                         return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2144                 if (is_signed)
2145                         *is_signed = enc & BTF_INT_SIGNED;
2146                 if (t->size == 1)
2147                         return EXT_CHAR;
2148                 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2149                         return EXT_UNKNOWN;
2150                 return EXT_INT;
2151         }
2152         case BTF_KIND_ENUM:
2153                 if (t->size != 4)
2154                         return EXT_UNKNOWN;
2155                 if (strcmp(name, "libbpf_tristate"))
2156                         return EXT_UNKNOWN;
2157                 return EXT_TRISTATE;
2158         case BTF_KIND_ARRAY:
2159                 if (btf_array(t)->nelems == 0)
2160                         return EXT_UNKNOWN;
2161                 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2162                         return EXT_UNKNOWN;
2163                 return EXT_CHAR_ARR;
2164         default:
2165                 return EXT_UNKNOWN;
2166         }
2167 }
2168
2169 static int cmp_externs(const void *_a, const void *_b)
2170 {
2171         const struct extern_desc *a = _a;
2172         const struct extern_desc *b = _b;
2173
2174         /* descending order by alignment requirements */
2175         if (a->align != b->align)
2176                 return a->align > b->align ? -1 : 1;
2177         /* ascending order by size, within same alignment class */
2178         if (a->sz != b->sz)
2179                 return a->sz < b->sz ? -1 : 1;
2180         /* resolve ties by name */
2181         return strcmp(a->name, b->name);
2182 }
2183
2184 static int bpf_object__collect_externs(struct bpf_object *obj)
2185 {
2186         const struct btf_type *t;
2187         struct extern_desc *ext;
2188         int i, n, off, btf_id;
2189         struct btf_type *sec;
2190         const char *ext_name;
2191         Elf_Scn *scn;
2192         GElf_Shdr sh;
2193
2194         if (!obj->efile.symbols)
2195                 return 0;
2196
2197         scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2198         if (!scn)
2199                 return -LIBBPF_ERRNO__FORMAT;
2200         if (gelf_getshdr(scn, &sh) != &sh)
2201                 return -LIBBPF_ERRNO__FORMAT;
2202         n = sh.sh_size / sh.sh_entsize;
2203
2204         pr_debug("looking for externs among %d symbols...\n", n);
2205         for (i = 0; i < n; i++) {
2206                 GElf_Sym sym;
2207
2208                 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2209                         return -LIBBPF_ERRNO__FORMAT;
2210                 if (!sym_is_extern(&sym))
2211                         continue;
2212                 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2213                                       sym.st_name);
2214                 if (!ext_name || !ext_name[0])
2215                         continue;
2216
2217                 ext = obj->externs;
2218                 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2219                 if (!ext)
2220                         return -ENOMEM;
2221                 obj->externs = ext;
2222                 ext = &ext[obj->nr_extern];
2223                 memset(ext, 0, sizeof(*ext));
2224                 obj->nr_extern++;
2225
2226                 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2227                 if (ext->btf_id <= 0) {
2228                         pr_warn("failed to find BTF for extern '%s': %d\n",
2229                                 ext_name, ext->btf_id);
2230                         return ext->btf_id;
2231                 }
2232                 t = btf__type_by_id(obj->btf, ext->btf_id);
2233                 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2234                 ext->sym_idx = i;
2235                 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2236                 ext->sz = btf__resolve_size(obj->btf, t->type);
2237                 if (ext->sz <= 0) {
2238                         pr_warn("failed to resolve size of extern '%s': %d\n",
2239                                 ext_name, ext->sz);
2240                         return ext->sz;
2241                 }
2242                 ext->align = btf__align_of(obj->btf, t->type);
2243                 if (ext->align <= 0) {
2244                         pr_warn("failed to determine alignment of extern '%s': %d\n",
2245                                 ext_name, ext->align);
2246                         return -EINVAL;
2247                 }
2248                 ext->type = find_extern_type(obj->btf, t->type,
2249                                              &ext->is_signed);
2250                 if (ext->type == EXT_UNKNOWN) {
2251                         pr_warn("extern '%s' type is unsupported\n", ext_name);
2252                         return -ENOTSUP;
2253                 }
2254         }
2255         pr_debug("collected %d externs total\n", obj->nr_extern);
2256
2257         if (!obj->nr_extern)
2258                 return 0;
2259
2260         /* sort externs by (alignment, size, name) and calculate their offsets
2261          * within a map */
2262         qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2263         off = 0;
2264         for (i = 0; i < obj->nr_extern; i++) {
2265                 ext = &obj->externs[i];
2266                 ext->data_off = roundup(off, ext->align);
2267                 off = ext->data_off + ext->sz;
2268                 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2269                          i, ext->sym_idx, ext->data_off, ext->name);
2270         }
2271
2272         btf_id = btf__find_by_name(obj->btf, EXTERN_SEC);
2273         if (btf_id <= 0) {
2274                 pr_warn("no BTF info found for '%s' datasec\n", EXTERN_SEC);
2275                 return -ESRCH;
2276         }
2277
2278         sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2279         sec->size = off;
2280         n = btf_vlen(sec);
2281         for (i = 0; i < n; i++) {
2282                 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2283
2284                 t = btf__type_by_id(obj->btf, vs->type);
2285                 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2286                 ext = find_extern_by_name(obj, ext_name);
2287                 if (!ext) {
2288                         pr_warn("failed to find extern definition for BTF var '%s'\n",
2289                                 ext_name);
2290                         return -ESRCH;
2291                 }
2292                 vs->offset = ext->data_off;
2293                 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2294         }
2295
2296         return 0;
2297 }
2298
2299 static struct bpf_program *
2300 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2301 {
2302         struct bpf_program *prog;
2303         size_t i;
2304
2305         for (i = 0; i < obj->nr_programs; i++) {
2306                 prog = &obj->programs[i];
2307                 if (prog->idx == idx)
2308                         return prog;
2309         }
2310         return NULL;
2311 }
2312
2313 struct bpf_program *
2314 bpf_object__find_program_by_title(const struct bpf_object *obj,
2315                                   const char *title)
2316 {
2317         struct bpf_program *pos;
2318
2319         bpf_object__for_each_program(pos, obj) {
2320                 if (pos->section_name && !strcmp(pos->section_name, title))
2321                         return pos;
2322         }
2323         return NULL;
2324 }
2325
2326 struct bpf_program *
2327 bpf_object__find_program_by_name(const struct bpf_object *obj,
2328                                  const char *name)
2329 {
2330         struct bpf_program *prog;
2331
2332         bpf_object__for_each_program(prog, obj) {
2333                 if (!strcmp(prog->name, name))
2334                         return prog;
2335         }
2336         return NULL;
2337 }
2338
2339 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2340                                       int shndx)
2341 {
2342         return shndx == obj->efile.data_shndx ||
2343                shndx == obj->efile.bss_shndx ||
2344                shndx == obj->efile.rodata_shndx;
2345 }
2346
2347 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2348                                       int shndx)
2349 {
2350         return shndx == obj->efile.maps_shndx ||
2351                shndx == obj->efile.btf_maps_shndx;
2352 }
2353
2354 static enum libbpf_map_type
2355 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2356 {
2357         if (shndx == obj->efile.data_shndx)
2358                 return LIBBPF_MAP_DATA;
2359         else if (shndx == obj->efile.bss_shndx)
2360                 return LIBBPF_MAP_BSS;
2361         else if (shndx == obj->efile.rodata_shndx)
2362                 return LIBBPF_MAP_RODATA;
2363         else if (shndx == obj->efile.symbols_shndx)
2364                 return LIBBPF_MAP_EXTERN;
2365         else
2366                 return LIBBPF_MAP_UNSPEC;
2367 }
2368
2369 static int bpf_program__record_reloc(struct bpf_program *prog,
2370                                      struct reloc_desc *reloc_desc,
2371                                      __u32 insn_idx, const char *name,
2372                                      const GElf_Sym *sym, const GElf_Rel *rel)
2373 {
2374         struct bpf_insn *insn = &prog->insns[insn_idx];
2375         size_t map_idx, nr_maps = prog->obj->nr_maps;
2376         struct bpf_object *obj = prog->obj;
2377         __u32 shdr_idx = sym->st_shndx;
2378         enum libbpf_map_type type;
2379         struct bpf_map *map;
2380
2381         /* sub-program call relocation */
2382         if (insn->code == (BPF_JMP | BPF_CALL)) {
2383                 if (insn->src_reg != BPF_PSEUDO_CALL) {
2384                         pr_warn("incorrect bpf_call opcode\n");
2385                         return -LIBBPF_ERRNO__RELOC;
2386                 }
2387                 /* text_shndx can be 0, if no default "main" program exists */
2388                 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2389                         pr_warn("bad call relo against section %u\n", shdr_idx);
2390                         return -LIBBPF_ERRNO__RELOC;
2391                 }
2392                 if (sym->st_value % 8) {
2393                         pr_warn("bad call relo offset: %zu\n",
2394                                 (size_t)sym->st_value);
2395                         return -LIBBPF_ERRNO__RELOC;
2396                 }
2397                 reloc_desc->type = RELO_CALL;
2398                 reloc_desc->insn_idx = insn_idx;
2399                 reloc_desc->sym_off = sym->st_value;
2400                 obj->has_pseudo_calls = true;
2401                 return 0;
2402         }
2403
2404         if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2405                 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2406                         insn_idx, insn->code);
2407                 return -LIBBPF_ERRNO__RELOC;
2408         }
2409
2410         if (sym_is_extern(sym)) {
2411                 int sym_idx = GELF_R_SYM(rel->r_info);
2412                 int i, n = obj->nr_extern;
2413                 struct extern_desc *ext;
2414
2415                 for (i = 0; i < n; i++) {
2416                         ext = &obj->externs[i];
2417                         if (ext->sym_idx == sym_idx)
2418                                 break;
2419                 }
2420                 if (i >= n) {
2421                         pr_warn("extern relo failed to find extern for sym %d\n",
2422                                 sym_idx);
2423                         return -LIBBPF_ERRNO__RELOC;
2424                 }
2425                 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2426                          i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
2427                 reloc_desc->type = RELO_EXTERN;
2428                 reloc_desc->insn_idx = insn_idx;
2429                 reloc_desc->sym_off = ext->data_off;
2430                 return 0;
2431         }
2432
2433         if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
2434                 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2435                         name, shdr_idx);
2436                 return -LIBBPF_ERRNO__RELOC;
2437         }
2438
2439         type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
2440
2441         /* generic map reference relocation */
2442         if (type == LIBBPF_MAP_UNSPEC) {
2443                 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
2444                         pr_warn("bad map relo against section %u\n",
2445                                 shdr_idx);
2446                         return -LIBBPF_ERRNO__RELOC;
2447                 }
2448                 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2449                         map = &obj->maps[map_idx];
2450                         if (map->libbpf_type != type ||
2451                             map->sec_idx != sym->st_shndx ||
2452                             map->sec_offset != sym->st_value)
2453                                 continue;
2454                         pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2455                                  map_idx, map->name, map->sec_idx,
2456                                  map->sec_offset, insn_idx);
2457                         break;
2458                 }
2459                 if (map_idx >= nr_maps) {
2460                         pr_warn("map relo failed to find map for sec %u, off %zu\n",
2461                                 shdr_idx, (size_t)sym->st_value);
2462                         return -LIBBPF_ERRNO__RELOC;
2463                 }
2464                 reloc_desc->type = RELO_LD64;
2465                 reloc_desc->insn_idx = insn_idx;
2466                 reloc_desc->map_idx = map_idx;
2467                 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
2468                 return 0;
2469         }
2470
2471         /* global data map relocation */
2472         if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
2473                 pr_warn("bad data relo against section %u\n", shdr_idx);
2474                 return -LIBBPF_ERRNO__RELOC;
2475         }
2476         for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2477                 map = &obj->maps[map_idx];
2478                 if (map->libbpf_type != type)
2479                         continue;
2480                 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2481                          map_idx, map->name, map->sec_idx, map->sec_offset,
2482                          insn_idx);
2483                 break;
2484         }
2485         if (map_idx >= nr_maps) {
2486                 pr_warn("data relo failed to find map for sec %u\n",
2487                         shdr_idx);
2488                 return -LIBBPF_ERRNO__RELOC;
2489         }
2490
2491         reloc_desc->type = RELO_DATA;
2492         reloc_desc->insn_idx = insn_idx;
2493         reloc_desc->map_idx = map_idx;
2494         reloc_desc->sym_off = sym->st_value;
2495         return 0;
2496 }
2497
2498 static int
2499 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
2500                            Elf_Data *data, struct bpf_object *obj)
2501 {
2502         Elf_Data *symbols = obj->efile.symbols;
2503         int err, i, nrels;
2504
2505         pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
2506         nrels = shdr->sh_size / shdr->sh_entsize;
2507
2508         prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
2509         if (!prog->reloc_desc) {
2510                 pr_warn("failed to alloc memory in relocation\n");
2511                 return -ENOMEM;
2512         }
2513         prog->nr_reloc = nrels;
2514
2515         for (i = 0; i < nrels; i++) {
2516                 const char *name;
2517                 __u32 insn_idx;
2518                 GElf_Sym sym;
2519                 GElf_Rel rel;
2520
2521                 if (!gelf_getrel(data, i, &rel)) {
2522                         pr_warn("relocation: failed to get %d reloc\n", i);
2523                         return -LIBBPF_ERRNO__FORMAT;
2524                 }
2525                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
2526                         pr_warn("relocation: symbol %"PRIx64" not found\n",
2527                                 GELF_R_SYM(rel.r_info));
2528                         return -LIBBPF_ERRNO__FORMAT;
2529                 }
2530                 if (rel.r_offset % sizeof(struct bpf_insn))
2531                         return -LIBBPF_ERRNO__FORMAT;
2532
2533                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
2534                 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2535                                   sym.st_name) ? : "<?>";
2536
2537                 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
2538                          (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
2539                          (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
2540                          GELF_ST_BIND(sym.st_info), sym.st_name, name,
2541                          insn_idx);
2542
2543                 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
2544                                                 insn_idx, name, &sym, &rel);
2545                 if (err)
2546                         return err;
2547         }
2548         return 0;
2549 }
2550
2551 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
2552 {
2553         struct bpf_map_def *def = &map->def;
2554         __u32 key_type_id = 0, value_type_id = 0;
2555         int ret;
2556
2557         /* if it's BTF-defined map, we don't need to search for type IDs */
2558         if (map->sec_idx == obj->efile.btf_maps_shndx)
2559                 return 0;
2560
2561         if (!bpf_map__is_internal(map)) {
2562                 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
2563                                            def->value_size, &key_type_id,
2564                                            &value_type_id);
2565         } else {
2566                 /*
2567                  * LLVM annotates global data differently in BTF, that is,
2568                  * only as '.data', '.bss' or '.rodata'.
2569                  */
2570                 ret = btf__find_by_name(obj->btf,
2571                                 libbpf_type_to_btf_name[map->libbpf_type]);
2572         }
2573         if (ret < 0)
2574                 return ret;
2575
2576         map->btf_key_type_id = key_type_id;
2577         map->btf_value_type_id = bpf_map__is_internal(map) ?
2578                                  ret : value_type_id;
2579         return 0;
2580 }
2581
2582 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
2583 {
2584         struct bpf_map_info info = {};
2585         __u32 len = sizeof(info);
2586         int new_fd, err;
2587         char *new_name;
2588
2589         err = bpf_obj_get_info_by_fd(fd, &info, &len);
2590         if (err)
2591                 return err;
2592
2593         new_name = strdup(info.name);
2594         if (!new_name)
2595                 return -errno;
2596
2597         new_fd = open("/", O_RDONLY | O_CLOEXEC);
2598         if (new_fd < 0) {
2599                 err = -errno;
2600                 goto err_free_new_name;
2601         }
2602
2603         new_fd = dup3(fd, new_fd, O_CLOEXEC);
2604         if (new_fd < 0) {
2605                 err = -errno;
2606                 goto err_close_new_fd;
2607         }
2608
2609         err = zclose(map->fd);
2610         if (err) {
2611                 err = -errno;
2612                 goto err_close_new_fd;
2613         }
2614         free(map->name);
2615
2616         map->fd = new_fd;
2617         map->name = new_name;
2618         map->def.type = info.type;
2619         map->def.key_size = info.key_size;
2620         map->def.value_size = info.value_size;
2621         map->def.max_entries = info.max_entries;
2622         map->def.map_flags = info.map_flags;
2623         map->btf_key_type_id = info.btf_key_type_id;
2624         map->btf_value_type_id = info.btf_value_type_id;
2625         map->reused = true;
2626
2627         return 0;
2628
2629 err_close_new_fd:
2630         close(new_fd);
2631 err_free_new_name:
2632         free(new_name);
2633         return err;
2634 }
2635
2636 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2637 {
2638         if (!map || !max_entries)
2639                 return -EINVAL;
2640
2641         /* If map already created, its attributes can't be changed. */
2642         if (map->fd >= 0)
2643                 return -EBUSY;
2644
2645         map->def.max_entries = max_entries;
2646
2647         return 0;
2648 }
2649
2650 static int
2651 bpf_object__probe_name(struct bpf_object *obj)
2652 {
2653         struct bpf_load_program_attr attr;
2654         char *cp, errmsg[STRERR_BUFSIZE];
2655         struct bpf_insn insns[] = {
2656                 BPF_MOV64_IMM(BPF_REG_0, 0),
2657                 BPF_EXIT_INSN(),
2658         };
2659         int ret;
2660
2661         /* make sure basic loading works */
2662
2663         memset(&attr, 0, sizeof(attr));
2664         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2665         attr.insns = insns;
2666         attr.insns_cnt = ARRAY_SIZE(insns);
2667         attr.license = "GPL";
2668
2669         ret = bpf_load_program_xattr(&attr, NULL, 0);
2670         if (ret < 0) {
2671                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2672                 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2673                         __func__, cp, errno);
2674                 return -errno;
2675         }
2676         close(ret);
2677
2678         /* now try the same program, but with the name */
2679
2680         attr.name = "test";
2681         ret = bpf_load_program_xattr(&attr, NULL, 0);
2682         if (ret >= 0) {
2683                 obj->caps.name = 1;
2684                 close(ret);
2685         }
2686
2687         return 0;
2688 }
2689
2690 static int
2691 bpf_object__probe_global_data(struct bpf_object *obj)
2692 {
2693         struct bpf_load_program_attr prg_attr;
2694         struct bpf_create_map_attr map_attr;
2695         char *cp, errmsg[STRERR_BUFSIZE];
2696         struct bpf_insn insns[] = {
2697                 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2698                 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2699                 BPF_MOV64_IMM(BPF_REG_0, 0),
2700                 BPF_EXIT_INSN(),
2701         };
2702         int ret, map;
2703
2704         memset(&map_attr, 0, sizeof(map_attr));
2705         map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2706         map_attr.key_size = sizeof(int);
2707         map_attr.value_size = 32;
2708         map_attr.max_entries = 1;
2709
2710         map = bpf_create_map_xattr(&map_attr);
2711         if (map < 0) {
2712                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2713                 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2714                         __func__, cp, errno);
2715                 return -errno;
2716         }
2717
2718         insns[0].imm = map;
2719
2720         memset(&prg_attr, 0, sizeof(prg_attr));
2721         prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2722         prg_attr.insns = insns;
2723         prg_attr.insns_cnt = ARRAY_SIZE(insns);
2724         prg_attr.license = "GPL";
2725
2726         ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2727         if (ret >= 0) {
2728                 obj->caps.global_data = 1;
2729                 close(ret);
2730         }
2731
2732         close(map);
2733         return 0;
2734 }
2735
2736 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2737 {
2738         static const char strs[] = "\0int\0x\0a";
2739         /* void x(int a) {} */
2740         __u32 types[] = {
2741                 /* int */
2742                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2743                 /* FUNC_PROTO */                                /* [2] */
2744                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2745                 BTF_PARAM_ENC(7, 1),
2746                 /* FUNC x */                                    /* [3] */
2747                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2748         };
2749         int btf_fd;
2750
2751         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2752                                       strs, sizeof(strs));
2753         if (btf_fd >= 0) {
2754                 obj->caps.btf_func = 1;
2755                 close(btf_fd);
2756                 return 1;
2757         }
2758
2759         return 0;
2760 }
2761
2762 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2763 {
2764         static const char strs[] = "\0x\0.data";
2765         /* static int a; */
2766         __u32 types[] = {
2767                 /* int */
2768                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2769                 /* VAR x */                                     /* [2] */
2770                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2771                 BTF_VAR_STATIC,
2772                 /* DATASEC val */                               /* [3] */
2773                 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2774                 BTF_VAR_SECINFO_ENC(2, 0, 4),
2775         };
2776         int btf_fd;
2777
2778         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2779                                       strs, sizeof(strs));
2780         if (btf_fd >= 0) {
2781                 obj->caps.btf_datasec = 1;
2782                 close(btf_fd);
2783                 return 1;
2784         }
2785
2786         return 0;
2787 }
2788
2789 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2790 {
2791         struct bpf_create_map_attr attr = {
2792                 .map_type = BPF_MAP_TYPE_ARRAY,
2793                 .map_flags = BPF_F_MMAPABLE,
2794                 .key_size = sizeof(int),
2795                 .value_size = sizeof(int),
2796                 .max_entries = 1,
2797         };
2798         int fd;
2799
2800         fd = bpf_create_map_xattr(&attr);
2801         if (fd >= 0) {
2802                 obj->caps.array_mmap = 1;
2803                 close(fd);
2804                 return 1;
2805         }
2806
2807         return 0;
2808 }
2809
2810 static int
2811 bpf_object__probe_caps(struct bpf_object *obj)
2812 {
2813         int (*probe_fn[])(struct bpf_object *obj) = {
2814                 bpf_object__probe_name,
2815                 bpf_object__probe_global_data,
2816                 bpf_object__probe_btf_func,
2817                 bpf_object__probe_btf_datasec,
2818                 bpf_object__probe_array_mmap,
2819         };
2820         int i, ret;
2821
2822         for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2823                 ret = probe_fn[i](obj);
2824                 if (ret < 0)
2825                         pr_debug("Probe #%d failed with %d.\n", i, ret);
2826         }
2827
2828         return 0;
2829 }
2830
2831 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2832 {
2833         struct bpf_map_info map_info = {};
2834         char msg[STRERR_BUFSIZE];
2835         __u32 map_info_len;
2836
2837         map_info_len = sizeof(map_info);
2838
2839         if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2840                 pr_warn("failed to get map info for map FD %d: %s\n",
2841                         map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2842                 return false;
2843         }
2844
2845         return (map_info.type == map->def.type &&
2846                 map_info.key_size == map->def.key_size &&
2847                 map_info.value_size == map->def.value_size &&
2848                 map_info.max_entries == map->def.max_entries &&
2849                 map_info.map_flags == map->def.map_flags);
2850 }
2851
2852 static int
2853 bpf_object__reuse_map(struct bpf_map *map)
2854 {
2855         char *cp, errmsg[STRERR_BUFSIZE];
2856         int err, pin_fd;
2857
2858         pin_fd = bpf_obj_get(map->pin_path);
2859         if (pin_fd < 0) {
2860                 err = -errno;
2861                 if (err == -ENOENT) {
2862                         pr_debug("found no pinned map to reuse at '%s'\n",
2863                                  map->pin_path);
2864                         return 0;
2865                 }
2866
2867                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2868                 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2869                         map->pin_path, cp);
2870                 return err;
2871         }
2872
2873         if (!map_is_reuse_compat(map, pin_fd)) {
2874                 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2875                         map->pin_path);
2876                 close(pin_fd);
2877                 return -EINVAL;
2878         }
2879
2880         err = bpf_map__reuse_fd(map, pin_fd);
2881         if (err) {
2882                 close(pin_fd);
2883                 return err;
2884         }
2885         map->pinned = true;
2886         pr_debug("reused pinned map at '%s'\n", map->pin_path);
2887
2888         return 0;
2889 }
2890
2891 static int
2892 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2893 {
2894         enum libbpf_map_type map_type = map->libbpf_type;
2895         char *cp, errmsg[STRERR_BUFSIZE];
2896         int err, zero = 0;
2897
2898         /* kernel already zero-initializes .bss map. */
2899         if (map_type == LIBBPF_MAP_BSS)
2900                 return 0;
2901
2902         err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
2903         if (err) {
2904                 err = -errno;
2905                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2906                 pr_warn("Error setting initial map(%s) contents: %s\n",
2907                         map->name, cp);
2908                 return err;
2909         }
2910
2911         /* Freeze .rodata and .extern map as read-only from syscall side. */
2912         if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_EXTERN) {
2913                 err = bpf_map_freeze(map->fd);
2914                 if (err) {
2915                         err = -errno;
2916                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2917                         pr_warn("Error freezing map(%s) as read-only: %s\n",
2918                                 map->name, cp);
2919                         return err;
2920                 }
2921         }
2922         return 0;
2923 }
2924
2925 static int
2926 bpf_object__create_maps(struct bpf_object *obj)
2927 {
2928         struct bpf_create_map_attr create_attr = {};
2929         int nr_cpus = 0;
2930         unsigned int i;
2931         int err;
2932
2933         for (i = 0; i < obj->nr_maps; i++) {
2934                 struct bpf_map *map = &obj->maps[i];
2935                 struct bpf_map_def *def = &map->def;
2936                 char *cp, errmsg[STRERR_BUFSIZE];
2937                 int *pfd = &map->fd;
2938
2939                 if (map->pin_path) {
2940                         err = bpf_object__reuse_map(map);
2941                         if (err) {
2942                                 pr_warn("error reusing pinned map %s\n",
2943                                         map->name);
2944                                 return err;
2945                         }
2946                 }
2947
2948                 if (map->fd >= 0) {
2949                         pr_debug("skip map create (preset) %s: fd=%d\n",
2950                                  map->name, map->fd);
2951                         continue;
2952                 }
2953
2954                 if (obj->caps.name)
2955                         create_attr.name = map->name;
2956                 create_attr.map_ifindex = map->map_ifindex;
2957                 create_attr.map_type = def->type;
2958                 create_attr.map_flags = def->map_flags;
2959                 create_attr.key_size = def->key_size;
2960                 create_attr.value_size = def->value_size;
2961                 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2962                     !def->max_entries) {
2963                         if (!nr_cpus)
2964                                 nr_cpus = libbpf_num_possible_cpus();
2965                         if (nr_cpus < 0) {
2966                                 pr_warn("failed to determine number of system CPUs: %d\n",
2967                                         nr_cpus);
2968                                 err = nr_cpus;
2969                                 goto err_out;
2970                         }
2971                         pr_debug("map '%s': setting size to %d\n",
2972                                  map->name, nr_cpus);
2973                         create_attr.max_entries = nr_cpus;
2974                 } else {
2975                         create_attr.max_entries = def->max_entries;
2976                 }
2977                 create_attr.btf_fd = 0;
2978                 create_attr.btf_key_type_id = 0;
2979                 create_attr.btf_value_type_id = 0;
2980                 if (bpf_map_type__is_map_in_map(def->type) &&
2981                     map->inner_map_fd >= 0)
2982                         create_attr.inner_map_fd = map->inner_map_fd;
2983
2984                 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2985                         create_attr.btf_fd = btf__fd(obj->btf);
2986                         create_attr.btf_key_type_id = map->btf_key_type_id;
2987                         create_attr.btf_value_type_id = map->btf_value_type_id;
2988                 }
2989
2990                 *pfd = bpf_create_map_xattr(&create_attr);
2991                 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2992                                  create_attr.btf_value_type_id)) {
2993                         err = -errno;
2994                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2995                         pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2996                                 map->name, cp, err);
2997                         create_attr.btf_fd = 0;
2998                         create_attr.btf_key_type_id = 0;
2999                         create_attr.btf_value_type_id = 0;
3000                         map->btf_key_type_id = 0;
3001                         map->btf_value_type_id = 0;
3002                         *pfd = bpf_create_map_xattr(&create_attr);
3003                 }
3004
3005                 if (*pfd < 0) {
3006                         size_t j;
3007
3008                         err = -errno;
3009 err_out:
3010                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3011                         pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3012                                 map->name, cp, err);
3013                         pr_perm_msg(err);
3014                         for (j = 0; j < i; j++)
3015                                 zclose(obj->maps[j].fd);
3016                         return err;
3017                 }
3018
3019                 if (bpf_map__is_internal(map)) {
3020                         err = bpf_object__populate_internal_map(obj, map);
3021                         if (err < 0) {
3022                                 zclose(*pfd);
3023                                 goto err_out;
3024                         }
3025                 }
3026
3027                 if (map->pin_path && !map->pinned) {
3028                         err = bpf_map__pin(map, NULL);
3029                         if (err) {
3030                                 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3031                                         map->name, map->pin_path);
3032                                 return err;
3033                         }
3034                 }
3035
3036                 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
3037         }
3038
3039         return 0;
3040 }
3041
3042 static int
3043 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3044                         void *btf_prog_info, const char *info_name)
3045 {
3046         if (err != -ENOENT) {
3047                 pr_warn("Error in loading %s for sec %s.\n",
3048                         info_name, prog->section_name);
3049                 return err;
3050         }
3051
3052         /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3053
3054         if (btf_prog_info) {
3055                 /*
3056                  * Some info has already been found but has problem
3057                  * in the last btf_ext reloc. Must have to error out.
3058                  */
3059                 pr_warn("Error in relocating %s for sec %s.\n",
3060                         info_name, prog->section_name);
3061                 return err;
3062         }
3063
3064         /* Have problem loading the very first info. Ignore the rest. */
3065         pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3066                 info_name, prog->section_name, info_name);
3067         return 0;
3068 }
3069
3070 static int
3071 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3072                           const char *section_name,  __u32 insn_offset)
3073 {
3074         int err;
3075
3076         if (!insn_offset || prog->func_info) {
3077                 /*
3078                  * !insn_offset => main program
3079                  *
3080                  * For sub prog, the main program's func_info has to
3081                  * be loaded first (i.e. prog->func_info != NULL)
3082                  */
3083                 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3084                                                section_name, insn_offset,
3085                                                &prog->func_info,
3086                                                &prog->func_info_cnt);
3087                 if (err)
3088                         return check_btf_ext_reloc_err(prog, err,
3089                                                        prog->func_info,
3090                                                        "bpf_func_info");
3091
3092                 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3093         }
3094
3095         if (!insn_offset || prog->line_info) {
3096                 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3097                                                section_name, insn_offset,
3098                                                &prog->line_info,
3099                                                &prog->line_info_cnt);
3100                 if (err)
3101                         return check_btf_ext_reloc_err(prog, err,
3102                                                        prog->line_info,
3103                                                        "bpf_line_info");
3104
3105                 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3106         }
3107
3108         return 0;
3109 }
3110
3111 #define BPF_CORE_SPEC_MAX_LEN 64
3112
3113 /* represents BPF CO-RE field or array element accessor */
3114 struct bpf_core_accessor {
3115         __u32 type_id;          /* struct/union type or array element type */
3116         __u32 idx;              /* field index or array index */
3117         const char *name;       /* field name or NULL for array accessor */
3118 };
3119
3120 struct bpf_core_spec {
3121         const struct btf *btf;
3122         /* high-level spec: named fields and array indices only */
3123         struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3124         /* high-level spec length */
3125         int len;
3126         /* raw, low-level spec: 1-to-1 with accessor spec string */
3127         int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3128         /* raw spec length */
3129         int raw_len;
3130         /* field bit offset represented by spec */
3131         __u32 bit_offset;
3132 };
3133
3134 static bool str_is_empty(const char *s)
3135 {
3136         return !s || !s[0];
3137 }
3138
3139 static bool is_flex_arr(const struct btf *btf,
3140                         const struct bpf_core_accessor *acc,
3141                         const struct btf_array *arr)
3142 {
3143         const struct btf_type *t;
3144
3145         /* not a flexible array, if not inside a struct or has non-zero size */
3146         if (!acc->name || arr->nelems > 0)
3147                 return false;
3148
3149         /* has to be the last member of enclosing struct */
3150         t = btf__type_by_id(btf, acc->type_id);
3151         return acc->idx == btf_vlen(t) - 1;
3152 }
3153
3154 /*
3155  * Turn bpf_field_reloc into a low- and high-level spec representation,
3156  * validating correctness along the way, as well as calculating resulting
3157  * field bit offset, specified by accessor string. Low-level spec captures
3158  * every single level of nestedness, including traversing anonymous
3159  * struct/union members. High-level one only captures semantically meaningful
3160  * "turning points": named fields and array indicies.
3161  * E.g., for this case:
3162  *
3163  *   struct sample {
3164  *       int __unimportant;
3165  *       struct {
3166  *           int __1;
3167  *           int __2;
3168  *           int a[7];
3169  *       };
3170  *   };
3171  *
3172  *   struct sample *s = ...;
3173  *
3174  *   int x = &s->a[3]; // access string = '0:1:2:3'
3175  *
3176  * Low-level spec has 1:1 mapping with each element of access string (it's
3177  * just a parsed access string representation): [0, 1, 2, 3].
3178  *
3179  * High-level spec will capture only 3 points:
3180  *   - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3181  *   - field 'a' access (corresponds to '2' in low-level spec);
3182  *   - array element #3 access (corresponds to '3' in low-level spec).
3183  *
3184  */
3185 static int bpf_core_spec_parse(const struct btf *btf,
3186                                __u32 type_id,
3187                                const char *spec_str,
3188                                struct bpf_core_spec *spec)
3189 {
3190         int access_idx, parsed_len, i;
3191         struct bpf_core_accessor *acc;
3192         const struct btf_type *t;
3193         const char *name;
3194         __u32 id;
3195         __s64 sz;
3196
3197         if (str_is_empty(spec_str) || *spec_str == ':')
3198                 return -EINVAL;
3199
3200         memset(spec, 0, sizeof(*spec));
3201         spec->btf = btf;
3202
3203         /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3204         while (*spec_str) {
3205                 if (*spec_str == ':')
3206                         ++spec_str;
3207                 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3208                         return -EINVAL;
3209                 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3210                         return -E2BIG;
3211                 spec_str += parsed_len;
3212                 spec->raw_spec[spec->raw_len++] = access_idx;
3213         }
3214
3215         if (spec->raw_len == 0)
3216                 return -EINVAL;
3217
3218         /* first spec value is always reloc type array index */
3219         t = skip_mods_and_typedefs(btf, type_id, &id);
3220         if (!t)
3221                 return -EINVAL;
3222
3223         access_idx = spec->raw_spec[0];
3224         spec->spec[0].type_id = id;
3225         spec->spec[0].idx = access_idx;
3226         spec->len++;
3227
3228         sz = btf__resolve_size(btf, id);
3229         if (sz < 0)
3230                 return sz;
3231         spec->bit_offset = access_idx * sz * 8;
3232
3233         for (i = 1; i < spec->raw_len; i++) {
3234                 t = skip_mods_and_typedefs(btf, id, &id);
3235                 if (!t)
3236                         return -EINVAL;
3237
3238                 access_idx = spec->raw_spec[i];
3239                 acc = &spec->spec[spec->len];
3240
3241                 if (btf_is_composite(t)) {
3242                         const struct btf_member *m;
3243                         __u32 bit_offset;
3244
3245                         if (access_idx >= btf_vlen(t))
3246                                 return -EINVAL;
3247
3248                         bit_offset = btf_member_bit_offset(t, access_idx);
3249                         spec->bit_offset += bit_offset;
3250
3251                         m = btf_members(t) + access_idx;
3252                         if (m->name_off) {
3253                                 name = btf__name_by_offset(btf, m->name_off);
3254                                 if (str_is_empty(name))
3255                                         return -EINVAL;
3256
3257                                 acc->type_id = id;
3258                                 acc->idx = access_idx;
3259                                 acc->name = name;
3260                                 spec->len++;
3261                         }
3262
3263                         id = m->type;
3264                 } else if (btf_is_array(t)) {
3265                         const struct btf_array *a = btf_array(t);
3266                         bool flex;
3267
3268                         t = skip_mods_and_typedefs(btf, a->type, &id);
3269                         if (!t)
3270                                 return -EINVAL;
3271
3272                         flex = is_flex_arr(btf, acc - 1, a);
3273                         if (!flex && access_idx >= a->nelems)
3274                                 return -EINVAL;
3275
3276                         spec->spec[spec->len].type_id = id;
3277                         spec->spec[spec->len].idx = access_idx;
3278                         spec->len++;
3279
3280                         sz = btf__resolve_size(btf, id);
3281                         if (sz < 0)
3282                                 return sz;
3283                         spec->bit_offset += access_idx * sz * 8;
3284                 } else {
3285                         pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3286                                 type_id, spec_str, i, id, btf_kind(t));
3287                         return -EINVAL;
3288                 }
3289         }
3290
3291         return 0;
3292 }
3293
3294 static bool bpf_core_is_flavor_sep(const char *s)
3295 {
3296         /* check X___Y name pattern, where X and Y are not underscores */
3297         return s[0] != '_' &&                                 /* X */
3298                s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
3299                s[4] != '_';                                   /* Y */
3300 }
3301
3302 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
3303  * before last triple underscore. Struct name part after last triple
3304  * underscore is ignored by BPF CO-RE relocation during relocation matching.
3305  */
3306 static size_t bpf_core_essential_name_len(const char *name)
3307 {
3308         size_t n = strlen(name);
3309         int i;
3310
3311         for (i = n - 5; i >= 0; i--) {
3312                 if (bpf_core_is_flavor_sep(name + i))
3313                         return i + 1;
3314         }
3315         return n;
3316 }
3317
3318 /* dynamically sized list of type IDs */
3319 struct ids_vec {
3320         __u32 *data;
3321         int len;
3322 };
3323
3324 static void bpf_core_free_cands(struct ids_vec *cand_ids)
3325 {
3326         free(cand_ids->data);
3327         free(cand_ids);
3328 }
3329
3330 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
3331                                            __u32 local_type_id,
3332                                            const struct btf *targ_btf)
3333 {
3334         size_t local_essent_len, targ_essent_len;
3335         const char *local_name, *targ_name;
3336         const struct btf_type *t;
3337         struct ids_vec *cand_ids;
3338         __u32 *new_ids;
3339         int i, err, n;
3340
3341         t = btf__type_by_id(local_btf, local_type_id);
3342         if (!t)
3343                 return ERR_PTR(-EINVAL);
3344
3345         local_name = btf__name_by_offset(local_btf, t->name_off);
3346         if (str_is_empty(local_name))
3347                 return ERR_PTR(-EINVAL);
3348         local_essent_len = bpf_core_essential_name_len(local_name);
3349
3350         cand_ids = calloc(1, sizeof(*cand_ids));
3351         if (!cand_ids)
3352                 return ERR_PTR(-ENOMEM);
3353
3354         n = btf__get_nr_types(targ_btf);
3355         for (i = 1; i <= n; i++) {
3356                 t = btf__type_by_id(targ_btf, i);
3357                 targ_name = btf__name_by_offset(targ_btf, t->name_off);
3358                 if (str_is_empty(targ_name))
3359                         continue;
3360
3361                 targ_essent_len = bpf_core_essential_name_len(targ_name);
3362                 if (targ_essent_len != local_essent_len)
3363                         continue;
3364
3365                 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
3366                         pr_debug("[%d] %s: found candidate [%d] %s\n",
3367                                  local_type_id, local_name, i, targ_name);
3368                         new_ids = realloc(cand_ids->data, cand_ids->len + 1);
3369                         if (!new_ids) {
3370                                 err = -ENOMEM;
3371                                 goto err_out;
3372                         }
3373                         cand_ids->data = new_ids;
3374                         cand_ids->data[cand_ids->len++] = i;
3375                 }
3376         }
3377         return cand_ids;
3378 err_out:
3379         bpf_core_free_cands(cand_ids);
3380         return ERR_PTR(err);
3381 }
3382
3383 /* Check two types for compatibility, skipping const/volatile/restrict and
3384  * typedefs, to ensure we are relocating compatible entities:
3385  *   - any two STRUCTs/UNIONs are compatible and can be mixed;
3386  *   - any two FWDs are compatible, if their names match (modulo flavor suffix);
3387  *   - any two PTRs are always compatible;
3388  *   - for ENUMs, names should be the same (ignoring flavor suffix) or at
3389  *     least one of enums should be anonymous;
3390  *   - for ENUMs, check sizes, names are ignored;
3391  *   - for INT, size and signedness are ignored;
3392  *   - for ARRAY, dimensionality is ignored, element types are checked for
3393  *     compatibility recursively;
3394  *   - everything else shouldn't be ever a target of relocation.
3395  * These rules are not set in stone and probably will be adjusted as we get
3396  * more experience with using BPF CO-RE relocations.
3397  */
3398 static int bpf_core_fields_are_compat(const struct btf *local_btf,
3399                                       __u32 local_id,
3400                                       const struct btf *targ_btf,
3401                                       __u32 targ_id)
3402 {
3403         const struct btf_type *local_type, *targ_type;
3404
3405 recur:
3406         local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
3407         targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3408         if (!local_type || !targ_type)
3409                 return -EINVAL;
3410
3411         if (btf_is_composite(local_type) && btf_is_composite(targ_type))
3412                 return 1;
3413         if (btf_kind(local_type) != btf_kind(targ_type))
3414                 return 0;
3415
3416         switch (btf_kind(local_type)) {
3417         case BTF_KIND_PTR:
3418                 return 1;
3419         case BTF_KIND_FWD:
3420         case BTF_KIND_ENUM: {
3421                 const char *local_name, *targ_name;
3422                 size_t local_len, targ_len;
3423
3424                 local_name = btf__name_by_offset(local_btf,
3425                                                  local_type->name_off);
3426                 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
3427                 local_len = bpf_core_essential_name_len(local_name);
3428                 targ_len = bpf_core_essential_name_len(targ_name);
3429                 /* one of them is anonymous or both w/ same flavor-less names */
3430                 return local_len == 0 || targ_len == 0 ||
3431                        (local_len == targ_len &&
3432                         strncmp(local_name, targ_name, local_len) == 0);
3433         }
3434         case BTF_KIND_INT:
3435                 /* just reject deprecated bitfield-like integers; all other
3436                  * integers are by default compatible between each other
3437                  */
3438                 return btf_int_offset(local_type) == 0 &&
3439                        btf_int_offset(targ_type) == 0;
3440         case BTF_KIND_ARRAY:
3441                 local_id = btf_array(local_type)->type;
3442                 targ_id = btf_array(targ_type)->type;
3443                 goto recur;
3444         default:
3445                 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3446                         btf_kind(local_type), local_id, targ_id);
3447                 return 0;
3448         }
3449 }
3450
3451 /*
3452  * Given single high-level named field accessor in local type, find
3453  * corresponding high-level accessor for a target type. Along the way,
3454  * maintain low-level spec for target as well. Also keep updating target
3455  * bit offset.
3456  *
3457  * Searching is performed through recursive exhaustive enumeration of all
3458  * fields of a struct/union. If there are any anonymous (embedded)
3459  * structs/unions, they are recursively searched as well. If field with
3460  * desired name is found, check compatibility between local and target types,
3461  * before returning result.
3462  *
3463  * 1 is returned, if field is found.
3464  * 0 is returned if no compatible field is found.
3465  * <0 is returned on error.
3466  */
3467 static int bpf_core_match_member(const struct btf *local_btf,
3468                                  const struct bpf_core_accessor *local_acc,
3469                                  const struct btf *targ_btf,
3470                                  __u32 targ_id,
3471                                  struct bpf_core_spec *spec,
3472                                  __u32 *next_targ_id)
3473 {
3474         const struct btf_type *local_type, *targ_type;
3475         const struct btf_member *local_member, *m;
3476         const char *local_name, *targ_name;
3477         __u32 local_id;
3478         int i, n, found;
3479
3480         targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3481         if (!targ_type)
3482                 return -EINVAL;
3483         if (!btf_is_composite(targ_type))
3484                 return 0;
3485
3486         local_id = local_acc->type_id;
3487         local_type = btf__type_by_id(local_btf, local_id);
3488         local_member = btf_members(local_type) + local_acc->idx;
3489         local_name = btf__name_by_offset(local_btf, local_member->name_off);
3490
3491         n = btf_vlen(targ_type);
3492         m = btf_members(targ_type);
3493         for (i = 0; i < n; i++, m++) {
3494                 __u32 bit_offset;
3495
3496                 bit_offset = btf_member_bit_offset(targ_type, i);
3497
3498                 /* too deep struct/union/array nesting */
3499                 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3500                         return -E2BIG;
3501
3502                 /* speculate this member will be the good one */
3503                 spec->bit_offset += bit_offset;
3504                 spec->raw_spec[spec->raw_len++] = i;
3505
3506                 targ_name = btf__name_by_offset(targ_btf, m->name_off);
3507                 if (str_is_empty(targ_name)) {
3508                         /* embedded struct/union, we need to go deeper */
3509                         found = bpf_core_match_member(local_btf, local_acc,
3510                                                       targ_btf, m->type,
3511                                                       spec, next_targ_id);
3512                         if (found) /* either found or error */
3513                                 return found;
3514                 } else if (strcmp(local_name, targ_name) == 0) {
3515                         /* matching named field */
3516                         struct bpf_core_accessor *targ_acc;
3517
3518                         targ_acc = &spec->spec[spec->len++];
3519                         targ_acc->type_id = targ_id;
3520                         targ_acc->idx = i;
3521                         targ_acc->name = targ_name;
3522
3523                         *next_targ_id = m->type;
3524                         found = bpf_core_fields_are_compat(local_btf,
3525                                                            local_member->type,
3526                                                            targ_btf, m->type);
3527                         if (!found)
3528                                 spec->len--; /* pop accessor */
3529                         return found;
3530                 }
3531                 /* member turned out not to be what we looked for */
3532                 spec->bit_offset -= bit_offset;
3533                 spec->raw_len--;
3534         }
3535
3536         return 0;
3537 }
3538
3539 /*
3540  * Try to match local spec to a target type and, if successful, produce full
3541  * target spec (high-level, low-level + bit offset).
3542  */
3543 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
3544                                const struct btf *targ_btf, __u32 targ_id,
3545                                struct bpf_core_spec *targ_spec)
3546 {
3547         const struct btf_type *targ_type;
3548         const struct bpf_core_accessor *local_acc;
3549         struct bpf_core_accessor *targ_acc;
3550         int i, sz, matched;
3551
3552         memset(targ_spec, 0, sizeof(*targ_spec));
3553         targ_spec->btf = targ_btf;
3554
3555         local_acc = &local_spec->spec[0];
3556         targ_acc = &targ_spec->spec[0];
3557
3558         for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
3559                 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
3560                                                    &targ_id);
3561                 if (!targ_type)
3562                         return -EINVAL;
3563
3564                 if (local_acc->name) {
3565                         matched = bpf_core_match_member(local_spec->btf,
3566                                                         local_acc,
3567                                                         targ_btf, targ_id,
3568                                                         targ_spec, &targ_id);
3569                         if (matched <= 0)
3570                                 return matched;
3571                 } else {
3572                         /* for i=0, targ_id is already treated as array element
3573                          * type (because it's the original struct), for others
3574                          * we should find array element type first
3575                          */
3576                         if (i > 0) {
3577                                 const struct btf_array *a;
3578                                 bool flex;
3579
3580                                 if (!btf_is_array(targ_type))
3581                                         return 0;
3582
3583                                 a = btf_array(targ_type);
3584                                 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
3585                                 if (!flex && local_acc->idx >= a->nelems)
3586                                         return 0;
3587                                 if (!skip_mods_and_typedefs(targ_btf, a->type,
3588                                                             &targ_id))
3589                                         return -EINVAL;
3590                         }
3591
3592                         /* too deep struct/union/array nesting */
3593                         if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3594                                 return -E2BIG;
3595
3596                         targ_acc->type_id = targ_id;
3597                         targ_acc->idx = local_acc->idx;
3598                         targ_acc->name = NULL;
3599                         targ_spec->len++;
3600                         targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
3601                         targ_spec->raw_len++;
3602
3603                         sz = btf__resolve_size(targ_btf, targ_id);
3604                         if (sz < 0)
3605                                 return sz;
3606                         targ_spec->bit_offset += local_acc->idx * sz * 8;
3607                 }
3608         }
3609
3610         return 1;
3611 }
3612
3613 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
3614                                     const struct bpf_field_reloc *relo,
3615                                     const struct bpf_core_spec *spec,
3616                                     __u32 *val, bool *validate)
3617 {
3618         const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
3619         const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
3620         __u32 byte_off, byte_sz, bit_off, bit_sz;
3621         const struct btf_member *m;
3622         const struct btf_type *mt;
3623         bool bitfield;
3624         __s64 sz;
3625
3626         /* a[n] accessor needs special handling */
3627         if (!acc->name) {
3628                 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
3629                         *val = spec->bit_offset / 8;
3630                 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
3631                         sz = btf__resolve_size(spec->btf, acc->type_id);
3632                         if (sz < 0)
3633                                 return -EINVAL;
3634                         *val = sz;
3635                 } else {
3636                         pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
3637                                 bpf_program__title(prog, false),
3638                                 relo->kind, relo->insn_off / 8);
3639                         return -EINVAL;
3640                 }
3641                 if (validate)
3642                         *validate = true;
3643                 return 0;
3644         }
3645
3646         m = btf_members(t) + acc->idx;
3647         mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3648         bit_off = spec->bit_offset;
3649         bit_sz = btf_member_bitfield_size(t, acc->idx);
3650
3651         bitfield = bit_sz > 0;
3652         if (bitfield) {
3653                 byte_sz = mt->size;
3654                 byte_off = bit_off / 8 / byte_sz * byte_sz;
3655                 /* figure out smallest int size necessary for bitfield load */
3656                 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3657                         if (byte_sz >= 8) {
3658                                 /* bitfield can't be read with 64-bit read */
3659                                 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3660                                         bpf_program__title(prog, false),
3661                                         relo->kind, relo->insn_off / 8);
3662                                 return -E2BIG;
3663                         }
3664                         byte_sz *= 2;
3665                         byte_off = bit_off / 8 / byte_sz * byte_sz;
3666                 }
3667         } else {
3668                 sz = btf__resolve_size(spec->btf, m->type);
3669                 if (sz < 0)
3670                         return -EINVAL;
3671                 byte_sz = sz;
3672                 byte_off = spec->bit_offset / 8;
3673                 bit_sz = byte_sz * 8;
3674         }
3675
3676         /* for bitfields, all the relocatable aspects are ambiguous and we
3677          * might disagree with compiler, so turn off validation of expected
3678          * value, except for signedness
3679          */
3680         if (validate)
3681                 *validate = !bitfield;
3682
3683         switch (relo->kind) {
3684         case BPF_FIELD_BYTE_OFFSET:
3685                 *val = byte_off;
3686                 break;
3687         case BPF_FIELD_BYTE_SIZE:
3688                 *val = byte_sz;
3689                 break;
3690         case BPF_FIELD_SIGNED:
3691                 /* enums will be assumed unsigned */
3692                 *val = btf_is_enum(mt) ||
3693                        (btf_int_encoding(mt) & BTF_INT_SIGNED);
3694                 if (validate)
3695                         *validate = true; /* signedness is never ambiguous */
3696                 break;
3697         case BPF_FIELD_LSHIFT_U64:
3698 #if __BYTE_ORDER == __LITTLE_ENDIAN
3699                 *val = 64 - (bit_off + bit_sz - byte_off  * 8);
3700 #else
3701                 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3702 #endif
3703                 break;
3704         case BPF_FIELD_RSHIFT_U64:
3705                 *val = 64 - bit_sz;
3706                 if (validate)
3707                         *validate = true; /* right shift is never ambiguous */
3708                 break;
3709         case BPF_FIELD_EXISTS:
3710         default:
3711                 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3712                         bpf_program__title(prog, false),
3713                         relo->kind, relo->insn_off / 8);
3714                 return -EINVAL;
3715         }
3716
3717         return 0;
3718 }
3719
3720 /*
3721  * Patch relocatable BPF instruction.
3722  *
3723  * Patched value is determined by relocation kind and target specification.
3724  * For field existence relocation target spec will be NULL if field is not
3725  * found.
3726  * Expected insn->imm value is determined using relocation kind and local
3727  * spec, and is checked before patching instruction. If actual insn->imm value
3728  * is wrong, bail out with error.
3729  *
3730  * Currently three kinds of BPF instructions are supported:
3731  * 1. rX = <imm> (assignment with immediate operand);
3732  * 2. rX += <imm> (arithmetic operations with immediate operand);
3733  */
3734 static int bpf_core_reloc_insn(struct bpf_program *prog,
3735                                const struct bpf_field_reloc *relo,
3736                                const struct bpf_core_spec *local_spec,
3737                                const struct bpf_core_spec *targ_spec)
3738 {
3739         bool failed = false, validate = true;
3740         __u32 orig_val, new_val;
3741         struct bpf_insn *insn;
3742         int insn_idx, err;
3743         __u8 class;
3744
3745         if (relo->insn_off % sizeof(struct bpf_insn))
3746                 return -EINVAL;
3747         insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3748
3749         if (relo->kind == BPF_FIELD_EXISTS) {
3750                 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3751                 new_val = targ_spec ? 1 : 0;
3752         } else if (!targ_spec) {
3753                 failed = true;
3754                 new_val = (__u32)-1;
3755         } else {
3756                 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3757                                                &orig_val, &validate);
3758                 if (err)
3759                         return err;
3760                 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3761                                                &new_val, NULL);
3762                 if (err)
3763                         return err;
3764         }
3765
3766         insn = &prog->insns[insn_idx];
3767         class = BPF_CLASS(insn->code);
3768
3769         if (class == BPF_ALU || class == BPF_ALU64) {
3770                 if (BPF_SRC(insn->code) != BPF_K)
3771                         return -EINVAL;
3772                 if (!failed && validate && insn->imm != orig_val) {
3773                         pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3774                                 bpf_program__title(prog, false), insn_idx,
3775                                 insn->imm, orig_val, new_val);
3776                         return -EINVAL;
3777                 }
3778                 orig_val = insn->imm;
3779                 insn->imm = new_val;
3780                 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3781                          bpf_program__title(prog, false), insn_idx,
3782                          failed ? " w/ failed reloc" : "", orig_val, new_val);
3783         } else {
3784                 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3785                         bpf_program__title(prog, false),
3786                         insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3787                         insn->off, insn->imm);
3788                 return -EINVAL;
3789         }
3790
3791         return 0;
3792 }
3793
3794 static struct btf *btf_load_raw(const char *path)
3795 {
3796         struct btf *btf;
3797         size_t read_cnt;
3798         struct stat st;
3799         void *data;
3800         FILE *f;
3801
3802         if (stat(path, &st))
3803                 return ERR_PTR(-errno);
3804
3805         data = malloc(st.st_size);
3806         if (!data)
3807                 return ERR_PTR(-ENOMEM);
3808
3809         f = fopen(path, "rb");
3810         if (!f) {
3811                 btf = ERR_PTR(-errno);
3812                 goto cleanup;
3813         }
3814
3815         read_cnt = fread(data, 1, st.st_size, f);
3816         fclose(f);
3817         if (read_cnt < st.st_size) {
3818                 btf = ERR_PTR(-EBADF);
3819                 goto cleanup;
3820         }
3821
3822         btf = btf__new(data, read_cnt);
3823
3824 cleanup:
3825         free(data);
3826         return btf;
3827 }
3828
3829 /*
3830  * Probe few well-known locations for vmlinux kernel image and try to load BTF
3831  * data out of it to use for target BTF.
3832  */
3833 static struct btf *bpf_core_find_kernel_btf(void)
3834 {
3835         struct {
3836                 const char *path_fmt;
3837                 bool raw_btf;
3838         } locations[] = {
3839                 /* try canonical vmlinux BTF through sysfs first */
3840                 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3841                 /* fall back to trying to find vmlinux ELF on disk otherwise */
3842                 { "/boot/vmlinux-%1$s" },
3843                 { "/lib/modules/%1$s/vmlinux-%1$s" },
3844                 { "/lib/modules/%1$s/build/vmlinux" },
3845                 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3846                 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3847                 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3848                 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3849         };
3850         char path[PATH_MAX + 1];
3851         struct utsname buf;
3852         struct btf *btf;
3853         int i;
3854
3855         uname(&buf);
3856
3857         for (i = 0; i < ARRAY_SIZE(locations); i++) {
3858                 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3859
3860                 if (access(path, R_OK))
3861                         continue;
3862
3863                 if (locations[i].raw_btf)
3864                         btf = btf_load_raw(path);
3865                 else
3866                         btf = btf__parse_elf(path, NULL);
3867
3868                 pr_debug("loading kernel BTF '%s': %ld\n",
3869                          path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3870                 if (IS_ERR(btf))
3871                         continue;
3872
3873                 return btf;
3874         }
3875
3876         pr_warn("failed to find valid kernel BTF\n");
3877         return ERR_PTR(-ESRCH);
3878 }
3879
3880 /* Output spec definition in the format:
3881  * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3882  * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3883  */
3884 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3885 {
3886         const struct btf_type *t;
3887         const char *s;
3888         __u32 type_id;
3889         int i;
3890
3891         type_id = spec->spec[0].type_id;
3892         t = btf__type_by_id(spec->btf, type_id);
3893         s = btf__name_by_offset(spec->btf, t->name_off);
3894         libbpf_print(level, "[%u] %s + ", type_id, s);
3895
3896         for (i = 0; i < spec->raw_len; i++)
3897                 libbpf_print(level, "%d%s", spec->raw_spec[i],
3898                              i == spec->raw_len - 1 ? " => " : ":");
3899
3900         libbpf_print(level, "%u.%u @ &x",
3901                      spec->bit_offset / 8, spec->bit_offset % 8);
3902
3903         for (i = 0; i < spec->len; i++) {
3904                 if (spec->spec[i].name)
3905                         libbpf_print(level, ".%s", spec->spec[i].name);
3906                 else
3907                         libbpf_print(level, "[%u]", spec->spec[i].idx);
3908         }
3909
3910 }
3911
3912 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3913 {
3914         return (size_t)key;
3915 }
3916
3917 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3918 {
3919         return k1 == k2;
3920 }
3921
3922 static void *u32_as_hash_key(__u32 x)
3923 {
3924         return (void *)(uintptr_t)x;
3925 }
3926
3927 /*
3928  * CO-RE relocate single instruction.
3929  *
3930  * The outline and important points of the algorithm:
3931  * 1. For given local type, find corresponding candidate target types.
3932  *    Candidate type is a type with the same "essential" name, ignoring
3933  *    everything after last triple underscore (___). E.g., `sample`,
3934  *    `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3935  *    for each other. Names with triple underscore are referred to as
3936  *    "flavors" and are useful, among other things, to allow to
3937  *    specify/support incompatible variations of the same kernel struct, which
3938  *    might differ between different kernel versions and/or build
3939  *    configurations.
3940  *
3941  *    N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3942  *    converter, when deduplicated BTF of a kernel still contains more than
3943  *    one different types with the same name. In that case, ___2, ___3, etc
3944  *    are appended starting from second name conflict. But start flavors are
3945  *    also useful to be defined "locally", in BPF program, to extract same
3946  *    data from incompatible changes between different kernel
3947  *    versions/configurations. For instance, to handle field renames between
3948  *    kernel versions, one can use two flavors of the struct name with the
3949  *    same common name and use conditional relocations to extract that field,
3950  *    depending on target kernel version.
3951  * 2. For each candidate type, try to match local specification to this
3952  *    candidate target type. Matching involves finding corresponding
3953  *    high-level spec accessors, meaning that all named fields should match,
3954  *    as well as all array accesses should be within the actual bounds. Also,
3955  *    types should be compatible (see bpf_core_fields_are_compat for details).
3956  * 3. It is supported and expected that there might be multiple flavors
3957  *    matching the spec. As long as all the specs resolve to the same set of
3958  *    offsets across all candidates, there is no error. If there is any
3959  *    ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3960  *    imprefection of BTF deduplication, which can cause slight duplication of
3961  *    the same BTF type, if some directly or indirectly referenced (by
3962  *    pointer) type gets resolved to different actual types in different
3963  *    object files. If such situation occurs, deduplicated BTF will end up
3964  *    with two (or more) structurally identical types, which differ only in
3965  *    types they refer to through pointer. This should be OK in most cases and
3966  *    is not an error.
3967  * 4. Candidate types search is performed by linearly scanning through all
3968  *    types in target BTF. It is anticipated that this is overall more
3969  *    efficient memory-wise and not significantly worse (if not better)
3970  *    CPU-wise compared to prebuilding a map from all local type names to
3971  *    a list of candidate type names. It's also sped up by caching resolved
3972  *    list of matching candidates per each local "root" type ID, that has at
3973  *    least one bpf_field_reloc associated with it. This list is shared
3974  *    between multiple relocations for the same type ID and is updated as some
3975  *    of the candidates are pruned due to structural incompatibility.
3976  */
3977 static int bpf_core_reloc_field(struct bpf_program *prog,
3978                                  const struct bpf_field_reloc *relo,
3979                                  int relo_idx,
3980                                  const struct btf *local_btf,
3981                                  const struct btf *targ_btf,
3982                                  struct hashmap *cand_cache)
3983 {
3984         const char *prog_name = bpf_program__title(prog, false);
3985         struct bpf_core_spec local_spec, cand_spec, targ_spec;
3986         const void *type_key = u32_as_hash_key(relo->type_id);
3987         const struct btf_type *local_type, *cand_type;
3988         const char *local_name, *cand_name;
3989         struct ids_vec *cand_ids;
3990         __u32 local_id, cand_id;
3991         const char *spec_str;
3992         int i, j, err;
3993
3994         local_id = relo->type_id;
3995         local_type = btf__type_by_id(local_btf, local_id);
3996         if (!local_type)
3997                 return -EINVAL;
3998
3999         local_name = btf__name_by_offset(local_btf, local_type->name_off);
4000         if (str_is_empty(local_name))
4001                 return -EINVAL;
4002
4003         spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4004         if (str_is_empty(spec_str))
4005                 return -EINVAL;
4006
4007         err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4008         if (err) {
4009                 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4010                         prog_name, relo_idx, local_id, local_name, spec_str,
4011                         err);
4012                 return -EINVAL;
4013         }
4014
4015         pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4016                  relo->kind);
4017         bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4018         libbpf_print(LIBBPF_DEBUG, "\n");
4019
4020         if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4021                 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4022                 if (IS_ERR(cand_ids)) {
4023                         pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4024                                 prog_name, relo_idx, local_id, local_name,
4025                                 PTR_ERR(cand_ids));
4026                         return PTR_ERR(cand_ids);
4027                 }
4028                 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4029                 if (err) {
4030                         bpf_core_free_cands(cand_ids);
4031                         return err;
4032                 }
4033         }
4034
4035         for (i = 0, j = 0; i < cand_ids->len; i++) {
4036                 cand_id = cand_ids->data[i];
4037                 cand_type = btf__type_by_id(targ_btf, cand_id);
4038                 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4039
4040                 err = bpf_core_spec_match(&local_spec, targ_btf,
4041                                           cand_id, &cand_spec);
4042                 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4043                          prog_name, relo_idx, i, cand_name);
4044                 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4045                 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4046                 if (err < 0) {
4047                         pr_warn("prog '%s': relo #%d: matching error: %d\n",
4048                                 prog_name, relo_idx, err);
4049                         return err;
4050                 }
4051                 if (err == 0)
4052                         continue;
4053
4054                 if (j == 0) {
4055                         targ_spec = cand_spec;
4056                 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4057                         /* if there are many candidates, they should all
4058                          * resolve to the same bit offset
4059                          */
4060                         pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4061                                 prog_name, relo_idx, cand_spec.bit_offset,
4062                                 targ_spec.bit_offset);
4063                         return -EINVAL;
4064                 }
4065
4066                 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4067         }
4068
4069         /*
4070          * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
4071          * requested, it's expected that we might not find any candidates.
4072          * In this case, if field wasn't found in any candidate, the list of
4073          * candidates shouldn't change at all, we'll just handle relocating
4074          * appropriately, depending on relo's kind.
4075          */
4076         if (j > 0)
4077                 cand_ids->len = j;
4078
4079         if (j == 0 && !prog->obj->relaxed_core_relocs &&
4080             relo->kind != BPF_FIELD_EXISTS) {
4081                 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4082                         prog_name, relo_idx, local_id, local_name, spec_str);
4083                 return -ESRCH;
4084         }
4085
4086         /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4087         err = bpf_core_reloc_insn(prog, relo, &local_spec,
4088                                   j ? &targ_spec : NULL);
4089         if (err) {
4090                 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4091                         prog_name, relo_idx, relo->insn_off, err);
4092                 return -EINVAL;
4093         }
4094
4095         return 0;
4096 }
4097
4098 static int
4099 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4100 {
4101         const struct btf_ext_info_sec *sec;
4102         const struct bpf_field_reloc *rec;
4103         const struct btf_ext_info *seg;
4104         struct hashmap_entry *entry;
4105         struct hashmap *cand_cache = NULL;
4106         struct bpf_program *prog;
4107         struct btf *targ_btf;
4108         const char *sec_name;
4109         int i, err = 0;
4110
4111         if (targ_btf_path)
4112                 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4113         else
4114                 targ_btf = bpf_core_find_kernel_btf();
4115         if (IS_ERR(targ_btf)) {
4116                 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4117                 return PTR_ERR(targ_btf);
4118         }
4119
4120         cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4121         if (IS_ERR(cand_cache)) {
4122                 err = PTR_ERR(cand_cache);
4123                 goto out;
4124         }
4125
4126         seg = &obj->btf_ext->field_reloc_info;
4127         for_each_btf_ext_sec(seg, sec) {
4128                 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4129                 if (str_is_empty(sec_name)) {
4130                         err = -EINVAL;
4131                         goto out;
4132                 }
4133                 prog = bpf_object__find_program_by_title(obj, sec_name);
4134                 if (!prog) {
4135                         pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4136                                 sec_name);
4137                         err = -EINVAL;
4138                         goto out;
4139                 }
4140
4141                 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4142                          sec_name, sec->num_info);
4143
4144                 for_each_btf_ext_rec(seg, sec, i, rec) {
4145                         err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4146                                                    targ_btf, cand_cache);
4147                         if (err) {
4148                                 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4149                                         sec_name, i, err);
4150                                 goto out;
4151                         }
4152                 }
4153         }
4154
4155 out:
4156         btf__free(targ_btf);
4157         if (!IS_ERR_OR_NULL(cand_cache)) {
4158                 hashmap__for_each_entry(cand_cache, entry, i) {
4159                         bpf_core_free_cands(entry->value);
4160                 }
4161                 hashmap__free(cand_cache);
4162         }
4163         return err;
4164 }
4165
4166 static int
4167 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4168 {
4169         int err = 0;
4170
4171         if (obj->btf_ext->field_reloc_info.len)
4172                 err = bpf_core_reloc_fields(obj, targ_btf_path);
4173
4174         return err;
4175 }
4176
4177 static int
4178 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4179                         struct reloc_desc *relo)
4180 {
4181         struct bpf_insn *insn, *new_insn;
4182         struct bpf_program *text;
4183         size_t new_cnt;
4184         int err;
4185
4186         if (prog->idx == obj->efile.text_shndx) {
4187                 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
4188                         relo->insn_idx, relo->sym_off, relo->sym_off / 8);
4189                 return -LIBBPF_ERRNO__RELOC;
4190         }
4191
4192         if (prog->main_prog_cnt == 0) {
4193                 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4194                 if (!text) {
4195                         pr_warn("no .text section found yet relo into text exist\n");
4196                         return -LIBBPF_ERRNO__RELOC;
4197                 }
4198                 new_cnt = prog->insns_cnt + text->insns_cnt;
4199                 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4200                 if (!new_insn) {
4201                         pr_warn("oom in prog realloc\n");
4202                         return -ENOMEM;
4203                 }
4204                 prog->insns = new_insn;
4205
4206                 if (obj->btf_ext) {
4207                         err = bpf_program_reloc_btf_ext(prog, obj,
4208                                                         text->section_name,
4209                                                         prog->insns_cnt);
4210                         if (err)
4211                                 return err;
4212                 }
4213
4214                 memcpy(new_insn + prog->insns_cnt, text->insns,
4215                        text->insns_cnt * sizeof(*insn));
4216                 prog->main_prog_cnt = prog->insns_cnt;
4217                 prog->insns_cnt = new_cnt;
4218                 pr_debug("added %zd insn from %s to prog %s\n",
4219                          text->insns_cnt, text->section_name,
4220                          prog->section_name);
4221         }
4222         insn = &prog->insns[relo->insn_idx];
4223         insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4224         return 0;
4225 }
4226
4227 static int
4228 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4229 {
4230         int i, err;
4231
4232         if (!prog)
4233                 return 0;
4234
4235         if (obj->btf_ext) {
4236                 err = bpf_program_reloc_btf_ext(prog, obj,
4237                                                 prog->section_name, 0);
4238                 if (err)
4239                         return err;
4240         }
4241
4242         if (!prog->reloc_desc)
4243                 return 0;
4244
4245         for (i = 0; i < prog->nr_reloc; i++) {
4246                 struct reloc_desc *relo = &prog->reloc_desc[i];
4247                 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4248
4249                 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4250                         pr_warn("relocation out of range: '%s'\n",
4251                                 prog->section_name);
4252                         return -LIBBPF_ERRNO__RELOC;
4253                 }
4254
4255                 switch (relo->type) {
4256                 case RELO_LD64:
4257                         insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4258                         insn[0].imm = obj->maps[relo->map_idx].fd;
4259                         break;
4260                 case RELO_DATA:
4261                         insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4262                         insn[1].imm = insn[0].imm + relo->sym_off;
4263                         insn[0].imm = obj->maps[relo->map_idx].fd;
4264                         break;
4265                 case RELO_EXTERN:
4266                         insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4267                         insn[0].imm = obj->maps[obj->extern_map_idx].fd;
4268                         insn[1].imm = relo->sym_off;
4269                         break;
4270                 case RELO_CALL:
4271                         err = bpf_program__reloc_text(prog, obj, relo);
4272                         if (err)
4273                                 return err;
4274                         break;
4275                 default:
4276                         pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4277                         return -EINVAL;
4278                 }
4279         }
4280
4281         zfree(&prog->reloc_desc);
4282         prog->nr_reloc = 0;
4283         return 0;
4284 }
4285
4286 static int
4287 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4288 {
4289         struct bpf_program *prog;
4290         size_t i;
4291         int err;
4292
4293         if (obj->btf_ext) {
4294                 err = bpf_object__relocate_core(obj, targ_btf_path);
4295                 if (err) {
4296                         pr_warn("failed to perform CO-RE relocations: %d\n",
4297                                 err);
4298                         return err;
4299                 }
4300         }
4301         for (i = 0; i < obj->nr_programs; i++) {
4302                 prog = &obj->programs[i];
4303
4304                 err = bpf_program__relocate(prog, obj);
4305                 if (err) {
4306                         pr_warn("failed to relocate '%s'\n", prog->section_name);
4307                         return err;
4308                 }
4309         }
4310         return 0;
4311 }
4312
4313 static int bpf_object__collect_reloc(struct bpf_object *obj)
4314 {
4315         int i, err;
4316
4317         if (!obj_elf_valid(obj)) {
4318                 pr_warn("Internal error: elf object is closed\n");
4319                 return -LIBBPF_ERRNO__INTERNAL;
4320         }
4321
4322         for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
4323                 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
4324                 Elf_Data *data = obj->efile.reloc_sects[i].data;
4325                 int idx = shdr->sh_info;
4326                 struct bpf_program *prog;
4327
4328                 if (shdr->sh_type != SHT_REL) {
4329                         pr_warn("internal error at %d\n", __LINE__);
4330                         return -LIBBPF_ERRNO__INTERNAL;
4331                 }
4332
4333                 prog = bpf_object__find_prog_by_idx(obj, idx);
4334                 if (!prog) {
4335                         pr_warn("relocation failed: no section(%d)\n", idx);
4336                         return -LIBBPF_ERRNO__RELOC;
4337                 }
4338
4339                 err = bpf_program__collect_reloc(prog, shdr, data, obj);
4340                 if (err)
4341                         return err;
4342         }
4343         return 0;
4344 }
4345
4346 static int
4347 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
4348              char *license, __u32 kern_version, int *pfd)
4349 {
4350         struct bpf_load_program_attr load_attr;
4351         char *cp, errmsg[STRERR_BUFSIZE];
4352         int log_buf_size = BPF_LOG_BUF_SIZE;
4353         char *log_buf;
4354         int btf_fd, ret;
4355
4356         if (!insns || !insns_cnt)
4357                 return -EINVAL;
4358
4359         memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
4360         load_attr.prog_type = prog->type;
4361         load_attr.expected_attach_type = prog->expected_attach_type;
4362         if (prog->caps->name)
4363                 load_attr.name = prog->name;
4364         load_attr.insns = insns;
4365         load_attr.insns_cnt = insns_cnt;
4366         load_attr.license = license;
4367         if (prog->type == BPF_PROG_TYPE_TRACING) {
4368                 load_attr.attach_prog_fd = prog->attach_prog_fd;
4369                 load_attr.attach_btf_id = prog->attach_btf_id;
4370         } else {
4371                 load_attr.kern_version = kern_version;
4372                 load_attr.prog_ifindex = prog->prog_ifindex;
4373         }
4374         /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4375         if (prog->obj->btf_ext)
4376                 btf_fd = bpf_object__btf_fd(prog->obj);
4377         else
4378                 btf_fd = -1;
4379         load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
4380         load_attr.func_info = prog->func_info;
4381         load_attr.func_info_rec_size = prog->func_info_rec_size;
4382         load_attr.func_info_cnt = prog->func_info_cnt;
4383         load_attr.line_info = prog->line_info;
4384         load_attr.line_info_rec_size = prog->line_info_rec_size;
4385         load_attr.line_info_cnt = prog->line_info_cnt;
4386         load_attr.log_level = prog->log_level;
4387         load_attr.prog_flags = prog->prog_flags;
4388
4389 retry_load:
4390         log_buf = malloc(log_buf_size);
4391         if (!log_buf)
4392                 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
4393
4394         ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
4395
4396         if (ret >= 0) {
4397                 if (load_attr.log_level)
4398                         pr_debug("verifier log:\n%s", log_buf);
4399                 *pfd = ret;
4400                 ret = 0;
4401                 goto out;
4402         }
4403
4404         if (errno == ENOSPC) {
4405                 log_buf_size <<= 1;
4406                 free(log_buf);
4407                 goto retry_load;
4408         }
4409         ret = -errno;
4410         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4411         pr_warn("load bpf program failed: %s\n", cp);
4412         pr_perm_msg(ret);
4413
4414         if (log_buf && log_buf[0] != '\0') {
4415                 ret = -LIBBPF_ERRNO__VERIFY;
4416                 pr_warn("-- BEGIN DUMP LOG ---\n");
4417                 pr_warn("\n%s\n", log_buf);
4418                 pr_warn("-- END LOG --\n");
4419         } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
4420                 pr_warn("Program too large (%zu insns), at most %d insns\n",
4421                         load_attr.insns_cnt, BPF_MAXINSNS);
4422                 ret = -LIBBPF_ERRNO__PROG2BIG;
4423         } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
4424                 /* Wrong program type? */
4425                 int fd;
4426
4427                 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
4428                 load_attr.expected_attach_type = 0;
4429                 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
4430                 if (fd >= 0) {
4431                         close(fd);
4432                         ret = -LIBBPF_ERRNO__PROGTYPE;
4433                         goto out;
4434                 }
4435         }
4436
4437 out:
4438         free(log_buf);
4439         return ret;
4440 }
4441
4442 static int libbpf_find_attach_btf_id(const char *name,
4443                                      enum bpf_attach_type attach_type,
4444                                      __u32 attach_prog_fd);
4445
4446 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
4447 {
4448         int err = 0, fd, i, btf_id;
4449
4450         if (prog->type == BPF_PROG_TYPE_TRACING) {
4451                 btf_id = libbpf_find_attach_btf_id(prog->section_name,
4452                                                    prog->expected_attach_type,
4453                                                    prog->attach_prog_fd);
4454                 if (btf_id <= 0)
4455                         return btf_id;
4456                 prog->attach_btf_id = btf_id;
4457         }
4458
4459         if (prog->instances.nr < 0 || !prog->instances.fds) {
4460                 if (prog->preprocessor) {
4461                         pr_warn("Internal error: can't load program '%s'\n",
4462                                 prog->section_name);
4463                         return -LIBBPF_ERRNO__INTERNAL;
4464                 }
4465
4466                 prog->instances.fds = malloc(sizeof(int));
4467                 if (!prog->instances.fds) {
4468                         pr_warn("Not enough memory for BPF fds\n");
4469                         return -ENOMEM;
4470                 }
4471                 prog->instances.nr = 1;
4472                 prog->instances.fds[0] = -1;
4473         }
4474
4475         if (!prog->preprocessor) {
4476                 if (prog->instances.nr != 1) {
4477                         pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4478                                 prog->section_name, prog->instances.nr);
4479                 }
4480                 err = load_program(prog, prog->insns, prog->insns_cnt,
4481                                    license, kern_ver, &fd);
4482                 if (!err)
4483                         prog->instances.fds[0] = fd;
4484                 goto out;
4485         }
4486
4487         for (i = 0; i < prog->instances.nr; i++) {
4488                 struct bpf_prog_prep_result result;
4489                 bpf_program_prep_t preprocessor = prog->preprocessor;
4490
4491                 memset(&result, 0, sizeof(result));
4492                 err = preprocessor(prog, i, prog->insns,
4493                                    prog->insns_cnt, &result);
4494                 if (err) {
4495                         pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
4496                                 i, prog->section_name);
4497                         goto out;
4498                 }
4499
4500                 if (!result.new_insn_ptr || !result.new_insn_cnt) {
4501                         pr_debug("Skip loading the %dth instance of program '%s'\n",
4502                                  i, prog->section_name);
4503                         prog->instances.fds[i] = -1;
4504                         if (result.pfd)
4505                                 *result.pfd = -1;
4506                         continue;
4507                 }
4508
4509                 err = load_program(prog, result.new_insn_ptr,
4510                                    result.new_insn_cnt, license, kern_ver, &fd);
4511                 if (err) {
4512                         pr_warn("Loading the %dth instance of program '%s' failed\n",
4513                                 i, prog->section_name);
4514                         goto out;
4515                 }
4516
4517                 if (result.pfd)
4518                         *result.pfd = fd;
4519                 prog->instances.fds[i] = fd;
4520         }
4521 out:
4522         if (err)
4523                 pr_warn("failed to load program '%s'\n", prog->section_name);
4524         zfree(&prog->insns);
4525         prog->insns_cnt = 0;
4526         return err;
4527 }
4528
4529 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
4530                                              const struct bpf_object *obj)
4531 {
4532         return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
4533 }
4534
4535 static int
4536 bpf_object__load_progs(struct bpf_object *obj, int log_level)
4537 {
4538         size_t i;
4539         int err;
4540
4541         for (i = 0; i < obj->nr_programs; i++) {
4542                 if (bpf_program__is_function_storage(&obj->programs[i], obj))
4543                         continue;
4544                 obj->programs[i].log_level |= log_level;
4545                 err = bpf_program__load(&obj->programs[i],
4546                                         obj->license,
4547                                         obj->kern_version);
4548                 if (err)
4549                         return err;
4550         }
4551         return 0;
4552 }
4553
4554 static struct bpf_object *
4555 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
4556                    const struct bpf_object_open_opts *opts)
4557 {
4558         const char *obj_name, *kconfig_path;
4559         struct bpf_program *prog;
4560         struct bpf_object *obj;
4561         char tmp_name[64];
4562         int err;
4563
4564         if (elf_version(EV_CURRENT) == EV_NONE) {
4565                 pr_warn("failed to init libelf for %s\n",
4566                         path ? : "(mem buf)");
4567                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
4568         }
4569
4570         if (!OPTS_VALID(opts, bpf_object_open_opts))
4571                 return ERR_PTR(-EINVAL);
4572
4573         obj_name = OPTS_GET(opts, object_name, NULL);
4574         if (obj_buf) {
4575                 if (!obj_name) {
4576                         snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
4577                                  (unsigned long)obj_buf,
4578                                  (unsigned long)obj_buf_sz);
4579                         obj_name = tmp_name;
4580                 }
4581                 path = obj_name;
4582                 pr_debug("loading object '%s' from buffer\n", obj_name);
4583         }
4584
4585         obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
4586         if (IS_ERR(obj))
4587                 return obj;
4588
4589         obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
4590         kconfig_path = OPTS_GET(opts, kconfig_path, NULL);
4591         if (kconfig_path) {
4592                 obj->kconfig_path = strdup(kconfig_path);
4593                 if (!obj->kconfig_path)
4594                         return ERR_PTR(-ENOMEM);
4595         }
4596
4597         err = bpf_object__elf_init(obj);
4598         err = err ? : bpf_object__check_endianness(obj);
4599         err = err ? : bpf_object__elf_collect(obj);
4600         err = err ? : bpf_object__collect_externs(obj);
4601         err = err ? : bpf_object__finalize_btf(obj);
4602         err = err ? : bpf_object__init_maps(obj, opts);
4603         err = err ? : bpf_object__init_prog_names(obj);
4604         err = err ? : bpf_object__collect_reloc(obj);
4605         if (err)
4606                 goto out;
4607         bpf_object__elf_finish(obj);
4608
4609         bpf_object__for_each_program(prog, obj) {
4610                 enum bpf_prog_type prog_type;
4611                 enum bpf_attach_type attach_type;
4612
4613                 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
4614                                                &attach_type);
4615                 if (err == -ESRCH)
4616                         /* couldn't guess, but user might manually specify */
4617                         continue;
4618                 if (err)
4619                         goto out;
4620
4621                 bpf_program__set_type(prog, prog_type);
4622                 bpf_program__set_expected_attach_type(prog, attach_type);
4623                 if (prog_type == BPF_PROG_TYPE_TRACING)
4624                         prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
4625         }
4626
4627         return obj;
4628 out:
4629         bpf_object__close(obj);
4630         return ERR_PTR(err);
4631 }
4632
4633 static struct bpf_object *
4634 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
4635 {
4636         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4637                 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
4638         );
4639
4640         /* param validation */
4641         if (!attr->file)
4642                 return NULL;
4643
4644         pr_debug("loading %s\n", attr->file);
4645         return __bpf_object__open(attr->file, NULL, 0, &opts);
4646 }
4647
4648 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
4649 {
4650         return __bpf_object__open_xattr(attr, 0);
4651 }
4652
4653 struct bpf_object *bpf_object__open(const char *path)
4654 {
4655         struct bpf_object_open_attr attr = {
4656                 .file           = path,
4657                 .prog_type      = BPF_PROG_TYPE_UNSPEC,
4658         };
4659
4660         return bpf_object__open_xattr(&attr);
4661 }
4662
4663 struct bpf_object *
4664 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
4665 {
4666         if (!path)
4667                 return ERR_PTR(-EINVAL);
4668
4669         pr_debug("loading %s\n", path);
4670
4671         return __bpf_object__open(path, NULL, 0, opts);
4672 }
4673
4674 struct bpf_object *
4675 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
4676                      const struct bpf_object_open_opts *opts)
4677 {
4678         if (!obj_buf || obj_buf_sz == 0)
4679                 return ERR_PTR(-EINVAL);
4680
4681         return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
4682 }
4683
4684 struct bpf_object *
4685 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4686                         const char *name)
4687 {
4688         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
4689                 .object_name = name,
4690                 /* wrong default, but backwards-compatible */
4691                 .relaxed_maps = true,
4692         );
4693
4694         /* returning NULL is wrong, but backwards-compatible */
4695         if (!obj_buf || obj_buf_sz == 0)
4696                 return NULL;
4697
4698         return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
4699 }
4700
4701 int bpf_object__unload(struct bpf_object *obj)
4702 {
4703         size_t i;
4704
4705         if (!obj)
4706                 return -EINVAL;
4707
4708         for (i = 0; i < obj->nr_maps; i++)
4709                 zclose(obj->maps[i].fd);
4710
4711         for (i = 0; i < obj->nr_programs; i++)
4712                 bpf_program__unload(&obj->programs[i]);
4713
4714         return 0;
4715 }
4716
4717 static int bpf_object__sanitize_maps(struct bpf_object *obj)
4718 {
4719         struct bpf_map *m;
4720
4721         bpf_object__for_each_map(m, obj) {
4722                 if (!bpf_map__is_internal(m))
4723                         continue;
4724                 if (!obj->caps.global_data) {
4725                         pr_warn("kernel doesn't support global data\n");
4726                         return -ENOTSUP;
4727                 }
4728                 if (!obj->caps.array_mmap)
4729                         m->def.map_flags ^= BPF_F_MMAPABLE;
4730         }
4731
4732         return 0;
4733 }
4734
4735 static int bpf_object__resolve_externs(struct bpf_object *obj,
4736                                        const char *config_path)
4737 {
4738         bool need_config = false;
4739         struct extern_desc *ext;
4740         int err, i;
4741         void *data;
4742
4743         if (obj->nr_extern == 0)
4744                 return 0;
4745
4746         data = obj->maps[obj->extern_map_idx].mmaped;
4747
4748         for (i = 0; i < obj->nr_extern; i++) {
4749                 ext = &obj->externs[i];
4750
4751                 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
4752                         void *ext_val = data + ext->data_off;
4753                         __u32 kver = get_kernel_version();
4754
4755                         if (!kver) {
4756                                 pr_warn("failed to get kernel version\n");
4757                                 return -EINVAL;
4758                         }
4759                         err = set_ext_value_num(ext, ext_val, kver);
4760                         if (err)
4761                                 return err;
4762                         pr_debug("extern %s=0x%x\n", ext->name, kver);
4763                 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
4764                         need_config = true;
4765                 } else {
4766                         pr_warn("unrecognized extern '%s'\n", ext->name);
4767                         return -EINVAL;
4768                 }
4769         }
4770         if (need_config) {
4771                 err = bpf_object__read_kernel_config(obj, config_path, data);
4772                 if (err)
4773                         return -EINVAL;
4774         }
4775         for (i = 0; i < obj->nr_extern; i++) {
4776                 ext = &obj->externs[i];
4777
4778                 if (!ext->is_set && !ext->is_weak) {
4779                         pr_warn("extern %s (strong) not resolved\n", ext->name);
4780                         return -ESRCH;
4781                 } else if (!ext->is_set) {
4782                         pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
4783                                  ext->name);
4784                 }
4785         }
4786
4787         return 0;
4788 }
4789
4790 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4791 {
4792         struct bpf_object *obj;
4793         int err, i;
4794
4795         if (!attr)
4796                 return -EINVAL;
4797         obj = attr->obj;
4798         if (!obj)
4799                 return -EINVAL;
4800
4801         if (obj->loaded) {
4802                 pr_warn("object should not be loaded twice\n");
4803                 return -EINVAL;
4804         }
4805
4806         obj->loaded = true;
4807
4808         err = bpf_object__probe_caps(obj);
4809         err = err ? : bpf_object__resolve_externs(obj, obj->kconfig_path);
4810         err = err ? : bpf_object__sanitize_and_load_btf(obj);
4811         err = err ? : bpf_object__sanitize_maps(obj);
4812         err = err ? : bpf_object__create_maps(obj);
4813         err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
4814         err = err ? : bpf_object__load_progs(obj, attr->log_level);
4815         if (err)
4816                 goto out;
4817
4818         return 0;
4819 out:
4820         /* unpin any maps that were auto-pinned during load */
4821         for (i = 0; i < obj->nr_maps; i++)
4822                 if (obj->maps[i].pinned && !obj->maps[i].reused)
4823                         bpf_map__unpin(&obj->maps[i], NULL);
4824
4825         bpf_object__unload(obj);
4826         pr_warn("failed to load object '%s'\n", obj->path);
4827         return err;
4828 }
4829
4830 int bpf_object__load(struct bpf_object *obj)
4831 {
4832         struct bpf_object_load_attr attr = {
4833                 .obj = obj,
4834         };
4835
4836         return bpf_object__load_xattr(&attr);
4837 }
4838
4839 static int make_parent_dir(const char *path)
4840 {
4841         char *cp, errmsg[STRERR_BUFSIZE];
4842         char *dname, *dir;
4843         int err = 0;
4844
4845         dname = strdup(path);
4846         if (dname == NULL)
4847                 return -ENOMEM;
4848
4849         dir = dirname(dname);
4850         if (mkdir(dir, 0700) && errno != EEXIST)
4851                 err = -errno;
4852
4853         free(dname);
4854         if (err) {
4855                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4856                 pr_warn("failed to mkdir %s: %s\n", path, cp);
4857         }
4858         return err;
4859 }
4860
4861 static int check_path(const char *path)
4862 {
4863         char *cp, errmsg[STRERR_BUFSIZE];
4864         struct statfs st_fs;
4865         char *dname, *dir;
4866         int err = 0;
4867
4868         if (path == NULL)
4869                 return -EINVAL;
4870
4871         dname = strdup(path);
4872         if (dname == NULL)
4873                 return -ENOMEM;
4874
4875         dir = dirname(dname);
4876         if (statfs(dir, &st_fs)) {
4877                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4878                 pr_warn("failed to statfs %s: %s\n", dir, cp);
4879                 err = -errno;
4880         }
4881         free(dname);
4882
4883         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4884                 pr_warn("specified path %s is not on BPF FS\n", path);
4885                 err = -EINVAL;
4886         }
4887
4888         return err;
4889 }
4890
4891 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4892                               int instance)
4893 {
4894         char *cp, errmsg[STRERR_BUFSIZE];
4895         int err;
4896
4897         err = make_parent_dir(path);
4898         if (err)
4899                 return err;
4900
4901         err = check_path(path);
4902         if (err)
4903                 return err;
4904
4905         if (prog == NULL) {
4906                 pr_warn("invalid program pointer\n");
4907                 return -EINVAL;
4908         }
4909
4910         if (instance < 0 || instance >= prog->instances.nr) {
4911                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4912                         instance, prog->section_name, prog->instances.nr);
4913                 return -EINVAL;
4914         }
4915
4916         if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4917                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4918                 pr_warn("failed to pin program: %s\n", cp);
4919                 return -errno;
4920         }
4921         pr_debug("pinned program '%s'\n", path);
4922
4923         return 0;
4924 }
4925
4926 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4927                                 int instance)
4928 {
4929         int err;
4930
4931         err = check_path(path);
4932         if (err)
4933                 return err;
4934
4935         if (prog == NULL) {
4936                 pr_warn("invalid program pointer\n");
4937                 return -EINVAL;
4938         }
4939
4940         if (instance < 0 || instance >= prog->instances.nr) {
4941                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4942                         instance, prog->section_name, prog->instances.nr);
4943                 return -EINVAL;
4944         }
4945
4946         err = unlink(path);
4947         if (err != 0)
4948                 return -errno;
4949         pr_debug("unpinned program '%s'\n", path);
4950
4951         return 0;
4952 }
4953
4954 int bpf_program__pin(struct bpf_program *prog, const char *path)
4955 {
4956         int i, err;
4957
4958         err = make_parent_dir(path);
4959         if (err)
4960                 return err;
4961
4962         err = check_path(path);
4963         if (err)
4964                 return err;
4965
4966         if (prog == NULL) {
4967                 pr_warn("invalid program pointer\n");
4968                 return -EINVAL;
4969         }
4970
4971         if (prog->instances.nr <= 0) {
4972                 pr_warn("no instances of prog %s to pin\n",
4973                            prog->section_name);
4974                 return -EINVAL;
4975         }
4976
4977         if (prog->instances.nr == 1) {
4978                 /* don't create subdirs when pinning single instance */
4979                 return bpf_program__pin_instance(prog, path, 0);
4980         }
4981
4982         for (i = 0; i < prog->instances.nr; i++) {
4983                 char buf[PATH_MAX];
4984                 int len;
4985
4986                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4987                 if (len < 0) {
4988                         err = -EINVAL;
4989                         goto err_unpin;
4990                 } else if (len >= PATH_MAX) {
4991                         err = -ENAMETOOLONG;
4992                         goto err_unpin;
4993                 }
4994
4995                 err = bpf_program__pin_instance(prog, buf, i);
4996                 if (err)
4997                         goto err_unpin;
4998         }
4999
5000         return 0;
5001
5002 err_unpin:
5003         for (i = i - 1; i >= 0; i--) {
5004                 char buf[PATH_MAX];
5005                 int len;
5006
5007                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5008                 if (len < 0)
5009                         continue;
5010                 else if (len >= PATH_MAX)
5011                         continue;
5012
5013                 bpf_program__unpin_instance(prog, buf, i);
5014         }
5015
5016         rmdir(path);
5017
5018         return err;
5019 }
5020
5021 int bpf_program__unpin(struct bpf_program *prog, const char *path)
5022 {
5023         int i, err;
5024
5025         err = check_path(path);
5026         if (err)
5027                 return err;
5028
5029         if (prog == NULL) {
5030                 pr_warn("invalid program pointer\n");
5031                 return -EINVAL;
5032         }
5033
5034         if (prog->instances.nr <= 0) {
5035                 pr_warn("no instances of prog %s to pin\n",
5036                            prog->section_name);
5037                 return -EINVAL;
5038         }
5039
5040         if (prog->instances.nr == 1) {
5041                 /* don't create subdirs when pinning single instance */
5042                 return bpf_program__unpin_instance(prog, path, 0);
5043         }
5044
5045         for (i = 0; i < prog->instances.nr; i++) {
5046                 char buf[PATH_MAX];
5047                 int len;
5048
5049                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5050                 if (len < 0)
5051                         return -EINVAL;
5052                 else if (len >= PATH_MAX)
5053                         return -ENAMETOOLONG;
5054
5055                 err = bpf_program__unpin_instance(prog, buf, i);
5056                 if (err)
5057                         return err;
5058         }
5059
5060         err = rmdir(path);
5061         if (err)
5062                 return -errno;
5063
5064         return 0;
5065 }
5066
5067 int bpf_map__pin(struct bpf_map *map, const char *path)
5068 {
5069         char *cp, errmsg[STRERR_BUFSIZE];
5070         int err;
5071
5072         if (map == NULL) {
5073                 pr_warn("invalid map pointer\n");
5074                 return -EINVAL;
5075         }
5076
5077         if (map->pin_path) {
5078                 if (path && strcmp(path, map->pin_path)) {
5079                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5080                                 bpf_map__name(map), map->pin_path, path);
5081                         return -EINVAL;
5082                 } else if (map->pinned) {
5083                         pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5084                                  bpf_map__name(map), map->pin_path);
5085                         return 0;
5086                 }
5087         } else {
5088                 if (!path) {
5089                         pr_warn("missing a path to pin map '%s' at\n",
5090                                 bpf_map__name(map));
5091                         return -EINVAL;
5092                 } else if (map->pinned) {
5093                         pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5094                         return -EEXIST;
5095                 }
5096
5097                 map->pin_path = strdup(path);
5098                 if (!map->pin_path) {
5099                         err = -errno;
5100                         goto out_err;
5101                 }
5102         }
5103
5104         err = make_parent_dir(map->pin_path);
5105         if (err)
5106                 return err;
5107
5108         err = check_path(map->pin_path);
5109         if (err)
5110                 return err;
5111
5112         if (bpf_obj_pin(map->fd, map->pin_path)) {
5113                 err = -errno;
5114                 goto out_err;
5115         }
5116
5117         map->pinned = true;
5118         pr_debug("pinned map '%s'\n", map->pin_path);
5119
5120         return 0;
5121
5122 out_err:
5123         cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5124         pr_warn("failed to pin map: %s\n", cp);
5125         return err;
5126 }
5127
5128 int bpf_map__unpin(struct bpf_map *map, const char *path)
5129 {
5130         int err;
5131
5132         if (map == NULL) {
5133                 pr_warn("invalid map pointer\n");
5134                 return -EINVAL;
5135         }
5136
5137         if (map->pin_path) {
5138                 if (path && strcmp(path, map->pin_path)) {
5139                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5140                                 bpf_map__name(map), map->pin_path, path);
5141                         return -EINVAL;
5142                 }
5143                 path = map->pin_path;
5144         } else if (!path) {
5145                 pr_warn("no path to unpin map '%s' from\n",
5146                         bpf_map__name(map));
5147                 return -EINVAL;
5148         }
5149
5150         err = check_path(path);
5151         if (err)
5152                 return err;
5153
5154         err = unlink(path);
5155         if (err != 0)
5156                 return -errno;
5157
5158         map->pinned = false;
5159         pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
5160
5161         return 0;
5162 }
5163
5164 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
5165 {
5166         char *new = NULL;
5167
5168         if (path) {
5169                 new = strdup(path);
5170                 if (!new)
5171                         return -errno;
5172         }
5173
5174         free(map->pin_path);
5175         map->pin_path = new;
5176         return 0;
5177 }
5178
5179 const char *bpf_map__get_pin_path(const struct bpf_map *map)
5180 {
5181         return map->pin_path;
5182 }
5183
5184 bool bpf_map__is_pinned(const struct bpf_map *map)
5185 {
5186         return map->pinned;
5187 }
5188
5189 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
5190 {
5191         struct bpf_map *map;
5192         int err;
5193
5194         if (!obj)
5195                 return -ENOENT;
5196
5197         if (!obj->loaded) {
5198                 pr_warn("object not yet loaded; load it first\n");
5199                 return -ENOENT;
5200         }
5201
5202         bpf_object__for_each_map(map, obj) {
5203                 char *pin_path = NULL;
5204                 char buf[PATH_MAX];
5205
5206                 if (path) {
5207                         int len;
5208
5209                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
5210                                        bpf_map__name(map));
5211                         if (len < 0) {
5212                                 err = -EINVAL;
5213                                 goto err_unpin_maps;
5214                         } else if (len >= PATH_MAX) {
5215                                 err = -ENAMETOOLONG;
5216                                 goto err_unpin_maps;
5217                         }
5218                         pin_path = buf;
5219                 } else if (!map->pin_path) {
5220                         continue;
5221                 }
5222
5223                 err = bpf_map__pin(map, pin_path);
5224                 if (err)
5225                         goto err_unpin_maps;
5226         }
5227
5228         return 0;
5229
5230 err_unpin_maps:
5231         while ((map = bpf_map__prev(map, obj))) {
5232                 if (!map->pin_path)
5233                         continue;
5234
5235                 bpf_map__unpin(map, NULL);
5236         }
5237
5238         return err;
5239 }
5240
5241 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
5242 {
5243         struct bpf_map *map;
5244         int err;
5245
5246         if (!obj)
5247                 return -ENOENT;
5248
5249         bpf_object__for_each_map(map, obj) {
5250                 char *pin_path = NULL;
5251                 char buf[PATH_MAX];
5252
5253                 if (path) {
5254                         int len;
5255
5256                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
5257                                        bpf_map__name(map));
5258                         if (len < 0)
5259                                 return -EINVAL;
5260                         else if (len >= PATH_MAX)
5261                                 return -ENAMETOOLONG;
5262                         pin_path = buf;
5263                 } else if (!map->pin_path) {
5264                         continue;
5265                 }
5266
5267                 err = bpf_map__unpin(map, pin_path);
5268                 if (err)
5269                         return err;
5270         }
5271
5272         return 0;
5273 }
5274
5275 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
5276 {
5277         struct bpf_program *prog;
5278         int err;
5279
5280         if (!obj)
5281                 return -ENOENT;
5282
5283         if (!obj->loaded) {
5284                 pr_warn("object not yet loaded; load it first\n");
5285                 return -ENOENT;
5286         }
5287
5288         bpf_object__for_each_program(prog, obj) {
5289                 char buf[PATH_MAX];
5290                 int len;
5291
5292                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5293                                prog->pin_name);
5294                 if (len < 0) {
5295                         err = -EINVAL;
5296                         goto err_unpin_programs;
5297                 } else if (len >= PATH_MAX) {
5298                         err = -ENAMETOOLONG;
5299                         goto err_unpin_programs;
5300                 }
5301
5302                 err = bpf_program__pin(prog, buf);
5303                 if (err)
5304                         goto err_unpin_programs;
5305         }
5306
5307         return 0;
5308
5309 err_unpin_programs:
5310         while ((prog = bpf_program__prev(prog, obj))) {
5311                 char buf[PATH_MAX];
5312                 int len;
5313
5314                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5315                                prog->pin_name);
5316                 if (len < 0)
5317                         continue;
5318                 else if (len >= PATH_MAX)
5319                         continue;
5320
5321                 bpf_program__unpin(prog, buf);
5322         }
5323
5324         return err;
5325 }
5326
5327 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
5328 {
5329         struct bpf_program *prog;
5330         int err;
5331
5332         if (!obj)
5333                 return -ENOENT;
5334
5335         bpf_object__for_each_program(prog, obj) {
5336                 char buf[PATH_MAX];
5337                 int len;
5338
5339                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5340                                prog->pin_name);
5341                 if (len < 0)
5342                         return -EINVAL;
5343                 else if (len >= PATH_MAX)
5344                         return -ENAMETOOLONG;
5345
5346                 err = bpf_program__unpin(prog, buf);
5347                 if (err)
5348                         return err;
5349         }
5350
5351         return 0;
5352 }
5353
5354 int bpf_object__pin(struct bpf_object *obj, const char *path)
5355 {
5356         int err;
5357
5358         err = bpf_object__pin_maps(obj, path);
5359         if (err)
5360                 return err;
5361
5362         err = bpf_object__pin_programs(obj, path);
5363         if (err) {
5364                 bpf_object__unpin_maps(obj, path);
5365                 return err;
5366         }
5367
5368         return 0;
5369 }
5370
5371 void bpf_object__close(struct bpf_object *obj)
5372 {
5373         size_t i;
5374
5375         if (!obj)
5376                 return;
5377
5378         if (obj->clear_priv)
5379                 obj->clear_priv(obj, obj->priv);
5380
5381         bpf_object__elf_finish(obj);
5382         bpf_object__unload(obj);
5383         btf__free(obj->btf);
5384         btf_ext__free(obj->btf_ext);
5385
5386         for (i = 0; i < obj->nr_maps; i++) {
5387                 struct bpf_map *map = &obj->maps[i];
5388
5389                 if (map->clear_priv)
5390                         map->clear_priv(map, map->priv);
5391                 map->priv = NULL;
5392                 map->clear_priv = NULL;
5393
5394                 if (map->mmaped) {
5395                         munmap(map->mmaped, bpf_map_mmap_sz(map));
5396                         map->mmaped = NULL;
5397                 }
5398
5399                 zfree(&map->name);
5400                 zfree(&map->pin_path);
5401         }
5402
5403         zfree(&obj->kconfig_path);
5404         zfree(&obj->externs);
5405         obj->nr_extern = 0;
5406
5407         zfree(&obj->maps);
5408         obj->nr_maps = 0;
5409
5410         if (obj->programs && obj->nr_programs) {
5411                 for (i = 0; i < obj->nr_programs; i++)
5412                         bpf_program__exit(&obj->programs[i]);
5413         }
5414         zfree(&obj->programs);
5415
5416         list_del(&obj->list);
5417         free(obj);
5418 }
5419
5420 struct bpf_object *
5421 bpf_object__next(struct bpf_object *prev)
5422 {
5423         struct bpf_object *next;
5424
5425         if (!prev)
5426                 next = list_first_entry(&bpf_objects_list,
5427                                         struct bpf_object,
5428                                         list);
5429         else
5430                 next = list_next_entry(prev, list);
5431
5432         /* Empty list is noticed here so don't need checking on entry. */
5433         if (&next->list == &bpf_objects_list)
5434                 return NULL;
5435
5436         return next;
5437 }
5438
5439 const char *bpf_object__name(const struct bpf_object *obj)
5440 {
5441         return obj ? obj->name : ERR_PTR(-EINVAL);
5442 }
5443
5444 unsigned int bpf_object__kversion(const struct bpf_object *obj)
5445 {
5446         return obj ? obj->kern_version : 0;
5447 }
5448
5449 struct btf *bpf_object__btf(const struct bpf_object *obj)
5450 {
5451         return obj ? obj->btf : NULL;
5452 }
5453
5454 int bpf_object__btf_fd(const struct bpf_object *obj)
5455 {
5456         return obj->btf ? btf__fd(obj->btf) : -1;
5457 }
5458
5459 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
5460                          bpf_object_clear_priv_t clear_priv)
5461 {
5462         if (obj->priv && obj->clear_priv)
5463                 obj->clear_priv(obj, obj->priv);
5464
5465         obj->priv = priv;
5466         obj->clear_priv = clear_priv;
5467         return 0;
5468 }
5469
5470 void *bpf_object__priv(const struct bpf_object *obj)
5471 {
5472         return obj ? obj->priv : ERR_PTR(-EINVAL);
5473 }
5474
5475 static struct bpf_program *
5476 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
5477                     bool forward)
5478 {
5479         size_t nr_programs = obj->nr_programs;
5480         ssize_t idx;
5481
5482         if (!nr_programs)
5483                 return NULL;
5484
5485         if (!p)
5486                 /* Iter from the beginning */
5487                 return forward ? &obj->programs[0] :
5488                         &obj->programs[nr_programs - 1];
5489
5490         if (p->obj != obj) {
5491                 pr_warn("error: program handler doesn't match object\n");
5492                 return NULL;
5493         }
5494
5495         idx = (p - obj->programs) + (forward ? 1 : -1);
5496         if (idx >= obj->nr_programs || idx < 0)
5497                 return NULL;
5498         return &obj->programs[idx];
5499 }
5500
5501 struct bpf_program *
5502 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
5503 {
5504         struct bpf_program *prog = prev;
5505
5506         do {
5507                 prog = __bpf_program__iter(prog, obj, true);
5508         } while (prog && bpf_program__is_function_storage(prog, obj));
5509
5510         return prog;
5511 }
5512
5513 struct bpf_program *
5514 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
5515 {
5516         struct bpf_program *prog = next;
5517
5518         do {
5519                 prog = __bpf_program__iter(prog, obj, false);
5520         } while (prog && bpf_program__is_function_storage(prog, obj));
5521
5522         return prog;
5523 }
5524
5525 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
5526                           bpf_program_clear_priv_t clear_priv)
5527 {
5528         if (prog->priv && prog->clear_priv)
5529                 prog->clear_priv(prog, prog->priv);
5530
5531         prog->priv = priv;
5532         prog->clear_priv = clear_priv;
5533         return 0;
5534 }
5535
5536 void *bpf_program__priv(const struct bpf_program *prog)
5537 {
5538         return prog ? prog->priv : ERR_PTR(-EINVAL);
5539 }
5540
5541 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
5542 {
5543         prog->prog_ifindex = ifindex;
5544 }
5545
5546 const char *bpf_program__name(const struct bpf_program *prog)
5547 {
5548         return prog->name;
5549 }
5550
5551 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
5552 {
5553         const char *title;
5554
5555         title = prog->section_name;
5556         if (needs_copy) {
5557                 title = strdup(title);
5558                 if (!title) {
5559                         pr_warn("failed to strdup program title\n");
5560                         return ERR_PTR(-ENOMEM);
5561                 }
5562         }
5563
5564         return title;
5565 }
5566
5567 int bpf_program__fd(const struct bpf_program *prog)
5568 {
5569         return bpf_program__nth_fd(prog, 0);
5570 }
5571
5572 size_t bpf_program__size(const struct bpf_program *prog)
5573 {
5574         return prog->insns_cnt * sizeof(struct bpf_insn);
5575 }
5576
5577 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
5578                           bpf_program_prep_t prep)
5579 {
5580         int *instances_fds;
5581
5582         if (nr_instances <= 0 || !prep)
5583                 return -EINVAL;
5584
5585         if (prog->instances.nr > 0 || prog->instances.fds) {
5586                 pr_warn("Can't set pre-processor after loading\n");
5587                 return -EINVAL;
5588         }
5589
5590         instances_fds = malloc(sizeof(int) * nr_instances);
5591         if (!instances_fds) {
5592                 pr_warn("alloc memory failed for fds\n");
5593                 return -ENOMEM;
5594         }
5595
5596         /* fill all fd with -1 */
5597         memset(instances_fds, -1, sizeof(int) * nr_instances);
5598
5599         prog->instances.nr = nr_instances;
5600         prog->instances.fds = instances_fds;
5601         prog->preprocessor = prep;
5602         return 0;
5603 }
5604
5605 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
5606 {
5607         int fd;
5608
5609         if (!prog)
5610                 return -EINVAL;
5611
5612         if (n >= prog->instances.nr || n < 0) {
5613                 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
5614                         n, prog->section_name, prog->instances.nr);
5615                 return -EINVAL;
5616         }
5617
5618         fd = prog->instances.fds[n];
5619         if (fd < 0) {
5620                 pr_warn("%dth instance of program '%s' is invalid\n",
5621                         n, prog->section_name);
5622                 return -ENOENT;
5623         }
5624
5625         return fd;
5626 }
5627
5628 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
5629 {
5630         return prog->type;
5631 }
5632
5633 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5634 {
5635         prog->type = type;
5636 }
5637
5638 static bool bpf_program__is_type(const struct bpf_program *prog,
5639                                  enum bpf_prog_type type)
5640 {
5641         return prog ? (prog->type == type) : false;
5642 }
5643
5644 #define BPF_PROG_TYPE_FNS(NAME, TYPE)                           \
5645 int bpf_program__set_##NAME(struct bpf_program *prog)           \
5646 {                                                               \
5647         if (!prog)                                              \
5648                 return -EINVAL;                                 \
5649         bpf_program__set_type(prog, TYPE);                      \
5650         return 0;                                               \
5651 }                                                               \
5652                                                                 \
5653 bool bpf_program__is_##NAME(const struct bpf_program *prog)     \
5654 {                                                               \
5655         return bpf_program__is_type(prog, TYPE);                \
5656 }                                                               \
5657
5658 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
5659 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
5660 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
5661 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
5662 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
5663 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
5664 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
5665 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
5666 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
5667
5668 enum bpf_attach_type
5669 bpf_program__get_expected_attach_type(struct bpf_program *prog)
5670 {
5671         return prog->expected_attach_type;
5672 }
5673
5674 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
5675                                            enum bpf_attach_type type)
5676 {
5677         prog->expected_attach_type = type;
5678 }
5679
5680 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
5681         { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
5682
5683 /* Programs that can NOT be attached. */
5684 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
5685
5686 /* Programs that can be attached. */
5687 #define BPF_APROG_SEC(string, ptype, atype) \
5688         BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
5689
5690 /* Programs that must specify expected attach type at load time. */
5691 #define BPF_EAPROG_SEC(string, ptype, eatype) \
5692         BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
5693
5694 /* Programs that use BTF to identify attach point */
5695 #define BPF_PROG_BTF(string, ptype, eatype) \
5696         BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
5697
5698 /* Programs that can be attached but attach type can't be identified by section
5699  * name. Kept for backward compatibility.
5700  */
5701 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
5702
5703 #define SEC_DEF(sec_pfx, ptype, ...) {                                      \
5704         .sec = sec_pfx,                                                     \
5705         .len = sizeof(sec_pfx) - 1,                                         \
5706         .prog_type = BPF_PROG_TYPE_##ptype,                                 \
5707         __VA_ARGS__                                                         \
5708 }
5709
5710 struct bpf_sec_def;
5711
5712 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
5713                                         struct bpf_program *prog);
5714
5715 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5716                                       struct bpf_program *prog);
5717 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5718                                   struct bpf_program *prog);
5719 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5720                                       struct bpf_program *prog);
5721 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
5722                                      struct bpf_program *prog);
5723
5724 struct bpf_sec_def {
5725         const char *sec;
5726         size_t len;
5727         enum bpf_prog_type prog_type;
5728         enum bpf_attach_type expected_attach_type;
5729         bool is_attachable;
5730         bool is_attach_btf;
5731         enum bpf_attach_type attach_type;
5732         attach_fn_t attach_fn;
5733 };
5734
5735 static const struct bpf_sec_def section_defs[] = {
5736         BPF_PROG_SEC("socket",                  BPF_PROG_TYPE_SOCKET_FILTER),
5737         BPF_PROG_SEC("sk_reuseport",            BPF_PROG_TYPE_SK_REUSEPORT),
5738         SEC_DEF("kprobe/", KPROBE,
5739                 .attach_fn = attach_kprobe),
5740         BPF_PROG_SEC("uprobe/",                 BPF_PROG_TYPE_KPROBE),
5741         SEC_DEF("kretprobe/", KPROBE,
5742                 .attach_fn = attach_kprobe),
5743         BPF_PROG_SEC("uretprobe/",              BPF_PROG_TYPE_KPROBE),
5744         BPF_PROG_SEC("classifier",              BPF_PROG_TYPE_SCHED_CLS),
5745         BPF_PROG_SEC("action",                  BPF_PROG_TYPE_SCHED_ACT),
5746         SEC_DEF("tracepoint/", TRACEPOINT,
5747                 .attach_fn = attach_tp),
5748         SEC_DEF("tp/", TRACEPOINT,
5749                 .attach_fn = attach_tp),
5750         SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
5751                 .attach_fn = attach_raw_tp),
5752         SEC_DEF("raw_tp/", RAW_TRACEPOINT,
5753                 .attach_fn = attach_raw_tp),
5754         SEC_DEF("tp_btf/", TRACING,
5755                 .expected_attach_type = BPF_TRACE_RAW_TP,
5756                 .is_attach_btf = true,
5757                 .attach_fn = attach_trace),
5758         SEC_DEF("fentry/", TRACING,
5759                 .expected_attach_type = BPF_TRACE_FENTRY,
5760                 .is_attach_btf = true,
5761                 .attach_fn = attach_trace),
5762         SEC_DEF("fexit/", TRACING,
5763                 .expected_attach_type = BPF_TRACE_FEXIT,
5764                 .is_attach_btf = true,
5765                 .attach_fn = attach_trace),
5766         BPF_PROG_SEC("xdp",                     BPF_PROG_TYPE_XDP),
5767         BPF_PROG_SEC("perf_event",              BPF_PROG_TYPE_PERF_EVENT),
5768         BPF_PROG_SEC("lwt_in",                  BPF_PROG_TYPE_LWT_IN),
5769         BPF_PROG_SEC("lwt_out",                 BPF_PROG_TYPE_LWT_OUT),
5770         BPF_PROG_SEC("lwt_xmit",                BPF_PROG_TYPE_LWT_XMIT),
5771         BPF_PROG_SEC("lwt_seg6local",           BPF_PROG_TYPE_LWT_SEG6LOCAL),
5772         BPF_APROG_SEC("cgroup_skb/ingress",     BPF_PROG_TYPE_CGROUP_SKB,
5773                                                 BPF_CGROUP_INET_INGRESS),
5774         BPF_APROG_SEC("cgroup_skb/egress",      BPF_PROG_TYPE_CGROUP_SKB,
5775                                                 BPF_CGROUP_INET_EGRESS),
5776         BPF_APROG_COMPAT("cgroup/skb",          BPF_PROG_TYPE_CGROUP_SKB),
5777         BPF_APROG_SEC("cgroup/sock",            BPF_PROG_TYPE_CGROUP_SOCK,
5778                                                 BPF_CGROUP_INET_SOCK_CREATE),
5779         BPF_EAPROG_SEC("cgroup/post_bind4",     BPF_PROG_TYPE_CGROUP_SOCK,
5780                                                 BPF_CGROUP_INET4_POST_BIND),
5781         BPF_EAPROG_SEC("cgroup/post_bind6",     BPF_PROG_TYPE_CGROUP_SOCK,
5782                                                 BPF_CGROUP_INET6_POST_BIND),
5783         BPF_APROG_SEC("cgroup/dev",             BPF_PROG_TYPE_CGROUP_DEVICE,
5784                                                 BPF_CGROUP_DEVICE),
5785         BPF_APROG_SEC("sockops",                BPF_PROG_TYPE_SOCK_OPS,
5786                                                 BPF_CGROUP_SOCK_OPS),
5787         BPF_APROG_SEC("sk_skb/stream_parser",   BPF_PROG_TYPE_SK_SKB,
5788                                                 BPF_SK_SKB_STREAM_PARSER),
5789         BPF_APROG_SEC("sk_skb/stream_verdict",  BPF_PROG_TYPE_SK_SKB,
5790                                                 BPF_SK_SKB_STREAM_VERDICT),
5791         BPF_APROG_COMPAT("sk_skb",              BPF_PROG_TYPE_SK_SKB),
5792         BPF_APROG_SEC("sk_msg",                 BPF_PROG_TYPE_SK_MSG,
5793                                                 BPF_SK_MSG_VERDICT),
5794         BPF_APROG_SEC("lirc_mode2",             BPF_PROG_TYPE_LIRC_MODE2,
5795                                                 BPF_LIRC_MODE2),
5796         BPF_APROG_SEC("flow_dissector",         BPF_PROG_TYPE_FLOW_DISSECTOR,
5797                                                 BPF_FLOW_DISSECTOR),
5798         BPF_EAPROG_SEC("cgroup/bind4",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5799                                                 BPF_CGROUP_INET4_BIND),
5800         BPF_EAPROG_SEC("cgroup/bind6",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5801                                                 BPF_CGROUP_INET6_BIND),
5802         BPF_EAPROG_SEC("cgroup/connect4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5803                                                 BPF_CGROUP_INET4_CONNECT),
5804         BPF_EAPROG_SEC("cgroup/connect6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5805                                                 BPF_CGROUP_INET6_CONNECT),
5806         BPF_EAPROG_SEC("cgroup/sendmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5807                                                 BPF_CGROUP_UDP4_SENDMSG),
5808         BPF_EAPROG_SEC("cgroup/sendmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5809                                                 BPF_CGROUP_UDP6_SENDMSG),
5810         BPF_EAPROG_SEC("cgroup/recvmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5811                                                 BPF_CGROUP_UDP4_RECVMSG),
5812         BPF_EAPROG_SEC("cgroup/recvmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5813                                                 BPF_CGROUP_UDP6_RECVMSG),
5814         BPF_EAPROG_SEC("cgroup/sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,
5815                                                 BPF_CGROUP_SYSCTL),
5816         BPF_EAPROG_SEC("cgroup/getsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
5817                                                 BPF_CGROUP_GETSOCKOPT),
5818         BPF_EAPROG_SEC("cgroup/setsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
5819                                                 BPF_CGROUP_SETSOCKOPT),
5820 };
5821
5822 #undef BPF_PROG_SEC_IMPL
5823 #undef BPF_PROG_SEC
5824 #undef BPF_APROG_SEC
5825 #undef BPF_EAPROG_SEC
5826 #undef BPF_APROG_COMPAT
5827 #undef SEC_DEF
5828
5829 #define MAX_TYPE_NAME_SIZE 32
5830
5831 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
5832 {
5833         int i, n = ARRAY_SIZE(section_defs);
5834
5835         for (i = 0; i < n; i++) {
5836                 if (strncmp(sec_name,
5837                             section_defs[i].sec, section_defs[i].len))
5838                         continue;
5839                 return &section_defs[i];
5840         }
5841         return NULL;
5842 }
5843
5844 static char *libbpf_get_type_names(bool attach_type)
5845 {
5846         int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
5847         char *buf;
5848
5849         buf = malloc(len);
5850         if (!buf)
5851                 return NULL;
5852
5853         buf[0] = '\0';
5854         /* Forge string buf with all available names */
5855         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5856                 if (attach_type && !section_defs[i].is_attachable)
5857                         continue;
5858
5859                 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
5860                         free(buf);
5861                         return NULL;
5862                 }
5863                 strcat(buf, " ");
5864                 strcat(buf, section_defs[i].sec);
5865         }
5866
5867         return buf;
5868 }
5869
5870 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5871                              enum bpf_attach_type *expected_attach_type)
5872 {
5873         const struct bpf_sec_def *sec_def;
5874         char *type_names;
5875
5876         if (!name)
5877                 return -EINVAL;
5878
5879         sec_def = find_sec_def(name);
5880         if (sec_def) {
5881                 *prog_type = sec_def->prog_type;
5882                 *expected_attach_type = sec_def->expected_attach_type;
5883                 return 0;
5884         }
5885
5886         pr_debug("failed to guess program type from ELF section '%s'\n", name);
5887         type_names = libbpf_get_type_names(false);
5888         if (type_names != NULL) {
5889                 pr_debug("supported section(type) names are:%s\n", type_names);
5890                 free(type_names);
5891         }
5892
5893         return -ESRCH;
5894 }
5895
5896 #define BTF_PREFIX "btf_trace_"
5897 int libbpf_find_vmlinux_btf_id(const char *name,
5898                                enum bpf_attach_type attach_type)
5899 {
5900         struct btf *btf = bpf_core_find_kernel_btf();
5901         char raw_tp_btf[128] = BTF_PREFIX;
5902         char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5903         const char *btf_name;
5904         int err = -EINVAL;
5905         __u32 kind;
5906
5907         if (IS_ERR(btf)) {
5908                 pr_warn("vmlinux BTF is not found\n");
5909                 return -EINVAL;
5910         }
5911
5912         if (attach_type == BPF_TRACE_RAW_TP) {
5913                 /* prepend "btf_trace_" prefix per kernel convention */
5914                 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5915                 btf_name = raw_tp_btf;
5916                 kind = BTF_KIND_TYPEDEF;
5917         } else {
5918                 btf_name = name;
5919                 kind = BTF_KIND_FUNC;
5920         }
5921         err = btf__find_by_name_kind(btf, btf_name, kind);
5922         btf__free(btf);
5923         return err;
5924 }
5925
5926 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
5927 {
5928         struct bpf_prog_info_linear *info_linear;
5929         struct bpf_prog_info *info;
5930         struct btf *btf = NULL;
5931         int err = -EINVAL;
5932
5933         info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
5934         if (IS_ERR_OR_NULL(info_linear)) {
5935                 pr_warn("failed get_prog_info_linear for FD %d\n",
5936                         attach_prog_fd);
5937                 return -EINVAL;
5938         }
5939         info = &info_linear->info;
5940         if (!info->btf_id) {
5941                 pr_warn("The target program doesn't have BTF\n");
5942                 goto out;
5943         }
5944         if (btf__get_from_id(info->btf_id, &btf)) {
5945                 pr_warn("Failed to get BTF of the program\n");
5946                 goto out;
5947         }
5948         err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
5949         btf__free(btf);
5950         if (err <= 0) {
5951                 pr_warn("%s is not found in prog's BTF\n", name);
5952                 goto out;
5953         }
5954 out:
5955         free(info_linear);
5956         return err;
5957 }
5958
5959 static int libbpf_find_attach_btf_id(const char *name,
5960                                      enum bpf_attach_type attach_type,
5961                                      __u32 attach_prog_fd)
5962 {
5963         int i, err;
5964
5965         if (!name)
5966                 return -EINVAL;
5967
5968         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5969                 if (!section_defs[i].is_attach_btf)
5970                         continue;
5971                 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5972                         continue;
5973                 if (attach_prog_fd)
5974                         err = libbpf_find_prog_btf_id(name + section_defs[i].len,
5975                                                       attach_prog_fd);
5976                 else
5977                         err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
5978                                                          attach_type);
5979                 if (err <= 0)
5980                         pr_warn("%s is not found in vmlinux BTF\n", name);
5981                 return err;
5982         }
5983         pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
5984         return -ESRCH;
5985 }
5986
5987 int libbpf_attach_type_by_name(const char *name,
5988                                enum bpf_attach_type *attach_type)
5989 {
5990         char *type_names;
5991         int i;
5992
5993         if (!name)
5994                 return -EINVAL;
5995
5996         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5997                 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
5998                         continue;
5999                 if (!section_defs[i].is_attachable)
6000                         return -EINVAL;
6001                 *attach_type = section_defs[i].attach_type;
6002                 return 0;
6003         }
6004         pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
6005         type_names = libbpf_get_type_names(true);
6006         if (type_names != NULL) {
6007                 pr_debug("attachable section(type) names are:%s\n", type_names);
6008                 free(type_names);
6009         }
6010
6011         return -EINVAL;
6012 }
6013
6014 int bpf_map__fd(const struct bpf_map *map)
6015 {
6016         return map ? map->fd : -EINVAL;
6017 }
6018
6019 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
6020 {
6021         return map ? &map->def : ERR_PTR(-EINVAL);
6022 }
6023
6024 const char *bpf_map__name(const struct bpf_map *map)
6025 {
6026         return map ? map->name : NULL;
6027 }
6028
6029 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
6030 {
6031         return map ? map->btf_key_type_id : 0;
6032 }
6033
6034 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
6035 {
6036         return map ? map->btf_value_type_id : 0;
6037 }
6038
6039 int bpf_map__set_priv(struct bpf_map *map, void *priv,
6040                      bpf_map_clear_priv_t clear_priv)
6041 {
6042         if (!map)
6043                 return -EINVAL;
6044
6045         if (map->priv) {
6046                 if (map->clear_priv)
6047                         map->clear_priv(map, map->priv);
6048         }
6049
6050         map->priv = priv;
6051         map->clear_priv = clear_priv;
6052         return 0;
6053 }
6054
6055 void *bpf_map__priv(const struct bpf_map *map)
6056 {
6057         return map ? map->priv : ERR_PTR(-EINVAL);
6058 }
6059
6060 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
6061 {
6062         return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
6063 }
6064
6065 bool bpf_map__is_internal(const struct bpf_map *map)
6066 {
6067         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
6068 }
6069
6070 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
6071 {
6072         map->map_ifindex = ifindex;
6073 }
6074
6075 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
6076 {
6077         if (!bpf_map_type__is_map_in_map(map->def.type)) {
6078                 pr_warn("error: unsupported map type\n");
6079                 return -EINVAL;
6080         }
6081         if (map->inner_map_fd != -1) {
6082                 pr_warn("error: inner_map_fd already specified\n");
6083                 return -EINVAL;
6084         }
6085         map->inner_map_fd = fd;
6086         return 0;
6087 }
6088
6089 static struct bpf_map *
6090 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
6091 {
6092         ssize_t idx;
6093         struct bpf_map *s, *e;
6094
6095         if (!obj || !obj->maps)
6096                 return NULL;
6097
6098         s = obj->maps;
6099         e = obj->maps + obj->nr_maps;
6100
6101         if ((m < s) || (m >= e)) {
6102                 pr_warn("error in %s: map handler doesn't belong to object\n",
6103                          __func__);
6104                 return NULL;
6105         }
6106
6107         idx = (m - obj->maps) + i;
6108         if (idx >= obj->nr_maps || idx < 0)
6109                 return NULL;
6110         return &obj->maps[idx];
6111 }
6112
6113 struct bpf_map *
6114 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
6115 {
6116         if (prev == NULL)
6117                 return obj->maps;
6118
6119         return __bpf_map__iter(prev, obj, 1);
6120 }
6121
6122 struct bpf_map *
6123 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
6124 {
6125         if (next == NULL) {
6126                 if (!obj->nr_maps)
6127                         return NULL;
6128                 return obj->maps + obj->nr_maps - 1;
6129         }
6130
6131         return __bpf_map__iter(next, obj, -1);
6132 }
6133
6134 struct bpf_map *
6135 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
6136 {
6137         struct bpf_map *pos;
6138
6139         bpf_object__for_each_map(pos, obj) {
6140                 if (pos->name && !strcmp(pos->name, name))
6141                         return pos;
6142         }
6143         return NULL;
6144 }
6145
6146 int
6147 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
6148 {
6149         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
6150 }
6151
6152 struct bpf_map *
6153 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
6154 {
6155         return ERR_PTR(-ENOTSUP);
6156 }
6157
6158 long libbpf_get_error(const void *ptr)
6159 {
6160         return PTR_ERR_OR_ZERO(ptr);
6161 }
6162
6163 int bpf_prog_load(const char *file, enum bpf_prog_type type,
6164                   struct bpf_object **pobj, int *prog_fd)
6165 {
6166         struct bpf_prog_load_attr attr;
6167
6168         memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
6169         attr.file = file;
6170         attr.prog_type = type;
6171         attr.expected_attach_type = 0;
6172
6173         return bpf_prog_load_xattr(&attr, pobj, prog_fd);
6174 }
6175
6176 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
6177                         struct bpf_object **pobj, int *prog_fd)
6178 {
6179         struct bpf_object_open_attr open_attr = {};
6180         struct bpf_program *prog, *first_prog = NULL;
6181         struct bpf_object *obj;
6182         struct bpf_map *map;
6183         int err;
6184
6185         if (!attr)
6186                 return -EINVAL;
6187         if (!attr->file)
6188                 return -EINVAL;
6189
6190         open_attr.file = attr->file;
6191         open_attr.prog_type = attr->prog_type;
6192
6193         obj = bpf_object__open_xattr(&open_attr);
6194         if (IS_ERR_OR_NULL(obj))
6195                 return -ENOENT;
6196
6197         bpf_object__for_each_program(prog, obj) {
6198                 enum bpf_attach_type attach_type = attr->expected_attach_type;
6199                 /*
6200                  * to preserve backwards compatibility, bpf_prog_load treats
6201                  * attr->prog_type, if specified, as an override to whatever
6202                  * bpf_object__open guessed
6203                  */
6204                 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
6205                         bpf_program__set_type(prog, attr->prog_type);
6206                         bpf_program__set_expected_attach_type(prog,
6207                                                               attach_type);
6208                 }
6209                 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
6210                         /*
6211                          * we haven't guessed from section name and user
6212                          * didn't provide a fallback type, too bad...
6213                          */
6214                         bpf_object__close(obj);
6215                         return -EINVAL;
6216                 }
6217
6218                 prog->prog_ifindex = attr->ifindex;
6219                 prog->log_level = attr->log_level;
6220                 prog->prog_flags = attr->prog_flags;
6221                 if (!first_prog)
6222                         first_prog = prog;
6223         }
6224
6225         bpf_object__for_each_map(map, obj) {
6226                 if (!bpf_map__is_offload_neutral(map))
6227                         map->map_ifindex = attr->ifindex;
6228         }
6229
6230         if (!first_prog) {
6231                 pr_warn("object file doesn't contain bpf program\n");
6232                 bpf_object__close(obj);
6233                 return -ENOENT;
6234         }
6235
6236         err = bpf_object__load(obj);
6237         if (err) {
6238                 bpf_object__close(obj);
6239                 return -EINVAL;
6240         }
6241
6242         *pobj = obj;
6243         *prog_fd = bpf_program__fd(first_prog);
6244         return 0;
6245 }
6246
6247 struct bpf_link {
6248         int (*detach)(struct bpf_link *link);
6249         int (*destroy)(struct bpf_link *link);
6250         bool disconnected;
6251 };
6252
6253 /* Release "ownership" of underlying BPF resource (typically, BPF program
6254  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
6255  * link, when destructed through bpf_link__destroy() call won't attempt to
6256  * detach/unregisted that BPF resource. This is useful in situations where,
6257  * say, attached BPF program has to outlive userspace program that attached it
6258  * in the system. Depending on type of BPF program, though, there might be
6259  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
6260  * exit of userspace program doesn't trigger automatic detachment and clean up
6261  * inside the kernel.
6262  */
6263 void bpf_link__disconnect(struct bpf_link *link)
6264 {
6265         link->disconnected = true;
6266 }
6267
6268 int bpf_link__destroy(struct bpf_link *link)
6269 {
6270         int err = 0;
6271
6272         if (!link)
6273                 return 0;
6274
6275         if (!link->disconnected && link->detach)
6276                 err = link->detach(link);
6277         if (link->destroy)
6278                 link->destroy(link);
6279         free(link);
6280
6281         return err;
6282 }
6283
6284 struct bpf_link_fd {
6285         struct bpf_link link; /* has to be at the top of struct */
6286         int fd; /* hook FD */
6287 };
6288
6289 static int bpf_link__detach_perf_event(struct bpf_link *link)
6290 {
6291         struct bpf_link_fd *l = (void *)link;
6292         int err;
6293
6294         err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
6295         if (err)
6296                 err = -errno;
6297
6298         close(l->fd);
6299         return err;
6300 }
6301
6302 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
6303                                                 int pfd)
6304 {
6305         char errmsg[STRERR_BUFSIZE];
6306         struct bpf_link_fd *link;
6307         int prog_fd, err;
6308
6309         if (pfd < 0) {
6310                 pr_warn("program '%s': invalid perf event FD %d\n",
6311                         bpf_program__title(prog, false), pfd);
6312                 return ERR_PTR(-EINVAL);
6313         }
6314         prog_fd = bpf_program__fd(prog);
6315         if (prog_fd < 0) {
6316                 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6317                         bpf_program__title(prog, false));
6318                 return ERR_PTR(-EINVAL);
6319         }
6320
6321         link = calloc(1, sizeof(*link));
6322         if (!link)
6323                 return ERR_PTR(-ENOMEM);
6324         link->link.detach = &bpf_link__detach_perf_event;
6325         link->fd = pfd;
6326
6327         if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
6328                 err = -errno;
6329                 free(link);
6330                 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
6331                         bpf_program__title(prog, false), pfd,
6332                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6333                 return ERR_PTR(err);
6334         }
6335         if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6336                 err = -errno;
6337                 free(link);
6338                 pr_warn("program '%s': failed to enable pfd %d: %s\n",
6339                         bpf_program__title(prog, false), pfd,
6340                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6341                 return ERR_PTR(err);
6342         }
6343         return (struct bpf_link *)link;
6344 }
6345
6346 /*
6347  * this function is expected to parse integer in the range of [0, 2^31-1] from
6348  * given file using scanf format string fmt. If actual parsed value is
6349  * negative, the result might be indistinguishable from error
6350  */
6351 static int parse_uint_from_file(const char *file, const char *fmt)
6352 {
6353         char buf[STRERR_BUFSIZE];
6354         int err, ret;
6355         FILE *f;
6356
6357         f = fopen(file, "r");
6358         if (!f) {
6359                 err = -errno;
6360                 pr_debug("failed to open '%s': %s\n", file,
6361                          libbpf_strerror_r(err, buf, sizeof(buf)));
6362                 return err;
6363         }
6364         err = fscanf(f, fmt, &ret);
6365         if (err != 1) {
6366                 err = err == EOF ? -EIO : -errno;
6367                 pr_debug("failed to parse '%s': %s\n", file,
6368                         libbpf_strerror_r(err, buf, sizeof(buf)));
6369                 fclose(f);
6370                 return err;
6371         }
6372         fclose(f);
6373         return ret;
6374 }
6375
6376 static int determine_kprobe_perf_type(void)
6377 {
6378         const char *file = "/sys/bus/event_source/devices/kprobe/type";
6379
6380         return parse_uint_from_file(file, "%d\n");
6381 }
6382
6383 static int determine_uprobe_perf_type(void)
6384 {
6385         const char *file = "/sys/bus/event_source/devices/uprobe/type";
6386
6387         return parse_uint_from_file(file, "%d\n");
6388 }
6389
6390 static int determine_kprobe_retprobe_bit(void)
6391 {
6392         const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
6393
6394         return parse_uint_from_file(file, "config:%d\n");
6395 }
6396
6397 static int determine_uprobe_retprobe_bit(void)
6398 {
6399         const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
6400
6401         return parse_uint_from_file(file, "config:%d\n");
6402 }
6403
6404 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
6405                                  uint64_t offset, int pid)
6406 {
6407         struct perf_event_attr attr = {};
6408         char errmsg[STRERR_BUFSIZE];
6409         int type, pfd, err;
6410
6411         type = uprobe ? determine_uprobe_perf_type()
6412                       : determine_kprobe_perf_type();
6413         if (type < 0) {
6414                 pr_warn("failed to determine %s perf type: %s\n",
6415                         uprobe ? "uprobe" : "kprobe",
6416                         libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
6417                 return type;
6418         }
6419         if (retprobe) {
6420                 int bit = uprobe ? determine_uprobe_retprobe_bit()
6421                                  : determine_kprobe_retprobe_bit();
6422
6423                 if (bit < 0) {
6424                         pr_warn("failed to determine %s retprobe bit: %s\n",
6425                                 uprobe ? "uprobe" : "kprobe",
6426                                 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
6427                         return bit;
6428                 }
6429                 attr.config |= 1 << bit;
6430         }
6431         attr.size = sizeof(attr);
6432         attr.type = type;
6433         attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
6434         attr.config2 = offset;           /* kprobe_addr or probe_offset */
6435
6436         /* pid filter is meaningful only for uprobes */
6437         pfd = syscall(__NR_perf_event_open, &attr,
6438                       pid < 0 ? -1 : pid /* pid */,
6439                       pid == -1 ? 0 : -1 /* cpu */,
6440                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6441         if (pfd < 0) {
6442                 err = -errno;
6443                 pr_warn("%s perf_event_open() failed: %s\n",
6444                         uprobe ? "uprobe" : "kprobe",
6445                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6446                 return err;
6447         }
6448         return pfd;
6449 }
6450
6451 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
6452                                             bool retprobe,
6453                                             const char *func_name)
6454 {
6455         char errmsg[STRERR_BUFSIZE];
6456         struct bpf_link *link;
6457         int pfd, err;
6458
6459         pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
6460                                     0 /* offset */, -1 /* pid */);
6461         if (pfd < 0) {
6462                 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
6463                         bpf_program__title(prog, false),
6464                         retprobe ? "kretprobe" : "kprobe", func_name,
6465                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6466                 return ERR_PTR(pfd);
6467         }
6468         link = bpf_program__attach_perf_event(prog, pfd);
6469         if (IS_ERR(link)) {
6470                 close(pfd);
6471                 err = PTR_ERR(link);
6472                 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
6473                         bpf_program__title(prog, false),
6474                         retprobe ? "kretprobe" : "kprobe", func_name,
6475                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6476                 return link;
6477         }
6478         return link;
6479 }
6480
6481 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6482                                       struct bpf_program *prog)
6483 {
6484         const char *func_name;
6485         bool retprobe;
6486
6487         func_name = bpf_program__title(prog, false) + sec->len;
6488         retprobe = strcmp(sec->sec, "kretprobe/") == 0;
6489
6490         return bpf_program__attach_kprobe(prog, retprobe, func_name);
6491 }
6492
6493 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
6494                                             bool retprobe, pid_t pid,
6495                                             const char *binary_path,
6496                                             size_t func_offset)
6497 {
6498         char errmsg[STRERR_BUFSIZE];
6499         struct bpf_link *link;
6500         int pfd, err;
6501
6502         pfd = perf_event_open_probe(true /* uprobe */, retprobe,
6503                                     binary_path, func_offset, pid);
6504         if (pfd < 0) {
6505                 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
6506                         bpf_program__title(prog, false),
6507                         retprobe ? "uretprobe" : "uprobe",
6508                         binary_path, func_offset,
6509                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6510                 return ERR_PTR(pfd);
6511         }
6512         link = bpf_program__attach_perf_event(prog, pfd);
6513         if (IS_ERR(link)) {
6514                 close(pfd);
6515                 err = PTR_ERR(link);
6516                 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
6517                         bpf_program__title(prog, false),
6518                         retprobe ? "uretprobe" : "uprobe",
6519                         binary_path, func_offset,
6520                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6521                 return link;
6522         }
6523         return link;
6524 }
6525
6526 static int determine_tracepoint_id(const char *tp_category,
6527                                    const char *tp_name)
6528 {
6529         char file[PATH_MAX];
6530         int ret;
6531
6532         ret = snprintf(file, sizeof(file),
6533                        "/sys/kernel/debug/tracing/events/%s/%s/id",
6534                        tp_category, tp_name);
6535         if (ret < 0)
6536                 return -errno;
6537         if (ret >= sizeof(file)) {
6538                 pr_debug("tracepoint %s/%s path is too long\n",
6539                          tp_category, tp_name);
6540                 return -E2BIG;
6541         }
6542         return parse_uint_from_file(file, "%d\n");
6543 }
6544
6545 static int perf_event_open_tracepoint(const char *tp_category,
6546                                       const char *tp_name)
6547 {
6548         struct perf_event_attr attr = {};
6549         char errmsg[STRERR_BUFSIZE];
6550         int tp_id, pfd, err;
6551
6552         tp_id = determine_tracepoint_id(tp_category, tp_name);
6553         if (tp_id < 0) {
6554                 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
6555                         tp_category, tp_name,
6556                         libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
6557                 return tp_id;
6558         }
6559
6560         attr.type = PERF_TYPE_TRACEPOINT;
6561         attr.size = sizeof(attr);
6562         attr.config = tp_id;
6563
6564         pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
6565                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6566         if (pfd < 0) {
6567                 err = -errno;
6568                 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
6569                         tp_category, tp_name,
6570                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6571                 return err;
6572         }
6573         return pfd;
6574 }
6575
6576 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
6577                                                 const char *tp_category,
6578                                                 const char *tp_name)
6579 {
6580         char errmsg[STRERR_BUFSIZE];
6581         struct bpf_link *link;
6582         int pfd, err;
6583
6584         pfd = perf_event_open_tracepoint(tp_category, tp_name);
6585         if (pfd < 0) {
6586                 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
6587                         bpf_program__title(prog, false),
6588                         tp_category, tp_name,
6589                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6590                 return ERR_PTR(pfd);
6591         }
6592         link = bpf_program__attach_perf_event(prog, pfd);
6593         if (IS_ERR(link)) {
6594                 close(pfd);
6595                 err = PTR_ERR(link);
6596                 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
6597                         bpf_program__title(prog, false),
6598                         tp_category, tp_name,
6599                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6600                 return link;
6601         }
6602         return link;
6603 }
6604
6605 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6606                                   struct bpf_program *prog)
6607 {
6608         char *sec_name, *tp_cat, *tp_name;
6609         struct bpf_link *link;
6610
6611         sec_name = strdup(bpf_program__title(prog, false));
6612         if (!sec_name)
6613                 return ERR_PTR(-ENOMEM);
6614
6615         /* extract "tp/<category>/<name>" */
6616         tp_cat = sec_name + sec->len;
6617         tp_name = strchr(tp_cat, '/');
6618         if (!tp_name) {
6619                 link = ERR_PTR(-EINVAL);
6620                 goto out;
6621         }
6622         *tp_name = '\0';
6623         tp_name++;
6624
6625         link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
6626 out:
6627         free(sec_name);
6628         return link;
6629 }
6630
6631 static int bpf_link__detach_fd(struct bpf_link *link)
6632 {
6633         struct bpf_link_fd *l = (void *)link;
6634
6635         return close(l->fd);
6636 }
6637
6638 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
6639                                                     const char *tp_name)
6640 {
6641         char errmsg[STRERR_BUFSIZE];
6642         struct bpf_link_fd *link;
6643         int prog_fd, pfd;
6644
6645         prog_fd = bpf_program__fd(prog);
6646         if (prog_fd < 0) {
6647                 pr_warn("program '%s': can't attach before loaded\n",
6648                         bpf_program__title(prog, false));
6649                 return ERR_PTR(-EINVAL);
6650         }
6651
6652         link = calloc(1, sizeof(*link));
6653         if (!link)
6654                 return ERR_PTR(-ENOMEM);
6655         link->link.detach = &bpf_link__detach_fd;
6656
6657         pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
6658         if (pfd < 0) {
6659                 pfd = -errno;
6660                 free(link);
6661                 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
6662                         bpf_program__title(prog, false), tp_name,
6663                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6664                 return ERR_PTR(pfd);
6665         }
6666         link->fd = pfd;
6667         return (struct bpf_link *)link;
6668 }
6669
6670 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6671                                       struct bpf_program *prog)
6672 {
6673         const char *tp_name = bpf_program__title(prog, false) + sec->len;
6674
6675         return bpf_program__attach_raw_tracepoint(prog, tp_name);
6676 }
6677
6678 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
6679 {
6680         char errmsg[STRERR_BUFSIZE];
6681         struct bpf_link_fd *link;
6682         int prog_fd, pfd;
6683
6684         prog_fd = bpf_program__fd(prog);
6685         if (prog_fd < 0) {
6686                 pr_warn("program '%s': can't attach before loaded\n",
6687                         bpf_program__title(prog, false));
6688                 return ERR_PTR(-EINVAL);
6689         }
6690
6691         link = calloc(1, sizeof(*link));
6692         if (!link)
6693                 return ERR_PTR(-ENOMEM);
6694         link->link.detach = &bpf_link__detach_fd;
6695
6696         pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
6697         if (pfd < 0) {
6698                 pfd = -errno;
6699                 free(link);
6700                 pr_warn("program '%s': failed to attach to trace: %s\n",
6701                         bpf_program__title(prog, false),
6702                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6703                 return ERR_PTR(pfd);
6704         }
6705         link->fd = pfd;
6706         return (struct bpf_link *)link;
6707 }
6708
6709 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6710                                      struct bpf_program *prog)
6711 {
6712         return bpf_program__attach_trace(prog);
6713 }
6714
6715 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
6716 {
6717         const struct bpf_sec_def *sec_def;
6718
6719         sec_def = find_sec_def(bpf_program__title(prog, false));
6720         if (!sec_def || !sec_def->attach_fn)
6721                 return ERR_PTR(-ESRCH);
6722
6723         return sec_def->attach_fn(sec_def, prog);
6724 }
6725
6726 enum bpf_perf_event_ret
6727 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
6728                            void **copy_mem, size_t *copy_size,
6729                            bpf_perf_event_print_t fn, void *private_data)
6730 {
6731         struct perf_event_mmap_page *header = mmap_mem;
6732         __u64 data_head = ring_buffer_read_head(header);
6733         __u64 data_tail = header->data_tail;
6734         void *base = ((__u8 *)header) + page_size;
6735         int ret = LIBBPF_PERF_EVENT_CONT;
6736         struct perf_event_header *ehdr;
6737         size_t ehdr_size;
6738
6739         while (data_head != data_tail) {
6740                 ehdr = base + (data_tail & (mmap_size - 1));
6741                 ehdr_size = ehdr->size;
6742
6743                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
6744                         void *copy_start = ehdr;
6745                         size_t len_first = base + mmap_size - copy_start;
6746                         size_t len_secnd = ehdr_size - len_first;
6747
6748                         if (*copy_size < ehdr_size) {
6749                                 free(*copy_mem);
6750                                 *copy_mem = malloc(ehdr_size);
6751                                 if (!*copy_mem) {
6752                                         *copy_size = 0;
6753                                         ret = LIBBPF_PERF_EVENT_ERROR;
6754                                         break;
6755                                 }
6756                                 *copy_size = ehdr_size;
6757                         }
6758
6759                         memcpy(*copy_mem, copy_start, len_first);
6760                         memcpy(*copy_mem + len_first, base, len_secnd);
6761                         ehdr = *copy_mem;
6762                 }
6763
6764                 ret = fn(ehdr, private_data);
6765                 data_tail += ehdr_size;
6766                 if (ret != LIBBPF_PERF_EVENT_CONT)
6767                         break;
6768         }
6769
6770         ring_buffer_write_tail(header, data_tail);
6771         return ret;
6772 }
6773
6774 struct perf_buffer;
6775
6776 struct perf_buffer_params {
6777         struct perf_event_attr *attr;
6778         /* if event_cb is specified, it takes precendence */
6779         perf_buffer_event_fn event_cb;
6780         /* sample_cb and lost_cb are higher-level common-case callbacks */
6781         perf_buffer_sample_fn sample_cb;
6782         perf_buffer_lost_fn lost_cb;
6783         void *ctx;
6784         int cpu_cnt;
6785         int *cpus;
6786         int *map_keys;
6787 };
6788
6789 struct perf_cpu_buf {
6790         struct perf_buffer *pb;
6791         void *base; /* mmap()'ed memory */
6792         void *buf; /* for reconstructing segmented data */
6793         size_t buf_size;
6794         int fd;
6795         int cpu;
6796         int map_key;
6797 };
6798
6799 struct perf_buffer {
6800         perf_buffer_event_fn event_cb;
6801         perf_buffer_sample_fn sample_cb;
6802         perf_buffer_lost_fn lost_cb;
6803         void *ctx; /* passed into callbacks */
6804
6805         size_t page_size;
6806         size_t mmap_size;
6807         struct perf_cpu_buf **cpu_bufs;
6808         struct epoll_event *events;
6809         int cpu_cnt; /* number of allocated CPU buffers */
6810         int epoll_fd; /* perf event FD */
6811         int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
6812 };
6813
6814 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
6815                                       struct perf_cpu_buf *cpu_buf)
6816 {
6817         if (!cpu_buf)
6818                 return;
6819         if (cpu_buf->base &&
6820             munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
6821                 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
6822         if (cpu_buf->fd >= 0) {
6823                 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
6824                 close(cpu_buf->fd);
6825         }
6826         free(cpu_buf->buf);
6827         free(cpu_buf);
6828 }
6829
6830 void perf_buffer__free(struct perf_buffer *pb)
6831 {
6832         int i;
6833
6834         if (!pb)
6835                 return;
6836         if (pb->cpu_bufs) {
6837                 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
6838                         struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
6839
6840                         bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
6841                         perf_buffer__free_cpu_buf(pb, cpu_buf);
6842                 }
6843                 free(pb->cpu_bufs);
6844         }
6845         if (pb->epoll_fd >= 0)
6846                 close(pb->epoll_fd);
6847         free(pb->events);
6848         free(pb);
6849 }
6850
6851 static struct perf_cpu_buf *
6852 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
6853                           int cpu, int map_key)
6854 {
6855         struct perf_cpu_buf *cpu_buf;
6856         char msg[STRERR_BUFSIZE];
6857         int err;
6858
6859         cpu_buf = calloc(1, sizeof(*cpu_buf));
6860         if (!cpu_buf)
6861                 return ERR_PTR(-ENOMEM);
6862
6863         cpu_buf->pb = pb;
6864         cpu_buf->cpu = cpu;
6865         cpu_buf->map_key = map_key;
6866
6867         cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6868                               -1, PERF_FLAG_FD_CLOEXEC);
6869         if (cpu_buf->fd < 0) {
6870                 err = -errno;
6871                 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6872                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6873                 goto error;
6874         }
6875
6876         cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6877                              PROT_READ | PROT_WRITE, MAP_SHARED,
6878                              cpu_buf->fd, 0);
6879         if (cpu_buf->base == MAP_FAILED) {
6880                 cpu_buf->base = NULL;
6881                 err = -errno;
6882                 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6883                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6884                 goto error;
6885         }
6886
6887         if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6888                 err = -errno;
6889                 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6890                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
6891                 goto error;
6892         }
6893
6894         return cpu_buf;
6895
6896 error:
6897         perf_buffer__free_cpu_buf(pb, cpu_buf);
6898         return (struct perf_cpu_buf *)ERR_PTR(err);
6899 }
6900
6901 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6902                                               struct perf_buffer_params *p);
6903
6904 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6905                                      const struct perf_buffer_opts *opts)
6906 {
6907         struct perf_buffer_params p = {};
6908         struct perf_event_attr attr = { 0, };
6909
6910         attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6911         attr.type = PERF_TYPE_SOFTWARE;
6912         attr.sample_type = PERF_SAMPLE_RAW;
6913         attr.sample_period = 1;
6914         attr.wakeup_events = 1;
6915
6916         p.attr = &attr;
6917         p.sample_cb = opts ? opts->sample_cb : NULL;
6918         p.lost_cb = opts ? opts->lost_cb : NULL;
6919         p.ctx = opts ? opts->ctx : NULL;
6920
6921         return __perf_buffer__new(map_fd, page_cnt, &p);
6922 }
6923
6924 struct perf_buffer *
6925 perf_buffer__new_raw(int map_fd, size_t page_cnt,
6926                      const struct perf_buffer_raw_opts *opts)
6927 {
6928         struct perf_buffer_params p = {};
6929
6930         p.attr = opts->attr;
6931         p.event_cb = opts->event_cb;
6932         p.ctx = opts->ctx;
6933         p.cpu_cnt = opts->cpu_cnt;
6934         p.cpus = opts->cpus;
6935         p.map_keys = opts->map_keys;
6936
6937         return __perf_buffer__new(map_fd, page_cnt, &p);
6938 }
6939
6940 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6941                                               struct perf_buffer_params *p)
6942 {
6943         const char *online_cpus_file = "/sys/devices/system/cpu/online";
6944         struct bpf_map_info map = {};
6945         char msg[STRERR_BUFSIZE];
6946         struct perf_buffer *pb;
6947         bool *online = NULL;
6948         __u32 map_info_len;
6949         int err, i, j, n;
6950
6951         if (page_cnt & (page_cnt - 1)) {
6952                 pr_warn("page count should be power of two, but is %zu\n",
6953                         page_cnt);
6954                 return ERR_PTR(-EINVAL);
6955         }
6956
6957         map_info_len = sizeof(map);
6958         err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
6959         if (err) {
6960                 err = -errno;
6961                 pr_warn("failed to get map info for map FD %d: %s\n",
6962                         map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
6963                 return ERR_PTR(err);
6964         }
6965
6966         if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
6967                 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
6968                         map.name);
6969                 return ERR_PTR(-EINVAL);
6970         }
6971
6972         pb = calloc(1, sizeof(*pb));
6973         if (!pb)
6974                 return ERR_PTR(-ENOMEM);
6975
6976         pb->event_cb = p->event_cb;
6977         pb->sample_cb = p->sample_cb;
6978         pb->lost_cb = p->lost_cb;
6979         pb->ctx = p->ctx;
6980
6981         pb->page_size = getpagesize();
6982         pb->mmap_size = pb->page_size * page_cnt;
6983         pb->map_fd = map_fd;
6984
6985         pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
6986         if (pb->epoll_fd < 0) {
6987                 err = -errno;
6988                 pr_warn("failed to create epoll instance: %s\n",
6989                         libbpf_strerror_r(err, msg, sizeof(msg)));
6990                 goto error;
6991         }
6992
6993         if (p->cpu_cnt > 0) {
6994                 pb->cpu_cnt = p->cpu_cnt;
6995         } else {
6996                 pb->cpu_cnt = libbpf_num_possible_cpus();
6997                 if (pb->cpu_cnt < 0) {
6998                         err = pb->cpu_cnt;
6999                         goto error;
7000                 }
7001                 if (map.max_entries < pb->cpu_cnt)
7002                         pb->cpu_cnt = map.max_entries;
7003         }
7004
7005         pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
7006         if (!pb->events) {
7007                 err = -ENOMEM;
7008                 pr_warn("failed to allocate events: out of memory\n");
7009                 goto error;
7010         }
7011         pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
7012         if (!pb->cpu_bufs) {
7013                 err = -ENOMEM;
7014                 pr_warn("failed to allocate buffers: out of memory\n");
7015                 goto error;
7016         }
7017
7018         err = parse_cpu_mask_file(online_cpus_file, &online, &n);
7019         if (err) {
7020                 pr_warn("failed to get online CPU mask: %d\n", err);
7021                 goto error;
7022         }
7023
7024         for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
7025                 struct perf_cpu_buf *cpu_buf;
7026                 int cpu, map_key;
7027
7028                 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
7029                 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
7030
7031                 /* in case user didn't explicitly requested particular CPUs to
7032                  * be attached to, skip offline/not present CPUs
7033                  */
7034                 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
7035                         continue;
7036
7037                 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
7038                 if (IS_ERR(cpu_buf)) {
7039                         err = PTR_ERR(cpu_buf);
7040                         goto error;
7041                 }
7042
7043                 pb->cpu_bufs[j] = cpu_buf;
7044
7045                 err = bpf_map_update_elem(pb->map_fd, &map_key,
7046                                           &cpu_buf->fd, 0);
7047                 if (err) {
7048                         err = -errno;
7049                         pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7050                                 cpu, map_key, cpu_buf->fd,
7051                                 libbpf_strerror_r(err, msg, sizeof(msg)));
7052                         goto error;
7053                 }
7054
7055                 pb->events[j].events = EPOLLIN;
7056                 pb->events[j].data.ptr = cpu_buf;
7057                 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
7058                               &pb->events[j]) < 0) {
7059                         err = -errno;
7060                         pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7061                                 cpu, cpu_buf->fd,
7062                                 libbpf_strerror_r(err, msg, sizeof(msg)));
7063                         goto error;
7064                 }
7065                 j++;
7066         }
7067         pb->cpu_cnt = j;
7068         free(online);
7069
7070         return pb;
7071
7072 error:
7073         free(online);
7074         if (pb)
7075                 perf_buffer__free(pb);
7076         return ERR_PTR(err);
7077 }
7078
7079 struct perf_sample_raw {
7080         struct perf_event_header header;
7081         uint32_t size;
7082         char data[0];
7083 };
7084
7085 struct perf_sample_lost {
7086         struct perf_event_header header;
7087         uint64_t id;
7088         uint64_t lost;
7089         uint64_t sample_id;
7090 };
7091
7092 static enum bpf_perf_event_ret
7093 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
7094 {
7095         struct perf_cpu_buf *cpu_buf = ctx;
7096         struct perf_buffer *pb = cpu_buf->pb;
7097         void *data = e;
7098
7099         /* user wants full control over parsing perf event */
7100         if (pb->event_cb)
7101                 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
7102
7103         switch (e->type) {
7104         case PERF_RECORD_SAMPLE: {
7105                 struct perf_sample_raw *s = data;
7106
7107                 if (pb->sample_cb)
7108                         pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
7109                 break;
7110         }
7111         case PERF_RECORD_LOST: {
7112                 struct perf_sample_lost *s = data;
7113
7114                 if (pb->lost_cb)
7115                         pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
7116                 break;
7117         }
7118         default:
7119                 pr_warn("unknown perf sample type %d\n", e->type);
7120                 return LIBBPF_PERF_EVENT_ERROR;
7121         }
7122         return LIBBPF_PERF_EVENT_CONT;
7123 }
7124
7125 static int perf_buffer__process_records(struct perf_buffer *pb,
7126                                         struct perf_cpu_buf *cpu_buf)
7127 {
7128         enum bpf_perf_event_ret ret;
7129
7130         ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
7131                                          pb->page_size, &cpu_buf->buf,
7132                                          &cpu_buf->buf_size,
7133                                          perf_buffer__process_record, cpu_buf);
7134         if (ret != LIBBPF_PERF_EVENT_CONT)
7135                 return ret;
7136         return 0;
7137 }
7138
7139 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
7140 {
7141         int i, cnt, err;
7142
7143         cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
7144         for (i = 0; i < cnt; i++) {
7145                 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
7146
7147                 err = perf_buffer__process_records(pb, cpu_buf);
7148                 if (err) {
7149                         pr_warn("error while processing records: %d\n", err);
7150                         return err;
7151                 }
7152         }
7153         return cnt < 0 ? -errno : cnt;
7154 }
7155
7156 struct bpf_prog_info_array_desc {
7157         int     array_offset;   /* e.g. offset of jited_prog_insns */
7158         int     count_offset;   /* e.g. offset of jited_prog_len */
7159         int     size_offset;    /* > 0: offset of rec size,
7160                                  * < 0: fix size of -size_offset
7161                                  */
7162 };
7163
7164 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
7165         [BPF_PROG_INFO_JITED_INSNS] = {
7166                 offsetof(struct bpf_prog_info, jited_prog_insns),
7167                 offsetof(struct bpf_prog_info, jited_prog_len),
7168                 -1,
7169         },
7170         [BPF_PROG_INFO_XLATED_INSNS] = {
7171                 offsetof(struct bpf_prog_info, xlated_prog_insns),
7172                 offsetof(struct bpf_prog_info, xlated_prog_len),
7173                 -1,
7174         },
7175         [BPF_PROG_INFO_MAP_IDS] = {
7176                 offsetof(struct bpf_prog_info, map_ids),
7177                 offsetof(struct bpf_prog_info, nr_map_ids),
7178                 -(int)sizeof(__u32),
7179         },
7180         [BPF_PROG_INFO_JITED_KSYMS] = {
7181                 offsetof(struct bpf_prog_info, jited_ksyms),
7182                 offsetof(struct bpf_prog_info, nr_jited_ksyms),
7183                 -(int)sizeof(__u64),
7184         },
7185         [BPF_PROG_INFO_JITED_FUNC_LENS] = {
7186                 offsetof(struct bpf_prog_info, jited_func_lens),
7187                 offsetof(struct bpf_prog_info, nr_jited_func_lens),
7188                 -(int)sizeof(__u32),
7189         },
7190         [BPF_PROG_INFO_FUNC_INFO] = {
7191                 offsetof(struct bpf_prog_info, func_info),
7192                 offsetof(struct bpf_prog_info, nr_func_info),
7193                 offsetof(struct bpf_prog_info, func_info_rec_size),
7194         },
7195         [BPF_PROG_INFO_LINE_INFO] = {
7196                 offsetof(struct bpf_prog_info, line_info),
7197                 offsetof(struct bpf_prog_info, nr_line_info),
7198                 offsetof(struct bpf_prog_info, line_info_rec_size),
7199         },
7200         [BPF_PROG_INFO_JITED_LINE_INFO] = {
7201                 offsetof(struct bpf_prog_info, jited_line_info),
7202                 offsetof(struct bpf_prog_info, nr_jited_line_info),
7203                 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
7204         },
7205         [BPF_PROG_INFO_PROG_TAGS] = {
7206                 offsetof(struct bpf_prog_info, prog_tags),
7207                 offsetof(struct bpf_prog_info, nr_prog_tags),
7208                 -(int)sizeof(__u8) * BPF_TAG_SIZE,
7209         },
7210
7211 };
7212
7213 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
7214                                            int offset)
7215 {
7216         __u32 *array = (__u32 *)info;
7217
7218         if (offset >= 0)
7219                 return array[offset / sizeof(__u32)];
7220         return -(int)offset;
7221 }
7222
7223 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
7224                                            int offset)
7225 {
7226         __u64 *array = (__u64 *)info;
7227
7228         if (offset >= 0)
7229                 return array[offset / sizeof(__u64)];
7230         return -(int)offset;
7231 }
7232
7233 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
7234                                          __u32 val)
7235 {
7236         __u32 *array = (__u32 *)info;
7237
7238         if (offset >= 0)
7239                 array[offset / sizeof(__u32)] = val;
7240 }
7241
7242 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
7243                                          __u64 val)
7244 {
7245         __u64 *array = (__u64 *)info;
7246
7247         if (offset >= 0)
7248                 array[offset / sizeof(__u64)] = val;
7249 }
7250
7251 struct bpf_prog_info_linear *
7252 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
7253 {
7254         struct bpf_prog_info_linear *info_linear;
7255         struct bpf_prog_info info = {};
7256         __u32 info_len = sizeof(info);
7257         __u32 data_len = 0;
7258         int i, err;
7259         void *ptr;
7260
7261         if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
7262                 return ERR_PTR(-EINVAL);
7263
7264         /* step 1: get array dimensions */
7265         err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
7266         if (err) {
7267                 pr_debug("can't get prog info: %s", strerror(errno));
7268                 return ERR_PTR(-EFAULT);
7269         }
7270
7271         /* step 2: calculate total size of all arrays */
7272         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7273                 bool include_array = (arrays & (1UL << i)) > 0;
7274                 struct bpf_prog_info_array_desc *desc;
7275                 __u32 count, size;
7276
7277                 desc = bpf_prog_info_array_desc + i;
7278
7279                 /* kernel is too old to support this field */
7280                 if (info_len < desc->array_offset + sizeof(__u32) ||
7281                     info_len < desc->count_offset + sizeof(__u32) ||
7282                     (desc->size_offset > 0 && info_len < desc->size_offset))
7283                         include_array = false;
7284
7285                 if (!include_array) {
7286                         arrays &= ~(1UL << i);  /* clear the bit */
7287                         continue;
7288                 }
7289
7290                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7291                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7292
7293                 data_len += count * size;
7294         }
7295
7296         /* step 3: allocate continuous memory */
7297         data_len = roundup(data_len, sizeof(__u64));
7298         info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
7299         if (!info_linear)
7300                 return ERR_PTR(-ENOMEM);
7301
7302         /* step 4: fill data to info_linear->info */
7303         info_linear->arrays = arrays;
7304         memset(&info_linear->info, 0, sizeof(info));
7305         ptr = info_linear->data;
7306
7307         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7308                 struct bpf_prog_info_array_desc *desc;
7309                 __u32 count, size;
7310
7311                 if ((arrays & (1UL << i)) == 0)
7312                         continue;
7313
7314                 desc  = bpf_prog_info_array_desc + i;
7315                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7316                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7317                 bpf_prog_info_set_offset_u32(&info_linear->info,
7318                                              desc->count_offset, count);
7319                 bpf_prog_info_set_offset_u32(&info_linear->info,
7320                                              desc->size_offset, size);
7321                 bpf_prog_info_set_offset_u64(&info_linear->info,
7322                                              desc->array_offset,
7323                                              ptr_to_u64(ptr));
7324                 ptr += count * size;
7325         }
7326
7327         /* step 5: call syscall again to get required arrays */
7328         err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
7329         if (err) {
7330                 pr_debug("can't get prog info: %s", strerror(errno));
7331                 free(info_linear);
7332                 return ERR_PTR(-EFAULT);
7333         }
7334
7335         /* step 6: verify the data */
7336         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7337                 struct bpf_prog_info_array_desc *desc;
7338                 __u32 v1, v2;
7339
7340                 if ((arrays & (1UL << i)) == 0)
7341                         continue;
7342
7343                 desc = bpf_prog_info_array_desc + i;
7344                 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7345                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7346                                                    desc->count_offset);
7347                 if (v1 != v2)
7348                         pr_warn("%s: mismatch in element count\n", __func__);
7349
7350                 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7351                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7352                                                    desc->size_offset);
7353                 if (v1 != v2)
7354                         pr_warn("%s: mismatch in rec size\n", __func__);
7355         }
7356
7357         /* step 7: update info_len and data_len */
7358         info_linear->info_len = sizeof(struct bpf_prog_info);
7359         info_linear->data_len = data_len;
7360
7361         return info_linear;
7362 }
7363
7364 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
7365 {
7366         int i;
7367
7368         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7369                 struct bpf_prog_info_array_desc *desc;
7370                 __u64 addr, offs;
7371
7372                 if ((info_linear->arrays & (1UL << i)) == 0)
7373                         continue;
7374
7375                 desc = bpf_prog_info_array_desc + i;
7376                 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
7377                                                      desc->array_offset);
7378                 offs = addr - ptr_to_u64(info_linear->data);
7379                 bpf_prog_info_set_offset_u64(&info_linear->info,
7380                                              desc->array_offset, offs);
7381         }
7382 }
7383
7384 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
7385 {
7386         int i;
7387
7388         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7389                 struct bpf_prog_info_array_desc *desc;
7390                 __u64 addr, offs;
7391
7392                 if ((info_linear->arrays & (1UL << i)) == 0)
7393                         continue;
7394
7395                 desc = bpf_prog_info_array_desc + i;
7396                 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
7397                                                      desc->array_offset);
7398                 addr = offs + ptr_to_u64(info_linear->data);
7399                 bpf_prog_info_set_offset_u64(&info_linear->info,
7400                                              desc->array_offset, addr);
7401         }
7402 }
7403
7404 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
7405 {
7406         int err = 0, n, len, start, end = -1;
7407         bool *tmp;
7408
7409         *mask = NULL;
7410         *mask_sz = 0;
7411
7412         /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
7413         while (*s) {
7414                 if (*s == ',' || *s == '\n') {
7415                         s++;
7416                         continue;
7417                 }
7418                 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
7419                 if (n <= 0 || n > 2) {
7420                         pr_warn("Failed to get CPU range %s: %d\n", s, n);
7421                         err = -EINVAL;
7422                         goto cleanup;
7423                 } else if (n == 1) {
7424                         end = start;
7425                 }
7426                 if (start < 0 || start > end) {
7427                         pr_warn("Invalid CPU range [%d,%d] in %s\n",
7428                                 start, end, s);
7429                         err = -EINVAL;
7430                         goto cleanup;
7431                 }
7432                 tmp = realloc(*mask, end + 1);
7433                 if (!tmp) {
7434                         err = -ENOMEM;
7435                         goto cleanup;
7436                 }
7437                 *mask = tmp;
7438                 memset(tmp + *mask_sz, 0, start - *mask_sz);
7439                 memset(tmp + start, 1, end - start + 1);
7440                 *mask_sz = end + 1;
7441                 s += len;
7442         }
7443         if (!*mask_sz) {
7444                 pr_warn("Empty CPU range\n");
7445                 return -EINVAL;
7446         }
7447         return 0;
7448 cleanup:
7449         free(*mask);
7450         *mask = NULL;
7451         return err;
7452 }
7453
7454 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
7455 {
7456         int fd, err = 0, len;
7457         char buf[128];
7458
7459         fd = open(fcpu, O_RDONLY);
7460         if (fd < 0) {
7461                 err = -errno;
7462                 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
7463                 return err;
7464         }
7465         len = read(fd, buf, sizeof(buf));
7466         close(fd);
7467         if (len <= 0) {
7468                 err = len ? -errno : -EINVAL;
7469                 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
7470                 return err;
7471         }
7472         if (len >= sizeof(buf)) {
7473                 pr_warn("CPU mask is too big in file %s\n", fcpu);
7474                 return -E2BIG;
7475         }
7476         buf[len] = '\0';
7477
7478         return parse_cpu_mask_str(buf, mask, mask_sz);
7479 }
7480
7481 int libbpf_num_possible_cpus(void)
7482 {
7483         static const char *fcpu = "/sys/devices/system/cpu/possible";
7484         static int cpus;
7485         int err, n, i, tmp_cpus;
7486         bool *mask;
7487
7488         tmp_cpus = READ_ONCE(cpus);
7489         if (tmp_cpus > 0)
7490                 return tmp_cpus;
7491
7492         err = parse_cpu_mask_file(fcpu, &mask, &n);
7493         if (err)
7494                 return err;
7495
7496         tmp_cpus = 0;
7497         for (i = 0; i < n; i++) {
7498                 if (mask[i])
7499                         tmp_cpus++;
7500         }
7501         free(mask);
7502
7503         WRITE_ONCE(cpus, tmp_cpus);
7504         return tmp_cpus;
7505 }
7506
7507 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
7508                               const struct bpf_object_open_opts *opts)
7509 {
7510         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
7511                 .object_name = s->name,
7512         );
7513         struct bpf_object *obj;
7514         int i;
7515
7516         /* Attempt to preserve opts->object_name, unless overriden by user
7517          * explicitly. Overwriting object name for skeletons is discouraged,
7518          * as it breaks global data maps, because they contain object name
7519          * prefix as their own map name prefix. When skeleton is generated,
7520          * bpftool is making an assumption that this name will stay the same.
7521          */
7522         if (opts) {
7523                 memcpy(&skel_opts, opts, sizeof(*opts));
7524                 if (!opts->object_name)
7525                         skel_opts.object_name = s->name;
7526         }
7527
7528         obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
7529         if (IS_ERR(obj)) {
7530                 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
7531                         s->name, PTR_ERR(obj));
7532                 return PTR_ERR(obj);
7533         }
7534
7535         *s->obj = obj;
7536
7537         for (i = 0; i < s->map_cnt; i++) {
7538                 struct bpf_map **map = s->maps[i].map;
7539                 const char *name = s->maps[i].name;
7540                 void **mmaped = s->maps[i].mmaped;
7541
7542                 *map = bpf_object__find_map_by_name(obj, name);
7543                 if (!*map) {
7544                         pr_warn("failed to find skeleton map '%s'\n", name);
7545                         return -ESRCH;
7546                 }
7547
7548                 /* externs shouldn't be pre-setup from user code */
7549                 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_EXTERN)
7550                         *mmaped = (*map)->mmaped;
7551         }
7552
7553         for (i = 0; i < s->prog_cnt; i++) {
7554                 struct bpf_program **prog = s->progs[i].prog;
7555                 const char *name = s->progs[i].name;
7556
7557                 *prog = bpf_object__find_program_by_name(obj, name);
7558                 if (!*prog) {
7559                         pr_warn("failed to find skeleton program '%s'\n", name);
7560                         return -ESRCH;
7561                 }
7562         }
7563
7564         return 0;
7565 }
7566
7567 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
7568 {
7569         int i, err;
7570
7571         err = bpf_object__load(*s->obj);
7572         if (err) {
7573                 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
7574                 return err;
7575         }
7576
7577         for (i = 0; i < s->map_cnt; i++) {
7578                 struct bpf_map *map = *s->maps[i].map;
7579                 size_t mmap_sz = bpf_map_mmap_sz(map);
7580                 int prot, map_fd = bpf_map__fd(map);
7581                 void **mmaped = s->maps[i].mmaped;
7582
7583                 if (!mmaped)
7584                         continue;
7585
7586                 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
7587                         *mmaped = NULL;
7588                         continue;
7589                 }
7590
7591                 if (map->def.map_flags & BPF_F_RDONLY_PROG)
7592                         prot = PROT_READ;
7593                 else
7594                         prot = PROT_READ | PROT_WRITE;
7595
7596                 /* Remap anonymous mmap()-ed "map initialization image" as
7597                  * a BPF map-backed mmap()-ed memory, but preserving the same
7598                  * memory address. This will cause kernel to change process'
7599                  * page table to point to a different piece of kernel memory,
7600                  * but from userspace point of view memory address (and its
7601                  * contents, being identical at this point) will stay the
7602                  * same. This mapping will be released by bpf_object__close()
7603                  * as per normal clean up procedure, so we don't need to worry
7604                  * about it from skeleton's clean up perspective.
7605                  */
7606                 *mmaped = mmap(map->mmaped, mmap_sz, prot,
7607                                 MAP_SHARED | MAP_FIXED, map_fd, 0);
7608                 if (*mmaped == MAP_FAILED) {
7609                         err = -errno;
7610                         *mmaped = NULL;
7611                         pr_warn("failed to re-mmap() map '%s': %d\n",
7612                                  bpf_map__name(map), err);
7613                         return err;
7614                 }
7615         }
7616
7617         return 0;
7618 }
7619
7620 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
7621 {
7622         int i;
7623
7624         for (i = 0; i < s->prog_cnt; i++) {
7625                 struct bpf_program *prog = *s->progs[i].prog;
7626                 struct bpf_link **link = s->progs[i].link;
7627                 const struct bpf_sec_def *sec_def;
7628                 const char *sec_name = bpf_program__title(prog, false);
7629
7630                 sec_def = find_sec_def(sec_name);
7631                 if (!sec_def || !sec_def->attach_fn)
7632                         continue;
7633
7634                 *link = sec_def->attach_fn(sec_def, prog);
7635                 if (IS_ERR(*link)) {
7636                         pr_warn("failed to auto-attach program '%s': %ld\n",
7637                                 bpf_program__name(prog), PTR_ERR(*link));
7638                         return PTR_ERR(*link);
7639                 }
7640         }
7641
7642         return 0;
7643 }
7644
7645 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
7646 {
7647         int i;
7648
7649         for (i = 0; i < s->prog_cnt; i++) {
7650                 struct bpf_link **link = s->progs[i].link;
7651
7652                 if (!IS_ERR_OR_NULL(*link))
7653                         bpf_link__destroy(*link);
7654                 *link = NULL;
7655         }
7656 }
7657
7658 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
7659 {
7660         if (s->progs)
7661                 bpf_object__detach_skeleton(s);
7662         if (s->obj)
7663                 bpf_object__close(*s->obj);
7664         free(s->maps);
7665         free(s->progs);
7666         free(s);
7667 }