libbpf: Rename btf__get_from_id() as btf__load_from_kernel_by_id()
[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 <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/list.h>
35 #include <linux/limits.h>
36 #include <linux/perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <linux/version.h>
39 #include <sys/epoll.h>
40 #include <sys/ioctl.h>
41 #include <sys/mman.h>
42 #include <sys/stat.h>
43 #include <sys/types.h>
44 #include <sys/vfs.h>
45 #include <sys/utsname.h>
46 #include <sys/resource.h>
47 #include <libelf.h>
48 #include <gelf.h>
49 #include <zlib.h>
50
51 #include "libbpf.h"
52 #include "bpf.h"
53 #include "btf.h"
54 #include "str_error.h"
55 #include "libbpf_internal.h"
56 #include "hashmap.h"
57 #include "bpf_gen_internal.h"
58
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC            0xcafe4a11
61 #endif
62
63 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
64
65 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
66  * compilation if user enables corresponding warning. Disable it explicitly.
67  */
68 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
69
70 #define __printf(a, b)  __attribute__((format(printf, a, b)))
71
72 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
73 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
74
75 static int __base_pr(enum libbpf_print_level level, const char *format,
76                      va_list args)
77 {
78         if (level == LIBBPF_DEBUG)
79                 return 0;
80
81         return vfprintf(stderr, format, args);
82 }
83
84 static libbpf_print_fn_t __libbpf_pr = __base_pr;
85
86 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
87 {
88         libbpf_print_fn_t old_print_fn = __libbpf_pr;
89
90         __libbpf_pr = fn;
91         return old_print_fn;
92 }
93
94 __printf(2, 3)
95 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
96 {
97         va_list args;
98
99         if (!__libbpf_pr)
100                 return;
101
102         va_start(args, format);
103         __libbpf_pr(level, format, args);
104         va_end(args);
105 }
106
107 static void pr_perm_msg(int err)
108 {
109         struct rlimit limit;
110         char buf[100];
111
112         if (err != -EPERM || geteuid() != 0)
113                 return;
114
115         err = getrlimit(RLIMIT_MEMLOCK, &limit);
116         if (err)
117                 return;
118
119         if (limit.rlim_cur == RLIM_INFINITY)
120                 return;
121
122         if (limit.rlim_cur < 1024)
123                 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
124         else if (limit.rlim_cur < 1024*1024)
125                 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
126         else
127                 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
128
129         pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
130                 buf);
131 }
132
133 #define STRERR_BUFSIZE  128
134
135 /* Copied from tools/perf/util/util.h */
136 #ifndef zfree
137 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
138 #endif
139
140 #ifndef zclose
141 # define zclose(fd) ({                  \
142         int ___err = 0;                 \
143         if ((fd) >= 0)                  \
144                 ___err = close((fd));   \
145         fd = -1;                        \
146         ___err; })
147 #endif
148
149 static inline __u64 ptr_to_u64(const void *ptr)
150 {
151         return (__u64) (unsigned long) ptr;
152 }
153
154 /* this goes away in libbpf 1.0 */
155 enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE;
156
157 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
158 {
159         /* __LIBBPF_STRICT_LAST is the last power-of-2 value used + 1, so to
160          * get all possible values we compensate last +1, and then (2*x - 1)
161          * to get the bit mask
162          */
163         if (mode != LIBBPF_STRICT_ALL
164             && (mode & ~((__LIBBPF_STRICT_LAST - 1) * 2 - 1)))
165                 return errno = EINVAL, -EINVAL;
166
167         libbpf_mode = mode;
168         return 0;
169 }
170
171 enum kern_feature_id {
172         /* v4.14: kernel support for program & map names. */
173         FEAT_PROG_NAME,
174         /* v5.2: kernel support for global data sections. */
175         FEAT_GLOBAL_DATA,
176         /* BTF support */
177         FEAT_BTF,
178         /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
179         FEAT_BTF_FUNC,
180         /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
181         FEAT_BTF_DATASEC,
182         /* BTF_FUNC_GLOBAL is supported */
183         FEAT_BTF_GLOBAL_FUNC,
184         /* BPF_F_MMAPABLE is supported for arrays */
185         FEAT_ARRAY_MMAP,
186         /* kernel support for expected_attach_type in BPF_PROG_LOAD */
187         FEAT_EXP_ATTACH_TYPE,
188         /* bpf_probe_read_{kernel,user}[_str] helpers */
189         FEAT_PROBE_READ_KERN,
190         /* BPF_PROG_BIND_MAP is supported */
191         FEAT_PROG_BIND_MAP,
192         /* Kernel support for module BTFs */
193         FEAT_MODULE_BTF,
194         /* BTF_KIND_FLOAT support */
195         FEAT_BTF_FLOAT,
196         __FEAT_CNT,
197 };
198
199 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
200
201 enum reloc_type {
202         RELO_LD64,
203         RELO_CALL,
204         RELO_DATA,
205         RELO_EXTERN_VAR,
206         RELO_EXTERN_FUNC,
207         RELO_SUBPROG_ADDR,
208 };
209
210 struct reloc_desc {
211         enum reloc_type type;
212         int insn_idx;
213         int map_idx;
214         int sym_off;
215 };
216
217 struct bpf_sec_def;
218
219 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
220                                         struct bpf_program *prog);
221
222 struct bpf_sec_def {
223         const char *sec;
224         size_t len;
225         enum bpf_prog_type prog_type;
226         enum bpf_attach_type expected_attach_type;
227         bool is_exp_attach_type_optional;
228         bool is_attachable;
229         bool is_attach_btf;
230         bool is_sleepable;
231         attach_fn_t attach_fn;
232 };
233
234 /*
235  * bpf_prog should be a better name but it has been used in
236  * linux/filter.h.
237  */
238 struct bpf_program {
239         const struct bpf_sec_def *sec_def;
240         char *sec_name;
241         size_t sec_idx;
242         /* this program's instruction offset (in number of instructions)
243          * within its containing ELF section
244          */
245         size_t sec_insn_off;
246         /* number of original instructions in ELF section belonging to this
247          * program, not taking into account subprogram instructions possible
248          * appended later during relocation
249          */
250         size_t sec_insn_cnt;
251         /* Offset (in number of instructions) of the start of instruction
252          * belonging to this BPF program  within its containing main BPF
253          * program. For the entry-point (main) BPF program, this is always
254          * zero. For a sub-program, this gets reset before each of main BPF
255          * programs are processed and relocated and is used to determined
256          * whether sub-program was already appended to the main program, and
257          * if yes, at which instruction offset.
258          */
259         size_t sub_insn_off;
260
261         char *name;
262         /* sec_name with / replaced by _; makes recursive pinning
263          * in bpf_object__pin_programs easier
264          */
265         char *pin_name;
266
267         /* instructions that belong to BPF program; insns[0] is located at
268          * sec_insn_off instruction within its ELF section in ELF file, so
269          * when mapping ELF file instruction index to the local instruction,
270          * one needs to subtract sec_insn_off; and vice versa.
271          */
272         struct bpf_insn *insns;
273         /* actual number of instruction in this BPF program's image; for
274          * entry-point BPF programs this includes the size of main program
275          * itself plus all the used sub-programs, appended at the end
276          */
277         size_t insns_cnt;
278
279         struct reloc_desc *reloc_desc;
280         int nr_reloc;
281         int log_level;
282
283         struct {
284                 int nr;
285                 int *fds;
286         } instances;
287         bpf_program_prep_t preprocessor;
288
289         struct bpf_object *obj;
290         void *priv;
291         bpf_program_clear_priv_t clear_priv;
292
293         bool load;
294         bool mark_btf_static;
295         enum bpf_prog_type type;
296         enum bpf_attach_type expected_attach_type;
297         int prog_ifindex;
298         __u32 attach_btf_obj_fd;
299         __u32 attach_btf_id;
300         __u32 attach_prog_fd;
301         void *func_info;
302         __u32 func_info_rec_size;
303         __u32 func_info_cnt;
304
305         void *line_info;
306         __u32 line_info_rec_size;
307         __u32 line_info_cnt;
308         __u32 prog_flags;
309 };
310
311 struct bpf_struct_ops {
312         const char *tname;
313         const struct btf_type *type;
314         struct bpf_program **progs;
315         __u32 *kern_func_off;
316         /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
317         void *data;
318         /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
319          *      btf_vmlinux's format.
320          * struct bpf_struct_ops_tcp_congestion_ops {
321          *      [... some other kernel fields ...]
322          *      struct tcp_congestion_ops data;
323          * }
324          * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
325          * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
326          * from "data".
327          */
328         void *kern_vdata;
329         __u32 type_id;
330 };
331
332 #define DATA_SEC ".data"
333 #define BSS_SEC ".bss"
334 #define RODATA_SEC ".rodata"
335 #define KCONFIG_SEC ".kconfig"
336 #define KSYMS_SEC ".ksyms"
337 #define STRUCT_OPS_SEC ".struct_ops"
338
339 enum libbpf_map_type {
340         LIBBPF_MAP_UNSPEC,
341         LIBBPF_MAP_DATA,
342         LIBBPF_MAP_BSS,
343         LIBBPF_MAP_RODATA,
344         LIBBPF_MAP_KCONFIG,
345 };
346
347 static const char * const libbpf_type_to_btf_name[] = {
348         [LIBBPF_MAP_DATA]       = DATA_SEC,
349         [LIBBPF_MAP_BSS]        = BSS_SEC,
350         [LIBBPF_MAP_RODATA]     = RODATA_SEC,
351         [LIBBPF_MAP_KCONFIG]    = KCONFIG_SEC,
352 };
353
354 struct bpf_map {
355         char *name;
356         int fd;
357         int sec_idx;
358         size_t sec_offset;
359         int map_ifindex;
360         int inner_map_fd;
361         struct bpf_map_def def;
362         __u32 numa_node;
363         __u32 btf_var_idx;
364         __u32 btf_key_type_id;
365         __u32 btf_value_type_id;
366         __u32 btf_vmlinux_value_type_id;
367         void *priv;
368         bpf_map_clear_priv_t clear_priv;
369         enum libbpf_map_type libbpf_type;
370         void *mmaped;
371         struct bpf_struct_ops *st_ops;
372         struct bpf_map *inner_map;
373         void **init_slots;
374         int init_slots_sz;
375         char *pin_path;
376         bool pinned;
377         bool reused;
378 };
379
380 enum extern_type {
381         EXT_UNKNOWN,
382         EXT_KCFG,
383         EXT_KSYM,
384 };
385
386 enum kcfg_type {
387         KCFG_UNKNOWN,
388         KCFG_CHAR,
389         KCFG_BOOL,
390         KCFG_INT,
391         KCFG_TRISTATE,
392         KCFG_CHAR_ARR,
393 };
394
395 struct extern_desc {
396         enum extern_type type;
397         int sym_idx;
398         int btf_id;
399         int sec_btf_id;
400         const char *name;
401         bool is_set;
402         bool is_weak;
403         union {
404                 struct {
405                         enum kcfg_type type;
406                         int sz;
407                         int align;
408                         int data_off;
409                         bool is_signed;
410                 } kcfg;
411                 struct {
412                         unsigned long long addr;
413
414                         /* target btf_id of the corresponding kernel var. */
415                         int kernel_btf_obj_fd;
416                         int kernel_btf_id;
417
418                         /* local btf_id of the ksym extern's type. */
419                         __u32 type_id;
420                 } ksym;
421         };
422 };
423
424 static LIST_HEAD(bpf_objects_list);
425
426 struct module_btf {
427         struct btf *btf;
428         char *name;
429         __u32 id;
430         int fd;
431 };
432
433 struct bpf_object {
434         char name[BPF_OBJ_NAME_LEN];
435         char license[64];
436         __u32 kern_version;
437
438         struct bpf_program *programs;
439         size_t nr_programs;
440         struct bpf_map *maps;
441         size_t nr_maps;
442         size_t maps_cap;
443
444         char *kconfig;
445         struct extern_desc *externs;
446         int nr_extern;
447         int kconfig_map_idx;
448         int rodata_map_idx;
449
450         bool loaded;
451         bool has_subcalls;
452
453         struct bpf_gen *gen_loader;
454
455         /*
456          * Information when doing elf related work. Only valid if fd
457          * is valid.
458          */
459         struct {
460                 int fd;
461                 const void *obj_buf;
462                 size_t obj_buf_sz;
463                 Elf *elf;
464                 GElf_Ehdr ehdr;
465                 Elf_Data *symbols;
466                 Elf_Data *data;
467                 Elf_Data *rodata;
468                 Elf_Data *bss;
469                 Elf_Data *st_ops_data;
470                 size_t shstrndx; /* section index for section name strings */
471                 size_t strtabidx;
472                 struct {
473                         GElf_Shdr shdr;
474                         Elf_Data *data;
475                 } *reloc_sects;
476                 int nr_reloc_sects;
477                 int maps_shndx;
478                 int btf_maps_shndx;
479                 __u32 btf_maps_sec_btf_id;
480                 int text_shndx;
481                 int symbols_shndx;
482                 int data_shndx;
483                 int rodata_shndx;
484                 int bss_shndx;
485                 int st_ops_shndx;
486         } efile;
487         /*
488          * All loaded bpf_object is linked in a list, which is
489          * hidden to caller. bpf_objects__<func> handlers deal with
490          * all objects.
491          */
492         struct list_head list;
493
494         struct btf *btf;
495         struct btf_ext *btf_ext;
496
497         /* Parse and load BTF vmlinux if any of the programs in the object need
498          * it at load time.
499          */
500         struct btf *btf_vmlinux;
501         /* Path to the custom BTF to be used for BPF CO-RE relocations as an
502          * override for vmlinux BTF.
503          */
504         char *btf_custom_path;
505         /* vmlinux BTF override for CO-RE relocations */
506         struct btf *btf_vmlinux_override;
507         /* Lazily initialized kernel module BTFs */
508         struct module_btf *btf_modules;
509         bool btf_modules_loaded;
510         size_t btf_module_cnt;
511         size_t btf_module_cap;
512
513         void *priv;
514         bpf_object_clear_priv_t clear_priv;
515
516         char path[];
517 };
518 #define obj_elf_valid(o)        ((o)->efile.elf)
519
520 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
521 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
522 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
523 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
524 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr);
525 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
526 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
527
528 void bpf_program__unload(struct bpf_program *prog)
529 {
530         int i;
531
532         if (!prog)
533                 return;
534
535         /*
536          * If the object is opened but the program was never loaded,
537          * it is possible that prog->instances.nr == -1.
538          */
539         if (prog->instances.nr > 0) {
540                 for (i = 0; i < prog->instances.nr; i++)
541                         zclose(prog->instances.fds[i]);
542         } else if (prog->instances.nr != -1) {
543                 pr_warn("Internal error: instances.nr is %d\n",
544                         prog->instances.nr);
545         }
546
547         prog->instances.nr = -1;
548         zfree(&prog->instances.fds);
549
550         zfree(&prog->func_info);
551         zfree(&prog->line_info);
552 }
553
554 static void bpf_program__exit(struct bpf_program *prog)
555 {
556         if (!prog)
557                 return;
558
559         if (prog->clear_priv)
560                 prog->clear_priv(prog, prog->priv);
561
562         prog->priv = NULL;
563         prog->clear_priv = NULL;
564
565         bpf_program__unload(prog);
566         zfree(&prog->name);
567         zfree(&prog->sec_name);
568         zfree(&prog->pin_name);
569         zfree(&prog->insns);
570         zfree(&prog->reloc_desc);
571
572         prog->nr_reloc = 0;
573         prog->insns_cnt = 0;
574         prog->sec_idx = -1;
575 }
576
577 static char *__bpf_program__pin_name(struct bpf_program *prog)
578 {
579         char *name, *p;
580
581         name = p = strdup(prog->sec_name);
582         while ((p = strchr(p, '/')))
583                 *p = '_';
584
585         return name;
586 }
587
588 static bool insn_is_subprog_call(const struct bpf_insn *insn)
589 {
590         return BPF_CLASS(insn->code) == BPF_JMP &&
591                BPF_OP(insn->code) == BPF_CALL &&
592                BPF_SRC(insn->code) == BPF_K &&
593                insn->src_reg == BPF_PSEUDO_CALL &&
594                insn->dst_reg == 0 &&
595                insn->off == 0;
596 }
597
598 static bool is_call_insn(const struct bpf_insn *insn)
599 {
600         return insn->code == (BPF_JMP | BPF_CALL);
601 }
602
603 static bool insn_is_pseudo_func(struct bpf_insn *insn)
604 {
605         return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
606 }
607
608 static int
609 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
610                       const char *name, size_t sec_idx, const char *sec_name,
611                       size_t sec_off, void *insn_data, size_t insn_data_sz)
612 {
613         if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
614                 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
615                         sec_name, name, sec_off, insn_data_sz);
616                 return -EINVAL;
617         }
618
619         memset(prog, 0, sizeof(*prog));
620         prog->obj = obj;
621
622         prog->sec_idx = sec_idx;
623         prog->sec_insn_off = sec_off / BPF_INSN_SZ;
624         prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
625         /* insns_cnt can later be increased by appending used subprograms */
626         prog->insns_cnt = prog->sec_insn_cnt;
627
628         prog->type = BPF_PROG_TYPE_UNSPEC;
629         prog->load = true;
630
631         prog->instances.fds = NULL;
632         prog->instances.nr = -1;
633
634         prog->sec_name = strdup(sec_name);
635         if (!prog->sec_name)
636                 goto errout;
637
638         prog->name = strdup(name);
639         if (!prog->name)
640                 goto errout;
641
642         prog->pin_name = __bpf_program__pin_name(prog);
643         if (!prog->pin_name)
644                 goto errout;
645
646         prog->insns = malloc(insn_data_sz);
647         if (!prog->insns)
648                 goto errout;
649         memcpy(prog->insns, insn_data, insn_data_sz);
650
651         return 0;
652 errout:
653         pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
654         bpf_program__exit(prog);
655         return -ENOMEM;
656 }
657
658 static int
659 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
660                          const char *sec_name, int sec_idx)
661 {
662         Elf_Data *symbols = obj->efile.symbols;
663         struct bpf_program *prog, *progs;
664         void *data = sec_data->d_buf;
665         size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
666         int nr_progs, err, i;
667         const char *name;
668         GElf_Sym sym;
669
670         progs = obj->programs;
671         nr_progs = obj->nr_programs;
672         nr_syms = symbols->d_size / sizeof(GElf_Sym);
673         sec_off = 0;
674
675         for (i = 0; i < nr_syms; i++) {
676                 if (!gelf_getsym(symbols, i, &sym))
677                         continue;
678                 if (sym.st_shndx != sec_idx)
679                         continue;
680                 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
681                         continue;
682
683                 prog_sz = sym.st_size;
684                 sec_off = sym.st_value;
685
686                 name = elf_sym_str(obj, sym.st_name);
687                 if (!name) {
688                         pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
689                                 sec_name, sec_off);
690                         return -LIBBPF_ERRNO__FORMAT;
691                 }
692
693                 if (sec_off + prog_sz > sec_sz) {
694                         pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
695                                 sec_name, sec_off);
696                         return -LIBBPF_ERRNO__FORMAT;
697                 }
698
699                 if (sec_idx != obj->efile.text_shndx && GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
700                         pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
701                         return -ENOTSUP;
702                 }
703
704                 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
705                          sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
706
707                 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
708                 if (!progs) {
709                         /*
710                          * In this case the original obj->programs
711                          * is still valid, so don't need special treat for
712                          * bpf_close_object().
713                          */
714                         pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
715                                 sec_name, name);
716                         return -ENOMEM;
717                 }
718                 obj->programs = progs;
719
720                 prog = &progs[nr_progs];
721
722                 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
723                                             sec_off, data + sec_off, prog_sz);
724                 if (err)
725                         return err;
726
727                 /* if function is a global/weak symbol, but has restricted
728                  * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
729                  * as static to enable more permissive BPF verification mode
730                  * with more outside context available to BPF verifier
731                  */
732                 if (GELF_ST_BIND(sym.st_info) != STB_LOCAL
733                     && (GELF_ST_VISIBILITY(sym.st_other) == STV_HIDDEN
734                         || GELF_ST_VISIBILITY(sym.st_other) == STV_INTERNAL))
735                         prog->mark_btf_static = true;
736
737                 nr_progs++;
738                 obj->nr_programs = nr_progs;
739         }
740
741         return 0;
742 }
743
744 static __u32 get_kernel_version(void)
745 {
746         __u32 major, minor, patch;
747         struct utsname info;
748
749         uname(&info);
750         if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
751                 return 0;
752         return KERNEL_VERSION(major, minor, patch);
753 }
754
755 static const struct btf_member *
756 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
757 {
758         struct btf_member *m;
759         int i;
760
761         for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
762                 if (btf_member_bit_offset(t, i) == bit_offset)
763                         return m;
764         }
765
766         return NULL;
767 }
768
769 static const struct btf_member *
770 find_member_by_name(const struct btf *btf, const struct btf_type *t,
771                     const char *name)
772 {
773         struct btf_member *m;
774         int i;
775
776         for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
777                 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
778                         return m;
779         }
780
781         return NULL;
782 }
783
784 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
785 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
786                                    const char *name, __u32 kind);
787
788 static int
789 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
790                            const struct btf_type **type, __u32 *type_id,
791                            const struct btf_type **vtype, __u32 *vtype_id,
792                            const struct btf_member **data_member)
793 {
794         const struct btf_type *kern_type, *kern_vtype;
795         const struct btf_member *kern_data_member;
796         __s32 kern_vtype_id, kern_type_id;
797         __u32 i;
798
799         kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
800         if (kern_type_id < 0) {
801                 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
802                         tname);
803                 return kern_type_id;
804         }
805         kern_type = btf__type_by_id(btf, kern_type_id);
806
807         /* Find the corresponding "map_value" type that will be used
808          * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
809          * find "struct bpf_struct_ops_tcp_congestion_ops" from the
810          * btf_vmlinux.
811          */
812         kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
813                                                 tname, BTF_KIND_STRUCT);
814         if (kern_vtype_id < 0) {
815                 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
816                         STRUCT_OPS_VALUE_PREFIX, tname);
817                 return kern_vtype_id;
818         }
819         kern_vtype = btf__type_by_id(btf, kern_vtype_id);
820
821         /* Find "struct tcp_congestion_ops" from
822          * struct bpf_struct_ops_tcp_congestion_ops {
823          *      [ ... ]
824          *      struct tcp_congestion_ops data;
825          * }
826          */
827         kern_data_member = btf_members(kern_vtype);
828         for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
829                 if (kern_data_member->type == kern_type_id)
830                         break;
831         }
832         if (i == btf_vlen(kern_vtype)) {
833                 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
834                         tname, STRUCT_OPS_VALUE_PREFIX, tname);
835                 return -EINVAL;
836         }
837
838         *type = kern_type;
839         *type_id = kern_type_id;
840         *vtype = kern_vtype;
841         *vtype_id = kern_vtype_id;
842         *data_member = kern_data_member;
843
844         return 0;
845 }
846
847 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
848 {
849         return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
850 }
851
852 /* Init the map's fields that depend on kern_btf */
853 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
854                                          const struct btf *btf,
855                                          const struct btf *kern_btf)
856 {
857         const struct btf_member *member, *kern_member, *kern_data_member;
858         const struct btf_type *type, *kern_type, *kern_vtype;
859         __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
860         struct bpf_struct_ops *st_ops;
861         void *data, *kern_data;
862         const char *tname;
863         int err;
864
865         st_ops = map->st_ops;
866         type = st_ops->type;
867         tname = st_ops->tname;
868         err = find_struct_ops_kern_types(kern_btf, tname,
869                                          &kern_type, &kern_type_id,
870                                          &kern_vtype, &kern_vtype_id,
871                                          &kern_data_member);
872         if (err)
873                 return err;
874
875         pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
876                  map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
877
878         map->def.value_size = kern_vtype->size;
879         map->btf_vmlinux_value_type_id = kern_vtype_id;
880
881         st_ops->kern_vdata = calloc(1, kern_vtype->size);
882         if (!st_ops->kern_vdata)
883                 return -ENOMEM;
884
885         data = st_ops->data;
886         kern_data_off = kern_data_member->offset / 8;
887         kern_data = st_ops->kern_vdata + kern_data_off;
888
889         member = btf_members(type);
890         for (i = 0; i < btf_vlen(type); i++, member++) {
891                 const struct btf_type *mtype, *kern_mtype;
892                 __u32 mtype_id, kern_mtype_id;
893                 void *mdata, *kern_mdata;
894                 __s64 msize, kern_msize;
895                 __u32 moff, kern_moff;
896                 __u32 kern_member_idx;
897                 const char *mname;
898
899                 mname = btf__name_by_offset(btf, member->name_off);
900                 kern_member = find_member_by_name(kern_btf, kern_type, mname);
901                 if (!kern_member) {
902                         pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
903                                 map->name, mname);
904                         return -ENOTSUP;
905                 }
906
907                 kern_member_idx = kern_member - btf_members(kern_type);
908                 if (btf_member_bitfield_size(type, i) ||
909                     btf_member_bitfield_size(kern_type, kern_member_idx)) {
910                         pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
911                                 map->name, mname);
912                         return -ENOTSUP;
913                 }
914
915                 moff = member->offset / 8;
916                 kern_moff = kern_member->offset / 8;
917
918                 mdata = data + moff;
919                 kern_mdata = kern_data + kern_moff;
920
921                 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
922                 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
923                                                     &kern_mtype_id);
924                 if (BTF_INFO_KIND(mtype->info) !=
925                     BTF_INFO_KIND(kern_mtype->info)) {
926                         pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
927                                 map->name, mname, BTF_INFO_KIND(mtype->info),
928                                 BTF_INFO_KIND(kern_mtype->info));
929                         return -ENOTSUP;
930                 }
931
932                 if (btf_is_ptr(mtype)) {
933                         struct bpf_program *prog;
934
935                         prog = st_ops->progs[i];
936                         if (!prog)
937                                 continue;
938
939                         kern_mtype = skip_mods_and_typedefs(kern_btf,
940                                                             kern_mtype->type,
941                                                             &kern_mtype_id);
942
943                         /* mtype->type must be a func_proto which was
944                          * guaranteed in bpf_object__collect_st_ops_relos(),
945                          * so only check kern_mtype for func_proto here.
946                          */
947                         if (!btf_is_func_proto(kern_mtype)) {
948                                 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
949                                         map->name, mname);
950                                 return -ENOTSUP;
951                         }
952
953                         prog->attach_btf_id = kern_type_id;
954                         prog->expected_attach_type = kern_member_idx;
955
956                         st_ops->kern_func_off[i] = kern_data_off + kern_moff;
957
958                         pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
959                                  map->name, mname, prog->name, moff,
960                                  kern_moff);
961
962                         continue;
963                 }
964
965                 msize = btf__resolve_size(btf, mtype_id);
966                 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
967                 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
968                         pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
969                                 map->name, mname, (ssize_t)msize,
970                                 (ssize_t)kern_msize);
971                         return -ENOTSUP;
972                 }
973
974                 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
975                          map->name, mname, (unsigned int)msize,
976                          moff, kern_moff);
977                 memcpy(kern_mdata, mdata, msize);
978         }
979
980         return 0;
981 }
982
983 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
984 {
985         struct bpf_map *map;
986         size_t i;
987         int err;
988
989         for (i = 0; i < obj->nr_maps; i++) {
990                 map = &obj->maps[i];
991
992                 if (!bpf_map__is_struct_ops(map))
993                         continue;
994
995                 err = bpf_map__init_kern_struct_ops(map, obj->btf,
996                                                     obj->btf_vmlinux);
997                 if (err)
998                         return err;
999         }
1000
1001         return 0;
1002 }
1003
1004 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1005 {
1006         const struct btf_type *type, *datasec;
1007         const struct btf_var_secinfo *vsi;
1008         struct bpf_struct_ops *st_ops;
1009         const char *tname, *var_name;
1010         __s32 type_id, datasec_id;
1011         const struct btf *btf;
1012         struct bpf_map *map;
1013         __u32 i;
1014
1015         if (obj->efile.st_ops_shndx == -1)
1016                 return 0;
1017
1018         btf = obj->btf;
1019         datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1020                                             BTF_KIND_DATASEC);
1021         if (datasec_id < 0) {
1022                 pr_warn("struct_ops init: DATASEC %s not found\n",
1023                         STRUCT_OPS_SEC);
1024                 return -EINVAL;
1025         }
1026
1027         datasec = btf__type_by_id(btf, datasec_id);
1028         vsi = btf_var_secinfos(datasec);
1029         for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1030                 type = btf__type_by_id(obj->btf, vsi->type);
1031                 var_name = btf__name_by_offset(obj->btf, type->name_off);
1032
1033                 type_id = btf__resolve_type(obj->btf, vsi->type);
1034                 if (type_id < 0) {
1035                         pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1036                                 vsi->type, STRUCT_OPS_SEC);
1037                         return -EINVAL;
1038                 }
1039
1040                 type = btf__type_by_id(obj->btf, type_id);
1041                 tname = btf__name_by_offset(obj->btf, type->name_off);
1042                 if (!tname[0]) {
1043                         pr_warn("struct_ops init: anonymous type is not supported\n");
1044                         return -ENOTSUP;
1045                 }
1046                 if (!btf_is_struct(type)) {
1047                         pr_warn("struct_ops init: %s is not a struct\n", tname);
1048                         return -EINVAL;
1049                 }
1050
1051                 map = bpf_object__add_map(obj);
1052                 if (IS_ERR(map))
1053                         return PTR_ERR(map);
1054
1055                 map->sec_idx = obj->efile.st_ops_shndx;
1056                 map->sec_offset = vsi->offset;
1057                 map->name = strdup(var_name);
1058                 if (!map->name)
1059                         return -ENOMEM;
1060
1061                 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1062                 map->def.key_size = sizeof(int);
1063                 map->def.value_size = type->size;
1064                 map->def.max_entries = 1;
1065
1066                 map->st_ops = calloc(1, sizeof(*map->st_ops));
1067                 if (!map->st_ops)
1068                         return -ENOMEM;
1069                 st_ops = map->st_ops;
1070                 st_ops->data = malloc(type->size);
1071                 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1072                 st_ops->kern_func_off = malloc(btf_vlen(type) *
1073                                                sizeof(*st_ops->kern_func_off));
1074                 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1075                         return -ENOMEM;
1076
1077                 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1078                         pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1079                                 var_name, STRUCT_OPS_SEC);
1080                         return -EINVAL;
1081                 }
1082
1083                 memcpy(st_ops->data,
1084                        obj->efile.st_ops_data->d_buf + vsi->offset,
1085                        type->size);
1086                 st_ops->tname = tname;
1087                 st_ops->type = type;
1088                 st_ops->type_id = type_id;
1089
1090                 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1091                          tname, type_id, var_name, vsi->offset);
1092         }
1093
1094         return 0;
1095 }
1096
1097 static struct bpf_object *bpf_object__new(const char *path,
1098                                           const void *obj_buf,
1099                                           size_t obj_buf_sz,
1100                                           const char *obj_name)
1101 {
1102         struct bpf_object *obj;
1103         char *end;
1104
1105         obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1106         if (!obj) {
1107                 pr_warn("alloc memory failed for %s\n", path);
1108                 return ERR_PTR(-ENOMEM);
1109         }
1110
1111         strcpy(obj->path, path);
1112         if (obj_name) {
1113                 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1114                 obj->name[sizeof(obj->name) - 1] = 0;
1115         } else {
1116                 /* Using basename() GNU version which doesn't modify arg. */
1117                 strncpy(obj->name, basename((void *)path),
1118                         sizeof(obj->name) - 1);
1119                 end = strchr(obj->name, '.');
1120                 if (end)
1121                         *end = 0;
1122         }
1123
1124         obj->efile.fd = -1;
1125         /*
1126          * Caller of this function should also call
1127          * bpf_object__elf_finish() after data collection to return
1128          * obj_buf to user. If not, we should duplicate the buffer to
1129          * avoid user freeing them before elf finish.
1130          */
1131         obj->efile.obj_buf = obj_buf;
1132         obj->efile.obj_buf_sz = obj_buf_sz;
1133         obj->efile.maps_shndx = -1;
1134         obj->efile.btf_maps_shndx = -1;
1135         obj->efile.data_shndx = -1;
1136         obj->efile.rodata_shndx = -1;
1137         obj->efile.bss_shndx = -1;
1138         obj->efile.st_ops_shndx = -1;
1139         obj->kconfig_map_idx = -1;
1140         obj->rodata_map_idx = -1;
1141
1142         obj->kern_version = get_kernel_version();
1143         obj->loaded = false;
1144
1145         INIT_LIST_HEAD(&obj->list);
1146         list_add(&obj->list, &bpf_objects_list);
1147         return obj;
1148 }
1149
1150 static void bpf_object__elf_finish(struct bpf_object *obj)
1151 {
1152         if (!obj_elf_valid(obj))
1153                 return;
1154
1155         if (obj->efile.elf) {
1156                 elf_end(obj->efile.elf);
1157                 obj->efile.elf = NULL;
1158         }
1159         obj->efile.symbols = NULL;
1160         obj->efile.data = NULL;
1161         obj->efile.rodata = NULL;
1162         obj->efile.bss = NULL;
1163         obj->efile.st_ops_data = NULL;
1164
1165         zfree(&obj->efile.reloc_sects);
1166         obj->efile.nr_reloc_sects = 0;
1167         zclose(obj->efile.fd);
1168         obj->efile.obj_buf = NULL;
1169         obj->efile.obj_buf_sz = 0;
1170 }
1171
1172 static int bpf_object__elf_init(struct bpf_object *obj)
1173 {
1174         int err = 0;
1175         GElf_Ehdr *ep;
1176
1177         if (obj_elf_valid(obj)) {
1178                 pr_warn("elf: init internal error\n");
1179                 return -LIBBPF_ERRNO__LIBELF;
1180         }
1181
1182         if (obj->efile.obj_buf_sz > 0) {
1183                 /*
1184                  * obj_buf should have been validated by
1185                  * bpf_object__open_buffer().
1186                  */
1187                 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1188                                             obj->efile.obj_buf_sz);
1189         } else {
1190                 obj->efile.fd = open(obj->path, O_RDONLY);
1191                 if (obj->efile.fd < 0) {
1192                         char errmsg[STRERR_BUFSIZE], *cp;
1193
1194                         err = -errno;
1195                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1196                         pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1197                         return err;
1198                 }
1199
1200                 obj->efile.elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1201         }
1202
1203         if (!obj->efile.elf) {
1204                 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1205                 err = -LIBBPF_ERRNO__LIBELF;
1206                 goto errout;
1207         }
1208
1209         if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1210                 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1211                 err = -LIBBPF_ERRNO__FORMAT;
1212                 goto errout;
1213         }
1214         ep = &obj->efile.ehdr;
1215
1216         if (elf_getshdrstrndx(obj->efile.elf, &obj->efile.shstrndx)) {
1217                 pr_warn("elf: failed to get section names section index for %s: %s\n",
1218                         obj->path, elf_errmsg(-1));
1219                 err = -LIBBPF_ERRNO__FORMAT;
1220                 goto errout;
1221         }
1222
1223         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1224         if (!elf_rawdata(elf_getscn(obj->efile.elf, obj->efile.shstrndx), NULL)) {
1225                 pr_warn("elf: failed to get section names strings from %s: %s\n",
1226                         obj->path, elf_errmsg(-1));
1227                 err = -LIBBPF_ERRNO__FORMAT;
1228                 goto errout;
1229         }
1230
1231         /* Old LLVM set e_machine to EM_NONE */
1232         if (ep->e_type != ET_REL ||
1233             (ep->e_machine && ep->e_machine != EM_BPF)) {
1234                 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1235                 err = -LIBBPF_ERRNO__FORMAT;
1236                 goto errout;
1237         }
1238
1239         return 0;
1240 errout:
1241         bpf_object__elf_finish(obj);
1242         return err;
1243 }
1244
1245 static int bpf_object__check_endianness(struct bpf_object *obj)
1246 {
1247 #if __BYTE_ORDER == __LITTLE_ENDIAN
1248         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1249                 return 0;
1250 #elif __BYTE_ORDER == __BIG_ENDIAN
1251         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1252                 return 0;
1253 #else
1254 # error "Unrecognized __BYTE_ORDER__"
1255 #endif
1256         pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1257         return -LIBBPF_ERRNO__ENDIAN;
1258 }
1259
1260 static int
1261 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1262 {
1263         memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1264         pr_debug("license of %s is %s\n", obj->path, obj->license);
1265         return 0;
1266 }
1267
1268 static int
1269 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1270 {
1271         __u32 kver;
1272
1273         if (size != sizeof(kver)) {
1274                 pr_warn("invalid kver section in %s\n", obj->path);
1275                 return -LIBBPF_ERRNO__FORMAT;
1276         }
1277         memcpy(&kver, data, sizeof(kver));
1278         obj->kern_version = kver;
1279         pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1280         return 0;
1281 }
1282
1283 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1284 {
1285         if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1286             type == BPF_MAP_TYPE_HASH_OF_MAPS)
1287                 return true;
1288         return false;
1289 }
1290
1291 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1292                              __u32 *size)
1293 {
1294         int ret = -ENOENT;
1295
1296         *size = 0;
1297         if (!name) {
1298                 return -EINVAL;
1299         } else if (!strcmp(name, DATA_SEC)) {
1300                 if (obj->efile.data)
1301                         *size = obj->efile.data->d_size;
1302         } else if (!strcmp(name, BSS_SEC)) {
1303                 if (obj->efile.bss)
1304                         *size = obj->efile.bss->d_size;
1305         } else if (!strcmp(name, RODATA_SEC)) {
1306                 if (obj->efile.rodata)
1307                         *size = obj->efile.rodata->d_size;
1308         } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1309                 if (obj->efile.st_ops_data)
1310                         *size = obj->efile.st_ops_data->d_size;
1311         } else {
1312                 Elf_Scn *scn = elf_sec_by_name(obj, name);
1313                 Elf_Data *data = elf_sec_data(obj, scn);
1314
1315                 if (data) {
1316                         ret = 0; /* found it */
1317                         *size = data->d_size;
1318                 }
1319         }
1320
1321         return *size ? 0 : ret;
1322 }
1323
1324 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1325                                 __u32 *off)
1326 {
1327         Elf_Data *symbols = obj->efile.symbols;
1328         const char *sname;
1329         size_t si;
1330
1331         if (!name || !off)
1332                 return -EINVAL;
1333
1334         for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1335                 GElf_Sym sym;
1336
1337                 if (!gelf_getsym(symbols, si, &sym))
1338                         continue;
1339                 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1340                     GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1341                         continue;
1342
1343                 sname = elf_sym_str(obj, sym.st_name);
1344                 if (!sname) {
1345                         pr_warn("failed to get sym name string for var %s\n",
1346                                 name);
1347                         return -EIO;
1348                 }
1349                 if (strcmp(name, sname) == 0) {
1350                         *off = sym.st_value;
1351                         return 0;
1352                 }
1353         }
1354
1355         return -ENOENT;
1356 }
1357
1358 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1359 {
1360         struct bpf_map *new_maps;
1361         size_t new_cap;
1362         int i;
1363
1364         if (obj->nr_maps < obj->maps_cap)
1365                 return &obj->maps[obj->nr_maps++];
1366
1367         new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1368         new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
1369         if (!new_maps) {
1370                 pr_warn("alloc maps for object failed\n");
1371                 return ERR_PTR(-ENOMEM);
1372         }
1373
1374         obj->maps_cap = new_cap;
1375         obj->maps = new_maps;
1376
1377         /* zero out new maps */
1378         memset(obj->maps + obj->nr_maps, 0,
1379                (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1380         /*
1381          * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1382          * when failure (zclose won't close negative fd)).
1383          */
1384         for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1385                 obj->maps[i].fd = -1;
1386                 obj->maps[i].inner_map_fd = -1;
1387         }
1388
1389         return &obj->maps[obj->nr_maps++];
1390 }
1391
1392 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1393 {
1394         long page_sz = sysconf(_SC_PAGE_SIZE);
1395         size_t map_sz;
1396
1397         map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1398         map_sz = roundup(map_sz, page_sz);
1399         return map_sz;
1400 }
1401
1402 static char *internal_map_name(struct bpf_object *obj,
1403                                enum libbpf_map_type type)
1404 {
1405         char map_name[BPF_OBJ_NAME_LEN], *p;
1406         const char *sfx = libbpf_type_to_btf_name[type];
1407         int sfx_len = max((size_t)7, strlen(sfx));
1408         int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1409                           strlen(obj->name));
1410
1411         snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1412                  sfx_len, libbpf_type_to_btf_name[type]);
1413
1414         /* sanitise map name to characters allowed by kernel */
1415         for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1416                 if (!isalnum(*p) && *p != '_' && *p != '.')
1417                         *p = '_';
1418
1419         return strdup(map_name);
1420 }
1421
1422 static int
1423 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1424                               int sec_idx, void *data, size_t data_sz)
1425 {
1426         struct bpf_map_def *def;
1427         struct bpf_map *map;
1428         int err;
1429
1430         map = bpf_object__add_map(obj);
1431         if (IS_ERR(map))
1432                 return PTR_ERR(map);
1433
1434         map->libbpf_type = type;
1435         map->sec_idx = sec_idx;
1436         map->sec_offset = 0;
1437         map->name = internal_map_name(obj, type);
1438         if (!map->name) {
1439                 pr_warn("failed to alloc map name\n");
1440                 return -ENOMEM;
1441         }
1442
1443         def = &map->def;
1444         def->type = BPF_MAP_TYPE_ARRAY;
1445         def->key_size = sizeof(int);
1446         def->value_size = data_sz;
1447         def->max_entries = 1;
1448         def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1449                          ? BPF_F_RDONLY_PROG : 0;
1450         def->map_flags |= BPF_F_MMAPABLE;
1451
1452         pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1453                  map->name, map->sec_idx, map->sec_offset, def->map_flags);
1454
1455         map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1456                            MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1457         if (map->mmaped == MAP_FAILED) {
1458                 err = -errno;
1459                 map->mmaped = NULL;
1460                 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1461                         map->name, err);
1462                 zfree(&map->name);
1463                 return err;
1464         }
1465
1466         if (data)
1467                 memcpy(map->mmaped, data, data_sz);
1468
1469         pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1470         return 0;
1471 }
1472
1473 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1474 {
1475         int err;
1476
1477         /*
1478          * Populate obj->maps with libbpf internal maps.
1479          */
1480         if (obj->efile.data_shndx >= 0) {
1481                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1482                                                     obj->efile.data_shndx,
1483                                                     obj->efile.data->d_buf,
1484                                                     obj->efile.data->d_size);
1485                 if (err)
1486                         return err;
1487         }
1488         if (obj->efile.rodata_shndx >= 0) {
1489                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1490                                                     obj->efile.rodata_shndx,
1491                                                     obj->efile.rodata->d_buf,
1492                                                     obj->efile.rodata->d_size);
1493                 if (err)
1494                         return err;
1495
1496                 obj->rodata_map_idx = obj->nr_maps - 1;
1497         }
1498         if (obj->efile.bss_shndx >= 0) {
1499                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1500                                                     obj->efile.bss_shndx,
1501                                                     NULL,
1502                                                     obj->efile.bss->d_size);
1503                 if (err)
1504                         return err;
1505         }
1506         return 0;
1507 }
1508
1509
1510 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1511                                                const void *name)
1512 {
1513         int i;
1514
1515         for (i = 0; i < obj->nr_extern; i++) {
1516                 if (strcmp(obj->externs[i].name, name) == 0)
1517                         return &obj->externs[i];
1518         }
1519         return NULL;
1520 }
1521
1522 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1523                               char value)
1524 {
1525         switch (ext->kcfg.type) {
1526         case KCFG_BOOL:
1527                 if (value == 'm') {
1528                         pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1529                                 ext->name, value);
1530                         return -EINVAL;
1531                 }
1532                 *(bool *)ext_val = value == 'y' ? true : false;
1533                 break;
1534         case KCFG_TRISTATE:
1535                 if (value == 'y')
1536                         *(enum libbpf_tristate *)ext_val = TRI_YES;
1537                 else if (value == 'm')
1538                         *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1539                 else /* value == 'n' */
1540                         *(enum libbpf_tristate *)ext_val = TRI_NO;
1541                 break;
1542         case KCFG_CHAR:
1543                 *(char *)ext_val = value;
1544                 break;
1545         case KCFG_UNKNOWN:
1546         case KCFG_INT:
1547         case KCFG_CHAR_ARR:
1548         default:
1549                 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1550                         ext->name, value);
1551                 return -EINVAL;
1552         }
1553         ext->is_set = true;
1554         return 0;
1555 }
1556
1557 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1558                               const char *value)
1559 {
1560         size_t len;
1561
1562         if (ext->kcfg.type != KCFG_CHAR_ARR) {
1563                 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1564                 return -EINVAL;
1565         }
1566
1567         len = strlen(value);
1568         if (value[len - 1] != '"') {
1569                 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1570                         ext->name, value);
1571                 return -EINVAL;
1572         }
1573
1574         /* strip quotes */
1575         len -= 2;
1576         if (len >= ext->kcfg.sz) {
1577                 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1578                         ext->name, value, len, ext->kcfg.sz - 1);
1579                 len = ext->kcfg.sz - 1;
1580         }
1581         memcpy(ext_val, value + 1, len);
1582         ext_val[len] = '\0';
1583         ext->is_set = true;
1584         return 0;
1585 }
1586
1587 static int parse_u64(const char *value, __u64 *res)
1588 {
1589         char *value_end;
1590         int err;
1591
1592         errno = 0;
1593         *res = strtoull(value, &value_end, 0);
1594         if (errno) {
1595                 err = -errno;
1596                 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1597                 return err;
1598         }
1599         if (*value_end) {
1600                 pr_warn("failed to parse '%s' as integer completely\n", value);
1601                 return -EINVAL;
1602         }
1603         return 0;
1604 }
1605
1606 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1607 {
1608         int bit_sz = ext->kcfg.sz * 8;
1609
1610         if (ext->kcfg.sz == 8)
1611                 return true;
1612
1613         /* Validate that value stored in u64 fits in integer of `ext->sz`
1614          * bytes size without any loss of information. If the target integer
1615          * is signed, we rely on the following limits of integer type of
1616          * Y bits and subsequent transformation:
1617          *
1618          *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1619          *            0 <= X + 2^(Y-1) <= 2^Y - 1
1620          *            0 <= X + 2^(Y-1) <  2^Y
1621          *
1622          *  For unsigned target integer, check that all the (64 - Y) bits are
1623          *  zero.
1624          */
1625         if (ext->kcfg.is_signed)
1626                 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1627         else
1628                 return (v >> bit_sz) == 0;
1629 }
1630
1631 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1632                               __u64 value)
1633 {
1634         if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1635                 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1636                         ext->name, (unsigned long long)value);
1637                 return -EINVAL;
1638         }
1639         if (!is_kcfg_value_in_range(ext, value)) {
1640                 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1641                         ext->name, (unsigned long long)value, ext->kcfg.sz);
1642                 return -ERANGE;
1643         }
1644         switch (ext->kcfg.sz) {
1645                 case 1: *(__u8 *)ext_val = value; break;
1646                 case 2: *(__u16 *)ext_val = value; break;
1647                 case 4: *(__u32 *)ext_val = value; break;
1648                 case 8: *(__u64 *)ext_val = value; break;
1649                 default:
1650                         return -EINVAL;
1651         }
1652         ext->is_set = true;
1653         return 0;
1654 }
1655
1656 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1657                                             char *buf, void *data)
1658 {
1659         struct extern_desc *ext;
1660         char *sep, *value;
1661         int len, err = 0;
1662         void *ext_val;
1663         __u64 num;
1664
1665         if (strncmp(buf, "CONFIG_", 7))
1666                 return 0;
1667
1668         sep = strchr(buf, '=');
1669         if (!sep) {
1670                 pr_warn("failed to parse '%s': no separator\n", buf);
1671                 return -EINVAL;
1672         }
1673
1674         /* Trim ending '\n' */
1675         len = strlen(buf);
1676         if (buf[len - 1] == '\n')
1677                 buf[len - 1] = '\0';
1678         /* Split on '=' and ensure that a value is present. */
1679         *sep = '\0';
1680         if (!sep[1]) {
1681                 *sep = '=';
1682                 pr_warn("failed to parse '%s': no value\n", buf);
1683                 return -EINVAL;
1684         }
1685
1686         ext = find_extern_by_name(obj, buf);
1687         if (!ext || ext->is_set)
1688                 return 0;
1689
1690         ext_val = data + ext->kcfg.data_off;
1691         value = sep + 1;
1692
1693         switch (*value) {
1694         case 'y': case 'n': case 'm':
1695                 err = set_kcfg_value_tri(ext, ext_val, *value);
1696                 break;
1697         case '"':
1698                 err = set_kcfg_value_str(ext, ext_val, value);
1699                 break;
1700         default:
1701                 /* assume integer */
1702                 err = parse_u64(value, &num);
1703                 if (err) {
1704                         pr_warn("extern (kcfg) %s=%s should be integer\n",
1705                                 ext->name, value);
1706                         return err;
1707                 }
1708                 err = set_kcfg_value_num(ext, ext_val, num);
1709                 break;
1710         }
1711         if (err)
1712                 return err;
1713         pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1714         return 0;
1715 }
1716
1717 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1718 {
1719         char buf[PATH_MAX];
1720         struct utsname uts;
1721         int len, err = 0;
1722         gzFile file;
1723
1724         uname(&uts);
1725         len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1726         if (len < 0)
1727                 return -EINVAL;
1728         else if (len >= PATH_MAX)
1729                 return -ENAMETOOLONG;
1730
1731         /* gzopen also accepts uncompressed files. */
1732         file = gzopen(buf, "r");
1733         if (!file)
1734                 file = gzopen("/proc/config.gz", "r");
1735
1736         if (!file) {
1737                 pr_warn("failed to open system Kconfig\n");
1738                 return -ENOENT;
1739         }
1740
1741         while (gzgets(file, buf, sizeof(buf))) {
1742                 err = bpf_object__process_kconfig_line(obj, buf, data);
1743                 if (err) {
1744                         pr_warn("error parsing system Kconfig line '%s': %d\n",
1745                                 buf, err);
1746                         goto out;
1747                 }
1748         }
1749
1750 out:
1751         gzclose(file);
1752         return err;
1753 }
1754
1755 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1756                                         const char *config, void *data)
1757 {
1758         char buf[PATH_MAX];
1759         int err = 0;
1760         FILE *file;
1761
1762         file = fmemopen((void *)config, strlen(config), "r");
1763         if (!file) {
1764                 err = -errno;
1765                 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1766                 return err;
1767         }
1768
1769         while (fgets(buf, sizeof(buf), file)) {
1770                 err = bpf_object__process_kconfig_line(obj, buf, data);
1771                 if (err) {
1772                         pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1773                                 buf, err);
1774                         break;
1775                 }
1776         }
1777
1778         fclose(file);
1779         return err;
1780 }
1781
1782 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1783 {
1784         struct extern_desc *last_ext = NULL, *ext;
1785         size_t map_sz;
1786         int i, err;
1787
1788         for (i = 0; i < obj->nr_extern; i++) {
1789                 ext = &obj->externs[i];
1790                 if (ext->type == EXT_KCFG)
1791                         last_ext = ext;
1792         }
1793
1794         if (!last_ext)
1795                 return 0;
1796
1797         map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1798         err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1799                                             obj->efile.symbols_shndx,
1800                                             NULL, map_sz);
1801         if (err)
1802                 return err;
1803
1804         obj->kconfig_map_idx = obj->nr_maps - 1;
1805
1806         return 0;
1807 }
1808
1809 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1810 {
1811         Elf_Data *symbols = obj->efile.symbols;
1812         int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1813         Elf_Data *data = NULL;
1814         Elf_Scn *scn;
1815
1816         if (obj->efile.maps_shndx < 0)
1817                 return 0;
1818
1819         if (!symbols)
1820                 return -EINVAL;
1821
1822         scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1823         data = elf_sec_data(obj, scn);
1824         if (!scn || !data) {
1825                 pr_warn("elf: failed to get legacy map definitions for %s\n",
1826                         obj->path);
1827                 return -EINVAL;
1828         }
1829
1830         /*
1831          * Count number of maps. Each map has a name.
1832          * Array of maps is not supported: only the first element is
1833          * considered.
1834          *
1835          * TODO: Detect array of map and report error.
1836          */
1837         nr_syms = symbols->d_size / sizeof(GElf_Sym);
1838         for (i = 0; i < nr_syms; i++) {
1839                 GElf_Sym sym;
1840
1841                 if (!gelf_getsym(symbols, i, &sym))
1842                         continue;
1843                 if (sym.st_shndx != obj->efile.maps_shndx)
1844                         continue;
1845                 nr_maps++;
1846         }
1847         /* Assume equally sized map definitions */
1848         pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1849                  nr_maps, data->d_size, obj->path);
1850
1851         if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1852                 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1853                         obj->path);
1854                 return -EINVAL;
1855         }
1856         map_def_sz = data->d_size / nr_maps;
1857
1858         /* Fill obj->maps using data in "maps" section.  */
1859         for (i = 0; i < nr_syms; i++) {
1860                 GElf_Sym sym;
1861                 const char *map_name;
1862                 struct bpf_map_def *def;
1863                 struct bpf_map *map;
1864
1865                 if (!gelf_getsym(symbols, i, &sym))
1866                         continue;
1867                 if (sym.st_shndx != obj->efile.maps_shndx)
1868                         continue;
1869
1870                 map = bpf_object__add_map(obj);
1871                 if (IS_ERR(map))
1872                         return PTR_ERR(map);
1873
1874                 map_name = elf_sym_str(obj, sym.st_name);
1875                 if (!map_name) {
1876                         pr_warn("failed to get map #%d name sym string for obj %s\n",
1877                                 i, obj->path);
1878                         return -LIBBPF_ERRNO__FORMAT;
1879                 }
1880
1881                 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION
1882                     || GELF_ST_BIND(sym.st_info) == STB_LOCAL) {
1883                         pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
1884                         return -ENOTSUP;
1885                 }
1886
1887                 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1888                 map->sec_idx = sym.st_shndx;
1889                 map->sec_offset = sym.st_value;
1890                 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1891                          map_name, map->sec_idx, map->sec_offset);
1892                 if (sym.st_value + map_def_sz > data->d_size) {
1893                         pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1894                                 obj->path, map_name);
1895                         return -EINVAL;
1896                 }
1897
1898                 map->name = strdup(map_name);
1899                 if (!map->name) {
1900                         pr_warn("failed to alloc map name\n");
1901                         return -ENOMEM;
1902                 }
1903                 pr_debug("map %d is \"%s\"\n", i, map->name);
1904                 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1905                 /*
1906                  * If the definition of the map in the object file fits in
1907                  * bpf_map_def, copy it.  Any extra fields in our version
1908                  * of bpf_map_def will default to zero as a result of the
1909                  * calloc above.
1910                  */
1911                 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1912                         memcpy(&map->def, def, map_def_sz);
1913                 } else {
1914                         /*
1915                          * Here the map structure being read is bigger than what
1916                          * we expect, truncate if the excess bits are all zero.
1917                          * If they are not zero, reject this map as
1918                          * incompatible.
1919                          */
1920                         char *b;
1921
1922                         for (b = ((char *)def) + sizeof(struct bpf_map_def);
1923                              b < ((char *)def) + map_def_sz; b++) {
1924                                 if (*b != 0) {
1925                                         pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1926                                                 obj->path, map_name);
1927                                         if (strict)
1928                                                 return -EINVAL;
1929                                 }
1930                         }
1931                         memcpy(&map->def, def, sizeof(struct bpf_map_def));
1932                 }
1933         }
1934         return 0;
1935 }
1936
1937 const struct btf_type *
1938 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1939 {
1940         const struct btf_type *t = btf__type_by_id(btf, id);
1941
1942         if (res_id)
1943                 *res_id = id;
1944
1945         while (btf_is_mod(t) || btf_is_typedef(t)) {
1946                 if (res_id)
1947                         *res_id = t->type;
1948                 t = btf__type_by_id(btf, t->type);
1949         }
1950
1951         return t;
1952 }
1953
1954 static const struct btf_type *
1955 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1956 {
1957         const struct btf_type *t;
1958
1959         t = skip_mods_and_typedefs(btf, id, NULL);
1960         if (!btf_is_ptr(t))
1961                 return NULL;
1962
1963         t = skip_mods_and_typedefs(btf, t->type, res_id);
1964
1965         return btf_is_func_proto(t) ? t : NULL;
1966 }
1967
1968 static const char *__btf_kind_str(__u16 kind)
1969 {
1970         switch (kind) {
1971         case BTF_KIND_UNKN: return "void";
1972         case BTF_KIND_INT: return "int";
1973         case BTF_KIND_PTR: return "ptr";
1974         case BTF_KIND_ARRAY: return "array";
1975         case BTF_KIND_STRUCT: return "struct";
1976         case BTF_KIND_UNION: return "union";
1977         case BTF_KIND_ENUM: return "enum";
1978         case BTF_KIND_FWD: return "fwd";
1979         case BTF_KIND_TYPEDEF: return "typedef";
1980         case BTF_KIND_VOLATILE: return "volatile";
1981         case BTF_KIND_CONST: return "const";
1982         case BTF_KIND_RESTRICT: return "restrict";
1983         case BTF_KIND_FUNC: return "func";
1984         case BTF_KIND_FUNC_PROTO: return "func_proto";
1985         case BTF_KIND_VAR: return "var";
1986         case BTF_KIND_DATASEC: return "datasec";
1987         case BTF_KIND_FLOAT: return "float";
1988         default: return "unknown";
1989         }
1990 }
1991
1992 const char *btf_kind_str(const struct btf_type *t)
1993 {
1994         return __btf_kind_str(btf_kind(t));
1995 }
1996
1997 /*
1998  * Fetch integer attribute of BTF map definition. Such attributes are
1999  * represented using a pointer to an array, in which dimensionality of array
2000  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2001  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2002  * type definition, while using only sizeof(void *) space in ELF data section.
2003  */
2004 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2005                               const struct btf_member *m, __u32 *res)
2006 {
2007         const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2008         const char *name = btf__name_by_offset(btf, m->name_off);
2009         const struct btf_array *arr_info;
2010         const struct btf_type *arr_t;
2011
2012         if (!btf_is_ptr(t)) {
2013                 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2014                         map_name, name, btf_kind_str(t));
2015                 return false;
2016         }
2017
2018         arr_t = btf__type_by_id(btf, t->type);
2019         if (!arr_t) {
2020                 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2021                         map_name, name, t->type);
2022                 return false;
2023         }
2024         if (!btf_is_array(arr_t)) {
2025                 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2026                         map_name, name, btf_kind_str(arr_t));
2027                 return false;
2028         }
2029         arr_info = btf_array(arr_t);
2030         *res = arr_info->nelems;
2031         return true;
2032 }
2033
2034 static int build_map_pin_path(struct bpf_map *map, const char *path)
2035 {
2036         char buf[PATH_MAX];
2037         int len;
2038
2039         if (!path)
2040                 path = "/sys/fs/bpf";
2041
2042         len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2043         if (len < 0)
2044                 return -EINVAL;
2045         else if (len >= PATH_MAX)
2046                 return -ENAMETOOLONG;
2047
2048         return bpf_map__set_pin_path(map, buf);
2049 }
2050
2051 int parse_btf_map_def(const char *map_name, struct btf *btf,
2052                       const struct btf_type *def_t, bool strict,
2053                       struct btf_map_def *map_def, struct btf_map_def *inner_def)
2054 {
2055         const struct btf_type *t;
2056         const struct btf_member *m;
2057         bool is_inner = inner_def == NULL;
2058         int vlen, i;
2059
2060         vlen = btf_vlen(def_t);
2061         m = btf_members(def_t);
2062         for (i = 0; i < vlen; i++, m++) {
2063                 const char *name = btf__name_by_offset(btf, m->name_off);
2064
2065                 if (!name) {
2066                         pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2067                         return -EINVAL;
2068                 }
2069                 if (strcmp(name, "type") == 0) {
2070                         if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2071                                 return -EINVAL;
2072                         map_def->parts |= MAP_DEF_MAP_TYPE;
2073                 } else if (strcmp(name, "max_entries") == 0) {
2074                         if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2075                                 return -EINVAL;
2076                         map_def->parts |= MAP_DEF_MAX_ENTRIES;
2077                 } else if (strcmp(name, "map_flags") == 0) {
2078                         if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2079                                 return -EINVAL;
2080                         map_def->parts |= MAP_DEF_MAP_FLAGS;
2081                 } else if (strcmp(name, "numa_node") == 0) {
2082                         if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2083                                 return -EINVAL;
2084                         map_def->parts |= MAP_DEF_NUMA_NODE;
2085                 } else if (strcmp(name, "key_size") == 0) {
2086                         __u32 sz;
2087
2088                         if (!get_map_field_int(map_name, btf, m, &sz))
2089                                 return -EINVAL;
2090                         if (map_def->key_size && map_def->key_size != sz) {
2091                                 pr_warn("map '%s': conflicting key size %u != %u.\n",
2092                                         map_name, map_def->key_size, sz);
2093                                 return -EINVAL;
2094                         }
2095                         map_def->key_size = sz;
2096                         map_def->parts |= MAP_DEF_KEY_SIZE;
2097                 } else if (strcmp(name, "key") == 0) {
2098                         __s64 sz;
2099
2100                         t = btf__type_by_id(btf, m->type);
2101                         if (!t) {
2102                                 pr_warn("map '%s': key type [%d] not found.\n",
2103                                         map_name, m->type);
2104                                 return -EINVAL;
2105                         }
2106                         if (!btf_is_ptr(t)) {
2107                                 pr_warn("map '%s': key spec is not PTR: %s.\n",
2108                                         map_name, btf_kind_str(t));
2109                                 return -EINVAL;
2110                         }
2111                         sz = btf__resolve_size(btf, t->type);
2112                         if (sz < 0) {
2113                                 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2114                                         map_name, t->type, (ssize_t)sz);
2115                                 return sz;
2116                         }
2117                         if (map_def->key_size && map_def->key_size != sz) {
2118                                 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2119                                         map_name, map_def->key_size, (ssize_t)sz);
2120                                 return -EINVAL;
2121                         }
2122                         map_def->key_size = sz;
2123                         map_def->key_type_id = t->type;
2124                         map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2125                 } else if (strcmp(name, "value_size") == 0) {
2126                         __u32 sz;
2127
2128                         if (!get_map_field_int(map_name, btf, m, &sz))
2129                                 return -EINVAL;
2130                         if (map_def->value_size && map_def->value_size != sz) {
2131                                 pr_warn("map '%s': conflicting value size %u != %u.\n",
2132                                         map_name, map_def->value_size, sz);
2133                                 return -EINVAL;
2134                         }
2135                         map_def->value_size = sz;
2136                         map_def->parts |= MAP_DEF_VALUE_SIZE;
2137                 } else if (strcmp(name, "value") == 0) {
2138                         __s64 sz;
2139
2140                         t = btf__type_by_id(btf, m->type);
2141                         if (!t) {
2142                                 pr_warn("map '%s': value type [%d] not found.\n",
2143                                         map_name, m->type);
2144                                 return -EINVAL;
2145                         }
2146                         if (!btf_is_ptr(t)) {
2147                                 pr_warn("map '%s': value spec is not PTR: %s.\n",
2148                                         map_name, btf_kind_str(t));
2149                                 return -EINVAL;
2150                         }
2151                         sz = btf__resolve_size(btf, t->type);
2152                         if (sz < 0) {
2153                                 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2154                                         map_name, t->type, (ssize_t)sz);
2155                                 return sz;
2156                         }
2157                         if (map_def->value_size && map_def->value_size != sz) {
2158                                 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2159                                         map_name, map_def->value_size, (ssize_t)sz);
2160                                 return -EINVAL;
2161                         }
2162                         map_def->value_size = sz;
2163                         map_def->value_type_id = t->type;
2164                         map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2165                 }
2166                 else if (strcmp(name, "values") == 0) {
2167                         char inner_map_name[128];
2168                         int err;
2169
2170                         if (is_inner) {
2171                                 pr_warn("map '%s': multi-level inner maps not supported.\n",
2172                                         map_name);
2173                                 return -ENOTSUP;
2174                         }
2175                         if (i != vlen - 1) {
2176                                 pr_warn("map '%s': '%s' member should be last.\n",
2177                                         map_name, name);
2178                                 return -EINVAL;
2179                         }
2180                         if (!bpf_map_type__is_map_in_map(map_def->map_type)) {
2181                                 pr_warn("map '%s': should be map-in-map.\n",
2182                                         map_name);
2183                                 return -ENOTSUP;
2184                         }
2185                         if (map_def->value_size && map_def->value_size != 4) {
2186                                 pr_warn("map '%s': conflicting value size %u != 4.\n",
2187                                         map_name, map_def->value_size);
2188                                 return -EINVAL;
2189                         }
2190                         map_def->value_size = 4;
2191                         t = btf__type_by_id(btf, m->type);
2192                         if (!t) {
2193                                 pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2194                                         map_name, m->type);
2195                                 return -EINVAL;
2196                         }
2197                         if (!btf_is_array(t) || btf_array(t)->nelems) {
2198                                 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2199                                         map_name);
2200                                 return -EINVAL;
2201                         }
2202                         t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2203                         if (!btf_is_ptr(t)) {
2204                                 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2205                                         map_name, btf_kind_str(t));
2206                                 return -EINVAL;
2207                         }
2208                         t = skip_mods_and_typedefs(btf, t->type, NULL);
2209                         if (!btf_is_struct(t)) {
2210                                 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2211                                         map_name, btf_kind_str(t));
2212                                 return -EINVAL;
2213                         }
2214
2215                         snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2216                         err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2217                         if (err)
2218                                 return err;
2219
2220                         map_def->parts |= MAP_DEF_INNER_MAP;
2221                 } else if (strcmp(name, "pinning") == 0) {
2222                         __u32 val;
2223
2224                         if (is_inner) {
2225                                 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2226                                 return -EINVAL;
2227                         }
2228                         if (!get_map_field_int(map_name, btf, m, &val))
2229                                 return -EINVAL;
2230                         if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2231                                 pr_warn("map '%s': invalid pinning value %u.\n",
2232                                         map_name, val);
2233                                 return -EINVAL;
2234                         }
2235                         map_def->pinning = val;
2236                         map_def->parts |= MAP_DEF_PINNING;
2237                 } else {
2238                         if (strict) {
2239                                 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2240                                 return -ENOTSUP;
2241                         }
2242                         pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2243                 }
2244         }
2245
2246         if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2247                 pr_warn("map '%s': map type isn't specified.\n", map_name);
2248                 return -EINVAL;
2249         }
2250
2251         return 0;
2252 }
2253
2254 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2255 {
2256         map->def.type = def->map_type;
2257         map->def.key_size = def->key_size;
2258         map->def.value_size = def->value_size;
2259         map->def.max_entries = def->max_entries;
2260         map->def.map_flags = def->map_flags;
2261
2262         map->numa_node = def->numa_node;
2263         map->btf_key_type_id = def->key_type_id;
2264         map->btf_value_type_id = def->value_type_id;
2265
2266         if (def->parts & MAP_DEF_MAP_TYPE)
2267                 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2268
2269         if (def->parts & MAP_DEF_KEY_TYPE)
2270                 pr_debug("map '%s': found key [%u], sz = %u.\n",
2271                          map->name, def->key_type_id, def->key_size);
2272         else if (def->parts & MAP_DEF_KEY_SIZE)
2273                 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2274
2275         if (def->parts & MAP_DEF_VALUE_TYPE)
2276                 pr_debug("map '%s': found value [%u], sz = %u.\n",
2277                          map->name, def->value_type_id, def->value_size);
2278         else if (def->parts & MAP_DEF_VALUE_SIZE)
2279                 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2280
2281         if (def->parts & MAP_DEF_MAX_ENTRIES)
2282                 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2283         if (def->parts & MAP_DEF_MAP_FLAGS)
2284                 pr_debug("map '%s': found map_flags = %u.\n", map->name, def->map_flags);
2285         if (def->parts & MAP_DEF_PINNING)
2286                 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2287         if (def->parts & MAP_DEF_NUMA_NODE)
2288                 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2289
2290         if (def->parts & MAP_DEF_INNER_MAP)
2291                 pr_debug("map '%s': found inner map definition.\n", map->name);
2292 }
2293
2294 static const char *btf_var_linkage_str(__u32 linkage)
2295 {
2296         switch (linkage) {
2297         case BTF_VAR_STATIC: return "static";
2298         case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2299         case BTF_VAR_GLOBAL_EXTERN: return "extern";
2300         default: return "unknown";
2301         }
2302 }
2303
2304 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2305                                          const struct btf_type *sec,
2306                                          int var_idx, int sec_idx,
2307                                          const Elf_Data *data, bool strict,
2308                                          const char *pin_root_path)
2309 {
2310         struct btf_map_def map_def = {}, inner_def = {};
2311         const struct btf_type *var, *def;
2312         const struct btf_var_secinfo *vi;
2313         const struct btf_var *var_extra;
2314         const char *map_name;
2315         struct bpf_map *map;
2316         int err;
2317
2318         vi = btf_var_secinfos(sec) + var_idx;
2319         var = btf__type_by_id(obj->btf, vi->type);
2320         var_extra = btf_var(var);
2321         map_name = btf__name_by_offset(obj->btf, var->name_off);
2322
2323         if (map_name == NULL || map_name[0] == '\0') {
2324                 pr_warn("map #%d: empty name.\n", var_idx);
2325                 return -EINVAL;
2326         }
2327         if ((__u64)vi->offset + vi->size > data->d_size) {
2328                 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2329                 return -EINVAL;
2330         }
2331         if (!btf_is_var(var)) {
2332                 pr_warn("map '%s': unexpected var kind %s.\n",
2333                         map_name, btf_kind_str(var));
2334                 return -EINVAL;
2335         }
2336         if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2337                 pr_warn("map '%s': unsupported map linkage %s.\n",
2338                         map_name, btf_var_linkage_str(var_extra->linkage));
2339                 return -EOPNOTSUPP;
2340         }
2341
2342         def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2343         if (!btf_is_struct(def)) {
2344                 pr_warn("map '%s': unexpected def kind %s.\n",
2345                         map_name, btf_kind_str(var));
2346                 return -EINVAL;
2347         }
2348         if (def->size > vi->size) {
2349                 pr_warn("map '%s': invalid def size.\n", map_name);
2350                 return -EINVAL;
2351         }
2352
2353         map = bpf_object__add_map(obj);
2354         if (IS_ERR(map))
2355                 return PTR_ERR(map);
2356         map->name = strdup(map_name);
2357         if (!map->name) {
2358                 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2359                 return -ENOMEM;
2360         }
2361         map->libbpf_type = LIBBPF_MAP_UNSPEC;
2362         map->def.type = BPF_MAP_TYPE_UNSPEC;
2363         map->sec_idx = sec_idx;
2364         map->sec_offset = vi->offset;
2365         map->btf_var_idx = var_idx;
2366         pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2367                  map_name, map->sec_idx, map->sec_offset);
2368
2369         err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2370         if (err)
2371                 return err;
2372
2373         fill_map_from_def(map, &map_def);
2374
2375         if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2376                 err = build_map_pin_path(map, pin_root_path);
2377                 if (err) {
2378                         pr_warn("map '%s': couldn't build pin path.\n", map->name);
2379                         return err;
2380                 }
2381         }
2382
2383         if (map_def.parts & MAP_DEF_INNER_MAP) {
2384                 map->inner_map = calloc(1, sizeof(*map->inner_map));
2385                 if (!map->inner_map)
2386                         return -ENOMEM;
2387                 map->inner_map->fd = -1;
2388                 map->inner_map->sec_idx = sec_idx;
2389                 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2390                 if (!map->inner_map->name)
2391                         return -ENOMEM;
2392                 sprintf(map->inner_map->name, "%s.inner", map_name);
2393
2394                 fill_map_from_def(map->inner_map, &inner_def);
2395         }
2396
2397         return 0;
2398 }
2399
2400 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2401                                           const char *pin_root_path)
2402 {
2403         const struct btf_type *sec = NULL;
2404         int nr_types, i, vlen, err;
2405         const struct btf_type *t;
2406         const char *name;
2407         Elf_Data *data;
2408         Elf_Scn *scn;
2409
2410         if (obj->efile.btf_maps_shndx < 0)
2411                 return 0;
2412
2413         scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2414         data = elf_sec_data(obj, scn);
2415         if (!scn || !data) {
2416                 pr_warn("elf: failed to get %s map definitions for %s\n",
2417                         MAPS_ELF_SEC, obj->path);
2418                 return -EINVAL;
2419         }
2420
2421         nr_types = btf__get_nr_types(obj->btf);
2422         for (i = 1; i <= nr_types; i++) {
2423                 t = btf__type_by_id(obj->btf, i);
2424                 if (!btf_is_datasec(t))
2425                         continue;
2426                 name = btf__name_by_offset(obj->btf, t->name_off);
2427                 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2428                         sec = t;
2429                         obj->efile.btf_maps_sec_btf_id = i;
2430                         break;
2431                 }
2432         }
2433
2434         if (!sec) {
2435                 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2436                 return -ENOENT;
2437         }
2438
2439         vlen = btf_vlen(sec);
2440         for (i = 0; i < vlen; i++) {
2441                 err = bpf_object__init_user_btf_map(obj, sec, i,
2442                                                     obj->efile.btf_maps_shndx,
2443                                                     data, strict,
2444                                                     pin_root_path);
2445                 if (err)
2446                         return err;
2447         }
2448
2449         return 0;
2450 }
2451
2452 static int bpf_object__init_maps(struct bpf_object *obj,
2453                                  const struct bpf_object_open_opts *opts)
2454 {
2455         const char *pin_root_path;
2456         bool strict;
2457         int err;
2458
2459         strict = !OPTS_GET(opts, relaxed_maps, false);
2460         pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2461
2462         err = bpf_object__init_user_maps(obj, strict);
2463         err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2464         err = err ?: bpf_object__init_global_data_maps(obj);
2465         err = err ?: bpf_object__init_kconfig_map(obj);
2466         err = err ?: bpf_object__init_struct_ops_maps(obj);
2467
2468         return err;
2469 }
2470
2471 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2472 {
2473         GElf_Shdr sh;
2474
2475         if (elf_sec_hdr(obj, elf_sec_by_idx(obj, idx), &sh))
2476                 return false;
2477
2478         return sh.sh_flags & SHF_EXECINSTR;
2479 }
2480
2481 static bool btf_needs_sanitization(struct bpf_object *obj)
2482 {
2483         bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2484         bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2485         bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2486         bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2487
2488         return !has_func || !has_datasec || !has_func_global || !has_float;
2489 }
2490
2491 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2492 {
2493         bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2494         bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2495         bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2496         bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2497         struct btf_type *t;
2498         int i, j, vlen;
2499
2500         for (i = 1; i <= btf__get_nr_types(btf); i++) {
2501                 t = (struct btf_type *)btf__type_by_id(btf, i);
2502
2503                 if (!has_datasec && btf_is_var(t)) {
2504                         /* replace VAR with INT */
2505                         t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2506                         /*
2507                          * using size = 1 is the safest choice, 4 will be too
2508                          * big and cause kernel BTF validation failure if
2509                          * original variable took less than 4 bytes
2510                          */
2511                         t->size = 1;
2512                         *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2513                 } else if (!has_datasec && btf_is_datasec(t)) {
2514                         /* replace DATASEC with STRUCT */
2515                         const struct btf_var_secinfo *v = btf_var_secinfos(t);
2516                         struct btf_member *m = btf_members(t);
2517                         struct btf_type *vt;
2518                         char *name;
2519
2520                         name = (char *)btf__name_by_offset(btf, t->name_off);
2521                         while (*name) {
2522                                 if (*name == '.')
2523                                         *name = '_';
2524                                 name++;
2525                         }
2526
2527                         vlen = btf_vlen(t);
2528                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2529                         for (j = 0; j < vlen; j++, v++, m++) {
2530                                 /* order of field assignments is important */
2531                                 m->offset = v->offset * 8;
2532                                 m->type = v->type;
2533                                 /* preserve variable name as member name */
2534                                 vt = (void *)btf__type_by_id(btf, v->type);
2535                                 m->name_off = vt->name_off;
2536                         }
2537                 } else if (!has_func && btf_is_func_proto(t)) {
2538                         /* replace FUNC_PROTO with ENUM */
2539                         vlen = btf_vlen(t);
2540                         t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2541                         t->size = sizeof(__u32); /* kernel enforced */
2542                 } else if (!has_func && btf_is_func(t)) {
2543                         /* replace FUNC with TYPEDEF */
2544                         t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2545                 } else if (!has_func_global && btf_is_func(t)) {
2546                         /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2547                         t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2548                 } else if (!has_float && btf_is_float(t)) {
2549                         /* replace FLOAT with an equally-sized empty STRUCT;
2550                          * since C compilers do not accept e.g. "float" as a
2551                          * valid struct name, make it anonymous
2552                          */
2553                         t->name_off = 0;
2554                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2555                 }
2556         }
2557 }
2558
2559 static bool libbpf_needs_btf(const struct bpf_object *obj)
2560 {
2561         return obj->efile.btf_maps_shndx >= 0 ||
2562                obj->efile.st_ops_shndx >= 0 ||
2563                obj->nr_extern > 0;
2564 }
2565
2566 static bool kernel_needs_btf(const struct bpf_object *obj)
2567 {
2568         return obj->efile.st_ops_shndx >= 0;
2569 }
2570
2571 static int bpf_object__init_btf(struct bpf_object *obj,
2572                                 Elf_Data *btf_data,
2573                                 Elf_Data *btf_ext_data)
2574 {
2575         int err = -ENOENT;
2576
2577         if (btf_data) {
2578                 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2579                 err = libbpf_get_error(obj->btf);
2580                 if (err) {
2581                         obj->btf = NULL;
2582                         pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2583                         goto out;
2584                 }
2585                 /* enforce 8-byte pointers for BPF-targeted BTFs */
2586                 btf__set_pointer_size(obj->btf, 8);
2587         }
2588         if (btf_ext_data) {
2589                 if (!obj->btf) {
2590                         pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2591                                  BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2592                         goto out;
2593                 }
2594                 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2595                 err = libbpf_get_error(obj->btf_ext);
2596                 if (err) {
2597                         pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2598                                 BTF_EXT_ELF_SEC, err);
2599                         obj->btf_ext = NULL;
2600                         goto out;
2601                 }
2602         }
2603 out:
2604         if (err && libbpf_needs_btf(obj)) {
2605                 pr_warn("BTF is required, but is missing or corrupted.\n");
2606                 return err;
2607         }
2608         return 0;
2609 }
2610
2611 static int bpf_object__finalize_btf(struct bpf_object *obj)
2612 {
2613         int err;
2614
2615         if (!obj->btf)
2616                 return 0;
2617
2618         err = btf__finalize_data(obj, obj->btf);
2619         if (err) {
2620                 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2621                 return err;
2622         }
2623
2624         return 0;
2625 }
2626
2627 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2628 {
2629         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2630             prog->type == BPF_PROG_TYPE_LSM)
2631                 return true;
2632
2633         /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2634          * also need vmlinux BTF
2635          */
2636         if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2637                 return true;
2638
2639         return false;
2640 }
2641
2642 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2643 {
2644         struct bpf_program *prog;
2645         int i;
2646
2647         /* CO-RE relocations need kernel BTF, only when btf_custom_path
2648          * is not specified
2649          */
2650         if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2651                 return true;
2652
2653         /* Support for typed ksyms needs kernel BTF */
2654         for (i = 0; i < obj->nr_extern; i++) {
2655                 const struct extern_desc *ext;
2656
2657                 ext = &obj->externs[i];
2658                 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2659                         return true;
2660         }
2661
2662         bpf_object__for_each_program(prog, obj) {
2663                 if (!prog->load)
2664                         continue;
2665                 if (prog_needs_vmlinux_btf(prog))
2666                         return true;
2667         }
2668
2669         return false;
2670 }
2671
2672 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2673 {
2674         int err;
2675
2676         /* btf_vmlinux could be loaded earlier */
2677         if (obj->btf_vmlinux || obj->gen_loader)
2678                 return 0;
2679
2680         if (!force && !obj_needs_vmlinux_btf(obj))
2681                 return 0;
2682
2683         obj->btf_vmlinux = libbpf_find_kernel_btf();
2684         err = libbpf_get_error(obj->btf_vmlinux);
2685         if (err) {
2686                 pr_warn("Error loading vmlinux BTF: %d\n", err);
2687                 obj->btf_vmlinux = NULL;
2688                 return err;
2689         }
2690         return 0;
2691 }
2692
2693 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2694 {
2695         struct btf *kern_btf = obj->btf;
2696         bool btf_mandatory, sanitize;
2697         int i, err = 0;
2698
2699         if (!obj->btf)
2700                 return 0;
2701
2702         if (!kernel_supports(obj, FEAT_BTF)) {
2703                 if (kernel_needs_btf(obj)) {
2704                         err = -EOPNOTSUPP;
2705                         goto report;
2706                 }
2707                 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2708                 return 0;
2709         }
2710
2711         /* Even though some subprogs are global/weak, user might prefer more
2712          * permissive BPF verification process that BPF verifier performs for
2713          * static functions, taking into account more context from the caller
2714          * functions. In such case, they need to mark such subprogs with
2715          * __attribute__((visibility("hidden"))) and libbpf will adjust
2716          * corresponding FUNC BTF type to be marked as static and trigger more
2717          * involved BPF verification process.
2718          */
2719         for (i = 0; i < obj->nr_programs; i++) {
2720                 struct bpf_program *prog = &obj->programs[i];
2721                 struct btf_type *t;
2722                 const char *name;
2723                 int j, n;
2724
2725                 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2726                         continue;
2727
2728                 n = btf__get_nr_types(obj->btf);
2729                 for (j = 1; j <= n; j++) {
2730                         t = btf_type_by_id(obj->btf, j);
2731                         if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2732                                 continue;
2733
2734                         name = btf__str_by_offset(obj->btf, t->name_off);
2735                         if (strcmp(name, prog->name) != 0)
2736                                 continue;
2737
2738                         t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
2739                         break;
2740                 }
2741         }
2742
2743         sanitize = btf_needs_sanitization(obj);
2744         if (sanitize) {
2745                 const void *raw_data;
2746                 __u32 sz;
2747
2748                 /* clone BTF to sanitize a copy and leave the original intact */
2749                 raw_data = btf__get_raw_data(obj->btf, &sz);
2750                 kern_btf = btf__new(raw_data, sz);
2751                 err = libbpf_get_error(kern_btf);
2752                 if (err)
2753                         return err;
2754
2755                 /* enforce 8-byte pointers for BPF-targeted BTFs */
2756                 btf__set_pointer_size(obj->btf, 8);
2757                 bpf_object__sanitize_btf(obj, kern_btf);
2758         }
2759
2760         if (obj->gen_loader) {
2761                 __u32 raw_size = 0;
2762                 const void *raw_data = btf__get_raw_data(kern_btf, &raw_size);
2763
2764                 if (!raw_data)
2765                         return -ENOMEM;
2766                 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
2767                 /* Pretend to have valid FD to pass various fd >= 0 checks.
2768                  * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
2769                  */
2770                 btf__set_fd(kern_btf, 0);
2771         } else {
2772                 err = btf__load_into_kernel(kern_btf);
2773         }
2774         if (sanitize) {
2775                 if (!err) {
2776                         /* move fd to libbpf's BTF */
2777                         btf__set_fd(obj->btf, btf__fd(kern_btf));
2778                         btf__set_fd(kern_btf, -1);
2779                 }
2780                 btf__free(kern_btf);
2781         }
2782 report:
2783         if (err) {
2784                 btf_mandatory = kernel_needs_btf(obj);
2785                 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2786                         btf_mandatory ? "BTF is mandatory, can't proceed."
2787                                       : "BTF is optional, ignoring.");
2788                 if (!btf_mandatory)
2789                         err = 0;
2790         }
2791         return err;
2792 }
2793
2794 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
2795 {
2796         const char *name;
2797
2798         name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
2799         if (!name) {
2800                 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2801                         off, obj->path, elf_errmsg(-1));
2802                 return NULL;
2803         }
2804
2805         return name;
2806 }
2807
2808 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
2809 {
2810         const char *name;
2811
2812         name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
2813         if (!name) {
2814                 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2815                         off, obj->path, elf_errmsg(-1));
2816                 return NULL;
2817         }
2818
2819         return name;
2820 }
2821
2822 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
2823 {
2824         Elf_Scn *scn;
2825
2826         scn = elf_getscn(obj->efile.elf, idx);
2827         if (!scn) {
2828                 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
2829                         idx, obj->path, elf_errmsg(-1));
2830                 return NULL;
2831         }
2832         return scn;
2833 }
2834
2835 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
2836 {
2837         Elf_Scn *scn = NULL;
2838         Elf *elf = obj->efile.elf;
2839         const char *sec_name;
2840
2841         while ((scn = elf_nextscn(elf, scn)) != NULL) {
2842                 sec_name = elf_sec_name(obj, scn);
2843                 if (!sec_name)
2844                         return NULL;
2845
2846                 if (strcmp(sec_name, name) != 0)
2847                         continue;
2848
2849                 return scn;
2850         }
2851         return NULL;
2852 }
2853
2854 static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr)
2855 {
2856         if (!scn)
2857                 return -EINVAL;
2858
2859         if (gelf_getshdr(scn, hdr) != hdr) {
2860                 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
2861                         elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2862                 return -EINVAL;
2863         }
2864
2865         return 0;
2866 }
2867
2868 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
2869 {
2870         const char *name;
2871         GElf_Shdr sh;
2872
2873         if (!scn)
2874                 return NULL;
2875
2876         if (elf_sec_hdr(obj, scn, &sh))
2877                 return NULL;
2878
2879         name = elf_sec_str(obj, sh.sh_name);
2880         if (!name) {
2881                 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
2882                         elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2883                 return NULL;
2884         }
2885
2886         return name;
2887 }
2888
2889 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
2890 {
2891         Elf_Data *data;
2892
2893         if (!scn)
2894                 return NULL;
2895
2896         data = elf_getdata(scn, 0);
2897         if (!data) {
2898                 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
2899                         elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
2900                         obj->path, elf_errmsg(-1));
2901                 return NULL;
2902         }
2903
2904         return data;
2905 }
2906
2907 static bool is_sec_name_dwarf(const char *name)
2908 {
2909         /* approximation, but the actual list is too long */
2910         return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
2911 }
2912
2913 static bool ignore_elf_section(GElf_Shdr *hdr, const char *name)
2914 {
2915         /* no special handling of .strtab */
2916         if (hdr->sh_type == SHT_STRTAB)
2917                 return true;
2918
2919         /* ignore .llvm_addrsig section as well */
2920         if (hdr->sh_type == SHT_LLVM_ADDRSIG)
2921                 return true;
2922
2923         /* no subprograms will lead to an empty .text section, ignore it */
2924         if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
2925             strcmp(name, ".text") == 0)
2926                 return true;
2927
2928         /* DWARF sections */
2929         if (is_sec_name_dwarf(name))
2930                 return true;
2931
2932         if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
2933                 name += sizeof(".rel") - 1;
2934                 /* DWARF section relocations */
2935                 if (is_sec_name_dwarf(name))
2936                         return true;
2937
2938                 /* .BTF and .BTF.ext don't need relocations */
2939                 if (strcmp(name, BTF_ELF_SEC) == 0 ||
2940                     strcmp(name, BTF_EXT_ELF_SEC) == 0)
2941                         return true;
2942         }
2943
2944         return false;
2945 }
2946
2947 static int cmp_progs(const void *_a, const void *_b)
2948 {
2949         const struct bpf_program *a = _a;
2950         const struct bpf_program *b = _b;
2951
2952         if (a->sec_idx != b->sec_idx)
2953                 return a->sec_idx < b->sec_idx ? -1 : 1;
2954
2955         /* sec_insn_off can't be the same within the section */
2956         return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
2957 }
2958
2959 static int bpf_object__elf_collect(struct bpf_object *obj)
2960 {
2961         Elf *elf = obj->efile.elf;
2962         Elf_Data *btf_ext_data = NULL;
2963         Elf_Data *btf_data = NULL;
2964         int idx = 0, err = 0;
2965         const char *name;
2966         Elf_Data *data;
2967         Elf_Scn *scn;
2968         GElf_Shdr sh;
2969
2970         /* a bunch of ELF parsing functionality depends on processing symbols,
2971          * so do the first pass and find the symbol table
2972          */
2973         scn = NULL;
2974         while ((scn = elf_nextscn(elf, scn)) != NULL) {
2975                 if (elf_sec_hdr(obj, scn, &sh))
2976                         return -LIBBPF_ERRNO__FORMAT;
2977
2978                 if (sh.sh_type == SHT_SYMTAB) {
2979                         if (obj->efile.symbols) {
2980                                 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
2981                                 return -LIBBPF_ERRNO__FORMAT;
2982                         }
2983
2984                         data = elf_sec_data(obj, scn);
2985                         if (!data)
2986                                 return -LIBBPF_ERRNO__FORMAT;
2987
2988                         obj->efile.symbols = data;
2989                         obj->efile.symbols_shndx = elf_ndxscn(scn);
2990                         obj->efile.strtabidx = sh.sh_link;
2991                 }
2992         }
2993
2994         scn = NULL;
2995         while ((scn = elf_nextscn(elf, scn)) != NULL) {
2996                 idx++;
2997
2998                 if (elf_sec_hdr(obj, scn, &sh))
2999                         return -LIBBPF_ERRNO__FORMAT;
3000
3001                 name = elf_sec_str(obj, sh.sh_name);
3002                 if (!name)
3003                         return -LIBBPF_ERRNO__FORMAT;
3004
3005                 if (ignore_elf_section(&sh, name))
3006                         continue;
3007
3008                 data = elf_sec_data(obj, scn);
3009                 if (!data)
3010                         return -LIBBPF_ERRNO__FORMAT;
3011
3012                 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3013                          idx, name, (unsigned long)data->d_size,
3014                          (int)sh.sh_link, (unsigned long)sh.sh_flags,
3015                          (int)sh.sh_type);
3016
3017                 if (strcmp(name, "license") == 0) {
3018                         err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3019                         if (err)
3020                                 return err;
3021                 } else if (strcmp(name, "version") == 0) {
3022                         err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3023                         if (err)
3024                                 return err;
3025                 } else if (strcmp(name, "maps") == 0) {
3026                         obj->efile.maps_shndx = idx;
3027                 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3028                         obj->efile.btf_maps_shndx = idx;
3029                 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3030                         btf_data = data;
3031                 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3032                         btf_ext_data = data;
3033                 } else if (sh.sh_type == SHT_SYMTAB) {
3034                         /* already processed during the first pass above */
3035                 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
3036                         if (sh.sh_flags & SHF_EXECINSTR) {
3037                                 if (strcmp(name, ".text") == 0)
3038                                         obj->efile.text_shndx = idx;
3039                                 err = bpf_object__add_programs(obj, data, name, idx);
3040                                 if (err)
3041                                         return err;
3042                         } else if (strcmp(name, DATA_SEC) == 0) {
3043                                 obj->efile.data = data;
3044                                 obj->efile.data_shndx = idx;
3045                         } else if (strcmp(name, RODATA_SEC) == 0) {
3046                                 obj->efile.rodata = data;
3047                                 obj->efile.rodata_shndx = idx;
3048                         } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3049                                 obj->efile.st_ops_data = data;
3050                                 obj->efile.st_ops_shndx = idx;
3051                         } else {
3052                                 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3053                                         idx, name);
3054                         }
3055                 } else if (sh.sh_type == SHT_REL) {
3056                         int nr_sects = obj->efile.nr_reloc_sects;
3057                         void *sects = obj->efile.reloc_sects;
3058                         int sec = sh.sh_info; /* points to other section */
3059
3060                         /* Only do relo for section with exec instructions */
3061                         if (!section_have_execinstr(obj, sec) &&
3062                             strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3063                             strcmp(name, ".rel" MAPS_ELF_SEC)) {
3064                                 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3065                                         idx, name, sec,
3066                                         elf_sec_name(obj, elf_sec_by_idx(obj, sec)) ?: "<?>");
3067                                 continue;
3068                         }
3069
3070                         sects = libbpf_reallocarray(sects, nr_sects + 1,
3071                                                     sizeof(*obj->efile.reloc_sects));
3072                         if (!sects)
3073                                 return -ENOMEM;
3074
3075                         obj->efile.reloc_sects = sects;
3076                         obj->efile.nr_reloc_sects++;
3077
3078                         obj->efile.reloc_sects[nr_sects].shdr = sh;
3079                         obj->efile.reloc_sects[nr_sects].data = data;
3080                 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3081                         obj->efile.bss = data;
3082                         obj->efile.bss_shndx = idx;
3083                 } else {
3084                         pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3085                                 (size_t)sh.sh_size);
3086                 }
3087         }
3088
3089         if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3090                 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3091                 return -LIBBPF_ERRNO__FORMAT;
3092         }
3093
3094         /* sort BPF programs by section name and in-section instruction offset
3095          * for faster search */
3096         qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3097
3098         return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3099 }
3100
3101 static bool sym_is_extern(const GElf_Sym *sym)
3102 {
3103         int bind = GELF_ST_BIND(sym->st_info);
3104         /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3105         return sym->st_shndx == SHN_UNDEF &&
3106                (bind == STB_GLOBAL || bind == STB_WEAK) &&
3107                GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
3108 }
3109
3110 static bool sym_is_subprog(const GElf_Sym *sym, int text_shndx)
3111 {
3112         int bind = GELF_ST_BIND(sym->st_info);
3113         int type = GELF_ST_TYPE(sym->st_info);
3114
3115         /* in .text section */
3116         if (sym->st_shndx != text_shndx)
3117                 return false;
3118
3119         /* local function */
3120         if (bind == STB_LOCAL && type == STT_SECTION)
3121                 return true;
3122
3123         /* global function */
3124         return bind == STB_GLOBAL && type == STT_FUNC;
3125 }
3126
3127 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3128 {
3129         const struct btf_type *t;
3130         const char *tname;
3131         int i, n;
3132
3133         if (!btf)
3134                 return -ESRCH;
3135
3136         n = btf__get_nr_types(btf);
3137         for (i = 1; i <= n; i++) {
3138                 t = btf__type_by_id(btf, i);
3139
3140                 if (!btf_is_var(t) && !btf_is_func(t))
3141                         continue;
3142
3143                 tname = btf__name_by_offset(btf, t->name_off);
3144                 if (strcmp(tname, ext_name))
3145                         continue;
3146
3147                 if (btf_is_var(t) &&
3148                     btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3149                         return -EINVAL;
3150
3151                 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3152                         return -EINVAL;
3153
3154                 return i;
3155         }
3156
3157         return -ENOENT;
3158 }
3159
3160 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3161         const struct btf_var_secinfo *vs;
3162         const struct btf_type *t;
3163         int i, j, n;
3164
3165         if (!btf)
3166                 return -ESRCH;
3167
3168         n = btf__get_nr_types(btf);
3169         for (i = 1; i <= n; i++) {
3170                 t = btf__type_by_id(btf, i);
3171
3172                 if (!btf_is_datasec(t))
3173                         continue;
3174
3175                 vs = btf_var_secinfos(t);
3176                 for (j = 0; j < btf_vlen(t); j++, vs++) {
3177                         if (vs->type == ext_btf_id)
3178                                 return i;
3179                 }
3180         }
3181
3182         return -ENOENT;
3183 }
3184
3185 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3186                                      bool *is_signed)
3187 {
3188         const struct btf_type *t;
3189         const char *name;
3190
3191         t = skip_mods_and_typedefs(btf, id, NULL);
3192         name = btf__name_by_offset(btf, t->name_off);
3193
3194         if (is_signed)
3195                 *is_signed = false;
3196         switch (btf_kind(t)) {
3197         case BTF_KIND_INT: {
3198                 int enc = btf_int_encoding(t);
3199
3200                 if (enc & BTF_INT_BOOL)
3201                         return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3202                 if (is_signed)
3203                         *is_signed = enc & BTF_INT_SIGNED;
3204                 if (t->size == 1)
3205                         return KCFG_CHAR;
3206                 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3207                         return KCFG_UNKNOWN;
3208                 return KCFG_INT;
3209         }
3210         case BTF_KIND_ENUM:
3211                 if (t->size != 4)
3212                         return KCFG_UNKNOWN;
3213                 if (strcmp(name, "libbpf_tristate"))
3214                         return KCFG_UNKNOWN;
3215                 return KCFG_TRISTATE;
3216         case BTF_KIND_ARRAY:
3217                 if (btf_array(t)->nelems == 0)
3218                         return KCFG_UNKNOWN;
3219                 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3220                         return KCFG_UNKNOWN;
3221                 return KCFG_CHAR_ARR;
3222         default:
3223                 return KCFG_UNKNOWN;
3224         }
3225 }
3226
3227 static int cmp_externs(const void *_a, const void *_b)
3228 {
3229         const struct extern_desc *a = _a;
3230         const struct extern_desc *b = _b;
3231
3232         if (a->type != b->type)
3233                 return a->type < b->type ? -1 : 1;
3234
3235         if (a->type == EXT_KCFG) {
3236                 /* descending order by alignment requirements */
3237                 if (a->kcfg.align != b->kcfg.align)
3238                         return a->kcfg.align > b->kcfg.align ? -1 : 1;
3239                 /* ascending order by size, within same alignment class */
3240                 if (a->kcfg.sz != b->kcfg.sz)
3241                         return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3242         }
3243
3244         /* resolve ties by name */
3245         return strcmp(a->name, b->name);
3246 }
3247
3248 static int find_int_btf_id(const struct btf *btf)
3249 {
3250         const struct btf_type *t;
3251         int i, n;
3252
3253         n = btf__get_nr_types(btf);
3254         for (i = 1; i <= n; i++) {
3255                 t = btf__type_by_id(btf, i);
3256
3257                 if (btf_is_int(t) && btf_int_bits(t) == 32)
3258                         return i;
3259         }
3260
3261         return 0;
3262 }
3263
3264 static int add_dummy_ksym_var(struct btf *btf)
3265 {
3266         int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3267         const struct btf_var_secinfo *vs;
3268         const struct btf_type *sec;
3269
3270         if (!btf)
3271                 return 0;
3272
3273         sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3274                                             BTF_KIND_DATASEC);
3275         if (sec_btf_id < 0)
3276                 return 0;
3277
3278         sec = btf__type_by_id(btf, sec_btf_id);
3279         vs = btf_var_secinfos(sec);
3280         for (i = 0; i < btf_vlen(sec); i++, vs++) {
3281                 const struct btf_type *vt;
3282
3283                 vt = btf__type_by_id(btf, vs->type);
3284                 if (btf_is_func(vt))
3285                         break;
3286         }
3287
3288         /* No func in ksyms sec.  No need to add dummy var. */
3289         if (i == btf_vlen(sec))
3290                 return 0;
3291
3292         int_btf_id = find_int_btf_id(btf);
3293         dummy_var_btf_id = btf__add_var(btf,
3294                                         "dummy_ksym",
3295                                         BTF_VAR_GLOBAL_ALLOCATED,
3296                                         int_btf_id);
3297         if (dummy_var_btf_id < 0)
3298                 pr_warn("cannot create a dummy_ksym var\n");
3299
3300         return dummy_var_btf_id;
3301 }
3302
3303 static int bpf_object__collect_externs(struct bpf_object *obj)
3304 {
3305         struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3306         const struct btf_type *t;
3307         struct extern_desc *ext;
3308         int i, n, off, dummy_var_btf_id;
3309         const char *ext_name, *sec_name;
3310         Elf_Scn *scn;
3311         GElf_Shdr sh;
3312
3313         if (!obj->efile.symbols)
3314                 return 0;
3315
3316         scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3317         if (elf_sec_hdr(obj, scn, &sh))
3318                 return -LIBBPF_ERRNO__FORMAT;
3319
3320         dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3321         if (dummy_var_btf_id < 0)
3322                 return dummy_var_btf_id;
3323
3324         n = sh.sh_size / sh.sh_entsize;
3325         pr_debug("looking for externs among %d symbols...\n", n);
3326
3327         for (i = 0; i < n; i++) {
3328                 GElf_Sym sym;
3329
3330                 if (!gelf_getsym(obj->efile.symbols, i, &sym))
3331                         return -LIBBPF_ERRNO__FORMAT;
3332                 if (!sym_is_extern(&sym))
3333                         continue;
3334                 ext_name = elf_sym_str(obj, sym.st_name);
3335                 if (!ext_name || !ext_name[0])
3336                         continue;
3337
3338                 ext = obj->externs;
3339                 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3340                 if (!ext)
3341                         return -ENOMEM;
3342                 obj->externs = ext;
3343                 ext = &ext[obj->nr_extern];
3344                 memset(ext, 0, sizeof(*ext));
3345                 obj->nr_extern++;
3346
3347                 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3348                 if (ext->btf_id <= 0) {
3349                         pr_warn("failed to find BTF for extern '%s': %d\n",
3350                                 ext_name, ext->btf_id);
3351                         return ext->btf_id;
3352                 }
3353                 t = btf__type_by_id(obj->btf, ext->btf_id);
3354                 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3355                 ext->sym_idx = i;
3356                 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
3357
3358                 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3359                 if (ext->sec_btf_id <= 0) {
3360                         pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3361                                 ext_name, ext->btf_id, ext->sec_btf_id);
3362                         return ext->sec_btf_id;
3363                 }
3364                 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3365                 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3366
3367                 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3368                         if (btf_is_func(t)) {
3369                                 pr_warn("extern function %s is unsupported under %s section\n",
3370                                         ext->name, KCONFIG_SEC);
3371                                 return -ENOTSUP;
3372                         }
3373                         kcfg_sec = sec;
3374                         ext->type = EXT_KCFG;
3375                         ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3376                         if (ext->kcfg.sz <= 0) {
3377                                 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3378                                         ext_name, ext->kcfg.sz);
3379                                 return ext->kcfg.sz;
3380                         }
3381                         ext->kcfg.align = btf__align_of(obj->btf, t->type);
3382                         if (ext->kcfg.align <= 0) {
3383                                 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3384                                         ext_name, ext->kcfg.align);
3385                                 return -EINVAL;
3386                         }
3387                         ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3388                                                         &ext->kcfg.is_signed);
3389                         if (ext->kcfg.type == KCFG_UNKNOWN) {
3390                                 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3391                                 return -ENOTSUP;
3392                         }
3393                 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3394                         if (btf_is_func(t) && ext->is_weak) {
3395                                 pr_warn("extern weak function %s is unsupported\n",
3396                                         ext->name);
3397                                 return -ENOTSUP;
3398                         }
3399                         ksym_sec = sec;
3400                         ext->type = EXT_KSYM;
3401                         skip_mods_and_typedefs(obj->btf, t->type,
3402                                                &ext->ksym.type_id);
3403                 } else {
3404                         pr_warn("unrecognized extern section '%s'\n", sec_name);
3405                         return -ENOTSUP;
3406                 }
3407         }
3408         pr_debug("collected %d externs total\n", obj->nr_extern);
3409
3410         if (!obj->nr_extern)
3411                 return 0;
3412
3413         /* sort externs by type, for kcfg ones also by (align, size, name) */
3414         qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3415
3416         /* for .ksyms section, we need to turn all externs into allocated
3417          * variables in BTF to pass kernel verification; we do this by
3418          * pretending that each extern is a 8-byte variable
3419          */
3420         if (ksym_sec) {
3421                 /* find existing 4-byte integer type in BTF to use for fake
3422                  * extern variables in DATASEC
3423                  */
3424                 int int_btf_id = find_int_btf_id(obj->btf);
3425                 /* For extern function, a dummy_var added earlier
3426                  * will be used to replace the vs->type and
3427                  * its name string will be used to refill
3428                  * the missing param's name.
3429                  */
3430                 const struct btf_type *dummy_var;
3431
3432                 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3433                 for (i = 0; i < obj->nr_extern; i++) {
3434                         ext = &obj->externs[i];
3435                         if (ext->type != EXT_KSYM)
3436                                 continue;
3437                         pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3438                                  i, ext->sym_idx, ext->name);
3439                 }
3440
3441                 sec = ksym_sec;
3442                 n = btf_vlen(sec);
3443                 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3444                         struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3445                         struct btf_type *vt;
3446
3447                         vt = (void *)btf__type_by_id(obj->btf, vs->type);
3448                         ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3449                         ext = find_extern_by_name(obj, ext_name);
3450                         if (!ext) {
3451                                 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3452                                         btf_kind_str(vt), ext_name);
3453                                 return -ESRCH;
3454                         }
3455                         if (btf_is_func(vt)) {
3456                                 const struct btf_type *func_proto;
3457                                 struct btf_param *param;
3458                                 int j;
3459
3460                                 func_proto = btf__type_by_id(obj->btf,
3461                                                              vt->type);
3462                                 param = btf_params(func_proto);
3463                                 /* Reuse the dummy_var string if the
3464                                  * func proto does not have param name.
3465                                  */
3466                                 for (j = 0; j < btf_vlen(func_proto); j++)
3467                                         if (param[j].type && !param[j].name_off)
3468                                                 param[j].name_off =
3469                                                         dummy_var->name_off;
3470                                 vs->type = dummy_var_btf_id;
3471                                 vt->info &= ~0xffff;
3472                                 vt->info |= BTF_FUNC_GLOBAL;
3473                         } else {
3474                                 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3475                                 vt->type = int_btf_id;
3476                         }
3477                         vs->offset = off;
3478                         vs->size = sizeof(int);
3479                 }
3480                 sec->size = off;
3481         }
3482
3483         if (kcfg_sec) {
3484                 sec = kcfg_sec;
3485                 /* for kcfg externs calculate their offsets within a .kconfig map */
3486                 off = 0;
3487                 for (i = 0; i < obj->nr_extern; i++) {
3488                         ext = &obj->externs[i];
3489                         if (ext->type != EXT_KCFG)
3490                                 continue;
3491
3492                         ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3493                         off = ext->kcfg.data_off + ext->kcfg.sz;
3494                         pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3495                                  i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3496                 }
3497                 sec->size = off;
3498                 n = btf_vlen(sec);
3499                 for (i = 0; i < n; i++) {
3500                         struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3501
3502                         t = btf__type_by_id(obj->btf, vs->type);
3503                         ext_name = btf__name_by_offset(obj->btf, t->name_off);
3504                         ext = find_extern_by_name(obj, ext_name);
3505                         if (!ext) {
3506                                 pr_warn("failed to find extern definition for BTF var '%s'\n",
3507                                         ext_name);
3508                                 return -ESRCH;
3509                         }
3510                         btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3511                         vs->offset = ext->kcfg.data_off;
3512                 }
3513         }
3514         return 0;
3515 }
3516
3517 struct bpf_program *
3518 bpf_object__find_program_by_title(const struct bpf_object *obj,
3519                                   const char *title)
3520 {
3521         struct bpf_program *pos;
3522
3523         bpf_object__for_each_program(pos, obj) {
3524                 if (pos->sec_name && !strcmp(pos->sec_name, title))
3525                         return pos;
3526         }
3527         return errno = ENOENT, NULL;
3528 }
3529
3530 static bool prog_is_subprog(const struct bpf_object *obj,
3531                             const struct bpf_program *prog)
3532 {
3533         /* For legacy reasons, libbpf supports an entry-point BPF programs
3534          * without SEC() attribute, i.e., those in the .text section. But if
3535          * there are 2 or more such programs in the .text section, they all
3536          * must be subprograms called from entry-point BPF programs in
3537          * designated SEC()'tions, otherwise there is no way to distinguish
3538          * which of those programs should be loaded vs which are a subprogram.
3539          * Similarly, if there is a function/program in .text and at least one
3540          * other BPF program with custom SEC() attribute, then we just assume
3541          * .text programs are subprograms (even if they are not called from
3542          * other programs), because libbpf never explicitly supported mixing
3543          * SEC()-designated BPF programs and .text entry-point BPF programs.
3544          */
3545         return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3546 }
3547
3548 struct bpf_program *
3549 bpf_object__find_program_by_name(const struct bpf_object *obj,
3550                                  const char *name)
3551 {
3552         struct bpf_program *prog;
3553
3554         bpf_object__for_each_program(prog, obj) {
3555                 if (prog_is_subprog(obj, prog))
3556                         continue;
3557                 if (!strcmp(prog->name, name))
3558                         return prog;
3559         }
3560         return errno = ENOENT, NULL;
3561 }
3562
3563 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3564                                       int shndx)
3565 {
3566         return shndx == obj->efile.data_shndx ||
3567                shndx == obj->efile.bss_shndx ||
3568                shndx == obj->efile.rodata_shndx;
3569 }
3570
3571 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3572                                       int shndx)
3573 {
3574         return shndx == obj->efile.maps_shndx ||
3575                shndx == obj->efile.btf_maps_shndx;
3576 }
3577
3578 static enum libbpf_map_type
3579 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3580 {
3581         if (shndx == obj->efile.data_shndx)
3582                 return LIBBPF_MAP_DATA;
3583         else if (shndx == obj->efile.bss_shndx)
3584                 return LIBBPF_MAP_BSS;
3585         else if (shndx == obj->efile.rodata_shndx)
3586                 return LIBBPF_MAP_RODATA;
3587         else if (shndx == obj->efile.symbols_shndx)
3588                 return LIBBPF_MAP_KCONFIG;
3589         else
3590                 return LIBBPF_MAP_UNSPEC;
3591 }
3592
3593 static int bpf_program__record_reloc(struct bpf_program *prog,
3594                                      struct reloc_desc *reloc_desc,
3595                                      __u32 insn_idx, const char *sym_name,
3596                                      const GElf_Sym *sym, const GElf_Rel *rel)
3597 {
3598         struct bpf_insn *insn = &prog->insns[insn_idx];
3599         size_t map_idx, nr_maps = prog->obj->nr_maps;
3600         struct bpf_object *obj = prog->obj;
3601         __u32 shdr_idx = sym->st_shndx;
3602         enum libbpf_map_type type;
3603         const char *sym_sec_name;
3604         struct bpf_map *map;
3605
3606         if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3607                 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3608                         prog->name, sym_name, insn_idx, insn->code);
3609                 return -LIBBPF_ERRNO__RELOC;
3610         }
3611
3612         if (sym_is_extern(sym)) {
3613                 int sym_idx = GELF_R_SYM(rel->r_info);
3614                 int i, n = obj->nr_extern;
3615                 struct extern_desc *ext;
3616
3617                 for (i = 0; i < n; i++) {
3618                         ext = &obj->externs[i];
3619                         if (ext->sym_idx == sym_idx)
3620                                 break;
3621                 }
3622                 if (i >= n) {
3623                         pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3624                                 prog->name, sym_name, sym_idx);
3625                         return -LIBBPF_ERRNO__RELOC;
3626                 }
3627                 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3628                          prog->name, i, ext->name, ext->sym_idx, insn_idx);
3629                 if (insn->code == (BPF_JMP | BPF_CALL))
3630                         reloc_desc->type = RELO_EXTERN_FUNC;
3631                 else
3632                         reloc_desc->type = RELO_EXTERN_VAR;
3633                 reloc_desc->insn_idx = insn_idx;
3634                 reloc_desc->sym_off = i; /* sym_off stores extern index */
3635                 return 0;
3636         }
3637
3638         /* sub-program call relocation */
3639         if (is_call_insn(insn)) {
3640                 if (insn->src_reg != BPF_PSEUDO_CALL) {
3641                         pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3642                         return -LIBBPF_ERRNO__RELOC;
3643                 }
3644                 /* text_shndx can be 0, if no default "main" program exists */
3645                 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3646                         sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3647                         pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3648                                 prog->name, sym_name, sym_sec_name);
3649                         return -LIBBPF_ERRNO__RELOC;
3650                 }
3651                 if (sym->st_value % BPF_INSN_SZ) {
3652                         pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3653                                 prog->name, sym_name, (size_t)sym->st_value);
3654                         return -LIBBPF_ERRNO__RELOC;
3655                 }
3656                 reloc_desc->type = RELO_CALL;
3657                 reloc_desc->insn_idx = insn_idx;
3658                 reloc_desc->sym_off = sym->st_value;
3659                 return 0;
3660         }
3661
3662         if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3663                 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3664                         prog->name, sym_name, shdr_idx);
3665                 return -LIBBPF_ERRNO__RELOC;
3666         }
3667
3668         /* loading subprog addresses */
3669         if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3670                 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3671                  * local_func: sym->st_value = 0, insn->imm = offset in the section.
3672                  */
3673                 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3674                         pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3675                                 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3676                         return -LIBBPF_ERRNO__RELOC;
3677                 }
3678
3679                 reloc_desc->type = RELO_SUBPROG_ADDR;
3680                 reloc_desc->insn_idx = insn_idx;
3681                 reloc_desc->sym_off = sym->st_value;
3682                 return 0;
3683         }
3684
3685         type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3686         sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3687
3688         /* generic map reference relocation */
3689         if (type == LIBBPF_MAP_UNSPEC) {
3690                 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3691                         pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
3692                                 prog->name, sym_name, sym_sec_name);
3693                         return -LIBBPF_ERRNO__RELOC;
3694                 }
3695                 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3696                         map = &obj->maps[map_idx];
3697                         if (map->libbpf_type != type ||
3698                             map->sec_idx != sym->st_shndx ||
3699                             map->sec_offset != sym->st_value)
3700                                 continue;
3701                         pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
3702                                  prog->name, map_idx, map->name, map->sec_idx,
3703                                  map->sec_offset, insn_idx);
3704                         break;
3705                 }
3706                 if (map_idx >= nr_maps) {
3707                         pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
3708                                 prog->name, sym_sec_name, (size_t)sym->st_value);
3709                         return -LIBBPF_ERRNO__RELOC;
3710                 }
3711                 reloc_desc->type = RELO_LD64;
3712                 reloc_desc->insn_idx = insn_idx;
3713                 reloc_desc->map_idx = map_idx;
3714                 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3715                 return 0;
3716         }
3717
3718         /* global data map relocation */
3719         if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3720                 pr_warn("prog '%s': bad data relo against section '%s'\n",
3721                         prog->name, sym_sec_name);
3722                 return -LIBBPF_ERRNO__RELOC;
3723         }
3724         for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3725                 map = &obj->maps[map_idx];
3726                 if (map->libbpf_type != type)
3727                         continue;
3728                 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3729                          prog->name, map_idx, map->name, map->sec_idx,
3730                          map->sec_offset, insn_idx);
3731                 break;
3732         }
3733         if (map_idx >= nr_maps) {
3734                 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
3735                         prog->name, sym_sec_name);
3736                 return -LIBBPF_ERRNO__RELOC;
3737         }
3738
3739         reloc_desc->type = RELO_DATA;
3740         reloc_desc->insn_idx = insn_idx;
3741         reloc_desc->map_idx = map_idx;
3742         reloc_desc->sym_off = sym->st_value;
3743         return 0;
3744 }
3745
3746 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
3747 {
3748         return insn_idx >= prog->sec_insn_off &&
3749                insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
3750 }
3751
3752 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
3753                                                  size_t sec_idx, size_t insn_idx)
3754 {
3755         int l = 0, r = obj->nr_programs - 1, m;
3756         struct bpf_program *prog;
3757
3758         while (l < r) {
3759                 m = l + (r - l + 1) / 2;
3760                 prog = &obj->programs[m];
3761
3762                 if (prog->sec_idx < sec_idx ||
3763                     (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
3764                         l = m;
3765                 else
3766                         r = m - 1;
3767         }
3768         /* matching program could be at index l, but it still might be the
3769          * wrong one, so we need to double check conditions for the last time
3770          */
3771         prog = &obj->programs[l];
3772         if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
3773                 return prog;
3774         return NULL;
3775 }
3776
3777 static int
3778 bpf_object__collect_prog_relos(struct bpf_object *obj, GElf_Shdr *shdr, Elf_Data *data)
3779 {
3780         Elf_Data *symbols = obj->efile.symbols;
3781         const char *relo_sec_name, *sec_name;
3782         size_t sec_idx = shdr->sh_info;
3783         struct bpf_program *prog;
3784         struct reloc_desc *relos;
3785         int err, i, nrels;
3786         const char *sym_name;
3787         __u32 insn_idx;
3788         Elf_Scn *scn;
3789         Elf_Data *scn_data;
3790         GElf_Sym sym;
3791         GElf_Rel rel;
3792
3793         scn = elf_sec_by_idx(obj, sec_idx);
3794         scn_data = elf_sec_data(obj, scn);
3795
3796         relo_sec_name = elf_sec_str(obj, shdr->sh_name);
3797         sec_name = elf_sec_name(obj, scn);
3798         if (!relo_sec_name || !sec_name)
3799                 return -EINVAL;
3800
3801         pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
3802                  relo_sec_name, sec_idx, sec_name);
3803         nrels = shdr->sh_size / shdr->sh_entsize;
3804
3805         for (i = 0; i < nrels; i++) {
3806                 if (!gelf_getrel(data, i, &rel)) {
3807                         pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
3808                         return -LIBBPF_ERRNO__FORMAT;
3809                 }
3810                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3811                         pr_warn("sec '%s': symbol 0x%zx not found for relo #%d\n",
3812                                 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3813                         return -LIBBPF_ERRNO__FORMAT;
3814                 }
3815
3816                 if (rel.r_offset % BPF_INSN_SZ || rel.r_offset >= scn_data->d_size) {
3817                         pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
3818                                 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3819                         return -LIBBPF_ERRNO__FORMAT;
3820                 }
3821
3822                 insn_idx = rel.r_offset / BPF_INSN_SZ;
3823                 /* relocations against static functions are recorded as
3824                  * relocations against the section that contains a function;
3825                  * in such case, symbol will be STT_SECTION and sym.st_name
3826                  * will point to empty string (0), so fetch section name
3827                  * instead
3828                  */
3829                 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION && sym.st_name == 0)
3830                         sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym.st_shndx));
3831                 else
3832                         sym_name = elf_sym_str(obj, sym.st_name);
3833                 sym_name = sym_name ?: "<?";
3834
3835                 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
3836                          relo_sec_name, i, insn_idx, sym_name);
3837
3838                 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
3839                 if (!prog) {
3840                         pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
3841                                 relo_sec_name, i, sec_name, insn_idx);
3842                         continue;
3843                 }
3844
3845                 relos = libbpf_reallocarray(prog->reloc_desc,
3846                                             prog->nr_reloc + 1, sizeof(*relos));
3847                 if (!relos)
3848                         return -ENOMEM;
3849                 prog->reloc_desc = relos;
3850
3851                 /* adjust insn_idx to local BPF program frame of reference */
3852                 insn_idx -= prog->sec_insn_off;
3853                 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
3854                                                 insn_idx, sym_name, &sym, &rel);
3855                 if (err)
3856                         return err;
3857
3858                 prog->nr_reloc++;
3859         }
3860         return 0;
3861 }
3862
3863 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3864 {
3865         struct bpf_map_def *def = &map->def;
3866         __u32 key_type_id = 0, value_type_id = 0;
3867         int ret;
3868
3869         /* if it's BTF-defined map, we don't need to search for type IDs.
3870          * For struct_ops map, it does not need btf_key_type_id and
3871          * btf_value_type_id.
3872          */
3873         if (map->sec_idx == obj->efile.btf_maps_shndx ||
3874             bpf_map__is_struct_ops(map))
3875                 return 0;
3876
3877         if (!bpf_map__is_internal(map)) {
3878                 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3879                                            def->value_size, &key_type_id,
3880                                            &value_type_id);
3881         } else {
3882                 /*
3883                  * LLVM annotates global data differently in BTF, that is,
3884                  * only as '.data', '.bss' or '.rodata'.
3885                  */
3886                 ret = btf__find_by_name(obj->btf,
3887                                 libbpf_type_to_btf_name[map->libbpf_type]);
3888         }
3889         if (ret < 0)
3890                 return ret;
3891
3892         map->btf_key_type_id = key_type_id;
3893         map->btf_value_type_id = bpf_map__is_internal(map) ?
3894                                  ret : value_type_id;
3895         return 0;
3896 }
3897
3898 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
3899 {
3900         char file[PATH_MAX], buff[4096];
3901         FILE *fp;
3902         __u32 val;
3903         int err;
3904
3905         snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
3906         memset(info, 0, sizeof(*info));
3907
3908         fp = fopen(file, "r");
3909         if (!fp) {
3910                 err = -errno;
3911                 pr_warn("failed to open %s: %d. No procfs support?\n", file,
3912                         err);
3913                 return err;
3914         }
3915
3916         while (fgets(buff, sizeof(buff), fp)) {
3917                 if (sscanf(buff, "map_type:\t%u", &val) == 1)
3918                         info->type = val;
3919                 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
3920                         info->key_size = val;
3921                 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
3922                         info->value_size = val;
3923                 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
3924                         info->max_entries = val;
3925                 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
3926                         info->map_flags = val;
3927         }
3928
3929         fclose(fp);
3930
3931         return 0;
3932 }
3933
3934 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3935 {
3936         struct bpf_map_info info = {};
3937         __u32 len = sizeof(info);
3938         int new_fd, err;
3939         char *new_name;
3940
3941         err = bpf_obj_get_info_by_fd(fd, &info, &len);
3942         if (err && errno == EINVAL)
3943                 err = bpf_get_map_info_from_fdinfo(fd, &info);
3944         if (err)
3945                 return libbpf_err(err);
3946
3947         new_name = strdup(info.name);
3948         if (!new_name)
3949                 return libbpf_err(-errno);
3950
3951         new_fd = open("/", O_RDONLY | O_CLOEXEC);
3952         if (new_fd < 0) {
3953                 err = -errno;
3954                 goto err_free_new_name;
3955         }
3956
3957         new_fd = dup3(fd, new_fd, O_CLOEXEC);
3958         if (new_fd < 0) {
3959                 err = -errno;
3960                 goto err_close_new_fd;
3961         }
3962
3963         err = zclose(map->fd);
3964         if (err) {
3965                 err = -errno;
3966                 goto err_close_new_fd;
3967         }
3968         free(map->name);
3969
3970         map->fd = new_fd;
3971         map->name = new_name;
3972         map->def.type = info.type;
3973         map->def.key_size = info.key_size;
3974         map->def.value_size = info.value_size;
3975         map->def.max_entries = info.max_entries;
3976         map->def.map_flags = info.map_flags;
3977         map->btf_key_type_id = info.btf_key_type_id;
3978         map->btf_value_type_id = info.btf_value_type_id;
3979         map->reused = true;
3980
3981         return 0;
3982
3983 err_close_new_fd:
3984         close(new_fd);
3985 err_free_new_name:
3986         free(new_name);
3987         return libbpf_err(err);
3988 }
3989
3990 __u32 bpf_map__max_entries(const struct bpf_map *map)
3991 {
3992         return map->def.max_entries;
3993 }
3994
3995 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
3996 {
3997         if (!bpf_map_type__is_map_in_map(map->def.type))
3998                 return errno = EINVAL, NULL;
3999
4000         return map->inner_map;
4001 }
4002
4003 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4004 {
4005         if (map->fd >= 0)
4006                 return libbpf_err(-EBUSY);
4007         map->def.max_entries = max_entries;
4008         return 0;
4009 }
4010
4011 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4012 {
4013         if (!map || !max_entries)
4014                 return libbpf_err(-EINVAL);
4015
4016         return bpf_map__set_max_entries(map, max_entries);
4017 }
4018
4019 static int
4020 bpf_object__probe_loading(struct bpf_object *obj)
4021 {
4022         struct bpf_load_program_attr attr;
4023         char *cp, errmsg[STRERR_BUFSIZE];
4024         struct bpf_insn insns[] = {
4025                 BPF_MOV64_IMM(BPF_REG_0, 0),
4026                 BPF_EXIT_INSN(),
4027         };
4028         int ret;
4029
4030         if (obj->gen_loader)
4031                 return 0;
4032
4033         /* make sure basic loading works */
4034
4035         memset(&attr, 0, sizeof(attr));
4036         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4037         attr.insns = insns;
4038         attr.insns_cnt = ARRAY_SIZE(insns);
4039         attr.license = "GPL";
4040
4041         ret = bpf_load_program_xattr(&attr, NULL, 0);
4042         if (ret < 0) {
4043                 attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
4044                 ret = bpf_load_program_xattr(&attr, NULL, 0);
4045         }
4046         if (ret < 0) {
4047                 ret = errno;
4048                 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4049                 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4050                         "program. Make sure your kernel supports BPF "
4051                         "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4052                         "set to big enough value.\n", __func__, cp, ret);
4053                 return -ret;
4054         }
4055         close(ret);
4056
4057         return 0;
4058 }
4059
4060 static int probe_fd(int fd)
4061 {
4062         if (fd >= 0)
4063                 close(fd);
4064         return fd >= 0;
4065 }
4066
4067 static int probe_kern_prog_name(void)
4068 {
4069         struct bpf_load_program_attr attr;
4070         struct bpf_insn insns[] = {
4071                 BPF_MOV64_IMM(BPF_REG_0, 0),
4072                 BPF_EXIT_INSN(),
4073         };
4074         int ret;
4075
4076         /* make sure loading with name works */
4077
4078         memset(&attr, 0, sizeof(attr));
4079         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4080         attr.insns = insns;
4081         attr.insns_cnt = ARRAY_SIZE(insns);
4082         attr.license = "GPL";
4083         attr.name = "test";
4084         ret = bpf_load_program_xattr(&attr, NULL, 0);
4085         return probe_fd(ret);
4086 }
4087
4088 static int probe_kern_global_data(void)
4089 {
4090         struct bpf_load_program_attr prg_attr;
4091         struct bpf_create_map_attr map_attr;
4092         char *cp, errmsg[STRERR_BUFSIZE];
4093         struct bpf_insn insns[] = {
4094                 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4095                 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4096                 BPF_MOV64_IMM(BPF_REG_0, 0),
4097                 BPF_EXIT_INSN(),
4098         };
4099         int ret, map;
4100
4101         memset(&map_attr, 0, sizeof(map_attr));
4102         map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4103         map_attr.key_size = sizeof(int);
4104         map_attr.value_size = 32;
4105         map_attr.max_entries = 1;
4106
4107         map = bpf_create_map_xattr(&map_attr);
4108         if (map < 0) {
4109                 ret = -errno;
4110                 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4111                 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4112                         __func__, cp, -ret);
4113                 return ret;
4114         }
4115
4116         insns[0].imm = map;
4117
4118         memset(&prg_attr, 0, sizeof(prg_attr));
4119         prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4120         prg_attr.insns = insns;
4121         prg_attr.insns_cnt = ARRAY_SIZE(insns);
4122         prg_attr.license = "GPL";
4123
4124         ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
4125         close(map);
4126         return probe_fd(ret);
4127 }
4128
4129 static int probe_kern_btf(void)
4130 {
4131         static const char strs[] = "\0int";
4132         __u32 types[] = {
4133                 /* int */
4134                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4135         };
4136
4137         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4138                                              strs, sizeof(strs)));
4139 }
4140
4141 static int probe_kern_btf_func(void)
4142 {
4143         static const char strs[] = "\0int\0x\0a";
4144         /* void x(int a) {} */
4145         __u32 types[] = {
4146                 /* int */
4147                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4148                 /* FUNC_PROTO */                                /* [2] */
4149                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4150                 BTF_PARAM_ENC(7, 1),
4151                 /* FUNC x */                                    /* [3] */
4152                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4153         };
4154
4155         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4156                                              strs, sizeof(strs)));
4157 }
4158
4159 static int probe_kern_btf_func_global(void)
4160 {
4161         static const char strs[] = "\0int\0x\0a";
4162         /* static void x(int a) {} */
4163         __u32 types[] = {
4164                 /* int */
4165                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4166                 /* FUNC_PROTO */                                /* [2] */
4167                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4168                 BTF_PARAM_ENC(7, 1),
4169                 /* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4170                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4171         };
4172
4173         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4174                                              strs, sizeof(strs)));
4175 }
4176
4177 static int probe_kern_btf_datasec(void)
4178 {
4179         static const char strs[] = "\0x\0.data";
4180         /* static int a; */
4181         __u32 types[] = {
4182                 /* int */
4183                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4184                 /* VAR x */                                     /* [2] */
4185                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4186                 BTF_VAR_STATIC,
4187                 /* DATASEC val */                               /* [3] */
4188                 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4189                 BTF_VAR_SECINFO_ENC(2, 0, 4),
4190         };
4191
4192         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4193                                              strs, sizeof(strs)));
4194 }
4195
4196 static int probe_kern_btf_float(void)
4197 {
4198         static const char strs[] = "\0float";
4199         __u32 types[] = {
4200                 /* float */
4201                 BTF_TYPE_FLOAT_ENC(1, 4),
4202         };
4203
4204         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4205                                              strs, sizeof(strs)));
4206 }
4207
4208 static int probe_kern_array_mmap(void)
4209 {
4210         struct bpf_create_map_attr attr = {
4211                 .map_type = BPF_MAP_TYPE_ARRAY,
4212                 .map_flags = BPF_F_MMAPABLE,
4213                 .key_size = sizeof(int),
4214                 .value_size = sizeof(int),
4215                 .max_entries = 1,
4216         };
4217
4218         return probe_fd(bpf_create_map_xattr(&attr));
4219 }
4220
4221 static int probe_kern_exp_attach_type(void)
4222 {
4223         struct bpf_load_program_attr attr;
4224         struct bpf_insn insns[] = {
4225                 BPF_MOV64_IMM(BPF_REG_0, 0),
4226                 BPF_EXIT_INSN(),
4227         };
4228
4229         memset(&attr, 0, sizeof(attr));
4230         /* use any valid combination of program type and (optional)
4231          * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4232          * to see if kernel supports expected_attach_type field for
4233          * BPF_PROG_LOAD command
4234          */
4235         attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
4236         attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
4237         attr.insns = insns;
4238         attr.insns_cnt = ARRAY_SIZE(insns);
4239         attr.license = "GPL";
4240
4241         return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4242 }
4243
4244 static int probe_kern_probe_read_kernel(void)
4245 {
4246         struct bpf_load_program_attr attr;
4247         struct bpf_insn insns[] = {
4248                 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),   /* r1 = r10 (fp) */
4249                 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),  /* r1 += -8 */
4250                 BPF_MOV64_IMM(BPF_REG_2, 8),            /* r2 = 8 */
4251                 BPF_MOV64_IMM(BPF_REG_3, 0),            /* r3 = 0 */
4252                 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4253                 BPF_EXIT_INSN(),
4254         };
4255
4256         memset(&attr, 0, sizeof(attr));
4257         attr.prog_type = BPF_PROG_TYPE_KPROBE;
4258         attr.insns = insns;
4259         attr.insns_cnt = ARRAY_SIZE(insns);
4260         attr.license = "GPL";
4261
4262         return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
4263 }
4264
4265 static int probe_prog_bind_map(void)
4266 {
4267         struct bpf_load_program_attr prg_attr;
4268         struct bpf_create_map_attr map_attr;
4269         char *cp, errmsg[STRERR_BUFSIZE];
4270         struct bpf_insn insns[] = {
4271                 BPF_MOV64_IMM(BPF_REG_0, 0),
4272                 BPF_EXIT_INSN(),
4273         };
4274         int ret, map, prog;
4275
4276         memset(&map_attr, 0, sizeof(map_attr));
4277         map_attr.map_type = BPF_MAP_TYPE_ARRAY;
4278         map_attr.key_size = sizeof(int);
4279         map_attr.value_size = 32;
4280         map_attr.max_entries = 1;
4281
4282         map = bpf_create_map_xattr(&map_attr);
4283         if (map < 0) {
4284                 ret = -errno;
4285                 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4286                 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4287                         __func__, cp, -ret);
4288                 return ret;
4289         }
4290
4291         memset(&prg_attr, 0, sizeof(prg_attr));
4292         prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4293         prg_attr.insns = insns;
4294         prg_attr.insns_cnt = ARRAY_SIZE(insns);
4295         prg_attr.license = "GPL";
4296
4297         prog = bpf_load_program_xattr(&prg_attr, NULL, 0);
4298         if (prog < 0) {
4299                 close(map);
4300                 return 0;
4301         }
4302
4303         ret = bpf_prog_bind_map(prog, map, NULL);
4304
4305         close(map);
4306         close(prog);
4307
4308         return ret >= 0;
4309 }
4310
4311 static int probe_module_btf(void)
4312 {
4313         static const char strs[] = "\0int";
4314         __u32 types[] = {
4315                 /* int */
4316                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4317         };
4318         struct bpf_btf_info info;
4319         __u32 len = sizeof(info);
4320         char name[16];
4321         int fd, err;
4322
4323         fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4324         if (fd < 0)
4325                 return 0; /* BTF not supported at all */
4326
4327         memset(&info, 0, sizeof(info));
4328         info.name = ptr_to_u64(name);
4329         info.name_len = sizeof(name);
4330
4331         /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4332          * kernel's module BTF support coincides with support for
4333          * name/name_len fields in struct bpf_btf_info.
4334          */
4335         err = bpf_obj_get_info_by_fd(fd, &info, &len);
4336         close(fd);
4337         return !err;
4338 }
4339
4340 enum kern_feature_result {
4341         FEAT_UNKNOWN = 0,
4342         FEAT_SUPPORTED = 1,
4343         FEAT_MISSING = 2,
4344 };
4345
4346 typedef int (*feature_probe_fn)(void);
4347
4348 static struct kern_feature_desc {
4349         const char *desc;
4350         feature_probe_fn probe;
4351         enum kern_feature_result res;
4352 } feature_probes[__FEAT_CNT] = {
4353         [FEAT_PROG_NAME] = {
4354                 "BPF program name", probe_kern_prog_name,
4355         },
4356         [FEAT_GLOBAL_DATA] = {
4357                 "global variables", probe_kern_global_data,
4358         },
4359         [FEAT_BTF] = {
4360                 "minimal BTF", probe_kern_btf,
4361         },
4362         [FEAT_BTF_FUNC] = {
4363                 "BTF functions", probe_kern_btf_func,
4364         },
4365         [FEAT_BTF_GLOBAL_FUNC] = {
4366                 "BTF global function", probe_kern_btf_func_global,
4367         },
4368         [FEAT_BTF_DATASEC] = {
4369                 "BTF data section and variable", probe_kern_btf_datasec,
4370         },
4371         [FEAT_ARRAY_MMAP] = {
4372                 "ARRAY map mmap()", probe_kern_array_mmap,
4373         },
4374         [FEAT_EXP_ATTACH_TYPE] = {
4375                 "BPF_PROG_LOAD expected_attach_type attribute",
4376                 probe_kern_exp_attach_type,
4377         },
4378         [FEAT_PROBE_READ_KERN] = {
4379                 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4380         },
4381         [FEAT_PROG_BIND_MAP] = {
4382                 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4383         },
4384         [FEAT_MODULE_BTF] = {
4385                 "module BTF support", probe_module_btf,
4386         },
4387         [FEAT_BTF_FLOAT] = {
4388                 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4389         },
4390 };
4391
4392 static bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4393 {
4394         struct kern_feature_desc *feat = &feature_probes[feat_id];
4395         int ret;
4396
4397         if (obj->gen_loader)
4398                 /* To generate loader program assume the latest kernel
4399                  * to avoid doing extra prog_load, map_create syscalls.
4400                  */
4401                 return true;
4402
4403         if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4404                 ret = feat->probe();
4405                 if (ret > 0) {
4406                         WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4407                 } else if (ret == 0) {
4408                         WRITE_ONCE(feat->res, FEAT_MISSING);
4409                 } else {
4410                         pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4411                         WRITE_ONCE(feat->res, FEAT_MISSING);
4412                 }
4413         }
4414
4415         return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4416 }
4417
4418 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4419 {
4420         struct bpf_map_info map_info = {};
4421         char msg[STRERR_BUFSIZE];
4422         __u32 map_info_len;
4423         int err;
4424
4425         map_info_len = sizeof(map_info);
4426
4427         err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4428         if (err && errno == EINVAL)
4429                 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4430         if (err) {
4431                 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4432                         libbpf_strerror_r(errno, msg, sizeof(msg)));
4433                 return false;
4434         }
4435
4436         return (map_info.type == map->def.type &&
4437                 map_info.key_size == map->def.key_size &&
4438                 map_info.value_size == map->def.value_size &&
4439                 map_info.max_entries == map->def.max_entries &&
4440                 map_info.map_flags == map->def.map_flags);
4441 }
4442
4443 static int
4444 bpf_object__reuse_map(struct bpf_map *map)
4445 {
4446         char *cp, errmsg[STRERR_BUFSIZE];
4447         int err, pin_fd;
4448
4449         pin_fd = bpf_obj_get(map->pin_path);
4450         if (pin_fd < 0) {
4451                 err = -errno;
4452                 if (err == -ENOENT) {
4453                         pr_debug("found no pinned map to reuse at '%s'\n",
4454                                  map->pin_path);
4455                         return 0;
4456                 }
4457
4458                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4459                 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4460                         map->pin_path, cp);
4461                 return err;
4462         }
4463
4464         if (!map_is_reuse_compat(map, pin_fd)) {
4465                 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4466                         map->pin_path);
4467                 close(pin_fd);
4468                 return -EINVAL;
4469         }
4470
4471         err = bpf_map__reuse_fd(map, pin_fd);
4472         if (err) {
4473                 close(pin_fd);
4474                 return err;
4475         }
4476         map->pinned = true;
4477         pr_debug("reused pinned map at '%s'\n", map->pin_path);
4478
4479         return 0;
4480 }
4481
4482 static int
4483 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4484 {
4485         enum libbpf_map_type map_type = map->libbpf_type;
4486         char *cp, errmsg[STRERR_BUFSIZE];
4487         int err, zero = 0;
4488
4489         if (obj->gen_loader) {
4490                 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4491                                          map->mmaped, map->def.value_size);
4492                 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4493                         bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4494                 return 0;
4495         }
4496         err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4497         if (err) {
4498                 err = -errno;
4499                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4500                 pr_warn("Error setting initial map(%s) contents: %s\n",
4501                         map->name, cp);
4502                 return err;
4503         }
4504
4505         /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4506         if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4507                 err = bpf_map_freeze(map->fd);
4508                 if (err) {
4509                         err = -errno;
4510                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4511                         pr_warn("Error freezing map(%s) as read-only: %s\n",
4512                                 map->name, cp);
4513                         return err;
4514                 }
4515         }
4516         return 0;
4517 }
4518
4519 static void bpf_map__destroy(struct bpf_map *map);
4520
4521 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4522 {
4523         struct bpf_create_map_attr create_attr;
4524         struct bpf_map_def *def = &map->def;
4525         int err = 0;
4526
4527         memset(&create_attr, 0, sizeof(create_attr));
4528
4529         if (kernel_supports(obj, FEAT_PROG_NAME))
4530                 create_attr.name = map->name;
4531         create_attr.map_ifindex = map->map_ifindex;
4532         create_attr.map_type = def->type;
4533         create_attr.map_flags = def->map_flags;
4534         create_attr.key_size = def->key_size;
4535         create_attr.value_size = def->value_size;
4536         create_attr.numa_node = map->numa_node;
4537
4538         if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4539                 int nr_cpus;
4540
4541                 nr_cpus = libbpf_num_possible_cpus();
4542                 if (nr_cpus < 0) {
4543                         pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4544                                 map->name, nr_cpus);
4545                         return nr_cpus;
4546                 }
4547                 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4548                 create_attr.max_entries = nr_cpus;
4549         } else {
4550                 create_attr.max_entries = def->max_entries;
4551         }
4552
4553         if (bpf_map__is_struct_ops(map))
4554                 create_attr.btf_vmlinux_value_type_id =
4555                         map->btf_vmlinux_value_type_id;
4556
4557         create_attr.btf_fd = 0;
4558         create_attr.btf_key_type_id = 0;
4559         create_attr.btf_value_type_id = 0;
4560         if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4561                 create_attr.btf_fd = btf__fd(obj->btf);
4562                 create_attr.btf_key_type_id = map->btf_key_type_id;
4563                 create_attr.btf_value_type_id = map->btf_value_type_id;
4564         }
4565
4566         if (bpf_map_type__is_map_in_map(def->type)) {
4567                 if (map->inner_map) {
4568                         err = bpf_object__create_map(obj, map->inner_map, true);
4569                         if (err) {
4570                                 pr_warn("map '%s': failed to create inner map: %d\n",
4571                                         map->name, err);
4572                                 return err;
4573                         }
4574                         map->inner_map_fd = bpf_map__fd(map->inner_map);
4575                 }
4576                 if (map->inner_map_fd >= 0)
4577                         create_attr.inner_map_fd = map->inner_map_fd;
4578         }
4579
4580         if (obj->gen_loader) {
4581                 bpf_gen__map_create(obj->gen_loader, &create_attr, is_inner ? -1 : map - obj->maps);
4582                 /* Pretend to have valid FD to pass various fd >= 0 checks.
4583                  * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4584                  */
4585                 map->fd = 0;
4586         } else {
4587                 map->fd = bpf_create_map_xattr(&create_attr);
4588         }
4589         if (map->fd < 0 && (create_attr.btf_key_type_id ||
4590                             create_attr.btf_value_type_id)) {
4591                 char *cp, errmsg[STRERR_BUFSIZE];
4592
4593                 err = -errno;
4594                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4595                 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4596                         map->name, cp, err);
4597                 create_attr.btf_fd = 0;
4598                 create_attr.btf_key_type_id = 0;
4599                 create_attr.btf_value_type_id = 0;
4600                 map->btf_key_type_id = 0;
4601                 map->btf_value_type_id = 0;
4602                 map->fd = bpf_create_map_xattr(&create_attr);
4603         }
4604
4605         err = map->fd < 0 ? -errno : 0;
4606
4607         if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4608                 if (obj->gen_loader)
4609                         map->inner_map->fd = -1;
4610                 bpf_map__destroy(map->inner_map);
4611                 zfree(&map->inner_map);
4612         }
4613
4614         return err;
4615 }
4616
4617 static int init_map_slots(struct bpf_object *obj, struct bpf_map *map)
4618 {
4619         const struct bpf_map *targ_map;
4620         unsigned int i;
4621         int fd, err = 0;
4622
4623         for (i = 0; i < map->init_slots_sz; i++) {
4624                 if (!map->init_slots[i])
4625                         continue;
4626
4627                 targ_map = map->init_slots[i];
4628                 fd = bpf_map__fd(targ_map);
4629                 if (obj->gen_loader) {
4630                         pr_warn("// TODO map_update_elem: idx %td key %d value==map_idx %td\n",
4631                                 map - obj->maps, i, targ_map - obj->maps);
4632                         return -ENOTSUP;
4633                 } else {
4634                         err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4635                 }
4636                 if (err) {
4637                         err = -errno;
4638                         pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4639                                 map->name, i, targ_map->name,
4640                                 fd, err);
4641                         return err;
4642                 }
4643                 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4644                          map->name, i, targ_map->name, fd);
4645         }
4646
4647         zfree(&map->init_slots);
4648         map->init_slots_sz = 0;
4649
4650         return 0;
4651 }
4652
4653 static int
4654 bpf_object__create_maps(struct bpf_object *obj)
4655 {
4656         struct bpf_map *map;
4657         char *cp, errmsg[STRERR_BUFSIZE];
4658         unsigned int i, j;
4659         int err;
4660         bool retried;
4661
4662         for (i = 0; i < obj->nr_maps; i++) {
4663                 map = &obj->maps[i];
4664
4665                 retried = false;
4666 retry:
4667                 if (map->pin_path) {
4668                         err = bpf_object__reuse_map(map);
4669                         if (err) {
4670                                 pr_warn("map '%s': error reusing pinned map\n",
4671                                         map->name);
4672                                 goto err_out;
4673                         }
4674                         if (retried && map->fd < 0) {
4675                                 pr_warn("map '%s': cannot find pinned map\n",
4676                                         map->name);
4677                                 err = -ENOENT;
4678                                 goto err_out;
4679                         }
4680                 }
4681
4682                 if (map->fd >= 0) {
4683                         pr_debug("map '%s': skipping creation (preset fd=%d)\n",
4684                                  map->name, map->fd);
4685                 } else {
4686                         err = bpf_object__create_map(obj, map, false);
4687                         if (err)
4688                                 goto err_out;
4689
4690                         pr_debug("map '%s': created successfully, fd=%d\n",
4691                                  map->name, map->fd);
4692
4693                         if (bpf_map__is_internal(map)) {
4694                                 err = bpf_object__populate_internal_map(obj, map);
4695                                 if (err < 0) {
4696                                         zclose(map->fd);
4697                                         goto err_out;
4698                                 }
4699                         }
4700
4701                         if (map->init_slots_sz) {
4702                                 err = init_map_slots(obj, map);
4703                                 if (err < 0) {
4704                                         zclose(map->fd);
4705                                         goto err_out;
4706                                 }
4707                         }
4708                 }
4709
4710                 if (map->pin_path && !map->pinned) {
4711                         err = bpf_map__pin(map, NULL);
4712                         if (err) {
4713                                 zclose(map->fd);
4714                                 if (!retried && err == -EEXIST) {
4715                                         retried = true;
4716                                         goto retry;
4717                                 }
4718                                 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
4719                                         map->name, map->pin_path, err);
4720                                 goto err_out;
4721                         }
4722                 }
4723         }
4724
4725         return 0;
4726
4727 err_out:
4728         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4729         pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
4730         pr_perm_msg(err);
4731         for (j = 0; j < i; j++)
4732                 zclose(obj->maps[j].fd);
4733         return err;
4734 }
4735
4736 static bool bpf_core_is_flavor_sep(const char *s)
4737 {
4738         /* check X___Y name pattern, where X and Y are not underscores */
4739         return s[0] != '_' &&                                 /* X */
4740                s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
4741                s[4] != '_';                                   /* Y */
4742 }
4743
4744 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
4745  * before last triple underscore. Struct name part after last triple
4746  * underscore is ignored by BPF CO-RE relocation during relocation matching.
4747  */
4748 size_t bpf_core_essential_name_len(const char *name)
4749 {
4750         size_t n = strlen(name);
4751         int i;
4752
4753         for (i = n - 5; i >= 0; i--) {
4754                 if (bpf_core_is_flavor_sep(name + i))
4755                         return i + 1;
4756         }
4757         return n;
4758 }
4759
4760 static void bpf_core_free_cands(struct bpf_core_cand_list *cands)
4761 {
4762         free(cands->cands);
4763         free(cands);
4764 }
4765
4766 static int bpf_core_add_cands(struct bpf_core_cand *local_cand,
4767                               size_t local_essent_len,
4768                               const struct btf *targ_btf,
4769                               const char *targ_btf_name,
4770                               int targ_start_id,
4771                               struct bpf_core_cand_list *cands)
4772 {
4773         struct bpf_core_cand *new_cands, *cand;
4774         const struct btf_type *t;
4775         const char *targ_name;
4776         size_t targ_essent_len;
4777         int n, i;
4778
4779         n = btf__get_nr_types(targ_btf);
4780         for (i = targ_start_id; i <= n; i++) {
4781                 t = btf__type_by_id(targ_btf, i);
4782                 if (btf_kind(t) != btf_kind(local_cand->t))
4783                         continue;
4784
4785                 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4786                 if (str_is_empty(targ_name))
4787                         continue;
4788
4789                 targ_essent_len = bpf_core_essential_name_len(targ_name);
4790                 if (targ_essent_len != local_essent_len)
4791                         continue;
4792
4793                 if (strncmp(local_cand->name, targ_name, local_essent_len) != 0)
4794                         continue;
4795
4796                 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
4797                          local_cand->id, btf_kind_str(local_cand->t),
4798                          local_cand->name, i, btf_kind_str(t), targ_name,
4799                          targ_btf_name);
4800                 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
4801                                               sizeof(*cands->cands));
4802                 if (!new_cands)
4803                         return -ENOMEM;
4804
4805                 cand = &new_cands[cands->len];
4806                 cand->btf = targ_btf;
4807                 cand->t = t;
4808                 cand->name = targ_name;
4809                 cand->id = i;
4810
4811                 cands->cands = new_cands;
4812                 cands->len++;
4813         }
4814         return 0;
4815 }
4816
4817 static int load_module_btfs(struct bpf_object *obj)
4818 {
4819         struct bpf_btf_info info;
4820         struct module_btf *mod_btf;
4821         struct btf *btf;
4822         char name[64];
4823         __u32 id = 0, len;
4824         int err, fd;
4825
4826         if (obj->btf_modules_loaded)
4827                 return 0;
4828
4829         if (obj->gen_loader)
4830                 return 0;
4831
4832         /* don't do this again, even if we find no module BTFs */
4833         obj->btf_modules_loaded = true;
4834
4835         /* kernel too old to support module BTFs */
4836         if (!kernel_supports(obj, FEAT_MODULE_BTF))
4837                 return 0;
4838
4839         while (true) {
4840                 err = bpf_btf_get_next_id(id, &id);
4841                 if (err && errno == ENOENT)
4842                         return 0;
4843                 if (err) {
4844                         err = -errno;
4845                         pr_warn("failed to iterate BTF objects: %d\n", err);
4846                         return err;
4847                 }
4848
4849                 fd = bpf_btf_get_fd_by_id(id);
4850                 if (fd < 0) {
4851                         if (errno == ENOENT)
4852                                 continue; /* expected race: BTF was unloaded */
4853                         err = -errno;
4854                         pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
4855                         return err;
4856                 }
4857
4858                 len = sizeof(info);
4859                 memset(&info, 0, sizeof(info));
4860                 info.name = ptr_to_u64(name);
4861                 info.name_len = sizeof(name);
4862
4863                 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4864                 if (err) {
4865                         err = -errno;
4866                         pr_warn("failed to get BTF object #%d info: %d\n", id, err);
4867                         goto err_out;
4868                 }
4869
4870                 /* ignore non-module BTFs */
4871                 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
4872                         close(fd);
4873                         continue;
4874                 }
4875
4876                 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
4877                 err = libbpf_get_error(btf);
4878                 if (err) {
4879                         pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
4880                                 name, id, err);
4881                         goto err_out;
4882                 }
4883
4884                 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
4885                                         sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
4886                 if (err)
4887                         goto err_out;
4888
4889                 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
4890
4891                 mod_btf->btf = btf;
4892                 mod_btf->id = id;
4893                 mod_btf->fd = fd;
4894                 mod_btf->name = strdup(name);
4895                 if (!mod_btf->name) {
4896                         err = -ENOMEM;
4897                         goto err_out;
4898                 }
4899                 continue;
4900
4901 err_out:
4902                 close(fd);
4903                 return err;
4904         }
4905
4906         return 0;
4907 }
4908
4909 static struct bpf_core_cand_list *
4910 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
4911 {
4912         struct bpf_core_cand local_cand = {};
4913         struct bpf_core_cand_list *cands;
4914         const struct btf *main_btf;
4915         size_t local_essent_len;
4916         int err, i;
4917
4918         local_cand.btf = local_btf;
4919         local_cand.t = btf__type_by_id(local_btf, local_type_id);
4920         if (!local_cand.t)
4921                 return ERR_PTR(-EINVAL);
4922
4923         local_cand.name = btf__name_by_offset(local_btf, local_cand.t->name_off);
4924         if (str_is_empty(local_cand.name))
4925                 return ERR_PTR(-EINVAL);
4926         local_essent_len = bpf_core_essential_name_len(local_cand.name);
4927
4928         cands = calloc(1, sizeof(*cands));
4929         if (!cands)
4930                 return ERR_PTR(-ENOMEM);
4931
4932         /* Attempt to find target candidates in vmlinux BTF first */
4933         main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
4934         err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
4935         if (err)
4936                 goto err_out;
4937
4938         /* if vmlinux BTF has any candidate, don't got for module BTFs */
4939         if (cands->len)
4940                 return cands;
4941
4942         /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
4943         if (obj->btf_vmlinux_override)
4944                 return cands;
4945
4946         /* now look through module BTFs, trying to still find candidates */
4947         err = load_module_btfs(obj);
4948         if (err)
4949                 goto err_out;
4950
4951         for (i = 0; i < obj->btf_module_cnt; i++) {
4952                 err = bpf_core_add_cands(&local_cand, local_essent_len,
4953                                          obj->btf_modules[i].btf,
4954                                          obj->btf_modules[i].name,
4955                                          btf__get_nr_types(obj->btf_vmlinux) + 1,
4956                                          cands);
4957                 if (err)
4958                         goto err_out;
4959         }
4960
4961         return cands;
4962 err_out:
4963         bpf_core_free_cands(cands);
4964         return ERR_PTR(err);
4965 }
4966
4967 /* Check local and target types for compatibility. This check is used for
4968  * type-based CO-RE relocations and follow slightly different rules than
4969  * field-based relocations. This function assumes that root types were already
4970  * checked for name match. Beyond that initial root-level name check, names
4971  * are completely ignored. Compatibility rules are as follows:
4972  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
4973  *     kind should match for local and target types (i.e., STRUCT is not
4974  *     compatible with UNION);
4975  *   - for ENUMs, the size is ignored;
4976  *   - for INT, size and signedness are ignored;
4977  *   - for ARRAY, dimensionality is ignored, element types are checked for
4978  *     compatibility recursively;
4979  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
4980  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
4981  *   - FUNC_PROTOs are compatible if they have compatible signature: same
4982  *     number of input args and compatible return and argument types.
4983  * These rules are not set in stone and probably will be adjusted as we get
4984  * more experience with using BPF CO-RE relocations.
4985  */
4986 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
4987                               const struct btf *targ_btf, __u32 targ_id)
4988 {
4989         const struct btf_type *local_type, *targ_type;
4990         int depth = 32; /* max recursion depth */
4991
4992         /* caller made sure that names match (ignoring flavor suffix) */
4993         local_type = btf__type_by_id(local_btf, local_id);
4994         targ_type = btf__type_by_id(targ_btf, targ_id);
4995         if (btf_kind(local_type) != btf_kind(targ_type))
4996                 return 0;
4997
4998 recur:
4999         depth--;
5000         if (depth < 0)
5001                 return -EINVAL;
5002
5003         local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5004         targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5005         if (!local_type || !targ_type)
5006                 return -EINVAL;
5007
5008         if (btf_kind(local_type) != btf_kind(targ_type))
5009                 return 0;
5010
5011         switch (btf_kind(local_type)) {
5012         case BTF_KIND_UNKN:
5013         case BTF_KIND_STRUCT:
5014         case BTF_KIND_UNION:
5015         case BTF_KIND_ENUM:
5016         case BTF_KIND_FWD:
5017                 return 1;
5018         case BTF_KIND_INT:
5019                 /* just reject deprecated bitfield-like integers; all other
5020                  * integers are by default compatible between each other
5021                  */
5022                 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5023         case BTF_KIND_PTR:
5024                 local_id = local_type->type;
5025                 targ_id = targ_type->type;
5026                 goto recur;
5027         case BTF_KIND_ARRAY:
5028                 local_id = btf_array(local_type)->type;
5029                 targ_id = btf_array(targ_type)->type;
5030                 goto recur;
5031         case BTF_KIND_FUNC_PROTO: {
5032                 struct btf_param *local_p = btf_params(local_type);
5033                 struct btf_param *targ_p = btf_params(targ_type);
5034                 __u16 local_vlen = btf_vlen(local_type);
5035                 __u16 targ_vlen = btf_vlen(targ_type);
5036                 int i, err;
5037
5038                 if (local_vlen != targ_vlen)
5039                         return 0;
5040
5041                 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5042                         skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5043                         skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5044                         err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5045                         if (err <= 0)
5046                                 return err;
5047                 }
5048
5049                 /* tail recurse for return type check */
5050                 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5051                 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5052                 goto recur;
5053         }
5054         default:
5055                 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5056                         btf_kind_str(local_type), local_id, targ_id);
5057                 return 0;
5058         }
5059 }
5060
5061 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5062 {
5063         return (size_t)key;
5064 }
5065
5066 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5067 {
5068         return k1 == k2;
5069 }
5070
5071 static void *u32_as_hash_key(__u32 x)
5072 {
5073         return (void *)(uintptr_t)x;
5074 }
5075
5076 static int bpf_core_apply_relo(struct bpf_program *prog,
5077                                const struct bpf_core_relo *relo,
5078                                int relo_idx,
5079                                const struct btf *local_btf,
5080                                struct hashmap *cand_cache)
5081 {
5082         const void *type_key = u32_as_hash_key(relo->type_id);
5083         struct bpf_core_cand_list *cands = NULL;
5084         const char *prog_name = prog->name;
5085         const struct btf_type *local_type;
5086         const char *local_name;
5087         __u32 local_id = relo->type_id;
5088         struct bpf_insn *insn;
5089         int insn_idx, err;
5090
5091         if (relo->insn_off % BPF_INSN_SZ)
5092                 return -EINVAL;
5093         insn_idx = relo->insn_off / BPF_INSN_SZ;
5094         /* adjust insn_idx from section frame of reference to the local
5095          * program's frame of reference; (sub-)program code is not yet
5096          * relocated, so it's enough to just subtract in-section offset
5097          */
5098         insn_idx = insn_idx - prog->sec_insn_off;
5099         if (insn_idx > prog->insns_cnt)
5100                 return -EINVAL;
5101         insn = &prog->insns[insn_idx];
5102
5103         local_type = btf__type_by_id(local_btf, local_id);
5104         if (!local_type)
5105                 return -EINVAL;
5106
5107         local_name = btf__name_by_offset(local_btf, local_type->name_off);
5108         if (!local_name)
5109                 return -EINVAL;
5110
5111         if (prog->obj->gen_loader) {
5112                 pr_warn("// TODO core_relo: prog %td insn[%d] %s kind %d\n",
5113                         prog - prog->obj->programs, relo->insn_off / 8,
5114                         local_name, relo->kind);
5115                 return -ENOTSUP;
5116         }
5117
5118         if (relo->kind != BPF_TYPE_ID_LOCAL &&
5119             !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5120                 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5121                 if (IS_ERR(cands)) {
5122                         pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5123                                 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5124                                 local_name, PTR_ERR(cands));
5125                         return PTR_ERR(cands);
5126                 }
5127                 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5128                 if (err) {
5129                         bpf_core_free_cands(cands);
5130                         return err;
5131                 }
5132         }
5133
5134         return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo, relo_idx, local_btf, cands);
5135 }
5136
5137 static int
5138 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5139 {
5140         const struct btf_ext_info_sec *sec;
5141         const struct bpf_core_relo *rec;
5142         const struct btf_ext_info *seg;
5143         struct hashmap_entry *entry;
5144         struct hashmap *cand_cache = NULL;
5145         struct bpf_program *prog;
5146         const char *sec_name;
5147         int i, err = 0, insn_idx, sec_idx;
5148
5149         if (obj->btf_ext->core_relo_info.len == 0)
5150                 return 0;
5151
5152         if (targ_btf_path) {
5153                 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5154                 err = libbpf_get_error(obj->btf_vmlinux_override);
5155                 if (err) {
5156                         pr_warn("failed to parse target BTF: %d\n", err);
5157                         return err;
5158                 }
5159         }
5160
5161         cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5162         if (IS_ERR(cand_cache)) {
5163                 err = PTR_ERR(cand_cache);
5164                 goto out;
5165         }
5166
5167         seg = &obj->btf_ext->core_relo_info;
5168         for_each_btf_ext_sec(seg, sec) {
5169                 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5170                 if (str_is_empty(sec_name)) {
5171                         err = -EINVAL;
5172                         goto out;
5173                 }
5174                 /* bpf_object's ELF is gone by now so it's not easy to find
5175                  * section index by section name, but we can find *any*
5176                  * bpf_program within desired section name and use it's
5177                  * prog->sec_idx to do a proper search by section index and
5178                  * instruction offset
5179                  */
5180                 prog = NULL;
5181                 for (i = 0; i < obj->nr_programs; i++) {
5182                         prog = &obj->programs[i];
5183                         if (strcmp(prog->sec_name, sec_name) == 0)
5184                                 break;
5185                 }
5186                 if (!prog) {
5187                         pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5188                         return -ENOENT;
5189                 }
5190                 sec_idx = prog->sec_idx;
5191
5192                 pr_debug("sec '%s': found %d CO-RE relocations\n",
5193                          sec_name, sec->num_info);
5194
5195                 for_each_btf_ext_rec(seg, sec, i, rec) {
5196                         insn_idx = rec->insn_off / BPF_INSN_SZ;
5197                         prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5198                         if (!prog) {
5199                                 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5200                                         sec_name, insn_idx, i);
5201                                 err = -EINVAL;
5202                                 goto out;
5203                         }
5204                         /* no need to apply CO-RE relocation if the program is
5205                          * not going to be loaded
5206                          */
5207                         if (!prog->load)
5208                                 continue;
5209
5210                         err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
5211                         if (err) {
5212                                 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5213                                         prog->name, i, err);
5214                                 goto out;
5215                         }
5216                 }
5217         }
5218
5219 out:
5220         /* obj->btf_vmlinux and module BTFs are freed after object load */
5221         btf__free(obj->btf_vmlinux_override);
5222         obj->btf_vmlinux_override = NULL;
5223
5224         if (!IS_ERR_OR_NULL(cand_cache)) {
5225                 hashmap__for_each_entry(cand_cache, entry, i) {
5226                         bpf_core_free_cands(entry->value);
5227                 }
5228                 hashmap__free(cand_cache);
5229         }
5230         return err;
5231 }
5232
5233 /* Relocate data references within program code:
5234  *  - map references;
5235  *  - global variable references;
5236  *  - extern references.
5237  */
5238 static int
5239 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5240 {
5241         int i;
5242
5243         for (i = 0; i < prog->nr_reloc; i++) {
5244                 struct reloc_desc *relo = &prog->reloc_desc[i];
5245                 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5246                 struct extern_desc *ext;
5247
5248                 switch (relo->type) {
5249                 case RELO_LD64:
5250                         if (obj->gen_loader) {
5251                                 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5252                                 insn[0].imm = relo->map_idx;
5253                         } else {
5254                                 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5255                                 insn[0].imm = obj->maps[relo->map_idx].fd;
5256                         }
5257                         break;
5258                 case RELO_DATA:
5259                         insn[1].imm = insn[0].imm + relo->sym_off;
5260                         if (obj->gen_loader) {
5261                                 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5262                                 insn[0].imm = relo->map_idx;
5263                         } else {
5264                                 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5265                                 insn[0].imm = obj->maps[relo->map_idx].fd;
5266                         }
5267                         break;
5268                 case RELO_EXTERN_VAR:
5269                         ext = &obj->externs[relo->sym_off];
5270                         if (ext->type == EXT_KCFG) {
5271                                 if (obj->gen_loader) {
5272                                         insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5273                                         insn[0].imm = obj->kconfig_map_idx;
5274                                 } else {
5275                                         insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5276                                         insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5277                                 }
5278                                 insn[1].imm = ext->kcfg.data_off;
5279                         } else /* EXT_KSYM */ {
5280                                 if (ext->ksym.type_id) { /* typed ksyms */
5281                                         insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5282                                         insn[0].imm = ext->ksym.kernel_btf_id;
5283                                         insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5284                                 } else { /* typeless ksyms */
5285                                         insn[0].imm = (__u32)ext->ksym.addr;
5286                                         insn[1].imm = ext->ksym.addr >> 32;
5287                                 }
5288                         }
5289                         break;
5290                 case RELO_EXTERN_FUNC:
5291                         ext = &obj->externs[relo->sym_off];
5292                         insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5293                         insn[0].imm = ext->ksym.kernel_btf_id;
5294                         break;
5295                 case RELO_SUBPROG_ADDR:
5296                         if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5297                                 pr_warn("prog '%s': relo #%d: bad insn\n",
5298                                         prog->name, i);
5299                                 return -EINVAL;
5300                         }
5301                         /* handled already */
5302                         break;
5303                 case RELO_CALL:
5304                         /* handled already */
5305                         break;
5306                 default:
5307                         pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5308                                 prog->name, i, relo->type);
5309                         return -EINVAL;
5310                 }
5311         }
5312
5313         return 0;
5314 }
5315
5316 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5317                                     const struct bpf_program *prog,
5318                                     const struct btf_ext_info *ext_info,
5319                                     void **prog_info, __u32 *prog_rec_cnt,
5320                                     __u32 *prog_rec_sz)
5321 {
5322         void *copy_start = NULL, *copy_end = NULL;
5323         void *rec, *rec_end, *new_prog_info;
5324         const struct btf_ext_info_sec *sec;
5325         size_t old_sz, new_sz;
5326         const char *sec_name;
5327         int i, off_adj;
5328
5329         for_each_btf_ext_sec(ext_info, sec) {
5330                 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5331                 if (!sec_name)
5332                         return -EINVAL;
5333                 if (strcmp(sec_name, prog->sec_name) != 0)
5334                         continue;
5335
5336                 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5337                         __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5338
5339                         if (insn_off < prog->sec_insn_off)
5340                                 continue;
5341                         if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5342                                 break;
5343
5344                         if (!copy_start)
5345                                 copy_start = rec;
5346                         copy_end = rec + ext_info->rec_size;
5347                 }
5348
5349                 if (!copy_start)
5350                         return -ENOENT;
5351
5352                 /* append func/line info of a given (sub-)program to the main
5353                  * program func/line info
5354                  */
5355                 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5356                 new_sz = old_sz + (copy_end - copy_start);
5357                 new_prog_info = realloc(*prog_info, new_sz);
5358                 if (!new_prog_info)
5359                         return -ENOMEM;
5360                 *prog_info = new_prog_info;
5361                 *prog_rec_cnt = new_sz / ext_info->rec_size;
5362                 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5363
5364                 /* Kernel instruction offsets are in units of 8-byte
5365                  * instructions, while .BTF.ext instruction offsets generated
5366                  * by Clang are in units of bytes. So convert Clang offsets
5367                  * into kernel offsets and adjust offset according to program
5368                  * relocated position.
5369                  */
5370                 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5371                 rec = new_prog_info + old_sz;
5372                 rec_end = new_prog_info + new_sz;
5373                 for (; rec < rec_end; rec += ext_info->rec_size) {
5374                         __u32 *insn_off = rec;
5375
5376                         *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5377                 }
5378                 *prog_rec_sz = ext_info->rec_size;
5379                 return 0;
5380         }
5381
5382         return -ENOENT;
5383 }
5384
5385 static int
5386 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5387                               struct bpf_program *main_prog,
5388                               const struct bpf_program *prog)
5389 {
5390         int err;
5391
5392         /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5393          * supprot func/line info
5394          */
5395         if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5396                 return 0;
5397
5398         /* only attempt func info relocation if main program's func_info
5399          * relocation was successful
5400          */
5401         if (main_prog != prog && !main_prog->func_info)
5402                 goto line_info;
5403
5404         err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5405                                        &main_prog->func_info,
5406                                        &main_prog->func_info_cnt,
5407                                        &main_prog->func_info_rec_size);
5408         if (err) {
5409                 if (err != -ENOENT) {
5410                         pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5411                                 prog->name, err);
5412                         return err;
5413                 }
5414                 if (main_prog->func_info) {
5415                         /*
5416                          * Some info has already been found but has problem
5417                          * in the last btf_ext reloc. Must have to error out.
5418                          */
5419                         pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5420                         return err;
5421                 }
5422                 /* Have problem loading the very first info. Ignore the rest. */
5423                 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5424                         prog->name);
5425         }
5426
5427 line_info:
5428         /* don't relocate line info if main program's relocation failed */
5429         if (main_prog != prog && !main_prog->line_info)
5430                 return 0;
5431
5432         err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5433                                        &main_prog->line_info,
5434                                        &main_prog->line_info_cnt,
5435                                        &main_prog->line_info_rec_size);
5436         if (err) {
5437                 if (err != -ENOENT) {
5438                         pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5439                                 prog->name, err);
5440                         return err;
5441                 }
5442                 if (main_prog->line_info) {
5443                         /*
5444                          * Some info has already been found but has problem
5445                          * in the last btf_ext reloc. Must have to error out.
5446                          */
5447                         pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5448                         return err;
5449                 }
5450                 /* Have problem loading the very first info. Ignore the rest. */
5451                 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5452                         prog->name);
5453         }
5454         return 0;
5455 }
5456
5457 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5458 {
5459         size_t insn_idx = *(const size_t *)key;
5460         const struct reloc_desc *relo = elem;
5461
5462         if (insn_idx == relo->insn_idx)
5463                 return 0;
5464         return insn_idx < relo->insn_idx ? -1 : 1;
5465 }
5466
5467 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5468 {
5469         return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5470                        sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5471 }
5472
5473 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5474 {
5475         int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5476         struct reloc_desc *relos;
5477         int i;
5478
5479         if (main_prog == subprog)
5480                 return 0;
5481         relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5482         if (!relos)
5483                 return -ENOMEM;
5484         memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5485                sizeof(*relos) * subprog->nr_reloc);
5486
5487         for (i = main_prog->nr_reloc; i < new_cnt; i++)
5488                 relos[i].insn_idx += subprog->sub_insn_off;
5489         /* After insn_idx adjustment the 'relos' array is still sorted
5490          * by insn_idx and doesn't break bsearch.
5491          */
5492         main_prog->reloc_desc = relos;
5493         main_prog->nr_reloc = new_cnt;
5494         return 0;
5495 }
5496
5497 static int
5498 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5499                        struct bpf_program *prog)
5500 {
5501         size_t sub_insn_idx, insn_idx, new_cnt;
5502         struct bpf_program *subprog;
5503         struct bpf_insn *insns, *insn;
5504         struct reloc_desc *relo;
5505         int err;
5506
5507         err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5508         if (err)
5509                 return err;
5510
5511         for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
5512                 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5513                 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
5514                         continue;
5515
5516                 relo = find_prog_insn_relo(prog, insn_idx);
5517                 if (relo && relo->type == RELO_EXTERN_FUNC)
5518                         /* kfunc relocations will be handled later
5519                          * in bpf_object__relocate_data()
5520                          */
5521                         continue;
5522                 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
5523                         pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
5524                                 prog->name, insn_idx, relo->type);
5525                         return -LIBBPF_ERRNO__RELOC;
5526                 }
5527                 if (relo) {
5528                         /* sub-program instruction index is a combination of
5529                          * an offset of a symbol pointed to by relocation and
5530                          * call instruction's imm field; for global functions,
5531                          * call always has imm = -1, but for static functions
5532                          * relocation is against STT_SECTION and insn->imm
5533                          * points to a start of a static function
5534                          *
5535                          * for subprog addr relocation, the relo->sym_off + insn->imm is
5536                          * the byte offset in the corresponding section.
5537                          */
5538                         if (relo->type == RELO_CALL)
5539                                 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
5540                         else
5541                                 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
5542                 } else if (insn_is_pseudo_func(insn)) {
5543                         /*
5544                          * RELO_SUBPROG_ADDR relo is always emitted even if both
5545                          * functions are in the same section, so it shouldn't reach here.
5546                          */
5547                         pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
5548                                 prog->name, insn_idx);
5549                         return -LIBBPF_ERRNO__RELOC;
5550                 } else {
5551                         /* if subprogram call is to a static function within
5552                          * the same ELF section, there won't be any relocation
5553                          * emitted, but it also means there is no additional
5554                          * offset necessary, insns->imm is relative to
5555                          * instruction's original position within the section
5556                          */
5557                         sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
5558                 }
5559
5560                 /* we enforce that sub-programs should be in .text section */
5561                 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
5562                 if (!subprog) {
5563                         pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
5564                                 prog->name);
5565                         return -LIBBPF_ERRNO__RELOC;
5566                 }
5567
5568                 /* if it's the first call instruction calling into this
5569                  * subprogram (meaning this subprog hasn't been processed
5570                  * yet) within the context of current main program:
5571                  *   - append it at the end of main program's instructions blog;
5572                  *   - process is recursively, while current program is put on hold;
5573                  *   - if that subprogram calls some other not yet processes
5574                  *   subprogram, same thing will happen recursively until
5575                  *   there are no more unprocesses subprograms left to append
5576                  *   and relocate.
5577                  */
5578                 if (subprog->sub_insn_off == 0) {
5579                         subprog->sub_insn_off = main_prog->insns_cnt;
5580
5581                         new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
5582                         insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
5583                         if (!insns) {
5584                                 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
5585                                 return -ENOMEM;
5586                         }
5587                         main_prog->insns = insns;
5588                         main_prog->insns_cnt = new_cnt;
5589
5590                         memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
5591                                subprog->insns_cnt * sizeof(*insns));
5592
5593                         pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
5594                                  main_prog->name, subprog->insns_cnt, subprog->name);
5595
5596                         /* The subprog insns are now appended. Append its relos too. */
5597                         err = append_subprog_relos(main_prog, subprog);
5598                         if (err)
5599                                 return err;
5600                         err = bpf_object__reloc_code(obj, main_prog, subprog);
5601                         if (err)
5602                                 return err;
5603                 }
5604
5605                 /* main_prog->insns memory could have been re-allocated, so
5606                  * calculate pointer again
5607                  */
5608                 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
5609                 /* calculate correct instruction position within current main
5610                  * prog; each main prog can have a different set of
5611                  * subprograms appended (potentially in different order as
5612                  * well), so position of any subprog can be different for
5613                  * different main programs */
5614                 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
5615
5616                 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
5617                          prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
5618         }
5619
5620         return 0;
5621 }
5622
5623 /*
5624  * Relocate sub-program calls.
5625  *
5626  * Algorithm operates as follows. Each entry-point BPF program (referred to as
5627  * main prog) is processed separately. For each subprog (non-entry functions,
5628  * that can be called from either entry progs or other subprogs) gets their
5629  * sub_insn_off reset to zero. This serves as indicator that this subprogram
5630  * hasn't been yet appended and relocated within current main prog. Once its
5631  * relocated, sub_insn_off will point at the position within current main prog
5632  * where given subprog was appended. This will further be used to relocate all
5633  * the call instructions jumping into this subprog.
5634  *
5635  * We start with main program and process all call instructions. If the call
5636  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
5637  * is zero), subprog instructions are appended at the end of main program's
5638  * instruction array. Then main program is "put on hold" while we recursively
5639  * process newly appended subprogram. If that subprogram calls into another
5640  * subprogram that hasn't been appended, new subprogram is appended again to
5641  * the *main* prog's instructions (subprog's instructions are always left
5642  * untouched, as they need to be in unmodified state for subsequent main progs
5643  * and subprog instructions are always sent only as part of a main prog) and
5644  * the process continues recursively. Once all the subprogs called from a main
5645  * prog or any of its subprogs are appended (and relocated), all their
5646  * positions within finalized instructions array are known, so it's easy to
5647  * rewrite call instructions with correct relative offsets, corresponding to
5648  * desired target subprog.
5649  *
5650  * Its important to realize that some subprogs might not be called from some
5651  * main prog and any of its called/used subprogs. Those will keep their
5652  * subprog->sub_insn_off as zero at all times and won't be appended to current
5653  * main prog and won't be relocated within the context of current main prog.
5654  * They might still be used from other main progs later.
5655  *
5656  * Visually this process can be shown as below. Suppose we have two main
5657  * programs mainA and mainB and BPF object contains three subprogs: subA,
5658  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
5659  * subC both call subB:
5660  *
5661  *        +--------+ +-------+
5662  *        |        v v       |
5663  *     +--+---+ +--+-+-+ +---+--+
5664  *     | subA | | subB | | subC |
5665  *     +--+---+ +------+ +---+--+
5666  *        ^                  ^
5667  *        |                  |
5668  *    +---+-------+   +------+----+
5669  *    |   mainA   |   |   mainB   |
5670  *    +-----------+   +-----------+
5671  *
5672  * We'll start relocating mainA, will find subA, append it and start
5673  * processing sub A recursively:
5674  *
5675  *    +-----------+------+
5676  *    |   mainA   | subA |
5677  *    +-----------+------+
5678  *
5679  * At this point we notice that subB is used from subA, so we append it and
5680  * relocate (there are no further subcalls from subB):
5681  *
5682  *    +-----------+------+------+
5683  *    |   mainA   | subA | subB |
5684  *    +-----------+------+------+
5685  *
5686  * At this point, we relocate subA calls, then go one level up and finish with
5687  * relocatin mainA calls. mainA is done.
5688  *
5689  * For mainB process is similar but results in different order. We start with
5690  * mainB and skip subA and subB, as mainB never calls them (at least
5691  * directly), but we see subC is needed, so we append and start processing it:
5692  *
5693  *    +-----------+------+
5694  *    |   mainB   | subC |
5695  *    +-----------+------+
5696  * Now we see subC needs subB, so we go back to it, append and relocate it:
5697  *
5698  *    +-----------+------+------+
5699  *    |   mainB   | subC | subB |
5700  *    +-----------+------+------+
5701  *
5702  * At this point we unwind recursion, relocate calls in subC, then in mainB.
5703  */
5704 static int
5705 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
5706 {
5707         struct bpf_program *subprog;
5708         int i, err;
5709
5710         /* mark all subprogs as not relocated (yet) within the context of
5711          * current main program
5712          */
5713         for (i = 0; i < obj->nr_programs; i++) {
5714                 subprog = &obj->programs[i];
5715                 if (!prog_is_subprog(obj, subprog))
5716                         continue;
5717
5718                 subprog->sub_insn_off = 0;
5719         }
5720
5721         err = bpf_object__reloc_code(obj, prog, prog);
5722         if (err)
5723                 return err;
5724
5725
5726         return 0;
5727 }
5728
5729 static void
5730 bpf_object__free_relocs(struct bpf_object *obj)
5731 {
5732         struct bpf_program *prog;
5733         int i;
5734
5735         /* free up relocation descriptors */
5736         for (i = 0; i < obj->nr_programs; i++) {
5737                 prog = &obj->programs[i];
5738                 zfree(&prog->reloc_desc);
5739                 prog->nr_reloc = 0;
5740         }
5741 }
5742
5743 static int
5744 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
5745 {
5746         struct bpf_program *prog;
5747         size_t i, j;
5748         int err;
5749
5750         if (obj->btf_ext) {
5751                 err = bpf_object__relocate_core(obj, targ_btf_path);
5752                 if (err) {
5753                         pr_warn("failed to perform CO-RE relocations: %d\n",
5754                                 err);
5755                         return err;
5756                 }
5757         }
5758
5759         /* Before relocating calls pre-process relocations and mark
5760          * few ld_imm64 instructions that points to subprogs.
5761          * Otherwise bpf_object__reloc_code() later would have to consider
5762          * all ld_imm64 insns as relocation candidates. That would
5763          * reduce relocation speed, since amount of find_prog_insn_relo()
5764          * would increase and most of them will fail to find a relo.
5765          */
5766         for (i = 0; i < obj->nr_programs; i++) {
5767                 prog = &obj->programs[i];
5768                 for (j = 0; j < prog->nr_reloc; j++) {
5769                         struct reloc_desc *relo = &prog->reloc_desc[j];
5770                         struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5771
5772                         /* mark the insn, so it's recognized by insn_is_pseudo_func() */
5773                         if (relo->type == RELO_SUBPROG_ADDR)
5774                                 insn[0].src_reg = BPF_PSEUDO_FUNC;
5775                 }
5776         }
5777
5778         /* relocate subprogram calls and append used subprograms to main
5779          * programs; each copy of subprogram code needs to be relocated
5780          * differently for each main program, because its code location might
5781          * have changed.
5782          * Append subprog relos to main programs to allow data relos to be
5783          * processed after text is completely relocated.
5784          */
5785         for (i = 0; i < obj->nr_programs; i++) {
5786                 prog = &obj->programs[i];
5787                 /* sub-program's sub-calls are relocated within the context of
5788                  * its main program only
5789                  */
5790                 if (prog_is_subprog(obj, prog))
5791                         continue;
5792
5793                 err = bpf_object__relocate_calls(obj, prog);
5794                 if (err) {
5795                         pr_warn("prog '%s': failed to relocate calls: %d\n",
5796                                 prog->name, err);
5797                         return err;
5798                 }
5799         }
5800         /* Process data relos for main programs */
5801         for (i = 0; i < obj->nr_programs; i++) {
5802                 prog = &obj->programs[i];
5803                 if (prog_is_subprog(obj, prog))
5804                         continue;
5805                 err = bpf_object__relocate_data(obj, prog);
5806                 if (err) {
5807                         pr_warn("prog '%s': failed to relocate data references: %d\n",
5808                                 prog->name, err);
5809                         return err;
5810                 }
5811         }
5812         if (!obj->gen_loader)
5813                 bpf_object__free_relocs(obj);
5814         return 0;
5815 }
5816
5817 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5818                                             GElf_Shdr *shdr, Elf_Data *data);
5819
5820 static int bpf_object__collect_map_relos(struct bpf_object *obj,
5821                                          GElf_Shdr *shdr, Elf_Data *data)
5822 {
5823         const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
5824         int i, j, nrels, new_sz;
5825         const struct btf_var_secinfo *vi = NULL;
5826         const struct btf_type *sec, *var, *def;
5827         struct bpf_map *map = NULL, *targ_map;
5828         const struct btf_member *member;
5829         const char *name, *mname;
5830         Elf_Data *symbols;
5831         unsigned int moff;
5832         GElf_Sym sym;
5833         GElf_Rel rel;
5834         void *tmp;
5835
5836         if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5837                 return -EINVAL;
5838         sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5839         if (!sec)
5840                 return -EINVAL;
5841
5842         symbols = obj->efile.symbols;
5843         nrels = shdr->sh_size / shdr->sh_entsize;
5844         for (i = 0; i < nrels; i++) {
5845                 if (!gelf_getrel(data, i, &rel)) {
5846                         pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5847                         return -LIBBPF_ERRNO__FORMAT;
5848                 }
5849                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5850                         pr_warn(".maps relo #%d: symbol %zx not found\n",
5851                                 i, (size_t)GELF_R_SYM(rel.r_info));
5852                         return -LIBBPF_ERRNO__FORMAT;
5853                 }
5854                 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
5855                 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5856                         pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5857                                 i, name);
5858                         return -LIBBPF_ERRNO__RELOC;
5859                 }
5860
5861                 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5862                          i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5863                          (size_t)rel.r_offset, sym.st_name, name);
5864
5865                 for (j = 0; j < obj->nr_maps; j++) {
5866                         map = &obj->maps[j];
5867                         if (map->sec_idx != obj->efile.btf_maps_shndx)
5868                                 continue;
5869
5870                         vi = btf_var_secinfos(sec) + map->btf_var_idx;
5871                         if (vi->offset <= rel.r_offset &&
5872                             rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size)
5873                                 break;
5874                 }
5875                 if (j == obj->nr_maps) {
5876                         pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5877                                 i, name, (size_t)rel.r_offset);
5878                         return -EINVAL;
5879                 }
5880
5881                 if (!bpf_map_type__is_map_in_map(map->def.type))
5882                         return -EINVAL;
5883                 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5884                     map->def.key_size != sizeof(int)) {
5885                         pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5886                                 i, map->name, sizeof(int));
5887                         return -EINVAL;
5888                 }
5889
5890                 targ_map = bpf_object__find_map_by_name(obj, name);
5891                 if (!targ_map)
5892                         return -ESRCH;
5893
5894                 var = btf__type_by_id(obj->btf, vi->type);
5895                 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5896                 if (btf_vlen(def) == 0)
5897                         return -EINVAL;
5898                 member = btf_members(def) + btf_vlen(def) - 1;
5899                 mname = btf__name_by_offset(obj->btf, member->name_off);
5900                 if (strcmp(mname, "values"))
5901                         return -EINVAL;
5902
5903                 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5904                 if (rel.r_offset - vi->offset < moff)
5905                         return -EINVAL;
5906
5907                 moff = rel.r_offset - vi->offset - moff;
5908                 /* here we use BPF pointer size, which is always 64 bit, as we
5909                  * are parsing ELF that was built for BPF target
5910                  */
5911                 if (moff % bpf_ptr_sz)
5912                         return -EINVAL;
5913                 moff /= bpf_ptr_sz;
5914                 if (moff >= map->init_slots_sz) {
5915                         new_sz = moff + 1;
5916                         tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
5917                         if (!tmp)
5918                                 return -ENOMEM;
5919                         map->init_slots = tmp;
5920                         memset(map->init_slots + map->init_slots_sz, 0,
5921                                (new_sz - map->init_slots_sz) * host_ptr_sz);
5922                         map->init_slots_sz = new_sz;
5923                 }
5924                 map->init_slots[moff] = targ_map;
5925
5926                 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
5927                          i, map->name, moff, name);
5928         }
5929
5930         return 0;
5931 }
5932
5933 static int cmp_relocs(const void *_a, const void *_b)
5934 {
5935         const struct reloc_desc *a = _a;
5936         const struct reloc_desc *b = _b;
5937
5938         if (a->insn_idx != b->insn_idx)
5939                 return a->insn_idx < b->insn_idx ? -1 : 1;
5940
5941         /* no two relocations should have the same insn_idx, but ... */
5942         if (a->type != b->type)
5943                 return a->type < b->type ? -1 : 1;
5944
5945         return 0;
5946 }
5947
5948 static int bpf_object__collect_relos(struct bpf_object *obj)
5949 {
5950         int i, err;
5951
5952         for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
5953                 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
5954                 Elf_Data *data = obj->efile.reloc_sects[i].data;
5955                 int idx = shdr->sh_info;
5956
5957                 if (shdr->sh_type != SHT_REL) {
5958                         pr_warn("internal error at %d\n", __LINE__);
5959                         return -LIBBPF_ERRNO__INTERNAL;
5960                 }
5961
5962                 if (idx == obj->efile.st_ops_shndx)
5963                         err = bpf_object__collect_st_ops_relos(obj, shdr, data);
5964                 else if (idx == obj->efile.btf_maps_shndx)
5965                         err = bpf_object__collect_map_relos(obj, shdr, data);
5966                 else
5967                         err = bpf_object__collect_prog_relos(obj, shdr, data);
5968                 if (err)
5969                         return err;
5970         }
5971
5972         for (i = 0; i < obj->nr_programs; i++) {
5973                 struct bpf_program *p = &obj->programs[i];
5974
5975                 if (!p->nr_reloc)
5976                         continue;
5977
5978                 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
5979         }
5980         return 0;
5981 }
5982
5983 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
5984 {
5985         if (BPF_CLASS(insn->code) == BPF_JMP &&
5986             BPF_OP(insn->code) == BPF_CALL &&
5987             BPF_SRC(insn->code) == BPF_K &&
5988             insn->src_reg == 0 &&
5989             insn->dst_reg == 0) {
5990                     *func_id = insn->imm;
5991                     return true;
5992         }
5993         return false;
5994 }
5995
5996 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
5997 {
5998         struct bpf_insn *insn = prog->insns;
5999         enum bpf_func_id func_id;
6000         int i;
6001
6002         if (obj->gen_loader)
6003                 return 0;
6004
6005         for (i = 0; i < prog->insns_cnt; i++, insn++) {
6006                 if (!insn_is_helper_call(insn, &func_id))
6007                         continue;
6008
6009                 /* on kernels that don't yet support
6010                  * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6011                  * to bpf_probe_read() which works well for old kernels
6012                  */
6013                 switch (func_id) {
6014                 case BPF_FUNC_probe_read_kernel:
6015                 case BPF_FUNC_probe_read_user:
6016                         if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6017                                 insn->imm = BPF_FUNC_probe_read;
6018                         break;
6019                 case BPF_FUNC_probe_read_kernel_str:
6020                 case BPF_FUNC_probe_read_user_str:
6021                         if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6022                                 insn->imm = BPF_FUNC_probe_read_str;
6023                         break;
6024                 default:
6025                         break;
6026                 }
6027         }
6028         return 0;
6029 }
6030
6031 static int
6032 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
6033              char *license, __u32 kern_version, int *pfd)
6034 {
6035         struct bpf_prog_load_params load_attr = {};
6036         char *cp, errmsg[STRERR_BUFSIZE];
6037         size_t log_buf_size = 0;
6038         char *log_buf = NULL;
6039         int btf_fd, ret;
6040
6041         if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6042                 /*
6043                  * The program type must be set.  Most likely we couldn't find a proper
6044                  * section definition at load time, and thus we didn't infer the type.
6045                  */
6046                 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6047                         prog->name, prog->sec_name);
6048                 return -EINVAL;
6049         }
6050
6051         if (!insns || !insns_cnt)
6052                 return -EINVAL;
6053
6054         load_attr.prog_type = prog->type;
6055         /* old kernels might not support specifying expected_attach_type */
6056         if (!kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE) && prog->sec_def &&
6057             prog->sec_def->is_exp_attach_type_optional)
6058                 load_attr.expected_attach_type = 0;
6059         else
6060                 load_attr.expected_attach_type = prog->expected_attach_type;
6061         if (kernel_supports(prog->obj, FEAT_PROG_NAME))
6062                 load_attr.name = prog->name;
6063         load_attr.insns = insns;
6064         load_attr.insn_cnt = insns_cnt;
6065         load_attr.license = license;
6066         load_attr.attach_btf_id = prog->attach_btf_id;
6067         if (prog->attach_prog_fd)
6068                 load_attr.attach_prog_fd = prog->attach_prog_fd;
6069         else
6070                 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6071         load_attr.attach_btf_id = prog->attach_btf_id;
6072         load_attr.kern_version = kern_version;
6073         load_attr.prog_ifindex = prog->prog_ifindex;
6074
6075         /* specify func_info/line_info only if kernel supports them */
6076         btf_fd = bpf_object__btf_fd(prog->obj);
6077         if (btf_fd >= 0 && kernel_supports(prog->obj, FEAT_BTF_FUNC)) {
6078                 load_attr.prog_btf_fd = btf_fd;
6079                 load_attr.func_info = prog->func_info;
6080                 load_attr.func_info_rec_size = prog->func_info_rec_size;
6081                 load_attr.func_info_cnt = prog->func_info_cnt;
6082                 load_attr.line_info = prog->line_info;
6083                 load_attr.line_info_rec_size = prog->line_info_rec_size;
6084                 load_attr.line_info_cnt = prog->line_info_cnt;
6085         }
6086         load_attr.log_level = prog->log_level;
6087         load_attr.prog_flags = prog->prog_flags;
6088
6089         if (prog->obj->gen_loader) {
6090                 bpf_gen__prog_load(prog->obj->gen_loader, &load_attr,
6091                                    prog - prog->obj->programs);
6092                 *pfd = -1;
6093                 return 0;
6094         }
6095 retry_load:
6096         if (log_buf_size) {
6097                 log_buf = malloc(log_buf_size);
6098                 if (!log_buf)
6099                         return -ENOMEM;
6100
6101                 *log_buf = 0;
6102         }
6103
6104         load_attr.log_buf = log_buf;
6105         load_attr.log_buf_sz = log_buf_size;
6106         ret = libbpf__bpf_prog_load(&load_attr);
6107
6108         if (ret >= 0) {
6109                 if (log_buf && load_attr.log_level)
6110                         pr_debug("verifier log:\n%s", log_buf);
6111
6112                 if (prog->obj->rodata_map_idx >= 0 &&
6113                     kernel_supports(prog->obj, FEAT_PROG_BIND_MAP)) {
6114                         struct bpf_map *rodata_map =
6115                                 &prog->obj->maps[prog->obj->rodata_map_idx];
6116
6117                         if (bpf_prog_bind_map(ret, bpf_map__fd(rodata_map), NULL)) {
6118                                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6119                                 pr_warn("prog '%s': failed to bind .rodata map: %s\n",
6120                                         prog->name, cp);
6121                                 /* Don't fail hard if can't bind rodata. */
6122                         }
6123                 }
6124
6125                 *pfd = ret;
6126                 ret = 0;
6127                 goto out;
6128         }
6129
6130         if (!log_buf || errno == ENOSPC) {
6131                 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
6132                                    log_buf_size << 1);
6133
6134                 free(log_buf);
6135                 goto retry_load;
6136         }
6137         ret = errno ? -errno : -LIBBPF_ERRNO__LOAD;
6138         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6139         pr_warn("load bpf program failed: %s\n", cp);
6140         pr_perm_msg(ret);
6141
6142         if (log_buf && log_buf[0] != '\0') {
6143                 ret = -LIBBPF_ERRNO__VERIFY;
6144                 pr_warn("-- BEGIN DUMP LOG ---\n");
6145                 pr_warn("\n%s\n", log_buf);
6146                 pr_warn("-- END LOG --\n");
6147         } else if (load_attr.insn_cnt >= BPF_MAXINSNS) {
6148                 pr_warn("Program too large (%zu insns), at most %d insns\n",
6149                         load_attr.insn_cnt, BPF_MAXINSNS);
6150                 ret = -LIBBPF_ERRNO__PROG2BIG;
6151         } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
6152                 /* Wrong program type? */
6153                 int fd;
6154
6155                 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
6156                 load_attr.expected_attach_type = 0;
6157                 load_attr.log_buf = NULL;
6158                 load_attr.log_buf_sz = 0;
6159                 fd = libbpf__bpf_prog_load(&load_attr);
6160                 if (fd >= 0) {
6161                         close(fd);
6162                         ret = -LIBBPF_ERRNO__PROGTYPE;
6163                         goto out;
6164                 }
6165         }
6166
6167 out:
6168         free(log_buf);
6169         return ret;
6170 }
6171
6172 static int bpf_program__record_externs(struct bpf_program *prog)
6173 {
6174         struct bpf_object *obj = prog->obj;
6175         int i;
6176
6177         for (i = 0; i < prog->nr_reloc; i++) {
6178                 struct reloc_desc *relo = &prog->reloc_desc[i];
6179                 struct extern_desc *ext = &obj->externs[relo->sym_off];
6180
6181                 switch (relo->type) {
6182                 case RELO_EXTERN_VAR:
6183                         if (ext->type != EXT_KSYM)
6184                                 continue;
6185                         if (!ext->ksym.type_id) {
6186                                 pr_warn("typeless ksym %s is not supported yet\n",
6187                                         ext->name);
6188                                 return -ENOTSUP;
6189                         }
6190                         bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_VAR,
6191                                                relo->insn_idx);
6192                         break;
6193                 case RELO_EXTERN_FUNC:
6194                         bpf_gen__record_extern(obj->gen_loader, ext->name, BTF_KIND_FUNC,
6195                                                relo->insn_idx);
6196                         break;
6197                 default:
6198                         continue;
6199                 }
6200         }
6201         return 0;
6202 }
6203
6204 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id);
6205
6206 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
6207 {
6208         int err = 0, fd, i;
6209
6210         if (prog->obj->loaded) {
6211                 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
6212                 return libbpf_err(-EINVAL);
6213         }
6214
6215         if ((prog->type == BPF_PROG_TYPE_TRACING ||
6216              prog->type == BPF_PROG_TYPE_LSM ||
6217              prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6218                 int btf_obj_fd = 0, btf_type_id = 0;
6219
6220                 err = libbpf_find_attach_btf_id(prog, &btf_obj_fd, &btf_type_id);
6221                 if (err)
6222                         return libbpf_err(err);
6223
6224                 prog->attach_btf_obj_fd = btf_obj_fd;
6225                 prog->attach_btf_id = btf_type_id;
6226         }
6227
6228         if (prog->instances.nr < 0 || !prog->instances.fds) {
6229                 if (prog->preprocessor) {
6230                         pr_warn("Internal error: can't load program '%s'\n",
6231                                 prog->name);
6232                         return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
6233                 }
6234
6235                 prog->instances.fds = malloc(sizeof(int));
6236                 if (!prog->instances.fds) {
6237                         pr_warn("Not enough memory for BPF fds\n");
6238                         return libbpf_err(-ENOMEM);
6239                 }
6240                 prog->instances.nr = 1;
6241                 prog->instances.fds[0] = -1;
6242         }
6243
6244         if (!prog->preprocessor) {
6245                 if (prog->instances.nr != 1) {
6246                         pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6247                                 prog->name, prog->instances.nr);
6248                 }
6249                 if (prog->obj->gen_loader)
6250                         bpf_program__record_externs(prog);
6251                 err = load_program(prog, prog->insns, prog->insns_cnt,
6252                                    license, kern_ver, &fd);
6253                 if (!err)
6254                         prog->instances.fds[0] = fd;
6255                 goto out;
6256         }
6257
6258         for (i = 0; i < prog->instances.nr; i++) {
6259                 struct bpf_prog_prep_result result;
6260                 bpf_program_prep_t preprocessor = prog->preprocessor;
6261
6262                 memset(&result, 0, sizeof(result));
6263                 err = preprocessor(prog, i, prog->insns,
6264                                    prog->insns_cnt, &result);
6265                 if (err) {
6266                         pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
6267                                 i, prog->name);
6268                         goto out;
6269                 }
6270
6271                 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6272                         pr_debug("Skip loading the %dth instance of program '%s'\n",
6273                                  i, prog->name);
6274                         prog->instances.fds[i] = -1;
6275                         if (result.pfd)
6276                                 *result.pfd = -1;
6277                         continue;
6278                 }
6279
6280                 err = load_program(prog, result.new_insn_ptr,
6281                                    result.new_insn_cnt, license, kern_ver, &fd);
6282                 if (err) {
6283                         pr_warn("Loading the %dth instance of program '%s' failed\n",
6284                                 i, prog->name);
6285                         goto out;
6286                 }
6287
6288                 if (result.pfd)
6289                         *result.pfd = fd;
6290                 prog->instances.fds[i] = fd;
6291         }
6292 out:
6293         if (err)
6294                 pr_warn("failed to load program '%s'\n", prog->name);
6295         zfree(&prog->insns);
6296         prog->insns_cnt = 0;
6297         return libbpf_err(err);
6298 }
6299
6300 static int
6301 bpf_object__load_progs(struct bpf_object *obj, int log_level)
6302 {
6303         struct bpf_program *prog;
6304         size_t i;
6305         int err;
6306
6307         for (i = 0; i < obj->nr_programs; i++) {
6308                 prog = &obj->programs[i];
6309                 err = bpf_object__sanitize_prog(obj, prog);
6310                 if (err)
6311                         return err;
6312         }
6313
6314         for (i = 0; i < obj->nr_programs; i++) {
6315                 prog = &obj->programs[i];
6316                 if (prog_is_subprog(obj, prog))
6317                         continue;
6318                 if (!prog->load) {
6319                         pr_debug("prog '%s': skipped loading\n", prog->name);
6320                         continue;
6321                 }
6322                 prog->log_level |= log_level;
6323                 err = bpf_program__load(prog, obj->license, obj->kern_version);
6324                 if (err)
6325                         return err;
6326         }
6327         if (obj->gen_loader)
6328                 bpf_object__free_relocs(obj);
6329         return 0;
6330 }
6331
6332 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6333
6334 static struct bpf_object *
6335 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6336                    const struct bpf_object_open_opts *opts)
6337 {
6338         const char *obj_name, *kconfig, *btf_tmp_path;
6339         struct bpf_program *prog;
6340         struct bpf_object *obj;
6341         char tmp_name[64];
6342         int err;
6343
6344         if (elf_version(EV_CURRENT) == EV_NONE) {
6345                 pr_warn("failed to init libelf for %s\n",
6346                         path ? : "(mem buf)");
6347                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
6348         }
6349
6350         if (!OPTS_VALID(opts, bpf_object_open_opts))
6351                 return ERR_PTR(-EINVAL);
6352
6353         obj_name = OPTS_GET(opts, object_name, NULL);
6354         if (obj_buf) {
6355                 if (!obj_name) {
6356                         snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6357                                  (unsigned long)obj_buf,
6358                                  (unsigned long)obj_buf_sz);
6359                         obj_name = tmp_name;
6360                 }
6361                 path = obj_name;
6362                 pr_debug("loading object '%s' from buffer\n", obj_name);
6363         }
6364
6365         obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
6366         if (IS_ERR(obj))
6367                 return obj;
6368
6369         btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
6370         if (btf_tmp_path) {
6371                 if (strlen(btf_tmp_path) >= PATH_MAX) {
6372                         err = -ENAMETOOLONG;
6373                         goto out;
6374                 }
6375                 obj->btf_custom_path = strdup(btf_tmp_path);
6376                 if (!obj->btf_custom_path) {
6377                         err = -ENOMEM;
6378                         goto out;
6379                 }
6380         }
6381
6382         kconfig = OPTS_GET(opts, kconfig, NULL);
6383         if (kconfig) {
6384                 obj->kconfig = strdup(kconfig);
6385                 if (!obj->kconfig) {
6386                         err = -ENOMEM;
6387                         goto out;
6388                 }
6389         }
6390
6391         err = bpf_object__elf_init(obj);
6392         err = err ? : bpf_object__check_endianness(obj);
6393         err = err ? : bpf_object__elf_collect(obj);
6394         err = err ? : bpf_object__collect_externs(obj);
6395         err = err ? : bpf_object__finalize_btf(obj);
6396         err = err ? : bpf_object__init_maps(obj, opts);
6397         err = err ? : bpf_object__collect_relos(obj);
6398         if (err)
6399                 goto out;
6400         bpf_object__elf_finish(obj);
6401
6402         bpf_object__for_each_program(prog, obj) {
6403                 prog->sec_def = find_sec_def(prog->sec_name);
6404                 if (!prog->sec_def) {
6405                         /* couldn't guess, but user might manually specify */
6406                         pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6407                                 prog->name, prog->sec_name);
6408                         continue;
6409                 }
6410
6411                 if (prog->sec_def->is_sleepable)
6412                         prog->prog_flags |= BPF_F_SLEEPABLE;
6413                 bpf_program__set_type(prog, prog->sec_def->prog_type);
6414                 bpf_program__set_expected_attach_type(prog,
6415                                 prog->sec_def->expected_attach_type);
6416
6417                 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6418                     prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6419                         prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
6420         }
6421
6422         return obj;
6423 out:
6424         bpf_object__close(obj);
6425         return ERR_PTR(err);
6426 }
6427
6428 static struct bpf_object *
6429 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
6430 {
6431         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6432                 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
6433         );
6434
6435         /* param validation */
6436         if (!attr->file)
6437                 return NULL;
6438
6439         pr_debug("loading %s\n", attr->file);
6440         return __bpf_object__open(attr->file, NULL, 0, &opts);
6441 }
6442
6443 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
6444 {
6445         return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
6446 }
6447
6448 struct bpf_object *bpf_object__open(const char *path)
6449 {
6450         struct bpf_object_open_attr attr = {
6451                 .file           = path,
6452                 .prog_type      = BPF_PROG_TYPE_UNSPEC,
6453         };
6454
6455         return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
6456 }
6457
6458 struct bpf_object *
6459 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
6460 {
6461         if (!path)
6462                 return libbpf_err_ptr(-EINVAL);
6463
6464         pr_debug("loading %s\n", path);
6465
6466         return libbpf_ptr(__bpf_object__open(path, NULL, 0, opts));
6467 }
6468
6469 struct bpf_object *
6470 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
6471                      const struct bpf_object_open_opts *opts)
6472 {
6473         if (!obj_buf || obj_buf_sz == 0)
6474                 return libbpf_err_ptr(-EINVAL);
6475
6476         return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, opts));
6477 }
6478
6479 struct bpf_object *
6480 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
6481                         const char *name)
6482 {
6483         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
6484                 .object_name = name,
6485                 /* wrong default, but backwards-compatible */
6486                 .relaxed_maps = true,
6487         );
6488
6489         /* returning NULL is wrong, but backwards-compatible */
6490         if (!obj_buf || obj_buf_sz == 0)
6491                 return errno = EINVAL, NULL;
6492
6493         return libbpf_ptr(__bpf_object__open(NULL, obj_buf, obj_buf_sz, &opts));
6494 }
6495
6496 int bpf_object__unload(struct bpf_object *obj)
6497 {
6498         size_t i;
6499
6500         if (!obj)
6501                 return libbpf_err(-EINVAL);
6502
6503         for (i = 0; i < obj->nr_maps; i++) {
6504                 zclose(obj->maps[i].fd);
6505                 if (obj->maps[i].st_ops)
6506                         zfree(&obj->maps[i].st_ops->kern_vdata);
6507         }
6508
6509         for (i = 0; i < obj->nr_programs; i++)
6510                 bpf_program__unload(&obj->programs[i]);
6511
6512         return 0;
6513 }
6514
6515 static int bpf_object__sanitize_maps(struct bpf_object *obj)
6516 {
6517         struct bpf_map *m;
6518
6519         bpf_object__for_each_map(m, obj) {
6520                 if (!bpf_map__is_internal(m))
6521                         continue;
6522                 if (!kernel_supports(obj, FEAT_GLOBAL_DATA)) {
6523                         pr_warn("kernel doesn't support global data\n");
6524                         return -ENOTSUP;
6525                 }
6526                 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
6527                         m->def.map_flags ^= BPF_F_MMAPABLE;
6528         }
6529
6530         return 0;
6531 }
6532
6533 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
6534 {
6535         char sym_type, sym_name[500];
6536         unsigned long long sym_addr;
6537         const struct btf_type *t;
6538         struct extern_desc *ext;
6539         int ret, err = 0;
6540         FILE *f;
6541
6542         f = fopen("/proc/kallsyms", "r");
6543         if (!f) {
6544                 err = -errno;
6545                 pr_warn("failed to open /proc/kallsyms: %d\n", err);
6546                 return err;
6547         }
6548
6549         while (true) {
6550                 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
6551                              &sym_addr, &sym_type, sym_name);
6552                 if (ret == EOF && feof(f))
6553                         break;
6554                 if (ret != 3) {
6555                         pr_warn("failed to read kallsyms entry: %d\n", ret);
6556                         err = -EINVAL;
6557                         goto out;
6558                 }
6559
6560                 ext = find_extern_by_name(obj, sym_name);
6561                 if (!ext || ext->type != EXT_KSYM)
6562                         continue;
6563
6564                 t = btf__type_by_id(obj->btf, ext->btf_id);
6565                 if (!btf_is_var(t))
6566                         continue;
6567
6568                 if (ext->is_set && ext->ksym.addr != sym_addr) {
6569                         pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
6570                                 sym_name, ext->ksym.addr, sym_addr);
6571                         err = -EINVAL;
6572                         goto out;
6573                 }
6574                 if (!ext->is_set) {
6575                         ext->is_set = true;
6576                         ext->ksym.addr = sym_addr;
6577                         pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
6578                 }
6579         }
6580
6581 out:
6582         fclose(f);
6583         return err;
6584 }
6585
6586 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
6587                             __u16 kind, struct btf **res_btf,
6588                             int *res_btf_fd)
6589 {
6590         int i, id, btf_fd, err;
6591         struct btf *btf;
6592
6593         btf = obj->btf_vmlinux;
6594         btf_fd = 0;
6595         id = btf__find_by_name_kind(btf, ksym_name, kind);
6596
6597         if (id == -ENOENT) {
6598                 err = load_module_btfs(obj);
6599                 if (err)
6600                         return err;
6601
6602                 for (i = 0; i < obj->btf_module_cnt; i++) {
6603                         btf = obj->btf_modules[i].btf;
6604                         /* we assume module BTF FD is always >0 */
6605                         btf_fd = obj->btf_modules[i].fd;
6606                         id = btf__find_by_name_kind(btf, ksym_name, kind);
6607                         if (id != -ENOENT)
6608                                 break;
6609                 }
6610         }
6611         if (id <= 0) {
6612                 pr_warn("extern (%s ksym) '%s': failed to find BTF ID in kernel BTF(s).\n",
6613                         __btf_kind_str(kind), ksym_name);
6614                 return -ESRCH;
6615         }
6616
6617         *res_btf = btf;
6618         *res_btf_fd = btf_fd;
6619         return id;
6620 }
6621
6622 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
6623                                                struct extern_desc *ext)
6624 {
6625         const struct btf_type *targ_var, *targ_type;
6626         __u32 targ_type_id, local_type_id;
6627         const char *targ_var_name;
6628         int id, btf_fd = 0, err;
6629         struct btf *btf = NULL;
6630
6631         id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &btf_fd);
6632         if (id < 0)
6633                 return id;
6634
6635         /* find local type_id */
6636         local_type_id = ext->ksym.type_id;
6637
6638         /* find target type_id */
6639         targ_var = btf__type_by_id(btf, id);
6640         targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
6641         targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
6642
6643         err = bpf_core_types_are_compat(obj->btf, local_type_id,
6644                                         btf, targ_type_id);
6645         if (err <= 0) {
6646                 const struct btf_type *local_type;
6647                 const char *targ_name, *local_name;
6648
6649                 local_type = btf__type_by_id(obj->btf, local_type_id);
6650                 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
6651                 targ_name = btf__name_by_offset(btf, targ_type->name_off);
6652
6653                 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
6654                         ext->name, local_type_id,
6655                         btf_kind_str(local_type), local_name, targ_type_id,
6656                         btf_kind_str(targ_type), targ_name);
6657                 return -EINVAL;
6658         }
6659
6660         ext->is_set = true;
6661         ext->ksym.kernel_btf_obj_fd = btf_fd;
6662         ext->ksym.kernel_btf_id = id;
6663         pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
6664                  ext->name, id, btf_kind_str(targ_var), targ_var_name);
6665
6666         return 0;
6667 }
6668
6669 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
6670                                                 struct extern_desc *ext)
6671 {
6672         int local_func_proto_id, kfunc_proto_id, kfunc_id;
6673         const struct btf_type *kern_func;
6674         struct btf *kern_btf = NULL;
6675         int ret, kern_btf_fd = 0;
6676
6677         local_func_proto_id = ext->ksym.type_id;
6678
6679         kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC,
6680                                     &kern_btf, &kern_btf_fd);
6681         if (kfunc_id < 0) {
6682                 pr_warn("extern (func ksym) '%s': not found in kernel BTF\n",
6683                         ext->name);
6684                 return kfunc_id;
6685         }
6686
6687         if (kern_btf != obj->btf_vmlinux) {
6688                 pr_warn("extern (func ksym) '%s': function in kernel module is not supported\n",
6689                         ext->name);
6690                 return -ENOTSUP;
6691         }
6692
6693         kern_func = btf__type_by_id(kern_btf, kfunc_id);
6694         kfunc_proto_id = kern_func->type;
6695
6696         ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
6697                                         kern_btf, kfunc_proto_id);
6698         if (ret <= 0) {
6699                 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
6700                         ext->name, local_func_proto_id, kfunc_proto_id);
6701                 return -EINVAL;
6702         }
6703
6704         ext->is_set = true;
6705         ext->ksym.kernel_btf_obj_fd = kern_btf_fd;
6706         ext->ksym.kernel_btf_id = kfunc_id;
6707         pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
6708                  ext->name, kfunc_id);
6709
6710         return 0;
6711 }
6712
6713 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
6714 {
6715         const struct btf_type *t;
6716         struct extern_desc *ext;
6717         int i, err;
6718
6719         for (i = 0; i < obj->nr_extern; i++) {
6720                 ext = &obj->externs[i];
6721                 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
6722                         continue;
6723
6724                 if (obj->gen_loader) {
6725                         ext->is_set = true;
6726                         ext->ksym.kernel_btf_obj_fd = 0;
6727                         ext->ksym.kernel_btf_id = 0;
6728                         continue;
6729                 }
6730                 t = btf__type_by_id(obj->btf, ext->btf_id);
6731                 if (btf_is_var(t))
6732                         err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
6733                 else
6734                         err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
6735                 if (err)
6736                         return err;
6737         }
6738         return 0;
6739 }
6740
6741 static int bpf_object__resolve_externs(struct bpf_object *obj,
6742                                        const char *extra_kconfig)
6743 {
6744         bool need_config = false, need_kallsyms = false;
6745         bool need_vmlinux_btf = false;
6746         struct extern_desc *ext;
6747         void *kcfg_data = NULL;
6748         int err, i;
6749
6750         if (obj->nr_extern == 0)
6751                 return 0;
6752
6753         if (obj->kconfig_map_idx >= 0)
6754                 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
6755
6756         for (i = 0; i < obj->nr_extern; i++) {
6757                 ext = &obj->externs[i];
6758
6759                 if (ext->type == EXT_KCFG &&
6760                     strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
6761                         void *ext_val = kcfg_data + ext->kcfg.data_off;
6762                         __u32 kver = get_kernel_version();
6763
6764                         if (!kver) {
6765                                 pr_warn("failed to get kernel version\n");
6766                                 return -EINVAL;
6767                         }
6768                         err = set_kcfg_value_num(ext, ext_val, kver);
6769                         if (err)
6770                                 return err;
6771                         pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
6772                 } else if (ext->type == EXT_KCFG &&
6773                            strncmp(ext->name, "CONFIG_", 7) == 0) {
6774                         need_config = true;
6775                 } else if (ext->type == EXT_KSYM) {
6776                         if (ext->ksym.type_id)
6777                                 need_vmlinux_btf = true;
6778                         else
6779                                 need_kallsyms = true;
6780                 } else {
6781                         pr_warn("unrecognized extern '%s'\n", ext->name);
6782                         return -EINVAL;
6783                 }
6784         }
6785         if (need_config && extra_kconfig) {
6786                 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
6787                 if (err)
6788                         return -EINVAL;
6789                 need_config = false;
6790                 for (i = 0; i < obj->nr_extern; i++) {
6791                         ext = &obj->externs[i];
6792                         if (ext->type == EXT_KCFG && !ext->is_set) {
6793                                 need_config = true;
6794                                 break;
6795                         }
6796                 }
6797         }
6798         if (need_config) {
6799                 err = bpf_object__read_kconfig_file(obj, kcfg_data);
6800                 if (err)
6801                         return -EINVAL;
6802         }
6803         if (need_kallsyms) {
6804                 err = bpf_object__read_kallsyms_file(obj);
6805                 if (err)
6806                         return -EINVAL;
6807         }
6808         if (need_vmlinux_btf) {
6809                 err = bpf_object__resolve_ksyms_btf_id(obj);
6810                 if (err)
6811                         return -EINVAL;
6812         }
6813         for (i = 0; i < obj->nr_extern; i++) {
6814                 ext = &obj->externs[i];
6815
6816                 if (!ext->is_set && !ext->is_weak) {
6817                         pr_warn("extern %s (strong) not resolved\n", ext->name);
6818                         return -ESRCH;
6819                 } else if (!ext->is_set) {
6820                         pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
6821                                  ext->name);
6822                 }
6823         }
6824
6825         return 0;
6826 }
6827
6828 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
6829 {
6830         struct bpf_object *obj;
6831         int err, i;
6832
6833         if (!attr)
6834                 return libbpf_err(-EINVAL);
6835         obj = attr->obj;
6836         if (!obj)
6837                 return libbpf_err(-EINVAL);
6838
6839         if (obj->loaded) {
6840                 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
6841                 return libbpf_err(-EINVAL);
6842         }
6843
6844         if (obj->gen_loader)
6845                 bpf_gen__init(obj->gen_loader, attr->log_level);
6846
6847         err = bpf_object__probe_loading(obj);
6848         err = err ? : bpf_object__load_vmlinux_btf(obj, false);
6849         err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
6850         err = err ? : bpf_object__sanitize_and_load_btf(obj);
6851         err = err ? : bpf_object__sanitize_maps(obj);
6852         err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
6853         err = err ? : bpf_object__create_maps(obj);
6854         err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : attr->target_btf_path);
6855         err = err ? : bpf_object__load_progs(obj, attr->log_level);
6856
6857         if (obj->gen_loader) {
6858                 /* reset FDs */
6859                 btf__set_fd(obj->btf, -1);
6860                 for (i = 0; i < obj->nr_maps; i++)
6861                         obj->maps[i].fd = -1;
6862                 if (!err)
6863                         err = bpf_gen__finish(obj->gen_loader);
6864         }
6865
6866         /* clean up module BTFs */
6867         for (i = 0; i < obj->btf_module_cnt; i++) {
6868                 close(obj->btf_modules[i].fd);
6869                 btf__free(obj->btf_modules[i].btf);
6870                 free(obj->btf_modules[i].name);
6871         }
6872         free(obj->btf_modules);
6873
6874         /* clean up vmlinux BTF */
6875         btf__free(obj->btf_vmlinux);
6876         obj->btf_vmlinux = NULL;
6877
6878         obj->loaded = true; /* doesn't matter if successfully or not */
6879
6880         if (err)
6881                 goto out;
6882
6883         return 0;
6884 out:
6885         /* unpin any maps that were auto-pinned during load */
6886         for (i = 0; i < obj->nr_maps; i++)
6887                 if (obj->maps[i].pinned && !obj->maps[i].reused)
6888                         bpf_map__unpin(&obj->maps[i], NULL);
6889
6890         bpf_object__unload(obj);
6891         pr_warn("failed to load object '%s'\n", obj->path);
6892         return libbpf_err(err);
6893 }
6894
6895 int bpf_object__load(struct bpf_object *obj)
6896 {
6897         struct bpf_object_load_attr attr = {
6898                 .obj = obj,
6899         };
6900
6901         return bpf_object__load_xattr(&attr);
6902 }
6903
6904 static int make_parent_dir(const char *path)
6905 {
6906         char *cp, errmsg[STRERR_BUFSIZE];
6907         char *dname, *dir;
6908         int err = 0;
6909
6910         dname = strdup(path);
6911         if (dname == NULL)
6912                 return -ENOMEM;
6913
6914         dir = dirname(dname);
6915         if (mkdir(dir, 0700) && errno != EEXIST)
6916                 err = -errno;
6917
6918         free(dname);
6919         if (err) {
6920                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
6921                 pr_warn("failed to mkdir %s: %s\n", path, cp);
6922         }
6923         return err;
6924 }
6925
6926 static int check_path(const char *path)
6927 {
6928         char *cp, errmsg[STRERR_BUFSIZE];
6929         struct statfs st_fs;
6930         char *dname, *dir;
6931         int err = 0;
6932
6933         if (path == NULL)
6934                 return -EINVAL;
6935
6936         dname = strdup(path);
6937         if (dname == NULL)
6938                 return -ENOMEM;
6939
6940         dir = dirname(dname);
6941         if (statfs(dir, &st_fs)) {
6942                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6943                 pr_warn("failed to statfs %s: %s\n", dir, cp);
6944                 err = -errno;
6945         }
6946         free(dname);
6947
6948         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
6949                 pr_warn("specified path %s is not on BPF FS\n", path);
6950                 err = -EINVAL;
6951         }
6952
6953         return err;
6954 }
6955
6956 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
6957                               int instance)
6958 {
6959         char *cp, errmsg[STRERR_BUFSIZE];
6960         int err;
6961
6962         err = make_parent_dir(path);
6963         if (err)
6964                 return libbpf_err(err);
6965
6966         err = check_path(path);
6967         if (err)
6968                 return libbpf_err(err);
6969
6970         if (prog == NULL) {
6971                 pr_warn("invalid program pointer\n");
6972                 return libbpf_err(-EINVAL);
6973         }
6974
6975         if (instance < 0 || instance >= prog->instances.nr) {
6976                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
6977                         instance, prog->name, prog->instances.nr);
6978                 return libbpf_err(-EINVAL);
6979         }
6980
6981         if (bpf_obj_pin(prog->instances.fds[instance], path)) {
6982                 err = -errno;
6983                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
6984                 pr_warn("failed to pin program: %s\n", cp);
6985                 return libbpf_err(err);
6986         }
6987         pr_debug("pinned program '%s'\n", path);
6988
6989         return 0;
6990 }
6991
6992 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
6993                                 int instance)
6994 {
6995         int err;
6996
6997         err = check_path(path);
6998         if (err)
6999                 return libbpf_err(err);
7000
7001         if (prog == NULL) {
7002                 pr_warn("invalid program pointer\n");
7003                 return libbpf_err(-EINVAL);
7004         }
7005
7006         if (instance < 0 || instance >= prog->instances.nr) {
7007                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7008                         instance, prog->name, prog->instances.nr);
7009                 return libbpf_err(-EINVAL);
7010         }
7011
7012         err = unlink(path);
7013         if (err != 0)
7014                 return libbpf_err(-errno);
7015
7016         pr_debug("unpinned program '%s'\n", path);
7017
7018         return 0;
7019 }
7020
7021 int bpf_program__pin(struct bpf_program *prog, const char *path)
7022 {
7023         int i, err;
7024
7025         err = make_parent_dir(path);
7026         if (err)
7027                 return libbpf_err(err);
7028
7029         err = check_path(path);
7030         if (err)
7031                 return libbpf_err(err);
7032
7033         if (prog == NULL) {
7034                 pr_warn("invalid program pointer\n");
7035                 return libbpf_err(-EINVAL);
7036         }
7037
7038         if (prog->instances.nr <= 0) {
7039                 pr_warn("no instances of prog %s to pin\n", prog->name);
7040                 return libbpf_err(-EINVAL);
7041         }
7042
7043         if (prog->instances.nr == 1) {
7044                 /* don't create subdirs when pinning single instance */
7045                 return bpf_program__pin_instance(prog, path, 0);
7046         }
7047
7048         for (i = 0; i < prog->instances.nr; i++) {
7049                 char buf[PATH_MAX];
7050                 int len;
7051
7052                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7053                 if (len < 0) {
7054                         err = -EINVAL;
7055                         goto err_unpin;
7056                 } else if (len >= PATH_MAX) {
7057                         err = -ENAMETOOLONG;
7058                         goto err_unpin;
7059                 }
7060
7061                 err = bpf_program__pin_instance(prog, buf, i);
7062                 if (err)
7063                         goto err_unpin;
7064         }
7065
7066         return 0;
7067
7068 err_unpin:
7069         for (i = i - 1; i >= 0; i--) {
7070                 char buf[PATH_MAX];
7071                 int len;
7072
7073                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7074                 if (len < 0)
7075                         continue;
7076                 else if (len >= PATH_MAX)
7077                         continue;
7078
7079                 bpf_program__unpin_instance(prog, buf, i);
7080         }
7081
7082         rmdir(path);
7083
7084         return libbpf_err(err);
7085 }
7086
7087 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7088 {
7089         int i, err;
7090
7091         err = check_path(path);
7092         if (err)
7093                 return libbpf_err(err);
7094
7095         if (prog == NULL) {
7096                 pr_warn("invalid program pointer\n");
7097                 return libbpf_err(-EINVAL);
7098         }
7099
7100         if (prog->instances.nr <= 0) {
7101                 pr_warn("no instances of prog %s to pin\n", prog->name);
7102                 return libbpf_err(-EINVAL);
7103         }
7104
7105         if (prog->instances.nr == 1) {
7106                 /* don't create subdirs when pinning single instance */
7107                 return bpf_program__unpin_instance(prog, path, 0);
7108         }
7109
7110         for (i = 0; i < prog->instances.nr; i++) {
7111                 char buf[PATH_MAX];
7112                 int len;
7113
7114                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7115                 if (len < 0)
7116                         return libbpf_err(-EINVAL);
7117                 else if (len >= PATH_MAX)
7118                         return libbpf_err(-ENAMETOOLONG);
7119
7120                 err = bpf_program__unpin_instance(prog, buf, i);
7121                 if (err)
7122                         return err;
7123         }
7124
7125         err = rmdir(path);
7126         if (err)
7127                 return libbpf_err(-errno);
7128
7129         return 0;
7130 }
7131
7132 int bpf_map__pin(struct bpf_map *map, const char *path)
7133 {
7134         char *cp, errmsg[STRERR_BUFSIZE];
7135         int err;
7136
7137         if (map == NULL) {
7138                 pr_warn("invalid map pointer\n");
7139                 return libbpf_err(-EINVAL);
7140         }
7141
7142         if (map->pin_path) {
7143                 if (path && strcmp(path, map->pin_path)) {
7144                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7145                                 bpf_map__name(map), map->pin_path, path);
7146                         return libbpf_err(-EINVAL);
7147                 } else if (map->pinned) {
7148                         pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7149                                  bpf_map__name(map), map->pin_path);
7150                         return 0;
7151                 }
7152         } else {
7153                 if (!path) {
7154                         pr_warn("missing a path to pin map '%s' at\n",
7155                                 bpf_map__name(map));
7156                         return libbpf_err(-EINVAL);
7157                 } else if (map->pinned) {
7158                         pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7159                         return libbpf_err(-EEXIST);
7160                 }
7161
7162                 map->pin_path = strdup(path);
7163                 if (!map->pin_path) {
7164                         err = -errno;
7165                         goto out_err;
7166                 }
7167         }
7168
7169         err = make_parent_dir(map->pin_path);
7170         if (err)
7171                 return libbpf_err(err);
7172
7173         err = check_path(map->pin_path);
7174         if (err)
7175                 return libbpf_err(err);
7176
7177         if (bpf_obj_pin(map->fd, map->pin_path)) {
7178                 err = -errno;
7179                 goto out_err;
7180         }
7181
7182         map->pinned = true;
7183         pr_debug("pinned map '%s'\n", map->pin_path);
7184
7185         return 0;
7186
7187 out_err:
7188         cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7189         pr_warn("failed to pin map: %s\n", cp);
7190         return libbpf_err(err);
7191 }
7192
7193 int bpf_map__unpin(struct bpf_map *map, const char *path)
7194 {
7195         int err;
7196
7197         if (map == NULL) {
7198                 pr_warn("invalid map pointer\n");
7199                 return libbpf_err(-EINVAL);
7200         }
7201
7202         if (map->pin_path) {
7203                 if (path && strcmp(path, map->pin_path)) {
7204                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7205                                 bpf_map__name(map), map->pin_path, path);
7206                         return libbpf_err(-EINVAL);
7207                 }
7208                 path = map->pin_path;
7209         } else if (!path) {
7210                 pr_warn("no path to unpin map '%s' from\n",
7211                         bpf_map__name(map));
7212                 return libbpf_err(-EINVAL);
7213         }
7214
7215         err = check_path(path);
7216         if (err)
7217                 return libbpf_err(err);
7218
7219         err = unlink(path);
7220         if (err != 0)
7221                 return libbpf_err(-errno);
7222
7223         map->pinned = false;
7224         pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7225
7226         return 0;
7227 }
7228
7229 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7230 {
7231         char *new = NULL;
7232
7233         if (path) {
7234                 new = strdup(path);
7235                 if (!new)
7236                         return libbpf_err(-errno);
7237         }
7238
7239         free(map->pin_path);
7240         map->pin_path = new;
7241         return 0;
7242 }
7243
7244 const char *bpf_map__get_pin_path(const struct bpf_map *map)
7245 {
7246         return map->pin_path;
7247 }
7248
7249 const char *bpf_map__pin_path(const struct bpf_map *map)
7250 {
7251         return map->pin_path;
7252 }
7253
7254 bool bpf_map__is_pinned(const struct bpf_map *map)
7255 {
7256         return map->pinned;
7257 }
7258
7259 static void sanitize_pin_path(char *s)
7260 {
7261         /* bpffs disallows periods in path names */
7262         while (*s) {
7263                 if (*s == '.')
7264                         *s = '_';
7265                 s++;
7266         }
7267 }
7268
7269 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7270 {
7271         struct bpf_map *map;
7272         int err;
7273
7274         if (!obj)
7275                 return libbpf_err(-ENOENT);
7276
7277         if (!obj->loaded) {
7278                 pr_warn("object not yet loaded; load it first\n");
7279                 return libbpf_err(-ENOENT);
7280         }
7281
7282         bpf_object__for_each_map(map, obj) {
7283                 char *pin_path = NULL;
7284                 char buf[PATH_MAX];
7285
7286                 if (path) {
7287                         int len;
7288
7289                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
7290                                        bpf_map__name(map));
7291                         if (len < 0) {
7292                                 err = -EINVAL;
7293                                 goto err_unpin_maps;
7294                         } else if (len >= PATH_MAX) {
7295                                 err = -ENAMETOOLONG;
7296                                 goto err_unpin_maps;
7297                         }
7298                         sanitize_pin_path(buf);
7299                         pin_path = buf;
7300                 } else if (!map->pin_path) {
7301                         continue;
7302                 }
7303
7304                 err = bpf_map__pin(map, pin_path);
7305                 if (err)
7306                         goto err_unpin_maps;
7307         }
7308
7309         return 0;
7310
7311 err_unpin_maps:
7312         while ((map = bpf_map__prev(map, obj))) {
7313                 if (!map->pin_path)
7314                         continue;
7315
7316                 bpf_map__unpin(map, NULL);
7317         }
7318
7319         return libbpf_err(err);
7320 }
7321
7322 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7323 {
7324         struct bpf_map *map;
7325         int err;
7326
7327         if (!obj)
7328                 return libbpf_err(-ENOENT);
7329
7330         bpf_object__for_each_map(map, obj) {
7331                 char *pin_path = NULL;
7332                 char buf[PATH_MAX];
7333
7334                 if (path) {
7335                         int len;
7336
7337                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
7338                                        bpf_map__name(map));
7339                         if (len < 0)
7340                                 return libbpf_err(-EINVAL);
7341                         else if (len >= PATH_MAX)
7342                                 return libbpf_err(-ENAMETOOLONG);
7343                         sanitize_pin_path(buf);
7344                         pin_path = buf;
7345                 } else if (!map->pin_path) {
7346                         continue;
7347                 }
7348
7349                 err = bpf_map__unpin(map, pin_path);
7350                 if (err)
7351                         return libbpf_err(err);
7352         }
7353
7354         return 0;
7355 }
7356
7357 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
7358 {
7359         struct bpf_program *prog;
7360         int err;
7361
7362         if (!obj)
7363                 return libbpf_err(-ENOENT);
7364
7365         if (!obj->loaded) {
7366                 pr_warn("object not yet loaded; load it first\n");
7367                 return libbpf_err(-ENOENT);
7368         }
7369
7370         bpf_object__for_each_program(prog, obj) {
7371                 char buf[PATH_MAX];
7372                 int len;
7373
7374                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7375                                prog->pin_name);
7376                 if (len < 0) {
7377                         err = -EINVAL;
7378                         goto err_unpin_programs;
7379                 } else if (len >= PATH_MAX) {
7380                         err = -ENAMETOOLONG;
7381                         goto err_unpin_programs;
7382                 }
7383
7384                 err = bpf_program__pin(prog, buf);
7385                 if (err)
7386                         goto err_unpin_programs;
7387         }
7388
7389         return 0;
7390
7391 err_unpin_programs:
7392         while ((prog = bpf_program__prev(prog, obj))) {
7393                 char buf[PATH_MAX];
7394                 int len;
7395
7396                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7397                                prog->pin_name);
7398                 if (len < 0)
7399                         continue;
7400                 else if (len >= PATH_MAX)
7401                         continue;
7402
7403                 bpf_program__unpin(prog, buf);
7404         }
7405
7406         return libbpf_err(err);
7407 }
7408
7409 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
7410 {
7411         struct bpf_program *prog;
7412         int err;
7413
7414         if (!obj)
7415                 return libbpf_err(-ENOENT);
7416
7417         bpf_object__for_each_program(prog, obj) {
7418                 char buf[PATH_MAX];
7419                 int len;
7420
7421                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7422                                prog->pin_name);
7423                 if (len < 0)
7424                         return libbpf_err(-EINVAL);
7425                 else if (len >= PATH_MAX)
7426                         return libbpf_err(-ENAMETOOLONG);
7427
7428                 err = bpf_program__unpin(prog, buf);
7429                 if (err)
7430                         return libbpf_err(err);
7431         }
7432
7433         return 0;
7434 }
7435
7436 int bpf_object__pin(struct bpf_object *obj, const char *path)
7437 {
7438         int err;
7439
7440         err = bpf_object__pin_maps(obj, path);
7441         if (err)
7442                 return libbpf_err(err);
7443
7444         err = bpf_object__pin_programs(obj, path);
7445         if (err) {
7446                 bpf_object__unpin_maps(obj, path);
7447                 return libbpf_err(err);
7448         }
7449
7450         return 0;
7451 }
7452
7453 static void bpf_map__destroy(struct bpf_map *map)
7454 {
7455         if (map->clear_priv)
7456                 map->clear_priv(map, map->priv);
7457         map->priv = NULL;
7458         map->clear_priv = NULL;
7459
7460         if (map->inner_map) {
7461                 bpf_map__destroy(map->inner_map);
7462                 zfree(&map->inner_map);
7463         }
7464
7465         zfree(&map->init_slots);
7466         map->init_slots_sz = 0;
7467
7468         if (map->mmaped) {
7469                 munmap(map->mmaped, bpf_map_mmap_sz(map));
7470                 map->mmaped = NULL;
7471         }
7472
7473         if (map->st_ops) {
7474                 zfree(&map->st_ops->data);
7475                 zfree(&map->st_ops->progs);
7476                 zfree(&map->st_ops->kern_func_off);
7477                 zfree(&map->st_ops);
7478         }
7479
7480         zfree(&map->name);
7481         zfree(&map->pin_path);
7482
7483         if (map->fd >= 0)
7484                 zclose(map->fd);
7485 }
7486
7487 void bpf_object__close(struct bpf_object *obj)
7488 {
7489         size_t i;
7490
7491         if (IS_ERR_OR_NULL(obj))
7492                 return;
7493
7494         if (obj->clear_priv)
7495                 obj->clear_priv(obj, obj->priv);
7496
7497         bpf_gen__free(obj->gen_loader);
7498         bpf_object__elf_finish(obj);
7499         bpf_object__unload(obj);
7500         btf__free(obj->btf);
7501         btf_ext__free(obj->btf_ext);
7502
7503         for (i = 0; i < obj->nr_maps; i++)
7504                 bpf_map__destroy(&obj->maps[i]);
7505
7506         zfree(&obj->btf_custom_path);
7507         zfree(&obj->kconfig);
7508         zfree(&obj->externs);
7509         obj->nr_extern = 0;
7510
7511         zfree(&obj->maps);
7512         obj->nr_maps = 0;
7513
7514         if (obj->programs && obj->nr_programs) {
7515                 for (i = 0; i < obj->nr_programs; i++)
7516                         bpf_program__exit(&obj->programs[i]);
7517         }
7518         zfree(&obj->programs);
7519
7520         list_del(&obj->list);
7521         free(obj);
7522 }
7523
7524 struct bpf_object *
7525 bpf_object__next(struct bpf_object *prev)
7526 {
7527         struct bpf_object *next;
7528
7529         if (!prev)
7530                 next = list_first_entry(&bpf_objects_list,
7531                                         struct bpf_object,
7532                                         list);
7533         else
7534                 next = list_next_entry(prev, list);
7535
7536         /* Empty list is noticed here so don't need checking on entry. */
7537         if (&next->list == &bpf_objects_list)
7538                 return NULL;
7539
7540         return next;
7541 }
7542
7543 const char *bpf_object__name(const struct bpf_object *obj)
7544 {
7545         return obj ? obj->name : libbpf_err_ptr(-EINVAL);
7546 }
7547
7548 unsigned int bpf_object__kversion(const struct bpf_object *obj)
7549 {
7550         return obj ? obj->kern_version : 0;
7551 }
7552
7553 struct btf *bpf_object__btf(const struct bpf_object *obj)
7554 {
7555         return obj ? obj->btf : NULL;
7556 }
7557
7558 int bpf_object__btf_fd(const struct bpf_object *obj)
7559 {
7560         return obj->btf ? btf__fd(obj->btf) : -1;
7561 }
7562
7563 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
7564 {
7565         if (obj->loaded)
7566                 return libbpf_err(-EINVAL);
7567
7568         obj->kern_version = kern_version;
7569
7570         return 0;
7571 }
7572
7573 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
7574                          bpf_object_clear_priv_t clear_priv)
7575 {
7576         if (obj->priv && obj->clear_priv)
7577                 obj->clear_priv(obj, obj->priv);
7578
7579         obj->priv = priv;
7580         obj->clear_priv = clear_priv;
7581         return 0;
7582 }
7583
7584 void *bpf_object__priv(const struct bpf_object *obj)
7585 {
7586         return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
7587 }
7588
7589 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
7590 {
7591         struct bpf_gen *gen;
7592
7593         if (!opts)
7594                 return -EFAULT;
7595         if (!OPTS_VALID(opts, gen_loader_opts))
7596                 return -EINVAL;
7597         gen = calloc(sizeof(*gen), 1);
7598         if (!gen)
7599                 return -ENOMEM;
7600         gen->opts = opts;
7601         obj->gen_loader = gen;
7602         return 0;
7603 }
7604
7605 static struct bpf_program *
7606 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
7607                     bool forward)
7608 {
7609         size_t nr_programs = obj->nr_programs;
7610         ssize_t idx;
7611
7612         if (!nr_programs)
7613                 return NULL;
7614
7615         if (!p)
7616                 /* Iter from the beginning */
7617                 return forward ? &obj->programs[0] :
7618                         &obj->programs[nr_programs - 1];
7619
7620         if (p->obj != obj) {
7621                 pr_warn("error: program handler doesn't match object\n");
7622                 return errno = EINVAL, NULL;
7623         }
7624
7625         idx = (p - obj->programs) + (forward ? 1 : -1);
7626         if (idx >= obj->nr_programs || idx < 0)
7627                 return NULL;
7628         return &obj->programs[idx];
7629 }
7630
7631 struct bpf_program *
7632 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
7633 {
7634         struct bpf_program *prog = prev;
7635
7636         do {
7637                 prog = __bpf_program__iter(prog, obj, true);
7638         } while (prog && prog_is_subprog(obj, prog));
7639
7640         return prog;
7641 }
7642
7643 struct bpf_program *
7644 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
7645 {
7646         struct bpf_program *prog = next;
7647
7648         do {
7649                 prog = __bpf_program__iter(prog, obj, false);
7650         } while (prog && prog_is_subprog(obj, prog));
7651
7652         return prog;
7653 }
7654
7655 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
7656                           bpf_program_clear_priv_t clear_priv)
7657 {
7658         if (prog->priv && prog->clear_priv)
7659                 prog->clear_priv(prog, prog->priv);
7660
7661         prog->priv = priv;
7662         prog->clear_priv = clear_priv;
7663         return 0;
7664 }
7665
7666 void *bpf_program__priv(const struct bpf_program *prog)
7667 {
7668         return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
7669 }
7670
7671 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
7672 {
7673         prog->prog_ifindex = ifindex;
7674 }
7675
7676 const char *bpf_program__name(const struct bpf_program *prog)
7677 {
7678         return prog->name;
7679 }
7680
7681 const char *bpf_program__section_name(const struct bpf_program *prog)
7682 {
7683         return prog->sec_name;
7684 }
7685
7686 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
7687 {
7688         const char *title;
7689
7690         title = prog->sec_name;
7691         if (needs_copy) {
7692                 title = strdup(title);
7693                 if (!title) {
7694                         pr_warn("failed to strdup program title\n");
7695                         return libbpf_err_ptr(-ENOMEM);
7696                 }
7697         }
7698
7699         return title;
7700 }
7701
7702 bool bpf_program__autoload(const struct bpf_program *prog)
7703 {
7704         return prog->load;
7705 }
7706
7707 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
7708 {
7709         if (prog->obj->loaded)
7710                 return libbpf_err(-EINVAL);
7711
7712         prog->load = autoload;
7713         return 0;
7714 }
7715
7716 int bpf_program__fd(const struct bpf_program *prog)
7717 {
7718         return bpf_program__nth_fd(prog, 0);
7719 }
7720
7721 size_t bpf_program__size(const struct bpf_program *prog)
7722 {
7723         return prog->insns_cnt * BPF_INSN_SZ;
7724 }
7725
7726 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
7727                           bpf_program_prep_t prep)
7728 {
7729         int *instances_fds;
7730
7731         if (nr_instances <= 0 || !prep)
7732                 return libbpf_err(-EINVAL);
7733
7734         if (prog->instances.nr > 0 || prog->instances.fds) {
7735                 pr_warn("Can't set pre-processor after loading\n");
7736                 return libbpf_err(-EINVAL);
7737         }
7738
7739         instances_fds = malloc(sizeof(int) * nr_instances);
7740         if (!instances_fds) {
7741                 pr_warn("alloc memory failed for fds\n");
7742                 return libbpf_err(-ENOMEM);
7743         }
7744
7745         /* fill all fd with -1 */
7746         memset(instances_fds, -1, sizeof(int) * nr_instances);
7747
7748         prog->instances.nr = nr_instances;
7749         prog->instances.fds = instances_fds;
7750         prog->preprocessor = prep;
7751         return 0;
7752 }
7753
7754 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
7755 {
7756         int fd;
7757
7758         if (!prog)
7759                 return libbpf_err(-EINVAL);
7760
7761         if (n >= prog->instances.nr || n < 0) {
7762                 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
7763                         n, prog->name, prog->instances.nr);
7764                 return libbpf_err(-EINVAL);
7765         }
7766
7767         fd = prog->instances.fds[n];
7768         if (fd < 0) {
7769                 pr_warn("%dth instance of program '%s' is invalid\n",
7770                         n, prog->name);
7771                 return libbpf_err(-ENOENT);
7772         }
7773
7774         return fd;
7775 }
7776
7777 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
7778 {
7779         return prog->type;
7780 }
7781
7782 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
7783 {
7784         prog->type = type;
7785 }
7786
7787 static bool bpf_program__is_type(const struct bpf_program *prog,
7788                                  enum bpf_prog_type type)
7789 {
7790         return prog ? (prog->type == type) : false;
7791 }
7792
7793 #define BPF_PROG_TYPE_FNS(NAME, TYPE)                           \
7794 int bpf_program__set_##NAME(struct bpf_program *prog)           \
7795 {                                                               \
7796         if (!prog)                                              \
7797                 return libbpf_err(-EINVAL);                     \
7798         bpf_program__set_type(prog, TYPE);                      \
7799         return 0;                                               \
7800 }                                                               \
7801                                                                 \
7802 bool bpf_program__is_##NAME(const struct bpf_program *prog)     \
7803 {                                                               \
7804         return bpf_program__is_type(prog, TYPE);                \
7805 }                                                               \
7806
7807 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
7808 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
7809 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7810 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
7811 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
7812 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
7813 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7814 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
7815 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
7816 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
7817 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
7818 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
7819 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
7820
7821 enum bpf_attach_type
7822 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
7823 {
7824         return prog->expected_attach_type;
7825 }
7826
7827 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
7828                                            enum bpf_attach_type type)
7829 {
7830         prog->expected_attach_type = type;
7831 }
7832
7833 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional,           \
7834                           attachable, attach_btf)                           \
7835         {                                                                   \
7836                 .sec = string,                                              \
7837                 .len = sizeof(string) - 1,                                  \
7838                 .prog_type = ptype,                                         \
7839                 .expected_attach_type = eatype,                             \
7840                 .is_exp_attach_type_optional = eatype_optional,             \
7841                 .is_attachable = attachable,                                \
7842                 .is_attach_btf = attach_btf,                                \
7843         }
7844
7845 /* Programs that can NOT be attached. */
7846 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
7847
7848 /* Programs that can be attached. */
7849 #define BPF_APROG_SEC(string, ptype, atype) \
7850         BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
7851
7852 /* Programs that must specify expected attach type at load time. */
7853 #define BPF_EAPROG_SEC(string, ptype, eatype) \
7854         BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
7855
7856 /* Programs that use BTF to identify attach point */
7857 #define BPF_PROG_BTF(string, ptype, eatype) \
7858         BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
7859
7860 /* Programs that can be attached but attach type can't be identified by section
7861  * name. Kept for backward compatibility.
7862  */
7863 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
7864
7865 #define SEC_DEF(sec_pfx, ptype, ...) {                                      \
7866         .sec = sec_pfx,                                                     \
7867         .len = sizeof(sec_pfx) - 1,                                         \
7868         .prog_type = BPF_PROG_TYPE_##ptype,                                 \
7869         __VA_ARGS__                                                         \
7870 }
7871
7872 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7873                                       struct bpf_program *prog);
7874 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
7875                                   struct bpf_program *prog);
7876 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
7877                                       struct bpf_program *prog);
7878 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
7879                                      struct bpf_program *prog);
7880 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
7881                                    struct bpf_program *prog);
7882 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
7883                                     struct bpf_program *prog);
7884
7885 static const struct bpf_sec_def section_defs[] = {
7886         BPF_PROG_SEC("socket",                  BPF_PROG_TYPE_SOCKET_FILTER),
7887         BPF_EAPROG_SEC("sk_reuseport/migrate",  BPF_PROG_TYPE_SK_REUSEPORT,
7888                                                 BPF_SK_REUSEPORT_SELECT_OR_MIGRATE),
7889         BPF_EAPROG_SEC("sk_reuseport",          BPF_PROG_TYPE_SK_REUSEPORT,
7890                                                 BPF_SK_REUSEPORT_SELECT),
7891         SEC_DEF("kprobe/", KPROBE,
7892                 .attach_fn = attach_kprobe),
7893         BPF_PROG_SEC("uprobe/",                 BPF_PROG_TYPE_KPROBE),
7894         SEC_DEF("kretprobe/", KPROBE,
7895                 .attach_fn = attach_kprobe),
7896         BPF_PROG_SEC("uretprobe/",              BPF_PROG_TYPE_KPROBE),
7897         BPF_PROG_SEC("classifier",              BPF_PROG_TYPE_SCHED_CLS),
7898         BPF_PROG_SEC("action",                  BPF_PROG_TYPE_SCHED_ACT),
7899         SEC_DEF("tracepoint/", TRACEPOINT,
7900                 .attach_fn = attach_tp),
7901         SEC_DEF("tp/", TRACEPOINT,
7902                 .attach_fn = attach_tp),
7903         SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
7904                 .attach_fn = attach_raw_tp),
7905         SEC_DEF("raw_tp/", RAW_TRACEPOINT,
7906                 .attach_fn = attach_raw_tp),
7907         SEC_DEF("tp_btf/", TRACING,
7908                 .expected_attach_type = BPF_TRACE_RAW_TP,
7909                 .is_attach_btf = true,
7910                 .attach_fn = attach_trace),
7911         SEC_DEF("fentry/", TRACING,
7912                 .expected_attach_type = BPF_TRACE_FENTRY,
7913                 .is_attach_btf = true,
7914                 .attach_fn = attach_trace),
7915         SEC_DEF("fmod_ret/", TRACING,
7916                 .expected_attach_type = BPF_MODIFY_RETURN,
7917                 .is_attach_btf = true,
7918                 .attach_fn = attach_trace),
7919         SEC_DEF("fexit/", TRACING,
7920                 .expected_attach_type = BPF_TRACE_FEXIT,
7921                 .is_attach_btf = true,
7922                 .attach_fn = attach_trace),
7923         SEC_DEF("fentry.s/", TRACING,
7924                 .expected_attach_type = BPF_TRACE_FENTRY,
7925                 .is_attach_btf = true,
7926                 .is_sleepable = true,
7927                 .attach_fn = attach_trace),
7928         SEC_DEF("fmod_ret.s/", TRACING,
7929                 .expected_attach_type = BPF_MODIFY_RETURN,
7930                 .is_attach_btf = true,
7931                 .is_sleepable = true,
7932                 .attach_fn = attach_trace),
7933         SEC_DEF("fexit.s/", TRACING,
7934                 .expected_attach_type = BPF_TRACE_FEXIT,
7935                 .is_attach_btf = true,
7936                 .is_sleepable = true,
7937                 .attach_fn = attach_trace),
7938         SEC_DEF("freplace/", EXT,
7939                 .is_attach_btf = true,
7940                 .attach_fn = attach_trace),
7941         SEC_DEF("lsm/", LSM,
7942                 .is_attach_btf = true,
7943                 .expected_attach_type = BPF_LSM_MAC,
7944                 .attach_fn = attach_lsm),
7945         SEC_DEF("lsm.s/", LSM,
7946                 .is_attach_btf = true,
7947                 .is_sleepable = true,
7948                 .expected_attach_type = BPF_LSM_MAC,
7949                 .attach_fn = attach_lsm),
7950         SEC_DEF("iter/", TRACING,
7951                 .expected_attach_type = BPF_TRACE_ITER,
7952                 .is_attach_btf = true,
7953                 .attach_fn = attach_iter),
7954         SEC_DEF("syscall", SYSCALL,
7955                 .is_sleepable = true),
7956         BPF_EAPROG_SEC("xdp_devmap/",           BPF_PROG_TYPE_XDP,
7957                                                 BPF_XDP_DEVMAP),
7958         BPF_EAPROG_SEC("xdp_cpumap/",           BPF_PROG_TYPE_XDP,
7959                                                 BPF_XDP_CPUMAP),
7960         BPF_APROG_SEC("xdp",                    BPF_PROG_TYPE_XDP,
7961                                                 BPF_XDP),
7962         BPF_PROG_SEC("perf_event",              BPF_PROG_TYPE_PERF_EVENT),
7963         BPF_PROG_SEC("lwt_in",                  BPF_PROG_TYPE_LWT_IN),
7964         BPF_PROG_SEC("lwt_out",                 BPF_PROG_TYPE_LWT_OUT),
7965         BPF_PROG_SEC("lwt_xmit",                BPF_PROG_TYPE_LWT_XMIT),
7966         BPF_PROG_SEC("lwt_seg6local",           BPF_PROG_TYPE_LWT_SEG6LOCAL),
7967         BPF_APROG_SEC("cgroup_skb/ingress",     BPF_PROG_TYPE_CGROUP_SKB,
7968                                                 BPF_CGROUP_INET_INGRESS),
7969         BPF_APROG_SEC("cgroup_skb/egress",      BPF_PROG_TYPE_CGROUP_SKB,
7970                                                 BPF_CGROUP_INET_EGRESS),
7971         BPF_APROG_COMPAT("cgroup/skb",          BPF_PROG_TYPE_CGROUP_SKB),
7972         BPF_EAPROG_SEC("cgroup/sock_create",    BPF_PROG_TYPE_CGROUP_SOCK,
7973                                                 BPF_CGROUP_INET_SOCK_CREATE),
7974         BPF_EAPROG_SEC("cgroup/sock_release",   BPF_PROG_TYPE_CGROUP_SOCK,
7975                                                 BPF_CGROUP_INET_SOCK_RELEASE),
7976         BPF_APROG_SEC("cgroup/sock",            BPF_PROG_TYPE_CGROUP_SOCK,
7977                                                 BPF_CGROUP_INET_SOCK_CREATE),
7978         BPF_EAPROG_SEC("cgroup/post_bind4",     BPF_PROG_TYPE_CGROUP_SOCK,
7979                                                 BPF_CGROUP_INET4_POST_BIND),
7980         BPF_EAPROG_SEC("cgroup/post_bind6",     BPF_PROG_TYPE_CGROUP_SOCK,
7981                                                 BPF_CGROUP_INET6_POST_BIND),
7982         BPF_APROG_SEC("cgroup/dev",             BPF_PROG_TYPE_CGROUP_DEVICE,
7983                                                 BPF_CGROUP_DEVICE),
7984         BPF_APROG_SEC("sockops",                BPF_PROG_TYPE_SOCK_OPS,
7985                                                 BPF_CGROUP_SOCK_OPS),
7986         BPF_APROG_SEC("sk_skb/stream_parser",   BPF_PROG_TYPE_SK_SKB,
7987                                                 BPF_SK_SKB_STREAM_PARSER),
7988         BPF_APROG_SEC("sk_skb/stream_verdict",  BPF_PROG_TYPE_SK_SKB,
7989                                                 BPF_SK_SKB_STREAM_VERDICT),
7990         BPF_APROG_COMPAT("sk_skb",              BPF_PROG_TYPE_SK_SKB),
7991         BPF_APROG_SEC("sk_msg",                 BPF_PROG_TYPE_SK_MSG,
7992                                                 BPF_SK_MSG_VERDICT),
7993         BPF_APROG_SEC("lirc_mode2",             BPF_PROG_TYPE_LIRC_MODE2,
7994                                                 BPF_LIRC_MODE2),
7995         BPF_APROG_SEC("flow_dissector",         BPF_PROG_TYPE_FLOW_DISSECTOR,
7996                                                 BPF_FLOW_DISSECTOR),
7997         BPF_EAPROG_SEC("cgroup/bind4",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
7998                                                 BPF_CGROUP_INET4_BIND),
7999         BPF_EAPROG_SEC("cgroup/bind6",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8000                                                 BPF_CGROUP_INET6_BIND),
8001         BPF_EAPROG_SEC("cgroup/connect4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8002                                                 BPF_CGROUP_INET4_CONNECT),
8003         BPF_EAPROG_SEC("cgroup/connect6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8004                                                 BPF_CGROUP_INET6_CONNECT),
8005         BPF_EAPROG_SEC("cgroup/sendmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8006                                                 BPF_CGROUP_UDP4_SENDMSG),
8007         BPF_EAPROG_SEC("cgroup/sendmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8008                                                 BPF_CGROUP_UDP6_SENDMSG),
8009         BPF_EAPROG_SEC("cgroup/recvmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8010                                                 BPF_CGROUP_UDP4_RECVMSG),
8011         BPF_EAPROG_SEC("cgroup/recvmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8012                                                 BPF_CGROUP_UDP6_RECVMSG),
8013         BPF_EAPROG_SEC("cgroup/getpeername4",   BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8014                                                 BPF_CGROUP_INET4_GETPEERNAME),
8015         BPF_EAPROG_SEC("cgroup/getpeername6",   BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8016                                                 BPF_CGROUP_INET6_GETPEERNAME),
8017         BPF_EAPROG_SEC("cgroup/getsockname4",   BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8018                                                 BPF_CGROUP_INET4_GETSOCKNAME),
8019         BPF_EAPROG_SEC("cgroup/getsockname6",   BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8020                                                 BPF_CGROUP_INET6_GETSOCKNAME),
8021         BPF_EAPROG_SEC("cgroup/sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,
8022                                                 BPF_CGROUP_SYSCTL),
8023         BPF_EAPROG_SEC("cgroup/getsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
8024                                                 BPF_CGROUP_GETSOCKOPT),
8025         BPF_EAPROG_SEC("cgroup/setsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
8026                                                 BPF_CGROUP_SETSOCKOPT),
8027         BPF_PROG_SEC("struct_ops",              BPF_PROG_TYPE_STRUCT_OPS),
8028         BPF_EAPROG_SEC("sk_lookup/",            BPF_PROG_TYPE_SK_LOOKUP,
8029                                                 BPF_SK_LOOKUP),
8030 };
8031
8032 #undef BPF_PROG_SEC_IMPL
8033 #undef BPF_PROG_SEC
8034 #undef BPF_APROG_SEC
8035 #undef BPF_EAPROG_SEC
8036 #undef BPF_APROG_COMPAT
8037 #undef SEC_DEF
8038
8039 #define MAX_TYPE_NAME_SIZE 32
8040
8041 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8042 {
8043         int i, n = ARRAY_SIZE(section_defs);
8044
8045         for (i = 0; i < n; i++) {
8046                 if (strncmp(sec_name,
8047                             section_defs[i].sec, section_defs[i].len))
8048                         continue;
8049                 return &section_defs[i];
8050         }
8051         return NULL;
8052 }
8053
8054 static char *libbpf_get_type_names(bool attach_type)
8055 {
8056         int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8057         char *buf;
8058
8059         buf = malloc(len);
8060         if (!buf)
8061                 return NULL;
8062
8063         buf[0] = '\0';
8064         /* Forge string buf with all available names */
8065         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8066                 if (attach_type && !section_defs[i].is_attachable)
8067                         continue;
8068
8069                 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8070                         free(buf);
8071                         return NULL;
8072                 }
8073                 strcat(buf, " ");
8074                 strcat(buf, section_defs[i].sec);
8075         }
8076
8077         return buf;
8078 }
8079
8080 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8081                              enum bpf_attach_type *expected_attach_type)
8082 {
8083         const struct bpf_sec_def *sec_def;
8084         char *type_names;
8085
8086         if (!name)
8087                 return libbpf_err(-EINVAL);
8088
8089         sec_def = find_sec_def(name);
8090         if (sec_def) {
8091                 *prog_type = sec_def->prog_type;
8092                 *expected_attach_type = sec_def->expected_attach_type;
8093                 return 0;
8094         }
8095
8096         pr_debug("failed to guess program type from ELF section '%s'\n", name);
8097         type_names = libbpf_get_type_names(false);
8098         if (type_names != NULL) {
8099                 pr_debug("supported section(type) names are:%s\n", type_names);
8100                 free(type_names);
8101         }
8102
8103         return libbpf_err(-ESRCH);
8104 }
8105
8106 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8107                                                      size_t offset)
8108 {
8109         struct bpf_map *map;
8110         size_t i;
8111
8112         for (i = 0; i < obj->nr_maps; i++) {
8113                 map = &obj->maps[i];
8114                 if (!bpf_map__is_struct_ops(map))
8115                         continue;
8116                 if (map->sec_offset <= offset &&
8117                     offset - map->sec_offset < map->def.value_size)
8118                         return map;
8119         }
8120
8121         return NULL;
8122 }
8123
8124 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8125 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8126                                             GElf_Shdr *shdr, Elf_Data *data)
8127 {
8128         const struct btf_member *member;
8129         struct bpf_struct_ops *st_ops;
8130         struct bpf_program *prog;
8131         unsigned int shdr_idx;
8132         const struct btf *btf;
8133         struct bpf_map *map;
8134         Elf_Data *symbols;
8135         unsigned int moff, insn_idx;
8136         const char *name;
8137         __u32 member_idx;
8138         GElf_Sym sym;
8139         GElf_Rel rel;
8140         int i, nrels;
8141
8142         symbols = obj->efile.symbols;
8143         btf = obj->btf;
8144         nrels = shdr->sh_size / shdr->sh_entsize;
8145         for (i = 0; i < nrels; i++) {
8146                 if (!gelf_getrel(data, i, &rel)) {
8147                         pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8148                         return -LIBBPF_ERRNO__FORMAT;
8149                 }
8150
8151                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
8152                         pr_warn("struct_ops reloc: symbol %zx not found\n",
8153                                 (size_t)GELF_R_SYM(rel.r_info));
8154                         return -LIBBPF_ERRNO__FORMAT;
8155                 }
8156
8157                 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
8158                 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
8159                 if (!map) {
8160                         pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
8161                                 (size_t)rel.r_offset);
8162                         return -EINVAL;
8163                 }
8164
8165                 moff = rel.r_offset - map->sec_offset;
8166                 shdr_idx = sym.st_shndx;
8167                 st_ops = map->st_ops;
8168                 pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel.r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
8169                          map->name,
8170                          (long long)(rel.r_info >> 32),
8171                          (long long)sym.st_value,
8172                          shdr_idx, (size_t)rel.r_offset,
8173                          map->sec_offset, sym.st_name, name);
8174
8175                 if (shdr_idx >= SHN_LORESERVE) {
8176                         pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
8177                                 map->name, (size_t)rel.r_offset, shdr_idx);
8178                         return -LIBBPF_ERRNO__RELOC;
8179                 }
8180                 if (sym.st_value % BPF_INSN_SZ) {
8181                         pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8182                                 map->name, (unsigned long long)sym.st_value);
8183                         return -LIBBPF_ERRNO__FORMAT;
8184                 }
8185                 insn_idx = sym.st_value / BPF_INSN_SZ;
8186
8187                 member = find_member_by_offset(st_ops->type, moff * 8);
8188                 if (!member) {
8189                         pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8190                                 map->name, moff);
8191                         return -EINVAL;
8192                 }
8193                 member_idx = member - btf_members(st_ops->type);
8194                 name = btf__name_by_offset(btf, member->name_off);
8195
8196                 if (!resolve_func_ptr(btf, member->type, NULL)) {
8197                         pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8198                                 map->name, name);
8199                         return -EINVAL;
8200                 }
8201
8202                 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8203                 if (!prog) {
8204                         pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8205                                 map->name, shdr_idx, name);
8206                         return -EINVAL;
8207                 }
8208
8209                 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
8210                         const struct bpf_sec_def *sec_def;
8211
8212                         sec_def = find_sec_def(prog->sec_name);
8213                         if (sec_def &&
8214                             sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
8215                                 /* for pr_warn */
8216                                 prog->type = sec_def->prog_type;
8217                                 goto invalid_prog;
8218                         }
8219
8220                         prog->type = BPF_PROG_TYPE_STRUCT_OPS;
8221                         prog->attach_btf_id = st_ops->type_id;
8222                         prog->expected_attach_type = member_idx;
8223                 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
8224                            prog->attach_btf_id != st_ops->type_id ||
8225                            prog->expected_attach_type != member_idx) {
8226                         goto invalid_prog;
8227                 }
8228                 st_ops->progs[member_idx] = prog;
8229         }
8230
8231         return 0;
8232
8233 invalid_prog:
8234         pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
8235                 map->name, prog->name, prog->sec_name, prog->type,
8236                 prog->attach_btf_id, prog->expected_attach_type, name);
8237         return -EINVAL;
8238 }
8239
8240 #define BTF_TRACE_PREFIX "btf_trace_"
8241 #define BTF_LSM_PREFIX "bpf_lsm_"
8242 #define BTF_ITER_PREFIX "bpf_iter_"
8243 #define BTF_MAX_NAME_SIZE 128
8244
8245 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8246                                 const char **prefix, int *kind)
8247 {
8248         switch (attach_type) {
8249         case BPF_TRACE_RAW_TP:
8250                 *prefix = BTF_TRACE_PREFIX;
8251                 *kind = BTF_KIND_TYPEDEF;
8252                 break;
8253         case BPF_LSM_MAC:
8254                 *prefix = BTF_LSM_PREFIX;
8255                 *kind = BTF_KIND_FUNC;
8256                 break;
8257         case BPF_TRACE_ITER:
8258                 *prefix = BTF_ITER_PREFIX;
8259                 *kind = BTF_KIND_FUNC;
8260                 break;
8261         default:
8262                 *prefix = "";
8263                 *kind = BTF_KIND_FUNC;
8264         }
8265 }
8266
8267 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8268                                    const char *name, __u32 kind)
8269 {
8270         char btf_type_name[BTF_MAX_NAME_SIZE];
8271         int ret;
8272
8273         ret = snprintf(btf_type_name, sizeof(btf_type_name),
8274                        "%s%s", prefix, name);
8275         /* snprintf returns the number of characters written excluding the
8276          * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8277          * indicates truncation.
8278          */
8279         if (ret < 0 || ret >= sizeof(btf_type_name))
8280                 return -ENAMETOOLONG;
8281         return btf__find_by_name_kind(btf, btf_type_name, kind);
8282 }
8283
8284 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8285                                      enum bpf_attach_type attach_type)
8286 {
8287         const char *prefix;
8288         int kind;
8289
8290         btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8291         return find_btf_by_prefix_kind(btf, prefix, name, kind);
8292 }
8293
8294 int libbpf_find_vmlinux_btf_id(const char *name,
8295                                enum bpf_attach_type attach_type)
8296 {
8297         struct btf *btf;
8298         int err;
8299
8300         btf = libbpf_find_kernel_btf();
8301         err = libbpf_get_error(btf);
8302         if (err) {
8303                 pr_warn("vmlinux BTF is not found\n");
8304                 return libbpf_err(err);
8305         }
8306
8307         err = find_attach_btf_id(btf, name, attach_type);
8308         if (err <= 0)
8309                 pr_warn("%s is not found in vmlinux BTF\n", name);
8310
8311         btf__free(btf);
8312         return libbpf_err(err);
8313 }
8314
8315 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8316 {
8317         struct bpf_prog_info_linear *info_linear;
8318         struct bpf_prog_info *info;
8319         struct btf *btf;
8320         int err;
8321
8322         info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
8323         err = libbpf_get_error(info_linear);
8324         if (err) {
8325                 pr_warn("failed get_prog_info_linear for FD %d\n",
8326                         attach_prog_fd);
8327                 return err;
8328         }
8329
8330         err = -EINVAL;
8331         info = &info_linear->info;
8332         if (!info->btf_id) {
8333                 pr_warn("The target program doesn't have BTF\n");
8334                 goto out;
8335         }
8336         btf = btf__load_from_kernel_by_id(info->btf_id);
8337         if (libbpf_get_error(btf)) {
8338                 pr_warn("Failed to get BTF of the program\n");
8339                 goto out;
8340         }
8341         err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
8342         btf__free(btf);
8343         if (err <= 0) {
8344                 pr_warn("%s is not found in prog's BTF\n", name);
8345                 goto out;
8346         }
8347 out:
8348         free(info_linear);
8349         return err;
8350 }
8351
8352 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
8353                               enum bpf_attach_type attach_type,
8354                               int *btf_obj_fd, int *btf_type_id)
8355 {
8356         int ret, i;
8357
8358         ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
8359         if (ret > 0) {
8360                 *btf_obj_fd = 0; /* vmlinux BTF */
8361                 *btf_type_id = ret;
8362                 return 0;
8363         }
8364         if (ret != -ENOENT)
8365                 return ret;
8366
8367         ret = load_module_btfs(obj);
8368         if (ret)
8369                 return ret;
8370
8371         for (i = 0; i < obj->btf_module_cnt; i++) {
8372                 const struct module_btf *mod = &obj->btf_modules[i];
8373
8374                 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
8375                 if (ret > 0) {
8376                         *btf_obj_fd = mod->fd;
8377                         *btf_type_id = ret;
8378                         return 0;
8379                 }
8380                 if (ret == -ENOENT)
8381                         continue;
8382
8383                 return ret;
8384         }
8385
8386         return -ESRCH;
8387 }
8388
8389 static int libbpf_find_attach_btf_id(struct bpf_program *prog, int *btf_obj_fd, int *btf_type_id)
8390 {
8391         enum bpf_attach_type attach_type = prog->expected_attach_type;
8392         __u32 attach_prog_fd = prog->attach_prog_fd;
8393         const char *name = prog->sec_name, *attach_name;
8394         const struct bpf_sec_def *sec = NULL;
8395         int i, err = 0;
8396
8397         if (!name)
8398                 return -EINVAL;
8399
8400         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8401                 if (!section_defs[i].is_attach_btf)
8402                         continue;
8403                 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
8404                         continue;
8405
8406                 sec = &section_defs[i];
8407                 break;
8408         }
8409
8410         if (!sec) {
8411                 pr_warn("failed to identify BTF ID based on ELF section name '%s'\n", name);
8412                 return -ESRCH;
8413         }
8414         attach_name = name + sec->len;
8415
8416         /* BPF program's BTF ID */
8417         if (attach_prog_fd) {
8418                 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
8419                 if (err < 0) {
8420                         pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
8421                                  attach_prog_fd, attach_name, err);
8422                         return err;
8423                 }
8424                 *btf_obj_fd = 0;
8425                 *btf_type_id = err;
8426                 return 0;
8427         }
8428
8429         /* kernel/module BTF ID */
8430         if (prog->obj->gen_loader) {
8431                 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
8432                 *btf_obj_fd = 0;
8433                 *btf_type_id = 1;
8434         } else {
8435                 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
8436         }
8437         if (err) {
8438                 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
8439                 return err;
8440         }
8441         return 0;
8442 }
8443
8444 int libbpf_attach_type_by_name(const char *name,
8445                                enum bpf_attach_type *attach_type)
8446 {
8447         char *type_names;
8448         int i;
8449
8450         if (!name)
8451                 return libbpf_err(-EINVAL);
8452
8453         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8454                 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
8455                         continue;
8456                 if (!section_defs[i].is_attachable)
8457                         return libbpf_err(-EINVAL);
8458                 *attach_type = section_defs[i].expected_attach_type;
8459                 return 0;
8460         }
8461         pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
8462         type_names = libbpf_get_type_names(true);
8463         if (type_names != NULL) {
8464                 pr_debug("attachable section(type) names are:%s\n", type_names);
8465                 free(type_names);
8466         }
8467
8468         return libbpf_err(-EINVAL);
8469 }
8470
8471 int bpf_map__fd(const struct bpf_map *map)
8472 {
8473         return map ? map->fd : libbpf_err(-EINVAL);
8474 }
8475
8476 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
8477 {
8478         return map ? &map->def : libbpf_err_ptr(-EINVAL);
8479 }
8480
8481 const char *bpf_map__name(const struct bpf_map *map)
8482 {
8483         return map ? map->name : NULL;
8484 }
8485
8486 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
8487 {
8488         return map->def.type;
8489 }
8490
8491 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
8492 {
8493         if (map->fd >= 0)
8494                 return libbpf_err(-EBUSY);
8495         map->def.type = type;
8496         return 0;
8497 }
8498
8499 __u32 bpf_map__map_flags(const struct bpf_map *map)
8500 {
8501         return map->def.map_flags;
8502 }
8503
8504 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
8505 {
8506         if (map->fd >= 0)
8507                 return libbpf_err(-EBUSY);
8508         map->def.map_flags = flags;
8509         return 0;
8510 }
8511
8512 __u32 bpf_map__numa_node(const struct bpf_map *map)
8513 {
8514         return map->numa_node;
8515 }
8516
8517 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
8518 {
8519         if (map->fd >= 0)
8520                 return libbpf_err(-EBUSY);
8521         map->numa_node = numa_node;
8522         return 0;
8523 }
8524
8525 __u32 bpf_map__key_size(const struct bpf_map *map)
8526 {
8527         return map->def.key_size;
8528 }
8529
8530 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
8531 {
8532         if (map->fd >= 0)
8533                 return libbpf_err(-EBUSY);
8534         map->def.key_size = size;
8535         return 0;
8536 }
8537
8538 __u32 bpf_map__value_size(const struct bpf_map *map)
8539 {
8540         return map->def.value_size;
8541 }
8542
8543 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
8544 {
8545         if (map->fd >= 0)
8546                 return libbpf_err(-EBUSY);
8547         map->def.value_size = size;
8548         return 0;
8549 }
8550
8551 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8552 {
8553         return map ? map->btf_key_type_id : 0;
8554 }
8555
8556 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8557 {
8558         return map ? map->btf_value_type_id : 0;
8559 }
8560
8561 int bpf_map__set_priv(struct bpf_map *map, void *priv,
8562                      bpf_map_clear_priv_t clear_priv)
8563 {
8564         if (!map)
8565                 return libbpf_err(-EINVAL);
8566
8567         if (map->priv) {
8568                 if (map->clear_priv)
8569                         map->clear_priv(map, map->priv);
8570         }
8571
8572         map->priv = priv;
8573         map->clear_priv = clear_priv;
8574         return 0;
8575 }
8576
8577 void *bpf_map__priv(const struct bpf_map *map)
8578 {
8579         return map ? map->priv : libbpf_err_ptr(-EINVAL);
8580 }
8581
8582 int bpf_map__set_initial_value(struct bpf_map *map,
8583                                const void *data, size_t size)
8584 {
8585         if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
8586             size != map->def.value_size || map->fd >= 0)
8587                 return libbpf_err(-EINVAL);
8588
8589         memcpy(map->mmaped, data, size);
8590         return 0;
8591 }
8592
8593 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
8594 {
8595         if (!map->mmaped)
8596                 return NULL;
8597         *psize = map->def.value_size;
8598         return map->mmaped;
8599 }
8600
8601 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
8602 {
8603         return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
8604 }
8605
8606 bool bpf_map__is_internal(const struct bpf_map *map)
8607 {
8608         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
8609 }
8610
8611 __u32 bpf_map__ifindex(const struct bpf_map *map)
8612 {
8613         return map->map_ifindex;
8614 }
8615
8616 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
8617 {
8618         if (map->fd >= 0)
8619                 return libbpf_err(-EBUSY);
8620         map->map_ifindex = ifindex;
8621         return 0;
8622 }
8623
8624 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
8625 {
8626         if (!bpf_map_type__is_map_in_map(map->def.type)) {
8627                 pr_warn("error: unsupported map type\n");
8628                 return libbpf_err(-EINVAL);
8629         }
8630         if (map->inner_map_fd != -1) {
8631                 pr_warn("error: inner_map_fd already specified\n");
8632                 return libbpf_err(-EINVAL);
8633         }
8634         zfree(&map->inner_map);
8635         map->inner_map_fd = fd;
8636         return 0;
8637 }
8638
8639 static struct bpf_map *
8640 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
8641 {
8642         ssize_t idx;
8643         struct bpf_map *s, *e;
8644
8645         if (!obj || !obj->maps)
8646                 return errno = EINVAL, NULL;
8647
8648         s = obj->maps;
8649         e = obj->maps + obj->nr_maps;
8650
8651         if ((m < s) || (m >= e)) {
8652                 pr_warn("error in %s: map handler doesn't belong to object\n",
8653                          __func__);
8654                 return errno = EINVAL, NULL;
8655         }
8656
8657         idx = (m - obj->maps) + i;
8658         if (idx >= obj->nr_maps || idx < 0)
8659                 return NULL;
8660         return &obj->maps[idx];
8661 }
8662
8663 struct bpf_map *
8664 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
8665 {
8666         if (prev == NULL)
8667                 return obj->maps;
8668
8669         return __bpf_map__iter(prev, obj, 1);
8670 }
8671
8672 struct bpf_map *
8673 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
8674 {
8675         if (next == NULL) {
8676                 if (!obj->nr_maps)
8677                         return NULL;
8678                 return obj->maps + obj->nr_maps - 1;
8679         }
8680
8681         return __bpf_map__iter(next, obj, -1);
8682 }
8683
8684 struct bpf_map *
8685 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
8686 {
8687         struct bpf_map *pos;
8688
8689         bpf_object__for_each_map(pos, obj) {
8690                 if (pos->name && !strcmp(pos->name, name))
8691                         return pos;
8692         }
8693         return errno = ENOENT, NULL;
8694 }
8695
8696 int
8697 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
8698 {
8699         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
8700 }
8701
8702 struct bpf_map *
8703 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
8704 {
8705         return libbpf_err_ptr(-ENOTSUP);
8706 }
8707
8708 long libbpf_get_error(const void *ptr)
8709 {
8710         if (!IS_ERR_OR_NULL(ptr))
8711                 return 0;
8712
8713         if (IS_ERR(ptr))
8714                 errno = -PTR_ERR(ptr);
8715
8716         /* If ptr == NULL, then errno should be already set by the failing
8717          * API, because libbpf never returns NULL on success and it now always
8718          * sets errno on error. So no extra errno handling for ptr == NULL
8719          * case.
8720          */
8721         return -errno;
8722 }
8723
8724 int bpf_prog_load(const char *file, enum bpf_prog_type type,
8725                   struct bpf_object **pobj, int *prog_fd)
8726 {
8727         struct bpf_prog_load_attr attr;
8728
8729         memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
8730         attr.file = file;
8731         attr.prog_type = type;
8732         attr.expected_attach_type = 0;
8733
8734         return bpf_prog_load_xattr(&attr, pobj, prog_fd);
8735 }
8736
8737 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
8738                         struct bpf_object **pobj, int *prog_fd)
8739 {
8740         struct bpf_object_open_attr open_attr = {};
8741         struct bpf_program *prog, *first_prog = NULL;
8742         struct bpf_object *obj;
8743         struct bpf_map *map;
8744         int err;
8745
8746         if (!attr)
8747                 return libbpf_err(-EINVAL);
8748         if (!attr->file)
8749                 return libbpf_err(-EINVAL);
8750
8751         open_attr.file = attr->file;
8752         open_attr.prog_type = attr->prog_type;
8753
8754         obj = bpf_object__open_xattr(&open_attr);
8755         err = libbpf_get_error(obj);
8756         if (err)
8757                 return libbpf_err(-ENOENT);
8758
8759         bpf_object__for_each_program(prog, obj) {
8760                 enum bpf_attach_type attach_type = attr->expected_attach_type;
8761                 /*
8762                  * to preserve backwards compatibility, bpf_prog_load treats
8763                  * attr->prog_type, if specified, as an override to whatever
8764                  * bpf_object__open guessed
8765                  */
8766                 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
8767                         bpf_program__set_type(prog, attr->prog_type);
8768                         bpf_program__set_expected_attach_type(prog,
8769                                                               attach_type);
8770                 }
8771                 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
8772                         /*
8773                          * we haven't guessed from section name and user
8774                          * didn't provide a fallback type, too bad...
8775                          */
8776                         bpf_object__close(obj);
8777                         return libbpf_err(-EINVAL);
8778                 }
8779
8780                 prog->prog_ifindex = attr->ifindex;
8781                 prog->log_level = attr->log_level;
8782                 prog->prog_flags |= attr->prog_flags;
8783                 if (!first_prog)
8784                         first_prog = prog;
8785         }
8786
8787         bpf_object__for_each_map(map, obj) {
8788                 if (!bpf_map__is_offload_neutral(map))
8789                         map->map_ifindex = attr->ifindex;
8790         }
8791
8792         if (!first_prog) {
8793                 pr_warn("object file doesn't contain bpf program\n");
8794                 bpf_object__close(obj);
8795                 return libbpf_err(-ENOENT);
8796         }
8797
8798         err = bpf_object__load(obj);
8799         if (err) {
8800                 bpf_object__close(obj);
8801                 return libbpf_err(err);
8802         }
8803
8804         *pobj = obj;
8805         *prog_fd = bpf_program__fd(first_prog);
8806         return 0;
8807 }
8808
8809 struct bpf_link {
8810         int (*detach)(struct bpf_link *link);
8811         int (*destroy)(struct bpf_link *link);
8812         char *pin_path;         /* NULL, if not pinned */
8813         int fd;                 /* hook FD, -1 if not applicable */
8814         bool disconnected;
8815 };
8816
8817 /* Replace link's underlying BPF program with the new one */
8818 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
8819 {
8820         int ret;
8821
8822         ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
8823         return libbpf_err_errno(ret);
8824 }
8825
8826 /* Release "ownership" of underlying BPF resource (typically, BPF program
8827  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
8828  * link, when destructed through bpf_link__destroy() call won't attempt to
8829  * detach/unregisted that BPF resource. This is useful in situations where,
8830  * say, attached BPF program has to outlive userspace program that attached it
8831  * in the system. Depending on type of BPF program, though, there might be
8832  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
8833  * exit of userspace program doesn't trigger automatic detachment and clean up
8834  * inside the kernel.
8835  */
8836 void bpf_link__disconnect(struct bpf_link *link)
8837 {
8838         link->disconnected = true;
8839 }
8840
8841 int bpf_link__destroy(struct bpf_link *link)
8842 {
8843         int err = 0;
8844
8845         if (IS_ERR_OR_NULL(link))
8846                 return 0;
8847
8848         if (!link->disconnected && link->detach)
8849                 err = link->detach(link);
8850         if (link->destroy)
8851                 link->destroy(link);
8852         if (link->pin_path)
8853                 free(link->pin_path);
8854         free(link);
8855
8856         return libbpf_err(err);
8857 }
8858
8859 int bpf_link__fd(const struct bpf_link *link)
8860 {
8861         return link->fd;
8862 }
8863
8864 const char *bpf_link__pin_path(const struct bpf_link *link)
8865 {
8866         return link->pin_path;
8867 }
8868
8869 static int bpf_link__detach_fd(struct bpf_link *link)
8870 {
8871         return libbpf_err_errno(close(link->fd));
8872 }
8873
8874 struct bpf_link *bpf_link__open(const char *path)
8875 {
8876         struct bpf_link *link;
8877         int fd;
8878
8879         fd = bpf_obj_get(path);
8880         if (fd < 0) {
8881                 fd = -errno;
8882                 pr_warn("failed to open link at %s: %d\n", path, fd);
8883                 return libbpf_err_ptr(fd);
8884         }
8885
8886         link = calloc(1, sizeof(*link));
8887         if (!link) {
8888                 close(fd);
8889                 return libbpf_err_ptr(-ENOMEM);
8890         }
8891         link->detach = &bpf_link__detach_fd;
8892         link->fd = fd;
8893
8894         link->pin_path = strdup(path);
8895         if (!link->pin_path) {
8896                 bpf_link__destroy(link);
8897                 return libbpf_err_ptr(-ENOMEM);
8898         }
8899
8900         return link;
8901 }
8902
8903 int bpf_link__detach(struct bpf_link *link)
8904 {
8905         return bpf_link_detach(link->fd) ? -errno : 0;
8906 }
8907
8908 int bpf_link__pin(struct bpf_link *link, const char *path)
8909 {
8910         int err;
8911
8912         if (link->pin_path)
8913                 return libbpf_err(-EBUSY);
8914         err = make_parent_dir(path);
8915         if (err)
8916                 return libbpf_err(err);
8917         err = check_path(path);
8918         if (err)
8919                 return libbpf_err(err);
8920
8921         link->pin_path = strdup(path);
8922         if (!link->pin_path)
8923                 return libbpf_err(-ENOMEM);
8924
8925         if (bpf_obj_pin(link->fd, link->pin_path)) {
8926                 err = -errno;
8927                 zfree(&link->pin_path);
8928                 return libbpf_err(err);
8929         }
8930
8931         pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
8932         return 0;
8933 }
8934
8935 int bpf_link__unpin(struct bpf_link *link)
8936 {
8937         int err;
8938
8939         if (!link->pin_path)
8940                 return libbpf_err(-EINVAL);
8941
8942         err = unlink(link->pin_path);
8943         if (err != 0)
8944                 return -errno;
8945
8946         pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
8947         zfree(&link->pin_path);
8948         return 0;
8949 }
8950
8951 static int bpf_link__detach_perf_event(struct bpf_link *link)
8952 {
8953         int err;
8954
8955         err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
8956         if (err)
8957                 err = -errno;
8958
8959         close(link->fd);
8960         return libbpf_err(err);
8961 }
8962
8963 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog, int pfd)
8964 {
8965         char errmsg[STRERR_BUFSIZE];
8966         struct bpf_link *link;
8967         int prog_fd, err;
8968
8969         if (pfd < 0) {
8970                 pr_warn("prog '%s': invalid perf event FD %d\n",
8971                         prog->name, pfd);
8972                 return libbpf_err_ptr(-EINVAL);
8973         }
8974         prog_fd = bpf_program__fd(prog);
8975         if (prog_fd < 0) {
8976                 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
8977                         prog->name);
8978                 return libbpf_err_ptr(-EINVAL);
8979         }
8980
8981         link = calloc(1, sizeof(*link));
8982         if (!link)
8983                 return libbpf_err_ptr(-ENOMEM);
8984         link->detach = &bpf_link__detach_perf_event;
8985         link->fd = pfd;
8986
8987         if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
8988                 err = -errno;
8989                 free(link);
8990                 pr_warn("prog '%s': failed to attach to pfd %d: %s\n",
8991                         prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
8992                 if (err == -EPROTO)
8993                         pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
8994                                 prog->name, pfd);
8995                 return libbpf_err_ptr(err);
8996         }
8997         if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
8998                 err = -errno;
8999                 free(link);
9000                 pr_warn("prog '%s': failed to enable pfd %d: %s\n",
9001                         prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9002                 return libbpf_err_ptr(err);
9003         }
9004         return link;
9005 }
9006
9007 /*
9008  * this function is expected to parse integer in the range of [0, 2^31-1] from
9009  * given file using scanf format string fmt. If actual parsed value is
9010  * negative, the result might be indistinguishable from error
9011  */
9012 static int parse_uint_from_file(const char *file, const char *fmt)
9013 {
9014         char buf[STRERR_BUFSIZE];
9015         int err, ret;
9016         FILE *f;
9017
9018         f = fopen(file, "r");
9019         if (!f) {
9020                 err = -errno;
9021                 pr_debug("failed to open '%s': %s\n", file,
9022                          libbpf_strerror_r(err, buf, sizeof(buf)));
9023                 return err;
9024         }
9025         err = fscanf(f, fmt, &ret);
9026         if (err != 1) {
9027                 err = err == EOF ? -EIO : -errno;
9028                 pr_debug("failed to parse '%s': %s\n", file,
9029                         libbpf_strerror_r(err, buf, sizeof(buf)));
9030                 fclose(f);
9031                 return err;
9032         }
9033         fclose(f);
9034         return ret;
9035 }
9036
9037 static int determine_kprobe_perf_type(void)
9038 {
9039         const char *file = "/sys/bus/event_source/devices/kprobe/type";
9040
9041         return parse_uint_from_file(file, "%d\n");
9042 }
9043
9044 static int determine_uprobe_perf_type(void)
9045 {
9046         const char *file = "/sys/bus/event_source/devices/uprobe/type";
9047
9048         return parse_uint_from_file(file, "%d\n");
9049 }
9050
9051 static int determine_kprobe_retprobe_bit(void)
9052 {
9053         const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9054
9055         return parse_uint_from_file(file, "config:%d\n");
9056 }
9057
9058 static int determine_uprobe_retprobe_bit(void)
9059 {
9060         const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9061
9062         return parse_uint_from_file(file, "config:%d\n");
9063 }
9064
9065 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9066                                  uint64_t offset, int pid)
9067 {
9068         struct perf_event_attr attr = {};
9069         char errmsg[STRERR_BUFSIZE];
9070         int type, pfd, err;
9071
9072         type = uprobe ? determine_uprobe_perf_type()
9073                       : determine_kprobe_perf_type();
9074         if (type < 0) {
9075                 pr_warn("failed to determine %s perf type: %s\n",
9076                         uprobe ? "uprobe" : "kprobe",
9077                         libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9078                 return type;
9079         }
9080         if (retprobe) {
9081                 int bit = uprobe ? determine_uprobe_retprobe_bit()
9082                                  : determine_kprobe_retprobe_bit();
9083
9084                 if (bit < 0) {
9085                         pr_warn("failed to determine %s retprobe bit: %s\n",
9086                                 uprobe ? "uprobe" : "kprobe",
9087                                 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9088                         return bit;
9089                 }
9090                 attr.config |= 1 << bit;
9091         }
9092         attr.size = sizeof(attr);
9093         attr.type = type;
9094         attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9095         attr.config2 = offset;           /* kprobe_addr or probe_offset */
9096
9097         /* pid filter is meaningful only for uprobes */
9098         pfd = syscall(__NR_perf_event_open, &attr,
9099                       pid < 0 ? -1 : pid /* pid */,
9100                       pid == -1 ? 0 : -1 /* cpu */,
9101                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9102         if (pfd < 0) {
9103                 err = -errno;
9104                 pr_warn("%s perf_event_open() failed: %s\n",
9105                         uprobe ? "uprobe" : "kprobe",
9106                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9107                 return err;
9108         }
9109         return pfd;
9110 }
9111
9112 struct bpf_link *
9113 bpf_program__attach_kprobe_opts(struct bpf_program *prog,
9114                                 const char *func_name,
9115                                 struct bpf_kprobe_opts *opts)
9116 {
9117         char errmsg[STRERR_BUFSIZE];
9118         struct bpf_link *link;
9119         unsigned long offset;
9120         bool retprobe;
9121         int pfd, err;
9122
9123         if (!OPTS_VALID(opts, bpf_kprobe_opts))
9124                 return libbpf_err_ptr(-EINVAL);
9125
9126         retprobe = OPTS_GET(opts, retprobe, false);
9127         offset = OPTS_GET(opts, offset, 0);
9128
9129         pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
9130                                     offset, -1 /* pid */);
9131         if (pfd < 0) {
9132                 pr_warn("prog '%s': failed to create %s '%s' perf event: %s\n",
9133                         prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9134                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9135                 return libbpf_err_ptr(pfd);
9136         }
9137         link = bpf_program__attach_perf_event(prog, pfd);
9138         err = libbpf_get_error(link);
9139         if (err) {
9140                 close(pfd);
9141                 pr_warn("prog '%s': failed to attach to %s '%s': %s\n",
9142                         prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9143                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9144                 return libbpf_err_ptr(err);
9145         }
9146         return link;
9147 }
9148
9149 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
9150                                             bool retprobe,
9151                                             const char *func_name)
9152 {
9153         DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
9154                 .retprobe = retprobe,
9155         );
9156
9157         return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
9158 }
9159
9160 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
9161                                       struct bpf_program *prog)
9162 {
9163         DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
9164         unsigned long offset = 0;
9165         struct bpf_link *link;
9166         const char *func_name;
9167         char *func;
9168         int n, err;
9169
9170         func_name = prog->sec_name + sec->len;
9171         opts.retprobe = strcmp(sec->sec, "kretprobe/") == 0;
9172
9173         n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
9174         if (n < 1) {
9175                 err = -EINVAL;
9176                 pr_warn("kprobe name is invalid: %s\n", func_name);
9177                 return libbpf_err_ptr(err);
9178         }
9179         if (opts.retprobe && offset != 0) {
9180                 free(func);
9181                 err = -EINVAL;
9182                 pr_warn("kretprobes do not support offset specification\n");
9183                 return libbpf_err_ptr(err);
9184         }
9185
9186         opts.offset = offset;
9187         link = bpf_program__attach_kprobe_opts(prog, func, &opts);
9188         free(func);
9189         return link;
9190 }
9191
9192 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
9193                                             bool retprobe, pid_t pid,
9194                                             const char *binary_path,
9195                                             size_t func_offset)
9196 {
9197         char errmsg[STRERR_BUFSIZE];
9198         struct bpf_link *link;
9199         int pfd, err;
9200
9201         pfd = perf_event_open_probe(true /* uprobe */, retprobe,
9202                                     binary_path, func_offset, pid);
9203         if (pfd < 0) {
9204                 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
9205                         prog->name, retprobe ? "uretprobe" : "uprobe",
9206                         binary_path, func_offset,
9207                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9208                 return libbpf_err_ptr(pfd);
9209         }
9210         link = bpf_program__attach_perf_event(prog, pfd);
9211         err = libbpf_get_error(link);
9212         if (err) {
9213                 close(pfd);
9214                 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
9215                         prog->name, retprobe ? "uretprobe" : "uprobe",
9216                         binary_path, func_offset,
9217                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9218                 return libbpf_err_ptr(err);
9219         }
9220         return link;
9221 }
9222
9223 static int determine_tracepoint_id(const char *tp_category,
9224                                    const char *tp_name)
9225 {
9226         char file[PATH_MAX];
9227         int ret;
9228
9229         ret = snprintf(file, sizeof(file),
9230                        "/sys/kernel/debug/tracing/events/%s/%s/id",
9231                        tp_category, tp_name);
9232         if (ret < 0)
9233                 return -errno;
9234         if (ret >= sizeof(file)) {
9235                 pr_debug("tracepoint %s/%s path is too long\n",
9236                          tp_category, tp_name);
9237                 return -E2BIG;
9238         }
9239         return parse_uint_from_file(file, "%d\n");
9240 }
9241
9242 static int perf_event_open_tracepoint(const char *tp_category,
9243                                       const char *tp_name)
9244 {
9245         struct perf_event_attr attr = {};
9246         char errmsg[STRERR_BUFSIZE];
9247         int tp_id, pfd, err;
9248
9249         tp_id = determine_tracepoint_id(tp_category, tp_name);
9250         if (tp_id < 0) {
9251                 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
9252                         tp_category, tp_name,
9253                         libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
9254                 return tp_id;
9255         }
9256
9257         attr.type = PERF_TYPE_TRACEPOINT;
9258         attr.size = sizeof(attr);
9259         attr.config = tp_id;
9260
9261         pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
9262                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9263         if (pfd < 0) {
9264                 err = -errno;
9265                 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
9266                         tp_category, tp_name,
9267                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9268                 return err;
9269         }
9270         return pfd;
9271 }
9272
9273 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
9274                                                 const char *tp_category,
9275                                                 const char *tp_name)
9276 {
9277         char errmsg[STRERR_BUFSIZE];
9278         struct bpf_link *link;
9279         int pfd, err;
9280
9281         pfd = perf_event_open_tracepoint(tp_category, tp_name);
9282         if (pfd < 0) {
9283                 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
9284                         prog->name, tp_category, tp_name,
9285                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9286                 return libbpf_err_ptr(pfd);
9287         }
9288         link = bpf_program__attach_perf_event(prog, pfd);
9289         err = libbpf_get_error(link);
9290         if (err) {
9291                 close(pfd);
9292                 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
9293                         prog->name, tp_category, tp_name,
9294                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9295                 return libbpf_err_ptr(err);
9296         }
9297         return link;
9298 }
9299
9300 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
9301                                   struct bpf_program *prog)
9302 {
9303         char *sec_name, *tp_cat, *tp_name;
9304         struct bpf_link *link;
9305
9306         sec_name = strdup(prog->sec_name);
9307         if (!sec_name)
9308                 return libbpf_err_ptr(-ENOMEM);
9309
9310         /* extract "tp/<category>/<name>" */
9311         tp_cat = sec_name + sec->len;
9312         tp_name = strchr(tp_cat, '/');
9313         if (!tp_name) {
9314                 free(sec_name);
9315                 return libbpf_err_ptr(-EINVAL);
9316         }
9317         *tp_name = '\0';
9318         tp_name++;
9319
9320         link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
9321         free(sec_name);
9322         return link;
9323 }
9324
9325 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
9326                                                     const char *tp_name)
9327 {
9328         char errmsg[STRERR_BUFSIZE];
9329         struct bpf_link *link;
9330         int prog_fd, pfd;
9331
9332         prog_fd = bpf_program__fd(prog);
9333         if (prog_fd < 0) {
9334                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9335                 return libbpf_err_ptr(-EINVAL);
9336         }
9337
9338         link = calloc(1, sizeof(*link));
9339         if (!link)
9340                 return libbpf_err_ptr(-ENOMEM);
9341         link->detach = &bpf_link__detach_fd;
9342
9343         pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
9344         if (pfd < 0) {
9345                 pfd = -errno;
9346                 free(link);
9347                 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
9348                         prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9349                 return libbpf_err_ptr(pfd);
9350         }
9351         link->fd = pfd;
9352         return link;
9353 }
9354
9355 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
9356                                       struct bpf_program *prog)
9357 {
9358         const char *tp_name = prog->sec_name + sec->len;
9359
9360         return bpf_program__attach_raw_tracepoint(prog, tp_name);
9361 }
9362
9363 /* Common logic for all BPF program types that attach to a btf_id */
9364 static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
9365 {
9366         char errmsg[STRERR_BUFSIZE];
9367         struct bpf_link *link;
9368         int prog_fd, pfd;
9369
9370         prog_fd = bpf_program__fd(prog);
9371         if (prog_fd < 0) {
9372                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9373                 return libbpf_err_ptr(-EINVAL);
9374         }
9375
9376         link = calloc(1, sizeof(*link));
9377         if (!link)
9378                 return libbpf_err_ptr(-ENOMEM);
9379         link->detach = &bpf_link__detach_fd;
9380
9381         pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
9382         if (pfd < 0) {
9383                 pfd = -errno;
9384                 free(link);
9385                 pr_warn("prog '%s': failed to attach: %s\n",
9386                         prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9387                 return libbpf_err_ptr(pfd);
9388         }
9389         link->fd = pfd;
9390         return (struct bpf_link *)link;
9391 }
9392
9393 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
9394 {
9395         return bpf_program__attach_btf_id(prog);
9396 }
9397
9398 struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
9399 {
9400         return bpf_program__attach_btf_id(prog);
9401 }
9402
9403 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
9404                                      struct bpf_program *prog)
9405 {
9406         return bpf_program__attach_trace(prog);
9407 }
9408
9409 static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
9410                                    struct bpf_program *prog)
9411 {
9412         return bpf_program__attach_lsm(prog);
9413 }
9414
9415 static struct bpf_link *
9416 bpf_program__attach_fd(struct bpf_program *prog, int target_fd, int btf_id,
9417                        const char *target_name)
9418 {
9419         DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
9420                             .target_btf_id = btf_id);
9421         enum bpf_attach_type attach_type;
9422         char errmsg[STRERR_BUFSIZE];
9423         struct bpf_link *link;
9424         int prog_fd, link_fd;
9425
9426         prog_fd = bpf_program__fd(prog);
9427         if (prog_fd < 0) {
9428                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9429                 return libbpf_err_ptr(-EINVAL);
9430         }
9431
9432         link = calloc(1, sizeof(*link));
9433         if (!link)
9434                 return libbpf_err_ptr(-ENOMEM);
9435         link->detach = &bpf_link__detach_fd;
9436
9437         attach_type = bpf_program__get_expected_attach_type(prog);
9438         link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
9439         if (link_fd < 0) {
9440                 link_fd = -errno;
9441                 free(link);
9442                 pr_warn("prog '%s': failed to attach to %s: %s\n",
9443                         prog->name, target_name,
9444                         libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9445                 return libbpf_err_ptr(link_fd);
9446         }
9447         link->fd = link_fd;
9448         return link;
9449 }
9450
9451 struct bpf_link *
9452 bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
9453 {
9454         return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
9455 }
9456
9457 struct bpf_link *
9458 bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
9459 {
9460         return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
9461 }
9462
9463 struct bpf_link *bpf_program__attach_xdp(struct bpf_program *prog, int ifindex)
9464 {
9465         /* target_fd/target_ifindex use the same field in LINK_CREATE */
9466         return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
9467 }
9468
9469 struct bpf_link *bpf_program__attach_freplace(struct bpf_program *prog,
9470                                               int target_fd,
9471                                               const char *attach_func_name)
9472 {
9473         int btf_id;
9474
9475         if (!!target_fd != !!attach_func_name) {
9476                 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
9477                         prog->name);
9478                 return libbpf_err_ptr(-EINVAL);
9479         }
9480
9481         if (prog->type != BPF_PROG_TYPE_EXT) {
9482                 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
9483                         prog->name);
9484                 return libbpf_err_ptr(-EINVAL);
9485         }
9486
9487         if (target_fd) {
9488                 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
9489                 if (btf_id < 0)
9490                         return libbpf_err_ptr(btf_id);
9491
9492                 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
9493         } else {
9494                 /* no target, so use raw_tracepoint_open for compatibility
9495                  * with old kernels
9496                  */
9497                 return bpf_program__attach_trace(prog);
9498         }
9499 }
9500
9501 struct bpf_link *
9502 bpf_program__attach_iter(struct bpf_program *prog,
9503                          const struct bpf_iter_attach_opts *opts)
9504 {
9505         DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
9506         char errmsg[STRERR_BUFSIZE];
9507         struct bpf_link *link;
9508         int prog_fd, link_fd;
9509         __u32 target_fd = 0;
9510
9511         if (!OPTS_VALID(opts, bpf_iter_attach_opts))
9512                 return libbpf_err_ptr(-EINVAL);
9513
9514         link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
9515         link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
9516
9517         prog_fd = bpf_program__fd(prog);
9518         if (prog_fd < 0) {
9519                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9520                 return libbpf_err_ptr(-EINVAL);
9521         }
9522
9523         link = calloc(1, sizeof(*link));
9524         if (!link)
9525                 return libbpf_err_ptr(-ENOMEM);
9526         link->detach = &bpf_link__detach_fd;
9527
9528         link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
9529                                   &link_create_opts);
9530         if (link_fd < 0) {
9531                 link_fd = -errno;
9532                 free(link);
9533                 pr_warn("prog '%s': failed to attach to iterator: %s\n",
9534                         prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9535                 return libbpf_err_ptr(link_fd);
9536         }
9537         link->fd = link_fd;
9538         return link;
9539 }
9540
9541 static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
9542                                     struct bpf_program *prog)
9543 {
9544         return bpf_program__attach_iter(prog, NULL);
9545 }
9546
9547 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
9548 {
9549         const struct bpf_sec_def *sec_def;
9550
9551         sec_def = find_sec_def(prog->sec_name);
9552         if (!sec_def || !sec_def->attach_fn)
9553                 return libbpf_err_ptr(-ESRCH);
9554
9555         return sec_def->attach_fn(sec_def, prog);
9556 }
9557
9558 static int bpf_link__detach_struct_ops(struct bpf_link *link)
9559 {
9560         __u32 zero = 0;
9561
9562         if (bpf_map_delete_elem(link->fd, &zero))
9563                 return -errno;
9564
9565         return 0;
9566 }
9567
9568 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
9569 {
9570         struct bpf_struct_ops *st_ops;
9571         struct bpf_link *link;
9572         __u32 i, zero = 0;
9573         int err;
9574
9575         if (!bpf_map__is_struct_ops(map) || map->fd == -1)
9576                 return libbpf_err_ptr(-EINVAL);
9577
9578         link = calloc(1, sizeof(*link));
9579         if (!link)
9580                 return libbpf_err_ptr(-EINVAL);
9581
9582         st_ops = map->st_ops;
9583         for (i = 0; i < btf_vlen(st_ops->type); i++) {
9584                 struct bpf_program *prog = st_ops->progs[i];
9585                 void *kern_data;
9586                 int prog_fd;
9587
9588                 if (!prog)
9589                         continue;
9590
9591                 prog_fd = bpf_program__fd(prog);
9592                 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9593                 *(unsigned long *)kern_data = prog_fd;
9594         }
9595
9596         err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
9597         if (err) {
9598                 err = -errno;
9599                 free(link);
9600                 return libbpf_err_ptr(err);
9601         }
9602
9603         link->detach = bpf_link__detach_struct_ops;
9604         link->fd = map->fd;
9605
9606         return link;
9607 }
9608
9609 enum bpf_perf_event_ret
9610 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
9611                            void **copy_mem, size_t *copy_size,
9612                            bpf_perf_event_print_t fn, void *private_data)
9613 {
9614         struct perf_event_mmap_page *header = mmap_mem;
9615         __u64 data_head = ring_buffer_read_head(header);
9616         __u64 data_tail = header->data_tail;
9617         void *base = ((__u8 *)header) + page_size;
9618         int ret = LIBBPF_PERF_EVENT_CONT;
9619         struct perf_event_header *ehdr;
9620         size_t ehdr_size;
9621
9622         while (data_head != data_tail) {
9623                 ehdr = base + (data_tail & (mmap_size - 1));
9624                 ehdr_size = ehdr->size;
9625
9626                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
9627                         void *copy_start = ehdr;
9628                         size_t len_first = base + mmap_size - copy_start;
9629                         size_t len_secnd = ehdr_size - len_first;
9630
9631                         if (*copy_size < ehdr_size) {
9632                                 free(*copy_mem);
9633                                 *copy_mem = malloc(ehdr_size);
9634                                 if (!*copy_mem) {
9635                                         *copy_size = 0;
9636                                         ret = LIBBPF_PERF_EVENT_ERROR;
9637                                         break;
9638                                 }
9639                                 *copy_size = ehdr_size;
9640                         }
9641
9642                         memcpy(*copy_mem, copy_start, len_first);
9643                         memcpy(*copy_mem + len_first, base, len_secnd);
9644                         ehdr = *copy_mem;
9645                 }
9646
9647                 ret = fn(ehdr, private_data);
9648                 data_tail += ehdr_size;
9649                 if (ret != LIBBPF_PERF_EVENT_CONT)
9650                         break;
9651         }
9652
9653         ring_buffer_write_tail(header, data_tail);
9654         return libbpf_err(ret);
9655 }
9656
9657 struct perf_buffer;
9658
9659 struct perf_buffer_params {
9660         struct perf_event_attr *attr;
9661         /* if event_cb is specified, it takes precendence */
9662         perf_buffer_event_fn event_cb;
9663         /* sample_cb and lost_cb are higher-level common-case callbacks */
9664         perf_buffer_sample_fn sample_cb;
9665         perf_buffer_lost_fn lost_cb;
9666         void *ctx;
9667         int cpu_cnt;
9668         int *cpus;
9669         int *map_keys;
9670 };
9671
9672 struct perf_cpu_buf {
9673         struct perf_buffer *pb;
9674         void *base; /* mmap()'ed memory */
9675         void *buf; /* for reconstructing segmented data */
9676         size_t buf_size;
9677         int fd;
9678         int cpu;
9679         int map_key;
9680 };
9681
9682 struct perf_buffer {
9683         perf_buffer_event_fn event_cb;
9684         perf_buffer_sample_fn sample_cb;
9685         perf_buffer_lost_fn lost_cb;
9686         void *ctx; /* passed into callbacks */
9687
9688         size_t page_size;
9689         size_t mmap_size;
9690         struct perf_cpu_buf **cpu_bufs;
9691         struct epoll_event *events;
9692         int cpu_cnt; /* number of allocated CPU buffers */
9693         int epoll_fd; /* perf event FD */
9694         int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
9695 };
9696
9697 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
9698                                       struct perf_cpu_buf *cpu_buf)
9699 {
9700         if (!cpu_buf)
9701                 return;
9702         if (cpu_buf->base &&
9703             munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
9704                 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
9705         if (cpu_buf->fd >= 0) {
9706                 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
9707                 close(cpu_buf->fd);
9708         }
9709         free(cpu_buf->buf);
9710         free(cpu_buf);
9711 }
9712
9713 void perf_buffer__free(struct perf_buffer *pb)
9714 {
9715         int i;
9716
9717         if (IS_ERR_OR_NULL(pb))
9718                 return;
9719         if (pb->cpu_bufs) {
9720                 for (i = 0; i < pb->cpu_cnt; i++) {
9721                         struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
9722
9723                         if (!cpu_buf)
9724                                 continue;
9725
9726                         bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
9727                         perf_buffer__free_cpu_buf(pb, cpu_buf);
9728                 }
9729                 free(pb->cpu_bufs);
9730         }
9731         if (pb->epoll_fd >= 0)
9732                 close(pb->epoll_fd);
9733         free(pb->events);
9734         free(pb);
9735 }
9736
9737 static struct perf_cpu_buf *
9738 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
9739                           int cpu, int map_key)
9740 {
9741         struct perf_cpu_buf *cpu_buf;
9742         char msg[STRERR_BUFSIZE];
9743         int err;
9744
9745         cpu_buf = calloc(1, sizeof(*cpu_buf));
9746         if (!cpu_buf)
9747                 return ERR_PTR(-ENOMEM);
9748
9749         cpu_buf->pb = pb;
9750         cpu_buf->cpu = cpu;
9751         cpu_buf->map_key = map_key;
9752
9753         cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
9754                               -1, PERF_FLAG_FD_CLOEXEC);
9755         if (cpu_buf->fd < 0) {
9756                 err = -errno;
9757                 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
9758                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9759                 goto error;
9760         }
9761
9762         cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
9763                              PROT_READ | PROT_WRITE, MAP_SHARED,
9764                              cpu_buf->fd, 0);
9765         if (cpu_buf->base == MAP_FAILED) {
9766                 cpu_buf->base = NULL;
9767                 err = -errno;
9768                 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
9769                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9770                 goto error;
9771         }
9772
9773         if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9774                 err = -errno;
9775                 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
9776                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
9777                 goto error;
9778         }
9779
9780         return cpu_buf;
9781
9782 error:
9783         perf_buffer__free_cpu_buf(pb, cpu_buf);
9784         return (struct perf_cpu_buf *)ERR_PTR(err);
9785 }
9786
9787 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
9788                                               struct perf_buffer_params *p);
9789
9790 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
9791                                      const struct perf_buffer_opts *opts)
9792 {
9793         struct perf_buffer_params p = {};
9794         struct perf_event_attr attr = { 0, };
9795
9796         attr.config = PERF_COUNT_SW_BPF_OUTPUT;
9797         attr.type = PERF_TYPE_SOFTWARE;
9798         attr.sample_type = PERF_SAMPLE_RAW;
9799         attr.sample_period = 1;
9800         attr.wakeup_events = 1;
9801
9802         p.attr = &attr;
9803         p.sample_cb = opts ? opts->sample_cb : NULL;
9804         p.lost_cb = opts ? opts->lost_cb : NULL;
9805         p.ctx = opts ? opts->ctx : NULL;
9806
9807         return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
9808 }
9809
9810 struct perf_buffer *
9811 perf_buffer__new_raw(int map_fd, size_t page_cnt,
9812                      const struct perf_buffer_raw_opts *opts)
9813 {
9814         struct perf_buffer_params p = {};
9815
9816         p.attr = opts->attr;
9817         p.event_cb = opts->event_cb;
9818         p.ctx = opts->ctx;
9819         p.cpu_cnt = opts->cpu_cnt;
9820         p.cpus = opts->cpus;
9821         p.map_keys = opts->map_keys;
9822
9823         return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
9824 }
9825
9826 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
9827                                               struct perf_buffer_params *p)
9828 {
9829         const char *online_cpus_file = "/sys/devices/system/cpu/online";
9830         struct bpf_map_info map;
9831         char msg[STRERR_BUFSIZE];
9832         struct perf_buffer *pb;
9833         bool *online = NULL;
9834         __u32 map_info_len;
9835         int err, i, j, n;
9836
9837         if (page_cnt & (page_cnt - 1)) {
9838                 pr_warn("page count should be power of two, but is %zu\n",
9839                         page_cnt);
9840                 return ERR_PTR(-EINVAL);
9841         }
9842
9843         /* best-effort sanity checks */
9844         memset(&map, 0, sizeof(map));
9845         map_info_len = sizeof(map);
9846         err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
9847         if (err) {
9848                 err = -errno;
9849                 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
9850                  * -EBADFD, -EFAULT, or -E2BIG on real error
9851                  */
9852                 if (err != -EINVAL) {
9853                         pr_warn("failed to get map info for map FD %d: %s\n",
9854                                 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
9855                         return ERR_PTR(err);
9856                 }
9857                 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
9858                          map_fd);
9859         } else {
9860                 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
9861                         pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
9862                                 map.name);
9863                         return ERR_PTR(-EINVAL);
9864                 }
9865         }
9866
9867         pb = calloc(1, sizeof(*pb));
9868         if (!pb)
9869                 return ERR_PTR(-ENOMEM);
9870
9871         pb->event_cb = p->event_cb;
9872         pb->sample_cb = p->sample_cb;
9873         pb->lost_cb = p->lost_cb;
9874         pb->ctx = p->ctx;
9875
9876         pb->page_size = getpagesize();
9877         pb->mmap_size = pb->page_size * page_cnt;
9878         pb->map_fd = map_fd;
9879
9880         pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
9881         if (pb->epoll_fd < 0) {
9882                 err = -errno;
9883                 pr_warn("failed to create epoll instance: %s\n",
9884                         libbpf_strerror_r(err, msg, sizeof(msg)));
9885                 goto error;
9886         }
9887
9888         if (p->cpu_cnt > 0) {
9889                 pb->cpu_cnt = p->cpu_cnt;
9890         } else {
9891                 pb->cpu_cnt = libbpf_num_possible_cpus();
9892                 if (pb->cpu_cnt < 0) {
9893                         err = pb->cpu_cnt;
9894                         goto error;
9895                 }
9896                 if (map.max_entries && map.max_entries < pb->cpu_cnt)
9897                         pb->cpu_cnt = map.max_entries;
9898         }
9899
9900         pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
9901         if (!pb->events) {
9902                 err = -ENOMEM;
9903                 pr_warn("failed to allocate events: out of memory\n");
9904                 goto error;
9905         }
9906         pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
9907         if (!pb->cpu_bufs) {
9908                 err = -ENOMEM;
9909                 pr_warn("failed to allocate buffers: out of memory\n");
9910                 goto error;
9911         }
9912
9913         err = parse_cpu_mask_file(online_cpus_file, &online, &n);
9914         if (err) {
9915                 pr_warn("failed to get online CPU mask: %d\n", err);
9916                 goto error;
9917         }
9918
9919         for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
9920                 struct perf_cpu_buf *cpu_buf;
9921                 int cpu, map_key;
9922
9923                 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
9924                 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
9925
9926                 /* in case user didn't explicitly requested particular CPUs to
9927                  * be attached to, skip offline/not present CPUs
9928                  */
9929                 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
9930                         continue;
9931
9932                 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
9933                 if (IS_ERR(cpu_buf)) {
9934                         err = PTR_ERR(cpu_buf);
9935                         goto error;
9936                 }
9937
9938                 pb->cpu_bufs[j] = cpu_buf;
9939
9940                 err = bpf_map_update_elem(pb->map_fd, &map_key,
9941                                           &cpu_buf->fd, 0);
9942                 if (err) {
9943                         err = -errno;
9944                         pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
9945                                 cpu, map_key, cpu_buf->fd,
9946                                 libbpf_strerror_r(err, msg, sizeof(msg)));
9947                         goto error;
9948                 }
9949
9950                 pb->events[j].events = EPOLLIN;
9951                 pb->events[j].data.ptr = cpu_buf;
9952                 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
9953                               &pb->events[j]) < 0) {
9954                         err = -errno;
9955                         pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
9956                                 cpu, cpu_buf->fd,
9957                                 libbpf_strerror_r(err, msg, sizeof(msg)));
9958                         goto error;
9959                 }
9960                 j++;
9961         }
9962         pb->cpu_cnt = j;
9963         free(online);
9964
9965         return pb;
9966
9967 error:
9968         free(online);
9969         if (pb)
9970                 perf_buffer__free(pb);
9971         return ERR_PTR(err);
9972 }
9973
9974 struct perf_sample_raw {
9975         struct perf_event_header header;
9976         uint32_t size;
9977         char data[];
9978 };
9979
9980 struct perf_sample_lost {
9981         struct perf_event_header header;
9982         uint64_t id;
9983         uint64_t lost;
9984         uint64_t sample_id;
9985 };
9986
9987 static enum bpf_perf_event_ret
9988 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
9989 {
9990         struct perf_cpu_buf *cpu_buf = ctx;
9991         struct perf_buffer *pb = cpu_buf->pb;
9992         void *data = e;
9993
9994         /* user wants full control over parsing perf event */
9995         if (pb->event_cb)
9996                 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
9997
9998         switch (e->type) {
9999         case PERF_RECORD_SAMPLE: {
10000                 struct perf_sample_raw *s = data;
10001
10002                 if (pb->sample_cb)
10003                         pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
10004                 break;
10005         }
10006         case PERF_RECORD_LOST: {
10007                 struct perf_sample_lost *s = data;
10008
10009                 if (pb->lost_cb)
10010                         pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
10011                 break;
10012         }
10013         default:
10014                 pr_warn("unknown perf sample type %d\n", e->type);
10015                 return LIBBPF_PERF_EVENT_ERROR;
10016         }
10017         return LIBBPF_PERF_EVENT_CONT;
10018 }
10019
10020 static int perf_buffer__process_records(struct perf_buffer *pb,
10021                                         struct perf_cpu_buf *cpu_buf)
10022 {
10023         enum bpf_perf_event_ret ret;
10024
10025         ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
10026                                          pb->page_size, &cpu_buf->buf,
10027                                          &cpu_buf->buf_size,
10028                                          perf_buffer__process_record, cpu_buf);
10029         if (ret != LIBBPF_PERF_EVENT_CONT)
10030                 return ret;
10031         return 0;
10032 }
10033
10034 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
10035 {
10036         return pb->epoll_fd;
10037 }
10038
10039 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
10040 {
10041         int i, cnt, err;
10042
10043         cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
10044         if (cnt < 0)
10045                 return -errno;
10046
10047         for (i = 0; i < cnt; i++) {
10048                 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
10049
10050                 err = perf_buffer__process_records(pb, cpu_buf);
10051                 if (err) {
10052                         pr_warn("error while processing records: %d\n", err);
10053                         return libbpf_err(err);
10054                 }
10055         }
10056         return cnt;
10057 }
10058
10059 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
10060  * manager.
10061  */
10062 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
10063 {
10064         return pb->cpu_cnt;
10065 }
10066
10067 /*
10068  * Return perf_event FD of a ring buffer in *buf_idx* slot of
10069  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
10070  * select()/poll()/epoll() Linux syscalls.
10071  */
10072 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
10073 {
10074         struct perf_cpu_buf *cpu_buf;
10075
10076         if (buf_idx >= pb->cpu_cnt)
10077                 return libbpf_err(-EINVAL);
10078
10079         cpu_buf = pb->cpu_bufs[buf_idx];
10080         if (!cpu_buf)
10081                 return libbpf_err(-ENOENT);
10082
10083         return cpu_buf->fd;
10084 }
10085
10086 /*
10087  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
10088  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
10089  * consume, do nothing and return success.
10090  * Returns:
10091  *   - 0 on success;
10092  *   - <0 on failure.
10093  */
10094 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
10095 {
10096         struct perf_cpu_buf *cpu_buf;
10097
10098         if (buf_idx >= pb->cpu_cnt)
10099                 return libbpf_err(-EINVAL);
10100
10101         cpu_buf = pb->cpu_bufs[buf_idx];
10102         if (!cpu_buf)
10103                 return libbpf_err(-ENOENT);
10104
10105         return perf_buffer__process_records(pb, cpu_buf);
10106 }
10107
10108 int perf_buffer__consume(struct perf_buffer *pb)
10109 {
10110         int i, err;
10111
10112         for (i = 0; i < pb->cpu_cnt; i++) {
10113                 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10114
10115                 if (!cpu_buf)
10116                         continue;
10117
10118                 err = perf_buffer__process_records(pb, cpu_buf);
10119                 if (err) {
10120                         pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
10121                         return libbpf_err(err);
10122                 }
10123         }
10124         return 0;
10125 }
10126
10127 struct bpf_prog_info_array_desc {
10128         int     array_offset;   /* e.g. offset of jited_prog_insns */
10129         int     count_offset;   /* e.g. offset of jited_prog_len */
10130         int     size_offset;    /* > 0: offset of rec size,
10131                                  * < 0: fix size of -size_offset
10132                                  */
10133 };
10134
10135 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
10136         [BPF_PROG_INFO_JITED_INSNS] = {
10137                 offsetof(struct bpf_prog_info, jited_prog_insns),
10138                 offsetof(struct bpf_prog_info, jited_prog_len),
10139                 -1,
10140         },
10141         [BPF_PROG_INFO_XLATED_INSNS] = {
10142                 offsetof(struct bpf_prog_info, xlated_prog_insns),
10143                 offsetof(struct bpf_prog_info, xlated_prog_len),
10144                 -1,
10145         },
10146         [BPF_PROG_INFO_MAP_IDS] = {
10147                 offsetof(struct bpf_prog_info, map_ids),
10148                 offsetof(struct bpf_prog_info, nr_map_ids),
10149                 -(int)sizeof(__u32),
10150         },
10151         [BPF_PROG_INFO_JITED_KSYMS] = {
10152                 offsetof(struct bpf_prog_info, jited_ksyms),
10153                 offsetof(struct bpf_prog_info, nr_jited_ksyms),
10154                 -(int)sizeof(__u64),
10155         },
10156         [BPF_PROG_INFO_JITED_FUNC_LENS] = {
10157                 offsetof(struct bpf_prog_info, jited_func_lens),
10158                 offsetof(struct bpf_prog_info, nr_jited_func_lens),
10159                 -(int)sizeof(__u32),
10160         },
10161         [BPF_PROG_INFO_FUNC_INFO] = {
10162                 offsetof(struct bpf_prog_info, func_info),
10163                 offsetof(struct bpf_prog_info, nr_func_info),
10164                 offsetof(struct bpf_prog_info, func_info_rec_size),
10165         },
10166         [BPF_PROG_INFO_LINE_INFO] = {
10167                 offsetof(struct bpf_prog_info, line_info),
10168                 offsetof(struct bpf_prog_info, nr_line_info),
10169                 offsetof(struct bpf_prog_info, line_info_rec_size),
10170         },
10171         [BPF_PROG_INFO_JITED_LINE_INFO] = {
10172                 offsetof(struct bpf_prog_info, jited_line_info),
10173                 offsetof(struct bpf_prog_info, nr_jited_line_info),
10174                 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
10175         },
10176         [BPF_PROG_INFO_PROG_TAGS] = {
10177                 offsetof(struct bpf_prog_info, prog_tags),
10178                 offsetof(struct bpf_prog_info, nr_prog_tags),
10179                 -(int)sizeof(__u8) * BPF_TAG_SIZE,
10180         },
10181
10182 };
10183
10184 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
10185                                            int offset)
10186 {
10187         __u32 *array = (__u32 *)info;
10188
10189         if (offset >= 0)
10190                 return array[offset / sizeof(__u32)];
10191         return -(int)offset;
10192 }
10193
10194 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
10195                                            int offset)
10196 {
10197         __u64 *array = (__u64 *)info;
10198
10199         if (offset >= 0)
10200                 return array[offset / sizeof(__u64)];
10201         return -(int)offset;
10202 }
10203
10204 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
10205                                          __u32 val)
10206 {
10207         __u32 *array = (__u32 *)info;
10208
10209         if (offset >= 0)
10210                 array[offset / sizeof(__u32)] = val;
10211 }
10212
10213 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
10214                                          __u64 val)
10215 {
10216         __u64 *array = (__u64 *)info;
10217
10218         if (offset >= 0)
10219                 array[offset / sizeof(__u64)] = val;
10220 }
10221
10222 struct bpf_prog_info_linear *
10223 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
10224 {
10225         struct bpf_prog_info_linear *info_linear;
10226         struct bpf_prog_info info = {};
10227         __u32 info_len = sizeof(info);
10228         __u32 data_len = 0;
10229         int i, err;
10230         void *ptr;
10231
10232         if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
10233                 return libbpf_err_ptr(-EINVAL);
10234
10235         /* step 1: get array dimensions */
10236         err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
10237         if (err) {
10238                 pr_debug("can't get prog info: %s", strerror(errno));
10239                 return libbpf_err_ptr(-EFAULT);
10240         }
10241
10242         /* step 2: calculate total size of all arrays */
10243         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10244                 bool include_array = (arrays & (1UL << i)) > 0;
10245                 struct bpf_prog_info_array_desc *desc;
10246                 __u32 count, size;
10247
10248                 desc = bpf_prog_info_array_desc + i;
10249
10250                 /* kernel is too old to support this field */
10251                 if (info_len < desc->array_offset + sizeof(__u32) ||
10252                     info_len < desc->count_offset + sizeof(__u32) ||
10253                     (desc->size_offset > 0 && info_len < desc->size_offset))
10254                         include_array = false;
10255
10256                 if (!include_array) {
10257                         arrays &= ~(1UL << i);  /* clear the bit */
10258                         continue;
10259                 }
10260
10261                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10262                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10263
10264                 data_len += count * size;
10265         }
10266
10267         /* step 3: allocate continuous memory */
10268         data_len = roundup(data_len, sizeof(__u64));
10269         info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
10270         if (!info_linear)
10271                 return libbpf_err_ptr(-ENOMEM);
10272
10273         /* step 4: fill data to info_linear->info */
10274         info_linear->arrays = arrays;
10275         memset(&info_linear->info, 0, sizeof(info));
10276         ptr = info_linear->data;
10277
10278         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10279                 struct bpf_prog_info_array_desc *desc;
10280                 __u32 count, size;
10281
10282                 if ((arrays & (1UL << i)) == 0)
10283                         continue;
10284
10285                 desc  = bpf_prog_info_array_desc + i;
10286                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10287                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10288                 bpf_prog_info_set_offset_u32(&info_linear->info,
10289                                              desc->count_offset, count);
10290                 bpf_prog_info_set_offset_u32(&info_linear->info,
10291                                              desc->size_offset, size);
10292                 bpf_prog_info_set_offset_u64(&info_linear->info,
10293                                              desc->array_offset,
10294                                              ptr_to_u64(ptr));
10295                 ptr += count * size;
10296         }
10297
10298         /* step 5: call syscall again to get required arrays */
10299         err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
10300         if (err) {
10301                 pr_debug("can't get prog info: %s", strerror(errno));
10302                 free(info_linear);
10303                 return libbpf_err_ptr(-EFAULT);
10304         }
10305
10306         /* step 6: verify the data */
10307         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10308                 struct bpf_prog_info_array_desc *desc;
10309                 __u32 v1, v2;
10310
10311                 if ((arrays & (1UL << i)) == 0)
10312                         continue;
10313
10314                 desc = bpf_prog_info_array_desc + i;
10315                 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10316                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10317                                                    desc->count_offset);
10318                 if (v1 != v2)
10319                         pr_warn("%s: mismatch in element count\n", __func__);
10320
10321                 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10322                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10323                                                    desc->size_offset);
10324                 if (v1 != v2)
10325                         pr_warn("%s: mismatch in rec size\n", __func__);
10326         }
10327
10328         /* step 7: update info_len and data_len */
10329         info_linear->info_len = sizeof(struct bpf_prog_info);
10330         info_linear->data_len = data_len;
10331
10332         return info_linear;
10333 }
10334
10335 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
10336 {
10337         int i;
10338
10339         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10340                 struct bpf_prog_info_array_desc *desc;
10341                 __u64 addr, offs;
10342
10343                 if ((info_linear->arrays & (1UL << i)) == 0)
10344                         continue;
10345
10346                 desc = bpf_prog_info_array_desc + i;
10347                 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
10348                                                      desc->array_offset);
10349                 offs = addr - ptr_to_u64(info_linear->data);
10350                 bpf_prog_info_set_offset_u64(&info_linear->info,
10351                                              desc->array_offset, offs);
10352         }
10353 }
10354
10355 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
10356 {
10357         int i;
10358
10359         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10360                 struct bpf_prog_info_array_desc *desc;
10361                 __u64 addr, offs;
10362
10363                 if ((info_linear->arrays & (1UL << i)) == 0)
10364                         continue;
10365
10366                 desc = bpf_prog_info_array_desc + i;
10367                 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
10368                                                      desc->array_offset);
10369                 addr = offs + ptr_to_u64(info_linear->data);
10370                 bpf_prog_info_set_offset_u64(&info_linear->info,
10371                                              desc->array_offset, addr);
10372         }
10373 }
10374
10375 int bpf_program__set_attach_target(struct bpf_program *prog,
10376                                    int attach_prog_fd,
10377                                    const char *attach_func_name)
10378 {
10379         int btf_obj_fd = 0, btf_id = 0, err;
10380
10381         if (!prog || attach_prog_fd < 0 || !attach_func_name)
10382                 return libbpf_err(-EINVAL);
10383
10384         if (prog->obj->loaded)
10385                 return libbpf_err(-EINVAL);
10386
10387         if (attach_prog_fd) {
10388                 btf_id = libbpf_find_prog_btf_id(attach_func_name,
10389                                                  attach_prog_fd);
10390                 if (btf_id < 0)
10391                         return libbpf_err(btf_id);
10392         } else {
10393                 /* load btf_vmlinux, if not yet */
10394                 err = bpf_object__load_vmlinux_btf(prog->obj, true);
10395                 if (err)
10396                         return libbpf_err(err);
10397                 err = find_kernel_btf_id(prog->obj, attach_func_name,
10398                                          prog->expected_attach_type,
10399                                          &btf_obj_fd, &btf_id);
10400                 if (err)
10401                         return libbpf_err(err);
10402         }
10403
10404         prog->attach_btf_id = btf_id;
10405         prog->attach_btf_obj_fd = btf_obj_fd;
10406         prog->attach_prog_fd = attach_prog_fd;
10407         return 0;
10408 }
10409
10410 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
10411 {
10412         int err = 0, n, len, start, end = -1;
10413         bool *tmp;
10414
10415         *mask = NULL;
10416         *mask_sz = 0;
10417
10418         /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
10419         while (*s) {
10420                 if (*s == ',' || *s == '\n') {
10421                         s++;
10422                         continue;
10423                 }
10424                 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
10425                 if (n <= 0 || n > 2) {
10426                         pr_warn("Failed to get CPU range %s: %d\n", s, n);
10427                         err = -EINVAL;
10428                         goto cleanup;
10429                 } else if (n == 1) {
10430                         end = start;
10431                 }
10432                 if (start < 0 || start > end) {
10433                         pr_warn("Invalid CPU range [%d,%d] in %s\n",
10434                                 start, end, s);
10435                         err = -EINVAL;
10436                         goto cleanup;
10437                 }
10438                 tmp = realloc(*mask, end + 1);
10439                 if (!tmp) {
10440                         err = -ENOMEM;
10441                         goto cleanup;
10442                 }
10443                 *mask = tmp;
10444                 memset(tmp + *mask_sz, 0, start - *mask_sz);
10445                 memset(tmp + start, 1, end - start + 1);
10446                 *mask_sz = end + 1;
10447                 s += len;
10448         }
10449         if (!*mask_sz) {
10450                 pr_warn("Empty CPU range\n");
10451                 return -EINVAL;
10452         }
10453         return 0;
10454 cleanup:
10455         free(*mask);
10456         *mask = NULL;
10457         return err;
10458 }
10459
10460 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
10461 {
10462         int fd, err = 0, len;
10463         char buf[128];
10464
10465         fd = open(fcpu, O_RDONLY);
10466         if (fd < 0) {
10467                 err = -errno;
10468                 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
10469                 return err;
10470         }
10471         len = read(fd, buf, sizeof(buf));
10472         close(fd);
10473         if (len <= 0) {
10474                 err = len ? -errno : -EINVAL;
10475                 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
10476                 return err;
10477         }
10478         if (len >= sizeof(buf)) {
10479                 pr_warn("CPU mask is too big in file %s\n", fcpu);
10480                 return -E2BIG;
10481         }
10482         buf[len] = '\0';
10483
10484         return parse_cpu_mask_str(buf, mask, mask_sz);
10485 }
10486
10487 int libbpf_num_possible_cpus(void)
10488 {
10489         static const char *fcpu = "/sys/devices/system/cpu/possible";
10490         static int cpus;
10491         int err, n, i, tmp_cpus;
10492         bool *mask;
10493
10494         tmp_cpus = READ_ONCE(cpus);
10495         if (tmp_cpus > 0)
10496                 return tmp_cpus;
10497
10498         err = parse_cpu_mask_file(fcpu, &mask, &n);
10499         if (err)
10500                 return libbpf_err(err);
10501
10502         tmp_cpus = 0;
10503         for (i = 0; i < n; i++) {
10504                 if (mask[i])
10505                         tmp_cpus++;
10506         }
10507         free(mask);
10508
10509         WRITE_ONCE(cpus, tmp_cpus);
10510         return tmp_cpus;
10511 }
10512
10513 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
10514                               const struct bpf_object_open_opts *opts)
10515 {
10516         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
10517                 .object_name = s->name,
10518         );
10519         struct bpf_object *obj;
10520         int i, err;
10521
10522         /* Attempt to preserve opts->object_name, unless overriden by user
10523          * explicitly. Overwriting object name for skeletons is discouraged,
10524          * as it breaks global data maps, because they contain object name
10525          * prefix as their own map name prefix. When skeleton is generated,
10526          * bpftool is making an assumption that this name will stay the same.
10527          */
10528         if (opts) {
10529                 memcpy(&skel_opts, opts, sizeof(*opts));
10530                 if (!opts->object_name)
10531                         skel_opts.object_name = s->name;
10532         }
10533
10534         obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
10535         err = libbpf_get_error(obj);
10536         if (err) {
10537                 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
10538                         s->name, err);
10539                 return libbpf_err(err);
10540         }
10541
10542         *s->obj = obj;
10543
10544         for (i = 0; i < s->map_cnt; i++) {
10545                 struct bpf_map **map = s->maps[i].map;
10546                 const char *name = s->maps[i].name;
10547                 void **mmaped = s->maps[i].mmaped;
10548
10549                 *map = bpf_object__find_map_by_name(obj, name);
10550                 if (!*map) {
10551                         pr_warn("failed to find skeleton map '%s'\n", name);
10552                         return libbpf_err(-ESRCH);
10553                 }
10554
10555                 /* externs shouldn't be pre-setup from user code */
10556                 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
10557                         *mmaped = (*map)->mmaped;
10558         }
10559
10560         for (i = 0; i < s->prog_cnt; i++) {
10561                 struct bpf_program **prog = s->progs[i].prog;
10562                 const char *name = s->progs[i].name;
10563
10564                 *prog = bpf_object__find_program_by_name(obj, name);
10565                 if (!*prog) {
10566                         pr_warn("failed to find skeleton program '%s'\n", name);
10567                         return libbpf_err(-ESRCH);
10568                 }
10569         }
10570
10571         return 0;
10572 }
10573
10574 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
10575 {
10576         int i, err;
10577
10578         err = bpf_object__load(*s->obj);
10579         if (err) {
10580                 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
10581                 return libbpf_err(err);
10582         }
10583
10584         for (i = 0; i < s->map_cnt; i++) {
10585                 struct bpf_map *map = *s->maps[i].map;
10586                 size_t mmap_sz = bpf_map_mmap_sz(map);
10587                 int prot, map_fd = bpf_map__fd(map);
10588                 void **mmaped = s->maps[i].mmaped;
10589
10590                 if (!mmaped)
10591                         continue;
10592
10593                 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
10594                         *mmaped = NULL;
10595                         continue;
10596                 }
10597
10598                 if (map->def.map_flags & BPF_F_RDONLY_PROG)
10599                         prot = PROT_READ;
10600                 else
10601                         prot = PROT_READ | PROT_WRITE;
10602
10603                 /* Remap anonymous mmap()-ed "map initialization image" as
10604                  * a BPF map-backed mmap()-ed memory, but preserving the same
10605                  * memory address. This will cause kernel to change process'
10606                  * page table to point to a different piece of kernel memory,
10607                  * but from userspace point of view memory address (and its
10608                  * contents, being identical at this point) will stay the
10609                  * same. This mapping will be released by bpf_object__close()
10610                  * as per normal clean up procedure, so we don't need to worry
10611                  * about it from skeleton's clean up perspective.
10612                  */
10613                 *mmaped = mmap(map->mmaped, mmap_sz, prot,
10614                                 MAP_SHARED | MAP_FIXED, map_fd, 0);
10615                 if (*mmaped == MAP_FAILED) {
10616                         err = -errno;
10617                         *mmaped = NULL;
10618                         pr_warn("failed to re-mmap() map '%s': %d\n",
10619                                  bpf_map__name(map), err);
10620                         return libbpf_err(err);
10621                 }
10622         }
10623
10624         return 0;
10625 }
10626
10627 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
10628 {
10629         int i, err;
10630
10631         for (i = 0; i < s->prog_cnt; i++) {
10632                 struct bpf_program *prog = *s->progs[i].prog;
10633                 struct bpf_link **link = s->progs[i].link;
10634                 const struct bpf_sec_def *sec_def;
10635
10636                 if (!prog->load)
10637                         continue;
10638
10639                 sec_def = find_sec_def(prog->sec_name);
10640                 if (!sec_def || !sec_def->attach_fn)
10641                         continue;
10642
10643                 *link = sec_def->attach_fn(sec_def, prog);
10644                 err = libbpf_get_error(*link);
10645                 if (err) {
10646                         pr_warn("failed to auto-attach program '%s': %d\n",
10647                                 bpf_program__name(prog), err);
10648                         return libbpf_err(err);
10649                 }
10650         }
10651
10652         return 0;
10653 }
10654
10655 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
10656 {
10657         int i;
10658
10659         for (i = 0; i < s->prog_cnt; i++) {
10660                 struct bpf_link **link = s->progs[i].link;
10661
10662                 bpf_link__destroy(*link);
10663                 *link = NULL;
10664         }
10665 }
10666
10667 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
10668 {
10669         if (s->progs)
10670                 bpf_object__detach_skeleton(s);
10671         if (s->obj)
10672                 bpf_object__close(*s->obj);
10673         free(s->maps);
10674         free(s->progs);
10675         free(s);
10676 }