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