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