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