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