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