libbpf: Sanitize global functions
[linux-2.6-microblaze.git] / tools / lib / bpf / libbpf.c
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <asm/unistd.h>
28 #include <linux/err.h>
29 #include <linux/kernel.h>
30 #include <linux/bpf.h>
31 #include <linux/btf.h>
32 #include <linux/filter.h>
33 #include <linux/list.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/ring_buffer.h>
37 #include <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <tools/libc_compat.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
58 #ifndef EM_BPF
59 #define EM_BPF 247
60 #endif
61
62 #ifndef BPF_FS_MAGIC
63 #define BPF_FS_MAGIC            0xcafe4a11
64 #endif
65
66 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
67  * compilation if user enables corresponding warning. Disable it explicitly.
68  */
69 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
70
71 #define __printf(a, b)  __attribute__((format(printf, a, b)))
72
73 static struct btf *bpf_find_kernel_btf(void);
74 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
75 static struct bpf_program *bpf_object__find_prog_by_idx(struct bpf_object *obj,
76                                                         int idx);
77 static const struct btf_type *
78 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
79
80 static int __base_pr(enum libbpf_print_level level, const char *format,
81                      va_list args)
82 {
83         if (level == LIBBPF_DEBUG)
84                 return 0;
85
86         return vfprintf(stderr, format, args);
87 }
88
89 static libbpf_print_fn_t __libbpf_pr = __base_pr;
90
91 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
92 {
93         libbpf_print_fn_t old_print_fn = __libbpf_pr;
94
95         __libbpf_pr = fn;
96         return old_print_fn;
97 }
98
99 __printf(2, 3)
100 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
101 {
102         va_list args;
103
104         if (!__libbpf_pr)
105                 return;
106
107         va_start(args, format);
108         __libbpf_pr(level, format, args);
109         va_end(args);
110 }
111
112 static void pr_perm_msg(int err)
113 {
114         struct rlimit limit;
115         char buf[100];
116
117         if (err != -EPERM || geteuid() != 0)
118                 return;
119
120         err = getrlimit(RLIMIT_MEMLOCK, &limit);
121         if (err)
122                 return;
123
124         if (limit.rlim_cur == RLIM_INFINITY)
125                 return;
126
127         if (limit.rlim_cur < 1024)
128                 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
129         else if (limit.rlim_cur < 1024*1024)
130                 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
131         else
132                 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
133
134         pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
135                 buf);
136 }
137
138 #define STRERR_BUFSIZE  128
139
140 /* Copied from tools/perf/util/util.h */
141 #ifndef zfree
142 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
143 #endif
144
145 #ifndef zclose
146 # define zclose(fd) ({                  \
147         int ___err = 0;                 \
148         if ((fd) >= 0)                  \
149                 ___err = close((fd));   \
150         fd = -1;                        \
151         ___err; })
152 #endif
153
154 #ifdef HAVE_LIBELF_MMAP_SUPPORT
155 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
156 #else
157 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
158 #endif
159
160 static inline __u64 ptr_to_u64(const void *ptr)
161 {
162         return (__u64) (unsigned long) ptr;
163 }
164
165 struct bpf_capabilities {
166         /* v4.14: kernel support for program & map names. */
167         __u32 name:1;
168         /* v5.2: kernel support for global data sections. */
169         __u32 global_data:1;
170         /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
171         __u32 btf_func:1;
172         /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
173         __u32 btf_datasec:1;
174         /* BPF_F_MMAPABLE is supported for arrays */
175         __u32 array_mmap:1;
176         /* BTF_FUNC_GLOBAL is supported */
177         __u32 btf_func_global:1;
178 };
179
180 enum reloc_type {
181         RELO_LD64,
182         RELO_CALL,
183         RELO_DATA,
184         RELO_EXTERN,
185 };
186
187 struct reloc_desc {
188         enum reloc_type type;
189         int insn_idx;
190         int map_idx;
191         int sym_off;
192 };
193
194 /*
195  * bpf_prog should be a better name but it has been used in
196  * linux/filter.h.
197  */
198 struct bpf_program {
199         /* Index in elf obj file, for relocation use. */
200         int idx;
201         char *name;
202         int prog_ifindex;
203         char *section_name;
204         /* section_name with / replaced by _; makes recursive pinning
205          * in bpf_object__pin_programs easier
206          */
207         char *pin_name;
208         struct bpf_insn *insns;
209         size_t insns_cnt, main_prog_cnt;
210         enum bpf_prog_type type;
211
212         struct reloc_desc *reloc_desc;
213         int nr_reloc;
214         int log_level;
215
216         struct {
217                 int nr;
218                 int *fds;
219         } instances;
220         bpf_program_prep_t preprocessor;
221
222         struct bpf_object *obj;
223         void *priv;
224         bpf_program_clear_priv_t clear_priv;
225
226         enum bpf_attach_type expected_attach_type;
227         __u32 attach_btf_id;
228         __u32 attach_prog_fd;
229         void *func_info;
230         __u32 func_info_rec_size;
231         __u32 func_info_cnt;
232
233         struct bpf_capabilities *caps;
234
235         void *line_info;
236         __u32 line_info_rec_size;
237         __u32 line_info_cnt;
238         __u32 prog_flags;
239 };
240
241 struct bpf_struct_ops {
242         const char *tname;
243         const struct btf_type *type;
244         struct bpf_program **progs;
245         __u32 *kern_func_off;
246         /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
247         void *data;
248         /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
249          *      btf_vmlinux's format.
250          * struct bpf_struct_ops_tcp_congestion_ops {
251          *      [... some other kernel fields ...]
252          *      struct tcp_congestion_ops data;
253          * }
254          * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
255          * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
256          * from "data".
257          */
258         void *kern_vdata;
259         __u32 type_id;
260 };
261
262 #define DATA_SEC ".data"
263 #define BSS_SEC ".bss"
264 #define RODATA_SEC ".rodata"
265 #define KCONFIG_SEC ".kconfig"
266 #define STRUCT_OPS_SEC ".struct_ops"
267
268 enum libbpf_map_type {
269         LIBBPF_MAP_UNSPEC,
270         LIBBPF_MAP_DATA,
271         LIBBPF_MAP_BSS,
272         LIBBPF_MAP_RODATA,
273         LIBBPF_MAP_KCONFIG,
274 };
275
276 static const char * const libbpf_type_to_btf_name[] = {
277         [LIBBPF_MAP_DATA]       = DATA_SEC,
278         [LIBBPF_MAP_BSS]        = BSS_SEC,
279         [LIBBPF_MAP_RODATA]     = RODATA_SEC,
280         [LIBBPF_MAP_KCONFIG]    = KCONFIG_SEC,
281 };
282
283 struct bpf_map {
284         char *name;
285         int fd;
286         int sec_idx;
287         size_t sec_offset;
288         int map_ifindex;
289         int inner_map_fd;
290         struct bpf_map_def def;
291         __u32 btf_key_type_id;
292         __u32 btf_value_type_id;
293         __u32 btf_vmlinux_value_type_id;
294         void *priv;
295         bpf_map_clear_priv_t clear_priv;
296         enum libbpf_map_type libbpf_type;
297         void *mmaped;
298         struct bpf_struct_ops *st_ops;
299         char *pin_path;
300         bool pinned;
301         bool reused;
302 };
303
304 enum extern_type {
305         EXT_UNKNOWN,
306         EXT_CHAR,
307         EXT_BOOL,
308         EXT_INT,
309         EXT_TRISTATE,
310         EXT_CHAR_ARR,
311 };
312
313 struct extern_desc {
314         const char *name;
315         int sym_idx;
316         int btf_id;
317         enum extern_type type;
318         int sz;
319         int align;
320         int data_off;
321         bool is_signed;
322         bool is_weak;
323         bool is_set;
324 };
325
326 static LIST_HEAD(bpf_objects_list);
327
328 struct bpf_object {
329         char name[BPF_OBJ_NAME_LEN];
330         char license[64];
331         __u32 kern_version;
332
333         struct bpf_program *programs;
334         size_t nr_programs;
335         struct bpf_map *maps;
336         size_t nr_maps;
337         size_t maps_cap;
338
339         char *kconfig;
340         struct extern_desc *externs;
341         int nr_extern;
342         int kconfig_map_idx;
343
344         bool loaded;
345         bool has_pseudo_calls;
346         bool relaxed_core_relocs;
347
348         /*
349          * Information when doing elf related work. Only valid if fd
350          * is valid.
351          */
352         struct {
353                 int fd;
354                 const void *obj_buf;
355                 size_t obj_buf_sz;
356                 Elf *elf;
357                 GElf_Ehdr ehdr;
358                 Elf_Data *symbols;
359                 Elf_Data *data;
360                 Elf_Data *rodata;
361                 Elf_Data *bss;
362                 Elf_Data *st_ops_data;
363                 size_t strtabidx;
364                 struct {
365                         GElf_Shdr shdr;
366                         Elf_Data *data;
367                 } *reloc_sects;
368                 int nr_reloc_sects;
369                 int maps_shndx;
370                 int btf_maps_shndx;
371                 int text_shndx;
372                 int symbols_shndx;
373                 int data_shndx;
374                 int rodata_shndx;
375                 int bss_shndx;
376                 int st_ops_shndx;
377         } efile;
378         /*
379          * All loaded bpf_object is linked in a list, which is
380          * hidden to caller. bpf_objects__<func> handlers deal with
381          * all objects.
382          */
383         struct list_head list;
384
385         struct btf *btf;
386         struct btf_ext *btf_ext;
387
388         void *priv;
389         bpf_object_clear_priv_t clear_priv;
390
391         struct bpf_capabilities caps;
392
393         char path[];
394 };
395 #define obj_elf_valid(o)        ((o)->efile.elf)
396
397 void bpf_program__unload(struct bpf_program *prog)
398 {
399         int i;
400
401         if (!prog)
402                 return;
403
404         /*
405          * If the object is opened but the program was never loaded,
406          * it is possible that prog->instances.nr == -1.
407          */
408         if (prog->instances.nr > 0) {
409                 for (i = 0; i < prog->instances.nr; i++)
410                         zclose(prog->instances.fds[i]);
411         } else if (prog->instances.nr != -1) {
412                 pr_warn("Internal error: instances.nr is %d\n",
413                         prog->instances.nr);
414         }
415
416         prog->instances.nr = -1;
417         zfree(&prog->instances.fds);
418
419         zfree(&prog->func_info);
420         zfree(&prog->line_info);
421 }
422
423 static void bpf_program__exit(struct bpf_program *prog)
424 {
425         if (!prog)
426                 return;
427
428         if (prog->clear_priv)
429                 prog->clear_priv(prog, prog->priv);
430
431         prog->priv = NULL;
432         prog->clear_priv = NULL;
433
434         bpf_program__unload(prog);
435         zfree(&prog->name);
436         zfree(&prog->section_name);
437         zfree(&prog->pin_name);
438         zfree(&prog->insns);
439         zfree(&prog->reloc_desc);
440
441         prog->nr_reloc = 0;
442         prog->insns_cnt = 0;
443         prog->idx = -1;
444 }
445
446 static char *__bpf_program__pin_name(struct bpf_program *prog)
447 {
448         char *name, *p;
449
450         name = p = strdup(prog->section_name);
451         while ((p = strchr(p, '/')))
452                 *p = '_';
453
454         return name;
455 }
456
457 static int
458 bpf_program__init(void *data, size_t size, char *section_name, int idx,
459                   struct bpf_program *prog)
460 {
461         const size_t bpf_insn_sz = sizeof(struct bpf_insn);
462
463         if (size == 0 || size % bpf_insn_sz) {
464                 pr_warn("corrupted section '%s', size: %zu\n",
465                         section_name, size);
466                 return -EINVAL;
467         }
468
469         memset(prog, 0, sizeof(*prog));
470
471         prog->section_name = strdup(section_name);
472         if (!prog->section_name) {
473                 pr_warn("failed to alloc name for prog under section(%d) %s\n",
474                         idx, section_name);
475                 goto errout;
476         }
477
478         prog->pin_name = __bpf_program__pin_name(prog);
479         if (!prog->pin_name) {
480                 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
481                         idx, section_name);
482                 goto errout;
483         }
484
485         prog->insns = malloc(size);
486         if (!prog->insns) {
487                 pr_warn("failed to alloc insns for prog under section %s\n",
488                         section_name);
489                 goto errout;
490         }
491         prog->insns_cnt = size / bpf_insn_sz;
492         memcpy(prog->insns, data, size);
493         prog->idx = idx;
494         prog->instances.fds = NULL;
495         prog->instances.nr = -1;
496         prog->type = BPF_PROG_TYPE_UNSPEC;
497
498         return 0;
499 errout:
500         bpf_program__exit(prog);
501         return -ENOMEM;
502 }
503
504 static int
505 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
506                         char *section_name, int idx)
507 {
508         struct bpf_program prog, *progs;
509         int nr_progs, err;
510
511         err = bpf_program__init(data, size, section_name, idx, &prog);
512         if (err)
513                 return err;
514
515         prog.caps = &obj->caps;
516         progs = obj->programs;
517         nr_progs = obj->nr_programs;
518
519         progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
520         if (!progs) {
521                 /*
522                  * In this case the original obj->programs
523                  * is still valid, so don't need special treat for
524                  * bpf_close_object().
525                  */
526                 pr_warn("failed to alloc a new program under section '%s'\n",
527                         section_name);
528                 bpf_program__exit(&prog);
529                 return -ENOMEM;
530         }
531
532         pr_debug("found program %s\n", prog.section_name);
533         obj->programs = progs;
534         obj->nr_programs = nr_progs + 1;
535         prog.obj = obj;
536         progs[nr_progs] = prog;
537         return 0;
538 }
539
540 static int
541 bpf_object__init_prog_names(struct bpf_object *obj)
542 {
543         Elf_Data *symbols = obj->efile.symbols;
544         struct bpf_program *prog;
545         size_t pi, si;
546
547         for (pi = 0; pi < obj->nr_programs; pi++) {
548                 const char *name = NULL;
549
550                 prog = &obj->programs[pi];
551
552                 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
553                      si++) {
554                         GElf_Sym sym;
555
556                         if (!gelf_getsym(symbols, si, &sym))
557                                 continue;
558                         if (sym.st_shndx != prog->idx)
559                                 continue;
560                         if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
561                                 continue;
562
563                         name = elf_strptr(obj->efile.elf,
564                                           obj->efile.strtabidx,
565                                           sym.st_name);
566                         if (!name) {
567                                 pr_warn("failed to get sym name string for prog %s\n",
568                                         prog->section_name);
569                                 return -LIBBPF_ERRNO__LIBELF;
570                         }
571                 }
572
573                 if (!name && prog->idx == obj->efile.text_shndx)
574                         name = ".text";
575
576                 if (!name) {
577                         pr_warn("failed to find sym for prog %s\n",
578                                 prog->section_name);
579                         return -EINVAL;
580                 }
581
582                 prog->name = strdup(name);
583                 if (!prog->name) {
584                         pr_warn("failed to allocate memory for prog sym %s\n",
585                                 name);
586                         return -ENOMEM;
587                 }
588         }
589
590         return 0;
591 }
592
593 static __u32 get_kernel_version(void)
594 {
595         __u32 major, minor, patch;
596         struct utsname info;
597
598         uname(&info);
599         if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
600                 return 0;
601         return KERNEL_VERSION(major, minor, patch);
602 }
603
604 static const struct btf_member *
605 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
606 {
607         struct btf_member *m;
608         int i;
609
610         for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
611                 if (btf_member_bit_offset(t, i) == bit_offset)
612                         return m;
613         }
614
615         return NULL;
616 }
617
618 static const struct btf_member *
619 find_member_by_name(const struct btf *btf, const struct btf_type *t,
620                     const char *name)
621 {
622         struct btf_member *m;
623         int i;
624
625         for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
626                 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
627                         return m;
628         }
629
630         return NULL;
631 }
632
633 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
634 #define STRUCT_OPS_VALUE_PREFIX_LEN (sizeof(STRUCT_OPS_VALUE_PREFIX) - 1)
635
636 static int
637 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
638                            const struct btf_type **type, __u32 *type_id,
639                            const struct btf_type **vtype, __u32 *vtype_id,
640                            const struct btf_member **data_member)
641 {
642         const struct btf_type *kern_type, *kern_vtype;
643         const struct btf_member *kern_data_member;
644         __s32 kern_vtype_id, kern_type_id;
645         char vtname[128] = STRUCT_OPS_VALUE_PREFIX;
646         __u32 i;
647
648         kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
649         if (kern_type_id < 0) {
650                 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
651                         tname);
652                 return kern_type_id;
653         }
654         kern_type = btf__type_by_id(btf, kern_type_id);
655
656         /* Find the corresponding "map_value" type that will be used
657          * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
658          * find "struct bpf_struct_ops_tcp_congestion_ops" from the
659          * btf_vmlinux.
660          */
661         strncat(vtname + STRUCT_OPS_VALUE_PREFIX_LEN, tname,
662                 sizeof(vtname) - STRUCT_OPS_VALUE_PREFIX_LEN - 1);
663         kern_vtype_id = btf__find_by_name_kind(btf, vtname,
664                                                BTF_KIND_STRUCT);
665         if (kern_vtype_id < 0) {
666                 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
667                         vtname);
668                 return kern_vtype_id;
669         }
670         kern_vtype = btf__type_by_id(btf, kern_vtype_id);
671
672         /* Find "struct tcp_congestion_ops" from
673          * struct bpf_struct_ops_tcp_congestion_ops {
674          *      [ ... ]
675          *      struct tcp_congestion_ops data;
676          * }
677          */
678         kern_data_member = btf_members(kern_vtype);
679         for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
680                 if (kern_data_member->type == kern_type_id)
681                         break;
682         }
683         if (i == btf_vlen(kern_vtype)) {
684                 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
685                         tname, vtname);
686                 return -EINVAL;
687         }
688
689         *type = kern_type;
690         *type_id = kern_type_id;
691         *vtype = kern_vtype;
692         *vtype_id = kern_vtype_id;
693         *data_member = kern_data_member;
694
695         return 0;
696 }
697
698 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
699 {
700         return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
701 }
702
703 /* Init the map's fields that depend on kern_btf */
704 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
705                                          const struct btf *btf,
706                                          const struct btf *kern_btf)
707 {
708         const struct btf_member *member, *kern_member, *kern_data_member;
709         const struct btf_type *type, *kern_type, *kern_vtype;
710         __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
711         struct bpf_struct_ops *st_ops;
712         void *data, *kern_data;
713         const char *tname;
714         int err;
715
716         st_ops = map->st_ops;
717         type = st_ops->type;
718         tname = st_ops->tname;
719         err = find_struct_ops_kern_types(kern_btf, tname,
720                                          &kern_type, &kern_type_id,
721                                          &kern_vtype, &kern_vtype_id,
722                                          &kern_data_member);
723         if (err)
724                 return err;
725
726         pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
727                  map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
728
729         map->def.value_size = kern_vtype->size;
730         map->btf_vmlinux_value_type_id = kern_vtype_id;
731
732         st_ops->kern_vdata = calloc(1, kern_vtype->size);
733         if (!st_ops->kern_vdata)
734                 return -ENOMEM;
735
736         data = st_ops->data;
737         kern_data_off = kern_data_member->offset / 8;
738         kern_data = st_ops->kern_vdata + kern_data_off;
739
740         member = btf_members(type);
741         for (i = 0; i < btf_vlen(type); i++, member++) {
742                 const struct btf_type *mtype, *kern_mtype;
743                 __u32 mtype_id, kern_mtype_id;
744                 void *mdata, *kern_mdata;
745                 __s64 msize, kern_msize;
746                 __u32 moff, kern_moff;
747                 __u32 kern_member_idx;
748                 const char *mname;
749
750                 mname = btf__name_by_offset(btf, member->name_off);
751                 kern_member = find_member_by_name(kern_btf, kern_type, mname);
752                 if (!kern_member) {
753                         pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
754                                 map->name, mname);
755                         return -ENOTSUP;
756                 }
757
758                 kern_member_idx = kern_member - btf_members(kern_type);
759                 if (btf_member_bitfield_size(type, i) ||
760                     btf_member_bitfield_size(kern_type, kern_member_idx)) {
761                         pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
762                                 map->name, mname);
763                         return -ENOTSUP;
764                 }
765
766                 moff = member->offset / 8;
767                 kern_moff = kern_member->offset / 8;
768
769                 mdata = data + moff;
770                 kern_mdata = kern_data + kern_moff;
771
772                 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
773                 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
774                                                     &kern_mtype_id);
775                 if (BTF_INFO_KIND(mtype->info) !=
776                     BTF_INFO_KIND(kern_mtype->info)) {
777                         pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
778                                 map->name, mname, BTF_INFO_KIND(mtype->info),
779                                 BTF_INFO_KIND(kern_mtype->info));
780                         return -ENOTSUP;
781                 }
782
783                 if (btf_is_ptr(mtype)) {
784                         struct bpf_program *prog;
785
786                         mtype = skip_mods_and_typedefs(btf, mtype->type, &mtype_id);
787                         kern_mtype = skip_mods_and_typedefs(kern_btf,
788                                                             kern_mtype->type,
789                                                             &kern_mtype_id);
790                         if (!btf_is_func_proto(mtype) ||
791                             !btf_is_func_proto(kern_mtype)) {
792                                 pr_warn("struct_ops init_kern %s: non func ptr %s is not supported\n",
793                                         map->name, mname);
794                                 return -ENOTSUP;
795                         }
796
797                         prog = st_ops->progs[i];
798                         if (!prog) {
799                                 pr_debug("struct_ops init_kern %s: func ptr %s is not set\n",
800                                          map->name, mname);
801                                 continue;
802                         }
803
804                         prog->attach_btf_id = kern_type_id;
805                         prog->expected_attach_type = kern_member_idx;
806
807                         st_ops->kern_func_off[i] = kern_data_off + kern_moff;
808
809                         pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
810                                  map->name, mname, prog->name, moff,
811                                  kern_moff);
812
813                         continue;
814                 }
815
816                 msize = btf__resolve_size(btf, mtype_id);
817                 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
818                 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
819                         pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
820                                 map->name, mname, (ssize_t)msize,
821                                 (ssize_t)kern_msize);
822                         return -ENOTSUP;
823                 }
824
825                 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
826                          map->name, mname, (unsigned int)msize,
827                          moff, kern_moff);
828                 memcpy(kern_mdata, mdata, msize);
829         }
830
831         return 0;
832 }
833
834 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
835 {
836         struct btf *kern_btf = NULL;
837         struct bpf_map *map;
838         size_t i;
839         int err;
840
841         for (i = 0; i < obj->nr_maps; i++) {
842                 map = &obj->maps[i];
843
844                 if (!bpf_map__is_struct_ops(map))
845                         continue;
846
847                 if (!kern_btf) {
848                         kern_btf = bpf_find_kernel_btf();
849                         if (IS_ERR(kern_btf))
850                                 return PTR_ERR(kern_btf);
851                 }
852
853                 err = bpf_map__init_kern_struct_ops(map, obj->btf, kern_btf);
854                 if (err) {
855                         btf__free(kern_btf);
856                         return err;
857                 }
858         }
859
860         btf__free(kern_btf);
861         return 0;
862 }
863
864 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
865 {
866         const struct btf_type *type, *datasec;
867         const struct btf_var_secinfo *vsi;
868         struct bpf_struct_ops *st_ops;
869         const char *tname, *var_name;
870         __s32 type_id, datasec_id;
871         const struct btf *btf;
872         struct bpf_map *map;
873         __u32 i;
874
875         if (obj->efile.st_ops_shndx == -1)
876                 return 0;
877
878         btf = obj->btf;
879         datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
880                                             BTF_KIND_DATASEC);
881         if (datasec_id < 0) {
882                 pr_warn("struct_ops init: DATASEC %s not found\n",
883                         STRUCT_OPS_SEC);
884                 return -EINVAL;
885         }
886
887         datasec = btf__type_by_id(btf, datasec_id);
888         vsi = btf_var_secinfos(datasec);
889         for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
890                 type = btf__type_by_id(obj->btf, vsi->type);
891                 var_name = btf__name_by_offset(obj->btf, type->name_off);
892
893                 type_id = btf__resolve_type(obj->btf, vsi->type);
894                 if (type_id < 0) {
895                         pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
896                                 vsi->type, STRUCT_OPS_SEC);
897                         return -EINVAL;
898                 }
899
900                 type = btf__type_by_id(obj->btf, type_id);
901                 tname = btf__name_by_offset(obj->btf, type->name_off);
902                 if (!tname[0]) {
903                         pr_warn("struct_ops init: anonymous type is not supported\n");
904                         return -ENOTSUP;
905                 }
906                 if (!btf_is_struct(type)) {
907                         pr_warn("struct_ops init: %s is not a struct\n", tname);
908                         return -EINVAL;
909                 }
910
911                 map = bpf_object__add_map(obj);
912                 if (IS_ERR(map))
913                         return PTR_ERR(map);
914
915                 map->sec_idx = obj->efile.st_ops_shndx;
916                 map->sec_offset = vsi->offset;
917                 map->name = strdup(var_name);
918                 if (!map->name)
919                         return -ENOMEM;
920
921                 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
922                 map->def.key_size = sizeof(int);
923                 map->def.value_size = type->size;
924                 map->def.max_entries = 1;
925
926                 map->st_ops = calloc(1, sizeof(*map->st_ops));
927                 if (!map->st_ops)
928                         return -ENOMEM;
929                 st_ops = map->st_ops;
930                 st_ops->data = malloc(type->size);
931                 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
932                 st_ops->kern_func_off = malloc(btf_vlen(type) *
933                                                sizeof(*st_ops->kern_func_off));
934                 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
935                         return -ENOMEM;
936
937                 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
938                         pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
939                                 var_name, STRUCT_OPS_SEC);
940                         return -EINVAL;
941                 }
942
943                 memcpy(st_ops->data,
944                        obj->efile.st_ops_data->d_buf + vsi->offset,
945                        type->size);
946                 st_ops->tname = tname;
947                 st_ops->type = type;
948                 st_ops->type_id = type_id;
949
950                 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
951                          tname, type_id, var_name, vsi->offset);
952         }
953
954         return 0;
955 }
956
957 static struct bpf_object *bpf_object__new(const char *path,
958                                           const void *obj_buf,
959                                           size_t obj_buf_sz,
960                                           const char *obj_name)
961 {
962         struct bpf_object *obj;
963         char *end;
964
965         obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
966         if (!obj) {
967                 pr_warn("alloc memory failed for %s\n", path);
968                 return ERR_PTR(-ENOMEM);
969         }
970
971         strcpy(obj->path, path);
972         if (obj_name) {
973                 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
974                 obj->name[sizeof(obj->name) - 1] = 0;
975         } else {
976                 /* Using basename() GNU version which doesn't modify arg. */
977                 strncpy(obj->name, basename((void *)path),
978                         sizeof(obj->name) - 1);
979                 end = strchr(obj->name, '.');
980                 if (end)
981                         *end = 0;
982         }
983
984         obj->efile.fd = -1;
985         /*
986          * Caller of this function should also call
987          * bpf_object__elf_finish() after data collection to return
988          * obj_buf to user. If not, we should duplicate the buffer to
989          * avoid user freeing them before elf finish.
990          */
991         obj->efile.obj_buf = obj_buf;
992         obj->efile.obj_buf_sz = obj_buf_sz;
993         obj->efile.maps_shndx = -1;
994         obj->efile.btf_maps_shndx = -1;
995         obj->efile.data_shndx = -1;
996         obj->efile.rodata_shndx = -1;
997         obj->efile.bss_shndx = -1;
998         obj->efile.st_ops_shndx = -1;
999         obj->kconfig_map_idx = -1;
1000
1001         obj->kern_version = get_kernel_version();
1002         obj->loaded = false;
1003
1004         INIT_LIST_HEAD(&obj->list);
1005         list_add(&obj->list, &bpf_objects_list);
1006         return obj;
1007 }
1008
1009 static void bpf_object__elf_finish(struct bpf_object *obj)
1010 {
1011         if (!obj_elf_valid(obj))
1012                 return;
1013
1014         if (obj->efile.elf) {
1015                 elf_end(obj->efile.elf);
1016                 obj->efile.elf = NULL;
1017         }
1018         obj->efile.symbols = NULL;
1019         obj->efile.data = NULL;
1020         obj->efile.rodata = NULL;
1021         obj->efile.bss = NULL;
1022         obj->efile.st_ops_data = NULL;
1023
1024         zfree(&obj->efile.reloc_sects);
1025         obj->efile.nr_reloc_sects = 0;
1026         zclose(obj->efile.fd);
1027         obj->efile.obj_buf = NULL;
1028         obj->efile.obj_buf_sz = 0;
1029 }
1030
1031 static int bpf_object__elf_init(struct bpf_object *obj)
1032 {
1033         int err = 0;
1034         GElf_Ehdr *ep;
1035
1036         if (obj_elf_valid(obj)) {
1037                 pr_warn("elf init: internal error\n");
1038                 return -LIBBPF_ERRNO__LIBELF;
1039         }
1040
1041         if (obj->efile.obj_buf_sz > 0) {
1042                 /*
1043                  * obj_buf should have been validated by
1044                  * bpf_object__open_buffer().
1045                  */
1046                 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1047                                             obj->efile.obj_buf_sz);
1048         } else {
1049                 obj->efile.fd = open(obj->path, O_RDONLY);
1050                 if (obj->efile.fd < 0) {
1051                         char errmsg[STRERR_BUFSIZE], *cp;
1052
1053                         err = -errno;
1054                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1055                         pr_warn("failed to open %s: %s\n", obj->path, cp);
1056                         return err;
1057                 }
1058
1059                 obj->efile.elf = elf_begin(obj->efile.fd,
1060                                            LIBBPF_ELF_C_READ_MMAP, NULL);
1061         }
1062
1063         if (!obj->efile.elf) {
1064                 pr_warn("failed to open %s as ELF file\n", obj->path);
1065                 err = -LIBBPF_ERRNO__LIBELF;
1066                 goto errout;
1067         }
1068
1069         if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1070                 pr_warn("failed to get EHDR from %s\n", obj->path);
1071                 err = -LIBBPF_ERRNO__FORMAT;
1072                 goto errout;
1073         }
1074         ep = &obj->efile.ehdr;
1075
1076         /* Old LLVM set e_machine to EM_NONE */
1077         if (ep->e_type != ET_REL ||
1078             (ep->e_machine && ep->e_machine != EM_BPF)) {
1079                 pr_warn("%s is not an eBPF object file\n", obj->path);
1080                 err = -LIBBPF_ERRNO__FORMAT;
1081                 goto errout;
1082         }
1083
1084         return 0;
1085 errout:
1086         bpf_object__elf_finish(obj);
1087         return err;
1088 }
1089
1090 static int bpf_object__check_endianness(struct bpf_object *obj)
1091 {
1092 #if __BYTE_ORDER == __LITTLE_ENDIAN
1093         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1094                 return 0;
1095 #elif __BYTE_ORDER == __BIG_ENDIAN
1096         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1097                 return 0;
1098 #else
1099 # error "Unrecognized __BYTE_ORDER__"
1100 #endif
1101         pr_warn("endianness mismatch.\n");
1102         return -LIBBPF_ERRNO__ENDIAN;
1103 }
1104
1105 static int
1106 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1107 {
1108         memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1109         pr_debug("license of %s is %s\n", obj->path, obj->license);
1110         return 0;
1111 }
1112
1113 static int
1114 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1115 {
1116         __u32 kver;
1117
1118         if (size != sizeof(kver)) {
1119                 pr_warn("invalid kver section in %s\n", obj->path);
1120                 return -LIBBPF_ERRNO__FORMAT;
1121         }
1122         memcpy(&kver, data, sizeof(kver));
1123         obj->kern_version = kver;
1124         pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1125         return 0;
1126 }
1127
1128 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1129 {
1130         if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1131             type == BPF_MAP_TYPE_HASH_OF_MAPS)
1132                 return true;
1133         return false;
1134 }
1135
1136 static int bpf_object_search_section_size(const struct bpf_object *obj,
1137                                           const char *name, size_t *d_size)
1138 {
1139         const GElf_Ehdr *ep = &obj->efile.ehdr;
1140         Elf *elf = obj->efile.elf;
1141         Elf_Scn *scn = NULL;
1142         int idx = 0;
1143
1144         while ((scn = elf_nextscn(elf, scn)) != NULL) {
1145                 const char *sec_name;
1146                 Elf_Data *data;
1147                 GElf_Shdr sh;
1148
1149                 idx++;
1150                 if (gelf_getshdr(scn, &sh) != &sh) {
1151                         pr_warn("failed to get section(%d) header from %s\n",
1152                                 idx, obj->path);
1153                         return -EIO;
1154                 }
1155
1156                 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1157                 if (!sec_name) {
1158                         pr_warn("failed to get section(%d) name from %s\n",
1159                                 idx, obj->path);
1160                         return -EIO;
1161                 }
1162
1163                 if (strcmp(name, sec_name))
1164                         continue;
1165
1166                 data = elf_getdata(scn, 0);
1167                 if (!data) {
1168                         pr_warn("failed to get section(%d) data from %s(%s)\n",
1169                                 idx, name, obj->path);
1170                         return -EIO;
1171                 }
1172
1173                 *d_size = data->d_size;
1174                 return 0;
1175         }
1176
1177         return -ENOENT;
1178 }
1179
1180 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1181                              __u32 *size)
1182 {
1183         int ret = -ENOENT;
1184         size_t d_size;
1185
1186         *size = 0;
1187         if (!name) {
1188                 return -EINVAL;
1189         } else if (!strcmp(name, DATA_SEC)) {
1190                 if (obj->efile.data)
1191                         *size = obj->efile.data->d_size;
1192         } else if (!strcmp(name, BSS_SEC)) {
1193                 if (obj->efile.bss)
1194                         *size = obj->efile.bss->d_size;
1195         } else if (!strcmp(name, RODATA_SEC)) {
1196                 if (obj->efile.rodata)
1197                         *size = obj->efile.rodata->d_size;
1198         } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1199                 if (obj->efile.st_ops_data)
1200                         *size = obj->efile.st_ops_data->d_size;
1201         } else {
1202                 ret = bpf_object_search_section_size(obj, name, &d_size);
1203                 if (!ret)
1204                         *size = d_size;
1205         }
1206
1207         return *size ? 0 : ret;
1208 }
1209
1210 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1211                                 __u32 *off)
1212 {
1213         Elf_Data *symbols = obj->efile.symbols;
1214         const char *sname;
1215         size_t si;
1216
1217         if (!name || !off)
1218                 return -EINVAL;
1219
1220         for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1221                 GElf_Sym sym;
1222
1223                 if (!gelf_getsym(symbols, si, &sym))
1224                         continue;
1225                 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1226                     GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1227                         continue;
1228
1229                 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1230                                    sym.st_name);
1231                 if (!sname) {
1232                         pr_warn("failed to get sym name string for var %s\n",
1233                                 name);
1234                         return -EIO;
1235                 }
1236                 if (strcmp(name, sname) == 0) {
1237                         *off = sym.st_value;
1238                         return 0;
1239                 }
1240         }
1241
1242         return -ENOENT;
1243 }
1244
1245 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1246 {
1247         struct bpf_map *new_maps;
1248         size_t new_cap;
1249         int i;
1250
1251         if (obj->nr_maps < obj->maps_cap)
1252                 return &obj->maps[obj->nr_maps++];
1253
1254         new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1255         new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
1256         if (!new_maps) {
1257                 pr_warn("alloc maps for object failed\n");
1258                 return ERR_PTR(-ENOMEM);
1259         }
1260
1261         obj->maps_cap = new_cap;
1262         obj->maps = new_maps;
1263
1264         /* zero out new maps */
1265         memset(obj->maps + obj->nr_maps, 0,
1266                (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1267         /*
1268          * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1269          * when failure (zclose won't close negative fd)).
1270          */
1271         for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1272                 obj->maps[i].fd = -1;
1273                 obj->maps[i].inner_map_fd = -1;
1274         }
1275
1276         return &obj->maps[obj->nr_maps++];
1277 }
1278
1279 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1280 {
1281         long page_sz = sysconf(_SC_PAGE_SIZE);
1282         size_t map_sz;
1283
1284         map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
1285         map_sz = roundup(map_sz, page_sz);
1286         return map_sz;
1287 }
1288
1289 static char *internal_map_name(struct bpf_object *obj,
1290                                enum libbpf_map_type type)
1291 {
1292         char map_name[BPF_OBJ_NAME_LEN];
1293         const char *sfx = libbpf_type_to_btf_name[type];
1294         int sfx_len = max((size_t)7, strlen(sfx));
1295         int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1296                           strlen(obj->name));
1297
1298         snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1299                  sfx_len, libbpf_type_to_btf_name[type]);
1300
1301         return strdup(map_name);
1302 }
1303
1304 static int
1305 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1306                               int sec_idx, void *data, size_t data_sz)
1307 {
1308         struct bpf_map_def *def;
1309         struct bpf_map *map;
1310         int err;
1311
1312         map = bpf_object__add_map(obj);
1313         if (IS_ERR(map))
1314                 return PTR_ERR(map);
1315
1316         map->libbpf_type = type;
1317         map->sec_idx = sec_idx;
1318         map->sec_offset = 0;
1319         map->name = internal_map_name(obj, type);
1320         if (!map->name) {
1321                 pr_warn("failed to alloc map name\n");
1322                 return -ENOMEM;
1323         }
1324
1325         def = &map->def;
1326         def->type = BPF_MAP_TYPE_ARRAY;
1327         def->key_size = sizeof(int);
1328         def->value_size = data_sz;
1329         def->max_entries = 1;
1330         def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1331                          ? BPF_F_RDONLY_PROG : 0;
1332         def->map_flags |= BPF_F_MMAPABLE;
1333
1334         pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1335                  map->name, map->sec_idx, map->sec_offset, def->map_flags);
1336
1337         map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1338                            MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1339         if (map->mmaped == MAP_FAILED) {
1340                 err = -errno;
1341                 map->mmaped = NULL;
1342                 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1343                         map->name, err);
1344                 zfree(&map->name);
1345                 return err;
1346         }
1347
1348         if (data)
1349                 memcpy(map->mmaped, data, data_sz);
1350
1351         pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1352         return 0;
1353 }
1354
1355 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1356 {
1357         int err;
1358
1359         /*
1360          * Populate obj->maps with libbpf internal maps.
1361          */
1362         if (obj->efile.data_shndx >= 0) {
1363                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1364                                                     obj->efile.data_shndx,
1365                                                     obj->efile.data->d_buf,
1366                                                     obj->efile.data->d_size);
1367                 if (err)
1368                         return err;
1369         }
1370         if (obj->efile.rodata_shndx >= 0) {
1371                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1372                                                     obj->efile.rodata_shndx,
1373                                                     obj->efile.rodata->d_buf,
1374                                                     obj->efile.rodata->d_size);
1375                 if (err)
1376                         return err;
1377         }
1378         if (obj->efile.bss_shndx >= 0) {
1379                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1380                                                     obj->efile.bss_shndx,
1381                                                     NULL,
1382                                                     obj->efile.bss->d_size);
1383                 if (err)
1384                         return err;
1385         }
1386         return 0;
1387 }
1388
1389
1390 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1391                                                const void *name)
1392 {
1393         int i;
1394
1395         for (i = 0; i < obj->nr_extern; i++) {
1396                 if (strcmp(obj->externs[i].name, name) == 0)
1397                         return &obj->externs[i];
1398         }
1399         return NULL;
1400 }
1401
1402 static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1403                              char value)
1404 {
1405         switch (ext->type) {
1406         case EXT_BOOL:
1407                 if (value == 'm') {
1408                         pr_warn("extern %s=%c should be tristate or char\n",
1409                                 ext->name, value);
1410                         return -EINVAL;
1411                 }
1412                 *(bool *)ext_val = value == 'y' ? true : false;
1413                 break;
1414         case EXT_TRISTATE:
1415                 if (value == 'y')
1416                         *(enum libbpf_tristate *)ext_val = TRI_YES;
1417                 else if (value == 'm')
1418                         *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1419                 else /* value == 'n' */
1420                         *(enum libbpf_tristate *)ext_val = TRI_NO;
1421                 break;
1422         case EXT_CHAR:
1423                 *(char *)ext_val = value;
1424                 break;
1425         case EXT_UNKNOWN:
1426         case EXT_INT:
1427         case EXT_CHAR_ARR:
1428         default:
1429                 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1430                         ext->name, value);
1431                 return -EINVAL;
1432         }
1433         ext->is_set = true;
1434         return 0;
1435 }
1436
1437 static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1438                              const char *value)
1439 {
1440         size_t len;
1441
1442         if (ext->type != EXT_CHAR_ARR) {
1443                 pr_warn("extern %s=%s should char array\n", ext->name, value);
1444                 return -EINVAL;
1445         }
1446
1447         len = strlen(value);
1448         if (value[len - 1] != '"') {
1449                 pr_warn("extern '%s': invalid string config '%s'\n",
1450                         ext->name, value);
1451                 return -EINVAL;
1452         }
1453
1454         /* strip quotes */
1455         len -= 2;
1456         if (len >= ext->sz) {
1457                 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1458                         ext->name, value, len, ext->sz - 1);
1459                 len = ext->sz - 1;
1460         }
1461         memcpy(ext_val, value + 1, len);
1462         ext_val[len] = '\0';
1463         ext->is_set = true;
1464         return 0;
1465 }
1466
1467 static int parse_u64(const char *value, __u64 *res)
1468 {
1469         char *value_end;
1470         int err;
1471
1472         errno = 0;
1473         *res = strtoull(value, &value_end, 0);
1474         if (errno) {
1475                 err = -errno;
1476                 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1477                 return err;
1478         }
1479         if (*value_end) {
1480                 pr_warn("failed to parse '%s' as integer completely\n", value);
1481                 return -EINVAL;
1482         }
1483         return 0;
1484 }
1485
1486 static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1487 {
1488         int bit_sz = ext->sz * 8;
1489
1490         if (ext->sz == 8)
1491                 return true;
1492
1493         /* Validate that value stored in u64 fits in integer of `ext->sz`
1494          * bytes size without any loss of information. If the target integer
1495          * is signed, we rely on the following limits of integer type of
1496          * Y bits and subsequent transformation:
1497          *
1498          *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1499          *            0 <= X + 2^(Y-1) <= 2^Y - 1
1500          *            0 <= X + 2^(Y-1) <  2^Y
1501          *
1502          *  For unsigned target integer, check that all the (64 - Y) bits are
1503          *  zero.
1504          */
1505         if (ext->is_signed)
1506                 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1507         else
1508                 return (v >> bit_sz) == 0;
1509 }
1510
1511 static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1512                              __u64 value)
1513 {
1514         if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1515                 pr_warn("extern %s=%llu should be integer\n",
1516                         ext->name, (unsigned long long)value);
1517                 return -EINVAL;
1518         }
1519         if (!is_ext_value_in_range(ext, value)) {
1520                 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1521                         ext->name, (unsigned long long)value, ext->sz);
1522                 return -ERANGE;
1523         }
1524         switch (ext->sz) {
1525                 case 1: *(__u8 *)ext_val = value; break;
1526                 case 2: *(__u16 *)ext_val = value; break;
1527                 case 4: *(__u32 *)ext_val = value; break;
1528                 case 8: *(__u64 *)ext_val = value; break;
1529                 default:
1530                         return -EINVAL;
1531         }
1532         ext->is_set = true;
1533         return 0;
1534 }
1535
1536 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1537                                             char *buf, void *data)
1538 {
1539         struct extern_desc *ext;
1540         char *sep, *value;
1541         int len, err = 0;
1542         void *ext_val;
1543         __u64 num;
1544
1545         if (strncmp(buf, "CONFIG_", 7))
1546                 return 0;
1547
1548         sep = strchr(buf, '=');
1549         if (!sep) {
1550                 pr_warn("failed to parse '%s': no separator\n", buf);
1551                 return -EINVAL;
1552         }
1553
1554         /* Trim ending '\n' */
1555         len = strlen(buf);
1556         if (buf[len - 1] == '\n')
1557                 buf[len - 1] = '\0';
1558         /* Split on '=' and ensure that a value is present. */
1559         *sep = '\0';
1560         if (!sep[1]) {
1561                 *sep = '=';
1562                 pr_warn("failed to parse '%s': no value\n", buf);
1563                 return -EINVAL;
1564         }
1565
1566         ext = find_extern_by_name(obj, buf);
1567         if (!ext || ext->is_set)
1568                 return 0;
1569
1570         ext_val = data + ext->data_off;
1571         value = sep + 1;
1572
1573         switch (*value) {
1574         case 'y': case 'n': case 'm':
1575                 err = set_ext_value_tri(ext, ext_val, *value);
1576                 break;
1577         case '"':
1578                 err = set_ext_value_str(ext, ext_val, value);
1579                 break;
1580         default:
1581                 /* assume integer */
1582                 err = parse_u64(value, &num);
1583                 if (err) {
1584                         pr_warn("extern %s=%s should be integer\n",
1585                                 ext->name, value);
1586                         return err;
1587                 }
1588                 err = set_ext_value_num(ext, ext_val, num);
1589                 break;
1590         }
1591         if (err)
1592                 return err;
1593         pr_debug("extern %s=%s\n", ext->name, value);
1594         return 0;
1595 }
1596
1597 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1598 {
1599         char buf[PATH_MAX];
1600         struct utsname uts;
1601         int len, err = 0;
1602         gzFile file;
1603
1604         uname(&uts);
1605         len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1606         if (len < 0)
1607                 return -EINVAL;
1608         else if (len >= PATH_MAX)
1609                 return -ENAMETOOLONG;
1610
1611         /* gzopen also accepts uncompressed files. */
1612         file = gzopen(buf, "r");
1613         if (!file)
1614                 file = gzopen("/proc/config.gz", "r");
1615
1616         if (!file) {
1617                 pr_warn("failed to open system Kconfig\n");
1618                 return -ENOENT;
1619         }
1620
1621         while (gzgets(file, buf, sizeof(buf))) {
1622                 err = bpf_object__process_kconfig_line(obj, buf, data);
1623                 if (err) {
1624                         pr_warn("error parsing system Kconfig line '%s': %d\n",
1625                                 buf, err);
1626                         goto out;
1627                 }
1628         }
1629
1630 out:
1631         gzclose(file);
1632         return err;
1633 }
1634
1635 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1636                                         const char *config, void *data)
1637 {
1638         char buf[PATH_MAX];
1639         int err = 0;
1640         FILE *file;
1641
1642         file = fmemopen((void *)config, strlen(config), "r");
1643         if (!file) {
1644                 err = -errno;
1645                 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1646                 return err;
1647         }
1648
1649         while (fgets(buf, sizeof(buf), file)) {
1650                 err = bpf_object__process_kconfig_line(obj, buf, data);
1651                 if (err) {
1652                         pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1653                                 buf, err);
1654                         break;
1655                 }
1656         }
1657
1658         fclose(file);
1659         return err;
1660 }
1661
1662 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1663 {
1664         struct extern_desc *last_ext;
1665         size_t map_sz;
1666         int err;
1667
1668         if (obj->nr_extern == 0)
1669                 return 0;
1670
1671         last_ext = &obj->externs[obj->nr_extern - 1];
1672         map_sz = last_ext->data_off + last_ext->sz;
1673
1674         err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1675                                             obj->efile.symbols_shndx,
1676                                             NULL, map_sz);
1677         if (err)
1678                 return err;
1679
1680         obj->kconfig_map_idx = obj->nr_maps - 1;
1681
1682         return 0;
1683 }
1684
1685 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1686 {
1687         Elf_Data *symbols = obj->efile.symbols;
1688         int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1689         Elf_Data *data = NULL;
1690         Elf_Scn *scn;
1691
1692         if (obj->efile.maps_shndx < 0)
1693                 return 0;
1694
1695         if (!symbols)
1696                 return -EINVAL;
1697
1698         scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1699         if (scn)
1700                 data = elf_getdata(scn, NULL);
1701         if (!scn || !data) {
1702                 pr_warn("failed to get Elf_Data from map section %d\n",
1703                         obj->efile.maps_shndx);
1704                 return -EINVAL;
1705         }
1706
1707         /*
1708          * Count number of maps. Each map has a name.
1709          * Array of maps is not supported: only the first element is
1710          * considered.
1711          *
1712          * TODO: Detect array of map and report error.
1713          */
1714         nr_syms = symbols->d_size / sizeof(GElf_Sym);
1715         for (i = 0; i < nr_syms; i++) {
1716                 GElf_Sym sym;
1717
1718                 if (!gelf_getsym(symbols, i, &sym))
1719                         continue;
1720                 if (sym.st_shndx != obj->efile.maps_shndx)
1721                         continue;
1722                 nr_maps++;
1723         }
1724         /* Assume equally sized map definitions */
1725         pr_debug("maps in %s: %d maps in %zd bytes\n",
1726                  obj->path, nr_maps, data->d_size);
1727
1728         if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1729                 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1730                         obj->path, nr_maps, data->d_size);
1731                 return -EINVAL;
1732         }
1733         map_def_sz = data->d_size / nr_maps;
1734
1735         /* Fill obj->maps using data in "maps" section.  */
1736         for (i = 0; i < nr_syms; i++) {
1737                 GElf_Sym sym;
1738                 const char *map_name;
1739                 struct bpf_map_def *def;
1740                 struct bpf_map *map;
1741
1742                 if (!gelf_getsym(symbols, i, &sym))
1743                         continue;
1744                 if (sym.st_shndx != obj->efile.maps_shndx)
1745                         continue;
1746
1747                 map = bpf_object__add_map(obj);
1748                 if (IS_ERR(map))
1749                         return PTR_ERR(map);
1750
1751                 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1752                                       sym.st_name);
1753                 if (!map_name) {
1754                         pr_warn("failed to get map #%d name sym string for obj %s\n",
1755                                 i, obj->path);
1756                         return -LIBBPF_ERRNO__FORMAT;
1757                 }
1758
1759                 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1760                 map->sec_idx = sym.st_shndx;
1761                 map->sec_offset = sym.st_value;
1762                 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1763                          map_name, map->sec_idx, map->sec_offset);
1764                 if (sym.st_value + map_def_sz > data->d_size) {
1765                         pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1766                                 obj->path, map_name);
1767                         return -EINVAL;
1768                 }
1769
1770                 map->name = strdup(map_name);
1771                 if (!map->name) {
1772                         pr_warn("failed to alloc map name\n");
1773                         return -ENOMEM;
1774                 }
1775                 pr_debug("map %d is \"%s\"\n", i, map->name);
1776                 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1777                 /*
1778                  * If the definition of the map in the object file fits in
1779                  * bpf_map_def, copy it.  Any extra fields in our version
1780                  * of bpf_map_def will default to zero as a result of the
1781                  * calloc above.
1782                  */
1783                 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1784                         memcpy(&map->def, def, map_def_sz);
1785                 } else {
1786                         /*
1787                          * Here the map structure being read is bigger than what
1788                          * we expect, truncate if the excess bits are all zero.
1789                          * If they are not zero, reject this map as
1790                          * incompatible.
1791                          */
1792                         char *b;
1793
1794                         for (b = ((char *)def) + sizeof(struct bpf_map_def);
1795                              b < ((char *)def) + map_def_sz; b++) {
1796                                 if (*b != 0) {
1797                                         pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1798                                                 obj->path, map_name);
1799                                         if (strict)
1800                                                 return -EINVAL;
1801                                 }
1802                         }
1803                         memcpy(&map->def, def, sizeof(struct bpf_map_def));
1804                 }
1805         }
1806         return 0;
1807 }
1808
1809 static const struct btf_type *
1810 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1811 {
1812         const struct btf_type *t = btf__type_by_id(btf, id);
1813
1814         if (res_id)
1815                 *res_id = id;
1816
1817         while (btf_is_mod(t) || btf_is_typedef(t)) {
1818                 if (res_id)
1819                         *res_id = t->type;
1820                 t = btf__type_by_id(btf, t->type);
1821         }
1822
1823         return t;
1824 }
1825
1826 static const struct btf_type *
1827 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1828 {
1829         const struct btf_type *t;
1830
1831         t = skip_mods_and_typedefs(btf, id, NULL);
1832         if (!btf_is_ptr(t))
1833                 return NULL;
1834
1835         t = skip_mods_and_typedefs(btf, t->type, res_id);
1836
1837         return btf_is_func_proto(t) ? t : NULL;
1838 }
1839
1840 /*
1841  * Fetch integer attribute of BTF map definition. Such attributes are
1842  * represented using a pointer to an array, in which dimensionality of array
1843  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1844  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1845  * type definition, while using only sizeof(void *) space in ELF data section.
1846  */
1847 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1848                               const struct btf_type *def,
1849                               const struct btf_member *m, __u32 *res)
1850 {
1851         const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1852         const char *name = btf__name_by_offset(btf, m->name_off);
1853         const struct btf_array *arr_info;
1854         const struct btf_type *arr_t;
1855
1856         if (!btf_is_ptr(t)) {
1857                 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1858                         map_name, name, btf_kind(t));
1859                 return false;
1860         }
1861
1862         arr_t = btf__type_by_id(btf, t->type);
1863         if (!arr_t) {
1864                 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1865                         map_name, name, t->type);
1866                 return false;
1867         }
1868         if (!btf_is_array(arr_t)) {
1869                 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1870                         map_name, name, btf_kind(arr_t));
1871                 return false;
1872         }
1873         arr_info = btf_array(arr_t);
1874         *res = arr_info->nelems;
1875         return true;
1876 }
1877
1878 static int build_map_pin_path(struct bpf_map *map, const char *path)
1879 {
1880         char buf[PATH_MAX];
1881         int err, len;
1882
1883         if (!path)
1884                 path = "/sys/fs/bpf";
1885
1886         len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1887         if (len < 0)
1888                 return -EINVAL;
1889         else if (len >= PATH_MAX)
1890                 return -ENAMETOOLONG;
1891
1892         err = bpf_map__set_pin_path(map, buf);
1893         if (err)
1894                 return err;
1895
1896         return 0;
1897 }
1898
1899 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1900                                          const struct btf_type *sec,
1901                                          int var_idx, int sec_idx,
1902                                          const Elf_Data *data, bool strict,
1903                                          const char *pin_root_path)
1904 {
1905         const struct btf_type *var, *def, *t;
1906         const struct btf_var_secinfo *vi;
1907         const struct btf_var *var_extra;
1908         const struct btf_member *m;
1909         const char *map_name;
1910         struct bpf_map *map;
1911         int vlen, i;
1912
1913         vi = btf_var_secinfos(sec) + var_idx;
1914         var = btf__type_by_id(obj->btf, vi->type);
1915         var_extra = btf_var(var);
1916         map_name = btf__name_by_offset(obj->btf, var->name_off);
1917         vlen = btf_vlen(var);
1918
1919         if (map_name == NULL || map_name[0] == '\0') {
1920                 pr_warn("map #%d: empty name.\n", var_idx);
1921                 return -EINVAL;
1922         }
1923         if ((__u64)vi->offset + vi->size > data->d_size) {
1924                 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1925                 return -EINVAL;
1926         }
1927         if (!btf_is_var(var)) {
1928                 pr_warn("map '%s': unexpected var kind %u.\n",
1929                         map_name, btf_kind(var));
1930                 return -EINVAL;
1931         }
1932         if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1933             var_extra->linkage != BTF_VAR_STATIC) {
1934                 pr_warn("map '%s': unsupported var linkage %u.\n",
1935                         map_name, var_extra->linkage);
1936                 return -EOPNOTSUPP;
1937         }
1938
1939         def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1940         if (!btf_is_struct(def)) {
1941                 pr_warn("map '%s': unexpected def kind %u.\n",
1942                         map_name, btf_kind(var));
1943                 return -EINVAL;
1944         }
1945         if (def->size > vi->size) {
1946                 pr_warn("map '%s': invalid def size.\n", map_name);
1947                 return -EINVAL;
1948         }
1949
1950         map = bpf_object__add_map(obj);
1951         if (IS_ERR(map))
1952                 return PTR_ERR(map);
1953         map->name = strdup(map_name);
1954         if (!map->name) {
1955                 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1956                 return -ENOMEM;
1957         }
1958         map->libbpf_type = LIBBPF_MAP_UNSPEC;
1959         map->def.type = BPF_MAP_TYPE_UNSPEC;
1960         map->sec_idx = sec_idx;
1961         map->sec_offset = vi->offset;
1962         pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1963                  map_name, map->sec_idx, map->sec_offset);
1964
1965         vlen = btf_vlen(def);
1966         m = btf_members(def);
1967         for (i = 0; i < vlen; i++, m++) {
1968                 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1969
1970                 if (!name) {
1971                         pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1972                         return -EINVAL;
1973                 }
1974                 if (strcmp(name, "type") == 0) {
1975                         if (!get_map_field_int(map_name, obj->btf, def, m,
1976                                                &map->def.type))
1977                                 return -EINVAL;
1978                         pr_debug("map '%s': found type = %u.\n",
1979                                  map_name, map->def.type);
1980                 } else if (strcmp(name, "max_entries") == 0) {
1981                         if (!get_map_field_int(map_name, obj->btf, def, m,
1982                                                &map->def.max_entries))
1983                                 return -EINVAL;
1984                         pr_debug("map '%s': found max_entries = %u.\n",
1985                                  map_name, map->def.max_entries);
1986                 } else if (strcmp(name, "map_flags") == 0) {
1987                         if (!get_map_field_int(map_name, obj->btf, def, m,
1988                                                &map->def.map_flags))
1989                                 return -EINVAL;
1990                         pr_debug("map '%s': found map_flags = %u.\n",
1991                                  map_name, map->def.map_flags);
1992                 } else if (strcmp(name, "key_size") == 0) {
1993                         __u32 sz;
1994
1995                         if (!get_map_field_int(map_name, obj->btf, def, m,
1996                                                &sz))
1997                                 return -EINVAL;
1998                         pr_debug("map '%s': found key_size = %u.\n",
1999                                  map_name, sz);
2000                         if (map->def.key_size && map->def.key_size != sz) {
2001                                 pr_warn("map '%s': conflicting key size %u != %u.\n",
2002                                         map_name, map->def.key_size, sz);
2003                                 return -EINVAL;
2004                         }
2005                         map->def.key_size = sz;
2006                 } else if (strcmp(name, "key") == 0) {
2007                         __s64 sz;
2008
2009                         t = btf__type_by_id(obj->btf, m->type);
2010                         if (!t) {
2011                                 pr_warn("map '%s': key type [%d] not found.\n",
2012                                         map_name, m->type);
2013                                 return -EINVAL;
2014                         }
2015                         if (!btf_is_ptr(t)) {
2016                                 pr_warn("map '%s': key spec is not PTR: %u.\n",
2017                                         map_name, btf_kind(t));
2018                                 return -EINVAL;
2019                         }
2020                         sz = btf__resolve_size(obj->btf, t->type);
2021                         if (sz < 0) {
2022                                 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2023                                         map_name, t->type, (ssize_t)sz);
2024                                 return sz;
2025                         }
2026                         pr_debug("map '%s': found key [%u], sz = %zd.\n",
2027                                  map_name, t->type, (ssize_t)sz);
2028                         if (map->def.key_size && map->def.key_size != sz) {
2029                                 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2030                                         map_name, map->def.key_size, (ssize_t)sz);
2031                                 return -EINVAL;
2032                         }
2033                         map->def.key_size = sz;
2034                         map->btf_key_type_id = t->type;
2035                 } else if (strcmp(name, "value_size") == 0) {
2036                         __u32 sz;
2037
2038                         if (!get_map_field_int(map_name, obj->btf, def, m,
2039                                                &sz))
2040                                 return -EINVAL;
2041                         pr_debug("map '%s': found value_size = %u.\n",
2042                                  map_name, sz);
2043                         if (map->def.value_size && map->def.value_size != sz) {
2044                                 pr_warn("map '%s': conflicting value size %u != %u.\n",
2045                                         map_name, map->def.value_size, sz);
2046                                 return -EINVAL;
2047                         }
2048                         map->def.value_size = sz;
2049                 } else if (strcmp(name, "value") == 0) {
2050                         __s64 sz;
2051
2052                         t = btf__type_by_id(obj->btf, m->type);
2053                         if (!t) {
2054                                 pr_warn("map '%s': value type [%d] not found.\n",
2055                                         map_name, m->type);
2056                                 return -EINVAL;
2057                         }
2058                         if (!btf_is_ptr(t)) {
2059                                 pr_warn("map '%s': value spec is not PTR: %u.\n",
2060                                         map_name, btf_kind(t));
2061                                 return -EINVAL;
2062                         }
2063                         sz = btf__resolve_size(obj->btf, t->type);
2064                         if (sz < 0) {
2065                                 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2066                                         map_name, t->type, (ssize_t)sz);
2067                                 return sz;
2068                         }
2069                         pr_debug("map '%s': found value [%u], sz = %zd.\n",
2070                                  map_name, t->type, (ssize_t)sz);
2071                         if (map->def.value_size && map->def.value_size != sz) {
2072                                 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2073                                         map_name, map->def.value_size, (ssize_t)sz);
2074                                 return -EINVAL;
2075                         }
2076                         map->def.value_size = sz;
2077                         map->btf_value_type_id = t->type;
2078                 } else if (strcmp(name, "pinning") == 0) {
2079                         __u32 val;
2080                         int err;
2081
2082                         if (!get_map_field_int(map_name, obj->btf, def, m,
2083                                                &val))
2084                                 return -EINVAL;
2085                         pr_debug("map '%s': found pinning = %u.\n",
2086                                  map_name, val);
2087
2088                         if (val != LIBBPF_PIN_NONE &&
2089                             val != LIBBPF_PIN_BY_NAME) {
2090                                 pr_warn("map '%s': invalid pinning value %u.\n",
2091                                         map_name, val);
2092                                 return -EINVAL;
2093                         }
2094                         if (val == LIBBPF_PIN_BY_NAME) {
2095                                 err = build_map_pin_path(map, pin_root_path);
2096                                 if (err) {
2097                                         pr_warn("map '%s': couldn't build pin path.\n",
2098                                                 map_name);
2099                                         return err;
2100                                 }
2101                         }
2102                 } else {
2103                         if (strict) {
2104                                 pr_warn("map '%s': unknown field '%s'.\n",
2105                                         map_name, name);
2106                                 return -ENOTSUP;
2107                         }
2108                         pr_debug("map '%s': ignoring unknown field '%s'.\n",
2109                                  map_name, name);
2110                 }
2111         }
2112
2113         if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
2114                 pr_warn("map '%s': map type isn't specified.\n", map_name);
2115                 return -EINVAL;
2116         }
2117
2118         return 0;
2119 }
2120
2121 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2122                                           const char *pin_root_path)
2123 {
2124         const struct btf_type *sec = NULL;
2125         int nr_types, i, vlen, err;
2126         const struct btf_type *t;
2127         const char *name;
2128         Elf_Data *data;
2129         Elf_Scn *scn;
2130
2131         if (obj->efile.btf_maps_shndx < 0)
2132                 return 0;
2133
2134         scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
2135         if (scn)
2136                 data = elf_getdata(scn, NULL);
2137         if (!scn || !data) {
2138                 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
2139                         obj->efile.maps_shndx, MAPS_ELF_SEC);
2140                 return -EINVAL;
2141         }
2142
2143         nr_types = btf__get_nr_types(obj->btf);
2144         for (i = 1; i <= nr_types; i++) {
2145                 t = btf__type_by_id(obj->btf, i);
2146                 if (!btf_is_datasec(t))
2147                         continue;
2148                 name = btf__name_by_offset(obj->btf, t->name_off);
2149                 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2150                         sec = t;
2151                         break;
2152                 }
2153         }
2154
2155         if (!sec) {
2156                 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2157                 return -ENOENT;
2158         }
2159
2160         vlen = btf_vlen(sec);
2161         for (i = 0; i < vlen; i++) {
2162                 err = bpf_object__init_user_btf_map(obj, sec, i,
2163                                                     obj->efile.btf_maps_shndx,
2164                                                     data, strict,
2165                                                     pin_root_path);
2166                 if (err)
2167                         return err;
2168         }
2169
2170         return 0;
2171 }
2172
2173 static int bpf_object__init_maps(struct bpf_object *obj,
2174                                  const struct bpf_object_open_opts *opts)
2175 {
2176         const char *pin_root_path;
2177         bool strict;
2178         int err;
2179
2180         strict = !OPTS_GET(opts, relaxed_maps, false);
2181         pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2182
2183         err = bpf_object__init_user_maps(obj, strict);
2184         err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2185         err = err ?: bpf_object__init_global_data_maps(obj);
2186         err = err ?: bpf_object__init_kconfig_map(obj);
2187         err = err ?: bpf_object__init_struct_ops_maps(obj);
2188         if (err)
2189                 return err;
2190
2191         return 0;
2192 }
2193
2194 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2195 {
2196         Elf_Scn *scn;
2197         GElf_Shdr sh;
2198
2199         scn = elf_getscn(obj->efile.elf, idx);
2200         if (!scn)
2201                 return false;
2202
2203         if (gelf_getshdr(scn, &sh) != &sh)
2204                 return false;
2205
2206         if (sh.sh_flags & SHF_EXECINSTR)
2207                 return true;
2208
2209         return false;
2210 }
2211
2212 static void bpf_object__sanitize_btf(struct bpf_object *obj)
2213 {
2214         bool has_func_global = obj->caps.btf_func_global;
2215         bool has_datasec = obj->caps.btf_datasec;
2216         bool has_func = obj->caps.btf_func;
2217         struct btf *btf = obj->btf;
2218         struct btf_type *t;
2219         int i, j, vlen;
2220
2221         if (!obj->btf || (has_func && has_datasec && has_func_global))
2222                 return;
2223
2224         for (i = 1; i <= btf__get_nr_types(btf); i++) {
2225                 t = (struct btf_type *)btf__type_by_id(btf, i);
2226
2227                 if (!has_datasec && btf_is_var(t)) {
2228                         /* replace VAR with INT */
2229                         t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2230                         /*
2231                          * using size = 1 is the safest choice, 4 will be too
2232                          * big and cause kernel BTF validation failure if
2233                          * original variable took less than 4 bytes
2234                          */
2235                         t->size = 1;
2236                         *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2237                 } else if (!has_datasec && btf_is_datasec(t)) {
2238                         /* replace DATASEC with STRUCT */
2239                         const struct btf_var_secinfo *v = btf_var_secinfos(t);
2240                         struct btf_member *m = btf_members(t);
2241                         struct btf_type *vt;
2242                         char *name;
2243
2244                         name = (char *)btf__name_by_offset(btf, t->name_off);
2245                         while (*name) {
2246                                 if (*name == '.')
2247                                         *name = '_';
2248                                 name++;
2249                         }
2250
2251                         vlen = btf_vlen(t);
2252                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2253                         for (j = 0; j < vlen; j++, v++, m++) {
2254                                 /* order of field assignments is important */
2255                                 m->offset = v->offset * 8;
2256                                 m->type = v->type;
2257                                 /* preserve variable name as member name */
2258                                 vt = (void *)btf__type_by_id(btf, v->type);
2259                                 m->name_off = vt->name_off;
2260                         }
2261                 } else if (!has_func && btf_is_func_proto(t)) {
2262                         /* replace FUNC_PROTO with ENUM */
2263                         vlen = btf_vlen(t);
2264                         t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2265                         t->size = sizeof(__u32); /* kernel enforced */
2266                 } else if (!has_func && btf_is_func(t)) {
2267                         /* replace FUNC with TYPEDEF */
2268                         t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2269                 } else if (!has_func_global && btf_is_func(t)) {
2270                         /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2271                         t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2272                 }
2273         }
2274 }
2275
2276 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
2277 {
2278         if (!obj->btf_ext)
2279                 return;
2280
2281         if (!obj->caps.btf_func) {
2282                 btf_ext__free(obj->btf_ext);
2283                 obj->btf_ext = NULL;
2284         }
2285 }
2286
2287 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
2288 {
2289         return obj->efile.btf_maps_shndx >= 0 ||
2290                 obj->efile.st_ops_shndx >= 0 ||
2291                 obj->nr_extern > 0;
2292 }
2293
2294 static int bpf_object__init_btf(struct bpf_object *obj,
2295                                 Elf_Data *btf_data,
2296                                 Elf_Data *btf_ext_data)
2297 {
2298         bool btf_required = bpf_object__is_btf_mandatory(obj);
2299         int err = 0;
2300
2301         if (btf_data) {
2302                 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2303                 if (IS_ERR(obj->btf)) {
2304                         pr_warn("Error loading ELF section %s: %d.\n",
2305                                 BTF_ELF_SEC, err);
2306                         goto out;
2307                 }
2308         }
2309         if (btf_ext_data) {
2310                 if (!obj->btf) {
2311                         pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2312                                  BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2313                         goto out;
2314                 }
2315                 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
2316                                             btf_ext_data->d_size);
2317                 if (IS_ERR(obj->btf_ext)) {
2318                         pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2319                                 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
2320                         obj->btf_ext = NULL;
2321                         goto out;
2322                 }
2323         }
2324 out:
2325         if (err || IS_ERR(obj->btf)) {
2326                 if (btf_required)
2327                         err = err ? : PTR_ERR(obj->btf);
2328                 else
2329                         err = 0;
2330                 if (!IS_ERR_OR_NULL(obj->btf))
2331                         btf__free(obj->btf);
2332                 obj->btf = NULL;
2333         }
2334         if (btf_required && !obj->btf) {
2335                 pr_warn("BTF is required, but is missing or corrupted.\n");
2336                 return err == 0 ? -ENOENT : err;
2337         }
2338         return 0;
2339 }
2340
2341 static int bpf_object__finalize_btf(struct bpf_object *obj)
2342 {
2343         int err;
2344
2345         if (!obj->btf)
2346                 return 0;
2347
2348         err = btf__finalize_data(obj, obj->btf);
2349         if (!err)
2350                 return 0;
2351
2352         pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2353         btf__free(obj->btf);
2354         obj->btf = NULL;
2355         btf_ext__free(obj->btf_ext);
2356         obj->btf_ext = NULL;
2357
2358         if (bpf_object__is_btf_mandatory(obj)) {
2359                 pr_warn("BTF is required, but is missing or corrupted.\n");
2360                 return -ENOENT;
2361         }
2362         return 0;
2363 }
2364
2365 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2366 {
2367         int err = 0;
2368
2369         if (!obj->btf)
2370                 return 0;
2371
2372         bpf_object__sanitize_btf(obj);
2373         bpf_object__sanitize_btf_ext(obj);
2374
2375         err = btf__load(obj->btf);
2376         if (err) {
2377                 pr_warn("Error loading %s into kernel: %d.\n",
2378                         BTF_ELF_SEC, err);
2379                 btf__free(obj->btf);
2380                 obj->btf = NULL;
2381                 /* btf_ext can't exist without btf, so free it as well */
2382                 if (obj->btf_ext) {
2383                         btf_ext__free(obj->btf_ext);
2384                         obj->btf_ext = NULL;
2385                 }
2386
2387                 if (bpf_object__is_btf_mandatory(obj))
2388                         return err;
2389         }
2390         return 0;
2391 }
2392
2393 static int bpf_object__elf_collect(struct bpf_object *obj)
2394 {
2395         Elf *elf = obj->efile.elf;
2396         GElf_Ehdr *ep = &obj->efile.ehdr;
2397         Elf_Data *btf_ext_data = NULL;
2398         Elf_Data *btf_data = NULL;
2399         Elf_Scn *scn = NULL;
2400         int idx = 0, err = 0;
2401
2402         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2403         if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2404                 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2405                 return -LIBBPF_ERRNO__FORMAT;
2406         }
2407
2408         while ((scn = elf_nextscn(elf, scn)) != NULL) {
2409                 char *name;
2410                 GElf_Shdr sh;
2411                 Elf_Data *data;
2412
2413                 idx++;
2414                 if (gelf_getshdr(scn, &sh) != &sh) {
2415                         pr_warn("failed to get section(%d) header from %s\n",
2416                                 idx, obj->path);
2417                         return -LIBBPF_ERRNO__FORMAT;
2418                 }
2419
2420                 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2421                 if (!name) {
2422                         pr_warn("failed to get section(%d) name from %s\n",
2423                                 idx, obj->path);
2424                         return -LIBBPF_ERRNO__FORMAT;
2425                 }
2426
2427                 data = elf_getdata(scn, 0);
2428                 if (!data) {
2429                         pr_warn("failed to get section(%d) data from %s(%s)\n",
2430                                 idx, name, obj->path);
2431                         return -LIBBPF_ERRNO__FORMAT;
2432                 }
2433                 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2434                          idx, name, (unsigned long)data->d_size,
2435                          (int)sh.sh_link, (unsigned long)sh.sh_flags,
2436                          (int)sh.sh_type);
2437
2438                 if (strcmp(name, "license") == 0) {
2439                         err = bpf_object__init_license(obj,
2440                                                        data->d_buf,
2441                                                        data->d_size);
2442                         if (err)
2443                                 return err;
2444                 } else if (strcmp(name, "version") == 0) {
2445                         err = bpf_object__init_kversion(obj,
2446                                                         data->d_buf,
2447                                                         data->d_size);
2448                         if (err)
2449                                 return err;
2450                 } else if (strcmp(name, "maps") == 0) {
2451                         obj->efile.maps_shndx = idx;
2452                 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2453                         obj->efile.btf_maps_shndx = idx;
2454                 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2455                         btf_data = data;
2456                 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2457                         btf_ext_data = data;
2458                 } else if (sh.sh_type == SHT_SYMTAB) {
2459                         if (obj->efile.symbols) {
2460                                 pr_warn("bpf: multiple SYMTAB in %s\n",
2461                                         obj->path);
2462                                 return -LIBBPF_ERRNO__FORMAT;
2463                         }
2464                         obj->efile.symbols = data;
2465                         obj->efile.symbols_shndx = idx;
2466                         obj->efile.strtabidx = sh.sh_link;
2467                 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2468                         if (sh.sh_flags & SHF_EXECINSTR) {
2469                                 if (strcmp(name, ".text") == 0)
2470                                         obj->efile.text_shndx = idx;
2471                                 err = bpf_object__add_program(obj, data->d_buf,
2472                                                               data->d_size,
2473                                                               name, idx);
2474                                 if (err) {
2475                                         char errmsg[STRERR_BUFSIZE];
2476                                         char *cp;
2477
2478                                         cp = libbpf_strerror_r(-err, errmsg,
2479                                                                sizeof(errmsg));
2480                                         pr_warn("failed to alloc program %s (%s): %s",
2481                                                 name, obj->path, cp);
2482                                         return err;
2483                                 }
2484                         } else if (strcmp(name, DATA_SEC) == 0) {
2485                                 obj->efile.data = data;
2486                                 obj->efile.data_shndx = idx;
2487                         } else if (strcmp(name, RODATA_SEC) == 0) {
2488                                 obj->efile.rodata = data;
2489                                 obj->efile.rodata_shndx = idx;
2490                         } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
2491                                 obj->efile.st_ops_data = data;
2492                                 obj->efile.st_ops_shndx = idx;
2493                         } else {
2494                                 pr_debug("skip section(%d) %s\n", idx, name);
2495                         }
2496                 } else if (sh.sh_type == SHT_REL) {
2497                         int nr_sects = obj->efile.nr_reloc_sects;
2498                         void *sects = obj->efile.reloc_sects;
2499                         int sec = sh.sh_info; /* points to other section */
2500
2501                         /* Only do relo for section with exec instructions */
2502                         if (!section_have_execinstr(obj, sec) &&
2503                             strcmp(name, ".rel" STRUCT_OPS_SEC)) {
2504                                 pr_debug("skip relo %s(%d) for section(%d)\n",
2505                                          name, idx, sec);
2506                                 continue;
2507                         }
2508
2509                         sects = reallocarray(sects, nr_sects + 1,
2510                                              sizeof(*obj->efile.reloc_sects));
2511                         if (!sects) {
2512                                 pr_warn("reloc_sects realloc failed\n");
2513                                 return -ENOMEM;
2514                         }
2515
2516                         obj->efile.reloc_sects = sects;
2517                         obj->efile.nr_reloc_sects++;
2518
2519                         obj->efile.reloc_sects[nr_sects].shdr = sh;
2520                         obj->efile.reloc_sects[nr_sects].data = data;
2521                 } else if (sh.sh_type == SHT_NOBITS &&
2522                            strcmp(name, BSS_SEC) == 0) {
2523                         obj->efile.bss = data;
2524                         obj->efile.bss_shndx = idx;
2525                 } else {
2526                         pr_debug("skip section(%d) %s\n", idx, name);
2527                 }
2528         }
2529
2530         if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2531                 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2532                 return -LIBBPF_ERRNO__FORMAT;
2533         }
2534         return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2535 }
2536
2537 static bool sym_is_extern(const GElf_Sym *sym)
2538 {
2539         int bind = GELF_ST_BIND(sym->st_info);
2540         /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2541         return sym->st_shndx == SHN_UNDEF &&
2542                (bind == STB_GLOBAL || bind == STB_WEAK) &&
2543                GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2544 }
2545
2546 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2547 {
2548         const struct btf_type *t;
2549         const char *var_name;
2550         int i, n;
2551
2552         if (!btf)
2553                 return -ESRCH;
2554
2555         n = btf__get_nr_types(btf);
2556         for (i = 1; i <= n; i++) {
2557                 t = btf__type_by_id(btf, i);
2558
2559                 if (!btf_is_var(t))
2560                         continue;
2561
2562                 var_name = btf__name_by_offset(btf, t->name_off);
2563                 if (strcmp(var_name, ext_name))
2564                         continue;
2565
2566                 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2567                         return -EINVAL;
2568
2569                 return i;
2570         }
2571
2572         return -ENOENT;
2573 }
2574
2575 static enum extern_type find_extern_type(const struct btf *btf, int id,
2576                                          bool *is_signed)
2577 {
2578         const struct btf_type *t;
2579         const char *name;
2580
2581         t = skip_mods_and_typedefs(btf, id, NULL);
2582         name = btf__name_by_offset(btf, t->name_off);
2583
2584         if (is_signed)
2585                 *is_signed = false;
2586         switch (btf_kind(t)) {
2587         case BTF_KIND_INT: {
2588                 int enc = btf_int_encoding(t);
2589
2590                 if (enc & BTF_INT_BOOL)
2591                         return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2592                 if (is_signed)
2593                         *is_signed = enc & BTF_INT_SIGNED;
2594                 if (t->size == 1)
2595                         return EXT_CHAR;
2596                 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2597                         return EXT_UNKNOWN;
2598                 return EXT_INT;
2599         }
2600         case BTF_KIND_ENUM:
2601                 if (t->size != 4)
2602                         return EXT_UNKNOWN;
2603                 if (strcmp(name, "libbpf_tristate"))
2604                         return EXT_UNKNOWN;
2605                 return EXT_TRISTATE;
2606         case BTF_KIND_ARRAY:
2607                 if (btf_array(t)->nelems == 0)
2608                         return EXT_UNKNOWN;
2609                 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2610                         return EXT_UNKNOWN;
2611                 return EXT_CHAR_ARR;
2612         default:
2613                 return EXT_UNKNOWN;
2614         }
2615 }
2616
2617 static int cmp_externs(const void *_a, const void *_b)
2618 {
2619         const struct extern_desc *a = _a;
2620         const struct extern_desc *b = _b;
2621
2622         /* descending order by alignment requirements */
2623         if (a->align != b->align)
2624                 return a->align > b->align ? -1 : 1;
2625         /* ascending order by size, within same alignment class */
2626         if (a->sz != b->sz)
2627                 return a->sz < b->sz ? -1 : 1;
2628         /* resolve ties by name */
2629         return strcmp(a->name, b->name);
2630 }
2631
2632 static int bpf_object__collect_externs(struct bpf_object *obj)
2633 {
2634         const struct btf_type *t;
2635         struct extern_desc *ext;
2636         int i, n, off, btf_id;
2637         struct btf_type *sec;
2638         const char *ext_name;
2639         Elf_Scn *scn;
2640         GElf_Shdr sh;
2641
2642         if (!obj->efile.symbols)
2643                 return 0;
2644
2645         scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2646         if (!scn)
2647                 return -LIBBPF_ERRNO__FORMAT;
2648         if (gelf_getshdr(scn, &sh) != &sh)
2649                 return -LIBBPF_ERRNO__FORMAT;
2650         n = sh.sh_size / sh.sh_entsize;
2651
2652         pr_debug("looking for externs among %d symbols...\n", n);
2653         for (i = 0; i < n; i++) {
2654                 GElf_Sym sym;
2655
2656                 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2657                         return -LIBBPF_ERRNO__FORMAT;
2658                 if (!sym_is_extern(&sym))
2659                         continue;
2660                 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2661                                       sym.st_name);
2662                 if (!ext_name || !ext_name[0])
2663                         continue;
2664
2665                 ext = obj->externs;
2666                 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2667                 if (!ext)
2668                         return -ENOMEM;
2669                 obj->externs = ext;
2670                 ext = &ext[obj->nr_extern];
2671                 memset(ext, 0, sizeof(*ext));
2672                 obj->nr_extern++;
2673
2674                 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2675                 if (ext->btf_id <= 0) {
2676                         pr_warn("failed to find BTF for extern '%s': %d\n",
2677                                 ext_name, ext->btf_id);
2678                         return ext->btf_id;
2679                 }
2680                 t = btf__type_by_id(obj->btf, ext->btf_id);
2681                 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2682                 ext->sym_idx = i;
2683                 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2684                 ext->sz = btf__resolve_size(obj->btf, t->type);
2685                 if (ext->sz <= 0) {
2686                         pr_warn("failed to resolve size of extern '%s': %d\n",
2687                                 ext_name, ext->sz);
2688                         return ext->sz;
2689                 }
2690                 ext->align = btf__align_of(obj->btf, t->type);
2691                 if (ext->align <= 0) {
2692                         pr_warn("failed to determine alignment of extern '%s': %d\n",
2693                                 ext_name, ext->align);
2694                         return -EINVAL;
2695                 }
2696                 ext->type = find_extern_type(obj->btf, t->type,
2697                                              &ext->is_signed);
2698                 if (ext->type == EXT_UNKNOWN) {
2699                         pr_warn("extern '%s' type is unsupported\n", ext_name);
2700                         return -ENOTSUP;
2701                 }
2702         }
2703         pr_debug("collected %d externs total\n", obj->nr_extern);
2704
2705         if (!obj->nr_extern)
2706                 return 0;
2707
2708         /* sort externs by (alignment, size, name) and calculate their offsets
2709          * within a map */
2710         qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2711         off = 0;
2712         for (i = 0; i < obj->nr_extern; i++) {
2713                 ext = &obj->externs[i];
2714                 ext->data_off = roundup(off, ext->align);
2715                 off = ext->data_off + ext->sz;
2716                 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2717                          i, ext->sym_idx, ext->data_off, ext->name);
2718         }
2719
2720         btf_id = btf__find_by_name(obj->btf, KCONFIG_SEC);
2721         if (btf_id <= 0) {
2722                 pr_warn("no BTF info found for '%s' datasec\n", KCONFIG_SEC);
2723                 return -ESRCH;
2724         }
2725
2726         sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2727         sec->size = off;
2728         n = btf_vlen(sec);
2729         for (i = 0; i < n; i++) {
2730                 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2731
2732                 t = btf__type_by_id(obj->btf, vs->type);
2733                 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2734                 ext = find_extern_by_name(obj, ext_name);
2735                 if (!ext) {
2736                         pr_warn("failed to find extern definition for BTF var '%s'\n",
2737                                 ext_name);
2738                         return -ESRCH;
2739                 }
2740                 vs->offset = ext->data_off;
2741                 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2742         }
2743
2744         return 0;
2745 }
2746
2747 static struct bpf_program *
2748 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2749 {
2750         struct bpf_program *prog;
2751         size_t i;
2752
2753         for (i = 0; i < obj->nr_programs; i++) {
2754                 prog = &obj->programs[i];
2755                 if (prog->idx == idx)
2756                         return prog;
2757         }
2758         return NULL;
2759 }
2760
2761 struct bpf_program *
2762 bpf_object__find_program_by_title(const struct bpf_object *obj,
2763                                   const char *title)
2764 {
2765         struct bpf_program *pos;
2766
2767         bpf_object__for_each_program(pos, obj) {
2768                 if (pos->section_name && !strcmp(pos->section_name, title))
2769                         return pos;
2770         }
2771         return NULL;
2772 }
2773
2774 struct bpf_program *
2775 bpf_object__find_program_by_name(const struct bpf_object *obj,
2776                                  const char *name)
2777 {
2778         struct bpf_program *prog;
2779
2780         bpf_object__for_each_program(prog, obj) {
2781                 if (!strcmp(prog->name, name))
2782                         return prog;
2783         }
2784         return NULL;
2785 }
2786
2787 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2788                                       int shndx)
2789 {
2790         return shndx == obj->efile.data_shndx ||
2791                shndx == obj->efile.bss_shndx ||
2792                shndx == obj->efile.rodata_shndx;
2793 }
2794
2795 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2796                                       int shndx)
2797 {
2798         return shndx == obj->efile.maps_shndx ||
2799                shndx == obj->efile.btf_maps_shndx;
2800 }
2801
2802 static enum libbpf_map_type
2803 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2804 {
2805         if (shndx == obj->efile.data_shndx)
2806                 return LIBBPF_MAP_DATA;
2807         else if (shndx == obj->efile.bss_shndx)
2808                 return LIBBPF_MAP_BSS;
2809         else if (shndx == obj->efile.rodata_shndx)
2810                 return LIBBPF_MAP_RODATA;
2811         else if (shndx == obj->efile.symbols_shndx)
2812                 return LIBBPF_MAP_KCONFIG;
2813         else
2814                 return LIBBPF_MAP_UNSPEC;
2815 }
2816
2817 static int bpf_program__record_reloc(struct bpf_program *prog,
2818                                      struct reloc_desc *reloc_desc,
2819                                      __u32 insn_idx, const char *name,
2820                                      const GElf_Sym *sym, const GElf_Rel *rel)
2821 {
2822         struct bpf_insn *insn = &prog->insns[insn_idx];
2823         size_t map_idx, nr_maps = prog->obj->nr_maps;
2824         struct bpf_object *obj = prog->obj;
2825         __u32 shdr_idx = sym->st_shndx;
2826         enum libbpf_map_type type;
2827         struct bpf_map *map;
2828
2829         /* sub-program call relocation */
2830         if (insn->code == (BPF_JMP | BPF_CALL)) {
2831                 if (insn->src_reg != BPF_PSEUDO_CALL) {
2832                         pr_warn("incorrect bpf_call opcode\n");
2833                         return -LIBBPF_ERRNO__RELOC;
2834                 }
2835                 /* text_shndx can be 0, if no default "main" program exists */
2836                 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2837                         pr_warn("bad call relo against section %u\n", shdr_idx);
2838                         return -LIBBPF_ERRNO__RELOC;
2839                 }
2840                 if (sym->st_value % 8) {
2841                         pr_warn("bad call relo offset: %zu\n",
2842                                 (size_t)sym->st_value);
2843                         return -LIBBPF_ERRNO__RELOC;
2844                 }
2845                 reloc_desc->type = RELO_CALL;
2846                 reloc_desc->insn_idx = insn_idx;
2847                 reloc_desc->sym_off = sym->st_value;
2848                 obj->has_pseudo_calls = true;
2849                 return 0;
2850         }
2851
2852         if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2853                 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2854                         insn_idx, insn->code);
2855                 return -LIBBPF_ERRNO__RELOC;
2856         }
2857
2858         if (sym_is_extern(sym)) {
2859                 int sym_idx = GELF_R_SYM(rel->r_info);
2860                 int i, n = obj->nr_extern;
2861                 struct extern_desc *ext;
2862
2863                 for (i = 0; i < n; i++) {
2864                         ext = &obj->externs[i];
2865                         if (ext->sym_idx == sym_idx)
2866                                 break;
2867                 }
2868                 if (i >= n) {
2869                         pr_warn("extern relo failed to find extern for sym %d\n",
2870                                 sym_idx);
2871                         return -LIBBPF_ERRNO__RELOC;
2872                 }
2873                 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2874                          i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
2875                 reloc_desc->type = RELO_EXTERN;
2876                 reloc_desc->insn_idx = insn_idx;
2877                 reloc_desc->sym_off = ext->data_off;
2878                 return 0;
2879         }
2880
2881         if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
2882                 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2883                         name, shdr_idx);
2884                 return -LIBBPF_ERRNO__RELOC;
2885         }
2886
2887         type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
2888
2889         /* generic map reference relocation */
2890         if (type == LIBBPF_MAP_UNSPEC) {
2891                 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
2892                         pr_warn("bad map relo against section %u\n",
2893                                 shdr_idx);
2894                         return -LIBBPF_ERRNO__RELOC;
2895                 }
2896                 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2897                         map = &obj->maps[map_idx];
2898                         if (map->libbpf_type != type ||
2899                             map->sec_idx != sym->st_shndx ||
2900                             map->sec_offset != sym->st_value)
2901                                 continue;
2902                         pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2903                                  map_idx, map->name, map->sec_idx,
2904                                  map->sec_offset, insn_idx);
2905                         break;
2906                 }
2907                 if (map_idx >= nr_maps) {
2908                         pr_warn("map relo failed to find map for sec %u, off %zu\n",
2909                                 shdr_idx, (size_t)sym->st_value);
2910                         return -LIBBPF_ERRNO__RELOC;
2911                 }
2912                 reloc_desc->type = RELO_LD64;
2913                 reloc_desc->insn_idx = insn_idx;
2914                 reloc_desc->map_idx = map_idx;
2915                 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
2916                 return 0;
2917         }
2918
2919         /* global data map relocation */
2920         if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
2921                 pr_warn("bad data relo against section %u\n", shdr_idx);
2922                 return -LIBBPF_ERRNO__RELOC;
2923         }
2924         for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2925                 map = &obj->maps[map_idx];
2926                 if (map->libbpf_type != type)
2927                         continue;
2928                 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2929                          map_idx, map->name, map->sec_idx, map->sec_offset,
2930                          insn_idx);
2931                 break;
2932         }
2933         if (map_idx >= nr_maps) {
2934                 pr_warn("data relo failed to find map for sec %u\n",
2935                         shdr_idx);
2936                 return -LIBBPF_ERRNO__RELOC;
2937         }
2938
2939         reloc_desc->type = RELO_DATA;
2940         reloc_desc->insn_idx = insn_idx;
2941         reloc_desc->map_idx = map_idx;
2942         reloc_desc->sym_off = sym->st_value;
2943         return 0;
2944 }
2945
2946 static int
2947 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
2948                            Elf_Data *data, struct bpf_object *obj)
2949 {
2950         Elf_Data *symbols = obj->efile.symbols;
2951         int err, i, nrels;
2952
2953         pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
2954         nrels = shdr->sh_size / shdr->sh_entsize;
2955
2956         prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
2957         if (!prog->reloc_desc) {
2958                 pr_warn("failed to alloc memory in relocation\n");
2959                 return -ENOMEM;
2960         }
2961         prog->nr_reloc = nrels;
2962
2963         for (i = 0; i < nrels; i++) {
2964                 const char *name;
2965                 __u32 insn_idx;
2966                 GElf_Sym sym;
2967                 GElf_Rel rel;
2968
2969                 if (!gelf_getrel(data, i, &rel)) {
2970                         pr_warn("relocation: failed to get %d reloc\n", i);
2971                         return -LIBBPF_ERRNO__FORMAT;
2972                 }
2973                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
2974                         pr_warn("relocation: symbol %"PRIx64" not found\n",
2975                                 GELF_R_SYM(rel.r_info));
2976                         return -LIBBPF_ERRNO__FORMAT;
2977                 }
2978                 if (rel.r_offset % sizeof(struct bpf_insn))
2979                         return -LIBBPF_ERRNO__FORMAT;
2980
2981                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
2982                 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2983                                   sym.st_name) ? : "<?>";
2984
2985                 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
2986                          (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
2987                          (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
2988                          GELF_ST_BIND(sym.st_info), sym.st_name, name,
2989                          insn_idx);
2990
2991                 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
2992                                                 insn_idx, name, &sym, &rel);
2993                 if (err)
2994                         return err;
2995         }
2996         return 0;
2997 }
2998
2999 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3000 {
3001         struct bpf_map_def *def = &map->def;
3002         __u32 key_type_id = 0, value_type_id = 0;
3003         int ret;
3004
3005         /* if it's BTF-defined map, we don't need to search for type IDs.
3006          * For struct_ops map, it does not need btf_key_type_id and
3007          * btf_value_type_id.
3008          */
3009         if (map->sec_idx == obj->efile.btf_maps_shndx ||
3010             bpf_map__is_struct_ops(map))
3011                 return 0;
3012
3013         if (!bpf_map__is_internal(map)) {
3014                 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3015                                            def->value_size, &key_type_id,
3016                                            &value_type_id);
3017         } else {
3018                 /*
3019                  * LLVM annotates global data differently in BTF, that is,
3020                  * only as '.data', '.bss' or '.rodata'.
3021                  */
3022                 ret = btf__find_by_name(obj->btf,
3023                                 libbpf_type_to_btf_name[map->libbpf_type]);
3024         }
3025         if (ret < 0)
3026                 return ret;
3027
3028         map->btf_key_type_id = key_type_id;
3029         map->btf_value_type_id = bpf_map__is_internal(map) ?
3030                                  ret : value_type_id;
3031         return 0;
3032 }
3033
3034 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3035 {
3036         struct bpf_map_info info = {};
3037         __u32 len = sizeof(info);
3038         int new_fd, err;
3039         char *new_name;
3040
3041         err = bpf_obj_get_info_by_fd(fd, &info, &len);
3042         if (err)
3043                 return err;
3044
3045         new_name = strdup(info.name);
3046         if (!new_name)
3047                 return -errno;
3048
3049         new_fd = open("/", O_RDONLY | O_CLOEXEC);
3050         if (new_fd < 0) {
3051                 err = -errno;
3052                 goto err_free_new_name;
3053         }
3054
3055         new_fd = dup3(fd, new_fd, O_CLOEXEC);
3056         if (new_fd < 0) {
3057                 err = -errno;
3058                 goto err_close_new_fd;
3059         }
3060
3061         err = zclose(map->fd);
3062         if (err) {
3063                 err = -errno;
3064                 goto err_close_new_fd;
3065         }
3066         free(map->name);
3067
3068         map->fd = new_fd;
3069         map->name = new_name;
3070         map->def.type = info.type;
3071         map->def.key_size = info.key_size;
3072         map->def.value_size = info.value_size;
3073         map->def.max_entries = info.max_entries;
3074         map->def.map_flags = info.map_flags;
3075         map->btf_key_type_id = info.btf_key_type_id;
3076         map->btf_value_type_id = info.btf_value_type_id;
3077         map->reused = true;
3078
3079         return 0;
3080
3081 err_close_new_fd:
3082         close(new_fd);
3083 err_free_new_name:
3084         free(new_name);
3085         return err;
3086 }
3087
3088 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
3089 {
3090         if (!map || !max_entries)
3091                 return -EINVAL;
3092
3093         /* If map already created, its attributes can't be changed. */
3094         if (map->fd >= 0)
3095                 return -EBUSY;
3096
3097         map->def.max_entries = max_entries;
3098
3099         return 0;
3100 }
3101
3102 static int
3103 bpf_object__probe_name(struct bpf_object *obj)
3104 {
3105         struct bpf_load_program_attr attr;
3106         char *cp, errmsg[STRERR_BUFSIZE];
3107         struct bpf_insn insns[] = {
3108                 BPF_MOV64_IMM(BPF_REG_0, 0),
3109                 BPF_EXIT_INSN(),
3110         };
3111         int ret;
3112
3113         /* make sure basic loading works */
3114
3115         memset(&attr, 0, sizeof(attr));
3116         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3117         attr.insns = insns;
3118         attr.insns_cnt = ARRAY_SIZE(insns);
3119         attr.license = "GPL";
3120
3121         ret = bpf_load_program_xattr(&attr, NULL, 0);
3122         if (ret < 0) {
3123                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3124                 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
3125                         __func__, cp, errno);
3126                 return -errno;
3127         }
3128         close(ret);
3129
3130         /* now try the same program, but with the name */
3131
3132         attr.name = "test";
3133         ret = bpf_load_program_xattr(&attr, NULL, 0);
3134         if (ret >= 0) {
3135                 obj->caps.name = 1;
3136                 close(ret);
3137         }
3138
3139         return 0;
3140 }
3141
3142 static int
3143 bpf_object__probe_global_data(struct bpf_object *obj)
3144 {
3145         struct bpf_load_program_attr prg_attr;
3146         struct bpf_create_map_attr map_attr;
3147         char *cp, errmsg[STRERR_BUFSIZE];
3148         struct bpf_insn insns[] = {
3149                 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
3150                 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
3151                 BPF_MOV64_IMM(BPF_REG_0, 0),
3152                 BPF_EXIT_INSN(),
3153         };
3154         int ret, map;
3155
3156         memset(&map_attr, 0, sizeof(map_attr));
3157         map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3158         map_attr.key_size = sizeof(int);
3159         map_attr.value_size = 32;
3160         map_attr.max_entries = 1;
3161
3162         map = bpf_create_map_xattr(&map_attr);
3163         if (map < 0) {
3164                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3165                 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3166                         __func__, cp, errno);
3167                 return -errno;
3168         }
3169
3170         insns[0].imm = map;
3171
3172         memset(&prg_attr, 0, sizeof(prg_attr));
3173         prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3174         prg_attr.insns = insns;
3175         prg_attr.insns_cnt = ARRAY_SIZE(insns);
3176         prg_attr.license = "GPL";
3177
3178         ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
3179         if (ret >= 0) {
3180                 obj->caps.global_data = 1;
3181                 close(ret);
3182         }
3183
3184         close(map);
3185         return 0;
3186 }
3187
3188 static int bpf_object__probe_btf_func(struct bpf_object *obj)
3189 {
3190         static const char strs[] = "\0int\0x\0a";
3191         /* void x(int a) {} */
3192         __u32 types[] = {
3193                 /* int */
3194                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
3195                 /* FUNC_PROTO */                                /* [2] */
3196                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3197                 BTF_PARAM_ENC(7, 1),
3198                 /* FUNC x */                                    /* [3] */
3199                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
3200         };
3201         int btf_fd;
3202
3203         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3204                                       strs, sizeof(strs));
3205         if (btf_fd >= 0) {
3206                 obj->caps.btf_func = 1;
3207                 close(btf_fd);
3208                 return 1;
3209         }
3210
3211         return 0;
3212 }
3213
3214 static int bpf_object__probe_btf_func_global(struct bpf_object *obj)
3215 {
3216         static const char strs[] = "\0int\0x\0a";
3217         /* static void x(int a) {} */
3218         __u32 types[] = {
3219                 /* int */
3220                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
3221                 /* FUNC_PROTO */                                /* [2] */
3222                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3223                 BTF_PARAM_ENC(7, 1),
3224                 /* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
3225                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
3226         };
3227         int btf_fd;
3228
3229         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3230                                       strs, sizeof(strs));
3231         if (btf_fd >= 0) {
3232                 obj->caps.btf_func_global = 1;
3233                 close(btf_fd);
3234                 return 1;
3235         }
3236
3237         return 0;
3238 }
3239
3240 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
3241 {
3242         static const char strs[] = "\0x\0.data";
3243         /* static int a; */
3244         __u32 types[] = {
3245                 /* int */
3246                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
3247                 /* VAR x */                                     /* [2] */
3248                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
3249                 BTF_VAR_STATIC,
3250                 /* DATASEC val */                               /* [3] */
3251                 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
3252                 BTF_VAR_SECINFO_ENC(2, 0, 4),
3253         };
3254         int btf_fd;
3255
3256         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3257                                       strs, sizeof(strs));
3258         if (btf_fd >= 0) {
3259                 obj->caps.btf_datasec = 1;
3260                 close(btf_fd);
3261                 return 1;
3262         }
3263
3264         return 0;
3265 }
3266
3267 static int bpf_object__probe_array_mmap(struct bpf_object *obj)
3268 {
3269         struct bpf_create_map_attr attr = {
3270                 .map_type = BPF_MAP_TYPE_ARRAY,
3271                 .map_flags = BPF_F_MMAPABLE,
3272                 .key_size = sizeof(int),
3273                 .value_size = sizeof(int),
3274                 .max_entries = 1,
3275         };
3276         int fd;
3277
3278         fd = bpf_create_map_xattr(&attr);
3279         if (fd >= 0) {
3280                 obj->caps.array_mmap = 1;
3281                 close(fd);
3282                 return 1;
3283         }
3284
3285         return 0;
3286 }
3287
3288 static int
3289 bpf_object__probe_caps(struct bpf_object *obj)
3290 {
3291         int (*probe_fn[])(struct bpf_object *obj) = {
3292                 bpf_object__probe_name,
3293                 bpf_object__probe_global_data,
3294                 bpf_object__probe_btf_func,
3295                 bpf_object__probe_btf_func_global,
3296                 bpf_object__probe_btf_datasec,
3297                 bpf_object__probe_array_mmap,
3298         };
3299         int i, ret;
3300
3301         for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
3302                 ret = probe_fn[i](obj);
3303                 if (ret < 0)
3304                         pr_debug("Probe #%d failed with %d.\n", i, ret);
3305         }
3306
3307         return 0;
3308 }
3309
3310 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
3311 {
3312         struct bpf_map_info map_info = {};
3313         char msg[STRERR_BUFSIZE];
3314         __u32 map_info_len;
3315
3316         map_info_len = sizeof(map_info);
3317
3318         if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
3319                 pr_warn("failed to get map info for map FD %d: %s\n",
3320                         map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
3321                 return false;
3322         }
3323
3324         return (map_info.type == map->def.type &&
3325                 map_info.key_size == map->def.key_size &&
3326                 map_info.value_size == map->def.value_size &&
3327                 map_info.max_entries == map->def.max_entries &&
3328                 map_info.map_flags == map->def.map_flags);
3329 }
3330
3331 static int
3332 bpf_object__reuse_map(struct bpf_map *map)
3333 {
3334         char *cp, errmsg[STRERR_BUFSIZE];
3335         int err, pin_fd;
3336
3337         pin_fd = bpf_obj_get(map->pin_path);
3338         if (pin_fd < 0) {
3339                 err = -errno;
3340                 if (err == -ENOENT) {
3341                         pr_debug("found no pinned map to reuse at '%s'\n",
3342                                  map->pin_path);
3343                         return 0;
3344                 }
3345
3346                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3347                 pr_warn("couldn't retrieve pinned map '%s': %s\n",
3348                         map->pin_path, cp);
3349                 return err;
3350         }
3351
3352         if (!map_is_reuse_compat(map, pin_fd)) {
3353                 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
3354                         map->pin_path);
3355                 close(pin_fd);
3356                 return -EINVAL;
3357         }
3358
3359         err = bpf_map__reuse_fd(map, pin_fd);
3360         if (err) {
3361                 close(pin_fd);
3362                 return err;
3363         }
3364         map->pinned = true;
3365         pr_debug("reused pinned map at '%s'\n", map->pin_path);
3366
3367         return 0;
3368 }
3369
3370 static int
3371 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
3372 {
3373         enum libbpf_map_type map_type = map->libbpf_type;
3374         char *cp, errmsg[STRERR_BUFSIZE];
3375         int err, zero = 0;
3376
3377         /* kernel already zero-initializes .bss map. */
3378         if (map_type == LIBBPF_MAP_BSS)
3379                 return 0;
3380
3381         err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
3382         if (err) {
3383                 err = -errno;
3384                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3385                 pr_warn("Error setting initial map(%s) contents: %s\n",
3386                         map->name, cp);
3387                 return err;
3388         }
3389
3390         /* Freeze .rodata and .kconfig map as read-only from syscall side. */
3391         if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
3392                 err = bpf_map_freeze(map->fd);
3393                 if (err) {
3394                         err = -errno;
3395                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3396                         pr_warn("Error freezing map(%s) as read-only: %s\n",
3397                                 map->name, cp);
3398                         return err;
3399                 }
3400         }
3401         return 0;
3402 }
3403
3404 static int
3405 bpf_object__create_maps(struct bpf_object *obj)
3406 {
3407         struct bpf_create_map_attr create_attr = {};
3408         int nr_cpus = 0;
3409         unsigned int i;
3410         int err;
3411
3412         for (i = 0; i < obj->nr_maps; i++) {
3413                 struct bpf_map *map = &obj->maps[i];
3414                 struct bpf_map_def *def = &map->def;
3415                 char *cp, errmsg[STRERR_BUFSIZE];
3416                 int *pfd = &map->fd;
3417
3418                 if (map->pin_path) {
3419                         err = bpf_object__reuse_map(map);
3420                         if (err) {
3421                                 pr_warn("error reusing pinned map %s\n",
3422                                         map->name);
3423                                 return err;
3424                         }
3425                 }
3426
3427                 if (map->fd >= 0) {
3428                         pr_debug("skip map create (preset) %s: fd=%d\n",
3429                                  map->name, map->fd);
3430                         continue;
3431                 }
3432
3433                 if (obj->caps.name)
3434                         create_attr.name = map->name;
3435                 create_attr.map_ifindex = map->map_ifindex;
3436                 create_attr.map_type = def->type;
3437                 create_attr.map_flags = def->map_flags;
3438                 create_attr.key_size = def->key_size;
3439                 create_attr.value_size = def->value_size;
3440                 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
3441                     !def->max_entries) {
3442                         if (!nr_cpus)
3443                                 nr_cpus = libbpf_num_possible_cpus();
3444                         if (nr_cpus < 0) {
3445                                 pr_warn("failed to determine number of system CPUs: %d\n",
3446                                         nr_cpus);
3447                                 err = nr_cpus;
3448                                 goto err_out;
3449                         }
3450                         pr_debug("map '%s': setting size to %d\n",
3451                                  map->name, nr_cpus);
3452                         create_attr.max_entries = nr_cpus;
3453                 } else {
3454                         create_attr.max_entries = def->max_entries;
3455                 }
3456                 create_attr.btf_fd = 0;
3457                 create_attr.btf_key_type_id = 0;
3458                 create_attr.btf_value_type_id = 0;
3459                 if (bpf_map_type__is_map_in_map(def->type) &&
3460                     map->inner_map_fd >= 0)
3461                         create_attr.inner_map_fd = map->inner_map_fd;
3462                 if (bpf_map__is_struct_ops(map))
3463                         create_attr.btf_vmlinux_value_type_id =
3464                                 map->btf_vmlinux_value_type_id;
3465
3466                 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
3467                         create_attr.btf_fd = btf__fd(obj->btf);
3468                         create_attr.btf_key_type_id = map->btf_key_type_id;
3469                         create_attr.btf_value_type_id = map->btf_value_type_id;
3470                 }
3471
3472                 *pfd = bpf_create_map_xattr(&create_attr);
3473                 if (*pfd < 0 && (create_attr.btf_key_type_id ||
3474                                  create_attr.btf_value_type_id)) {
3475                         err = -errno;
3476                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3477                         pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3478                                 map->name, cp, err);
3479                         create_attr.btf_fd = 0;
3480                         create_attr.btf_key_type_id = 0;
3481                         create_attr.btf_value_type_id = 0;
3482                         map->btf_key_type_id = 0;
3483                         map->btf_value_type_id = 0;
3484                         *pfd = bpf_create_map_xattr(&create_attr);
3485                 }
3486
3487                 if (*pfd < 0) {
3488                         size_t j;
3489
3490                         err = -errno;
3491 err_out:
3492                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3493                         pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3494                                 map->name, cp, err);
3495                         pr_perm_msg(err);
3496                         for (j = 0; j < i; j++)
3497                                 zclose(obj->maps[j].fd);
3498                         return err;
3499                 }
3500
3501                 if (bpf_map__is_internal(map)) {
3502                         err = bpf_object__populate_internal_map(obj, map);
3503                         if (err < 0) {
3504                                 zclose(*pfd);
3505                                 goto err_out;
3506                         }
3507                 }
3508
3509                 if (map->pin_path && !map->pinned) {
3510                         err = bpf_map__pin(map, NULL);
3511                         if (err) {
3512                                 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3513                                         map->name, map->pin_path);
3514                                 return err;
3515                         }
3516                 }
3517
3518                 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
3519         }
3520
3521         return 0;
3522 }
3523
3524 static int
3525 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3526                         void *btf_prog_info, const char *info_name)
3527 {
3528         if (err != -ENOENT) {
3529                 pr_warn("Error in loading %s for sec %s.\n",
3530                         info_name, prog->section_name);
3531                 return err;
3532         }
3533
3534         /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3535
3536         if (btf_prog_info) {
3537                 /*
3538                  * Some info has already been found but has problem
3539                  * in the last btf_ext reloc. Must have to error out.
3540                  */
3541                 pr_warn("Error in relocating %s for sec %s.\n",
3542                         info_name, prog->section_name);
3543                 return err;
3544         }
3545
3546         /* Have problem loading the very first info. Ignore the rest. */
3547         pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3548                 info_name, prog->section_name, info_name);
3549         return 0;
3550 }
3551
3552 static int
3553 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3554                           const char *section_name,  __u32 insn_offset)
3555 {
3556         int err;
3557
3558         if (!insn_offset || prog->func_info) {
3559                 /*
3560                  * !insn_offset => main program
3561                  *
3562                  * For sub prog, the main program's func_info has to
3563                  * be loaded first (i.e. prog->func_info != NULL)
3564                  */
3565                 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3566                                                section_name, insn_offset,
3567                                                &prog->func_info,
3568                                                &prog->func_info_cnt);
3569                 if (err)
3570                         return check_btf_ext_reloc_err(prog, err,
3571                                                        prog->func_info,
3572                                                        "bpf_func_info");
3573
3574                 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3575         }
3576
3577         if (!insn_offset || prog->line_info) {
3578                 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3579                                                section_name, insn_offset,
3580                                                &prog->line_info,
3581                                                &prog->line_info_cnt);
3582                 if (err)
3583                         return check_btf_ext_reloc_err(prog, err,
3584                                                        prog->line_info,
3585                                                        "bpf_line_info");
3586
3587                 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3588         }
3589
3590         return 0;
3591 }
3592
3593 #define BPF_CORE_SPEC_MAX_LEN 64
3594
3595 /* represents BPF CO-RE field or array element accessor */
3596 struct bpf_core_accessor {
3597         __u32 type_id;          /* struct/union type or array element type */
3598         __u32 idx;              /* field index or array index */
3599         const char *name;       /* field name or NULL for array accessor */
3600 };
3601
3602 struct bpf_core_spec {
3603         const struct btf *btf;
3604         /* high-level spec: named fields and array indices only */
3605         struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3606         /* high-level spec length */
3607         int len;
3608         /* raw, low-level spec: 1-to-1 with accessor spec string */
3609         int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3610         /* raw spec length */
3611         int raw_len;
3612         /* field bit offset represented by spec */
3613         __u32 bit_offset;
3614 };
3615
3616 static bool str_is_empty(const char *s)
3617 {
3618         return !s || !s[0];
3619 }
3620
3621 static bool is_flex_arr(const struct btf *btf,
3622                         const struct bpf_core_accessor *acc,
3623                         const struct btf_array *arr)
3624 {
3625         const struct btf_type *t;
3626
3627         /* not a flexible array, if not inside a struct or has non-zero size */
3628         if (!acc->name || arr->nelems > 0)
3629                 return false;
3630
3631         /* has to be the last member of enclosing struct */
3632         t = btf__type_by_id(btf, acc->type_id);
3633         return acc->idx == btf_vlen(t) - 1;
3634 }
3635
3636 /*
3637  * Turn bpf_field_reloc into a low- and high-level spec representation,
3638  * validating correctness along the way, as well as calculating resulting
3639  * field bit offset, specified by accessor string. Low-level spec captures
3640  * every single level of nestedness, including traversing anonymous
3641  * struct/union members. High-level one only captures semantically meaningful
3642  * "turning points": named fields and array indicies.
3643  * E.g., for this case:
3644  *
3645  *   struct sample {
3646  *       int __unimportant;
3647  *       struct {
3648  *           int __1;
3649  *           int __2;
3650  *           int a[7];
3651  *       };
3652  *   };
3653  *
3654  *   struct sample *s = ...;
3655  *
3656  *   int x = &s->a[3]; // access string = '0:1:2:3'
3657  *
3658  * Low-level spec has 1:1 mapping with each element of access string (it's
3659  * just a parsed access string representation): [0, 1, 2, 3].
3660  *
3661  * High-level spec will capture only 3 points:
3662  *   - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3663  *   - field 'a' access (corresponds to '2' in low-level spec);
3664  *   - array element #3 access (corresponds to '3' in low-level spec).
3665  *
3666  */
3667 static int bpf_core_spec_parse(const struct btf *btf,
3668                                __u32 type_id,
3669                                const char *spec_str,
3670                                struct bpf_core_spec *spec)
3671 {
3672         int access_idx, parsed_len, i;
3673         struct bpf_core_accessor *acc;
3674         const struct btf_type *t;
3675         const char *name;
3676         __u32 id;
3677         __s64 sz;
3678
3679         if (str_is_empty(spec_str) || *spec_str == ':')
3680                 return -EINVAL;
3681
3682         memset(spec, 0, sizeof(*spec));
3683         spec->btf = btf;
3684
3685         /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3686         while (*spec_str) {
3687                 if (*spec_str == ':')
3688                         ++spec_str;
3689                 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3690                         return -EINVAL;
3691                 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3692                         return -E2BIG;
3693                 spec_str += parsed_len;
3694                 spec->raw_spec[spec->raw_len++] = access_idx;
3695         }
3696
3697         if (spec->raw_len == 0)
3698                 return -EINVAL;
3699
3700         /* first spec value is always reloc type array index */
3701         t = skip_mods_and_typedefs(btf, type_id, &id);
3702         if (!t)
3703                 return -EINVAL;
3704
3705         access_idx = spec->raw_spec[0];
3706         spec->spec[0].type_id = id;
3707         spec->spec[0].idx = access_idx;
3708         spec->len++;
3709
3710         sz = btf__resolve_size(btf, id);
3711         if (sz < 0)
3712                 return sz;
3713         spec->bit_offset = access_idx * sz * 8;
3714
3715         for (i = 1; i < spec->raw_len; i++) {
3716                 t = skip_mods_and_typedefs(btf, id, &id);
3717                 if (!t)
3718                         return -EINVAL;
3719
3720                 access_idx = spec->raw_spec[i];
3721                 acc = &spec->spec[spec->len];
3722
3723                 if (btf_is_composite(t)) {
3724                         const struct btf_member *m;
3725                         __u32 bit_offset;
3726
3727                         if (access_idx >= btf_vlen(t))
3728                                 return -EINVAL;
3729
3730                         bit_offset = btf_member_bit_offset(t, access_idx);
3731                         spec->bit_offset += bit_offset;
3732
3733                         m = btf_members(t) + access_idx;
3734                         if (m->name_off) {
3735                                 name = btf__name_by_offset(btf, m->name_off);
3736                                 if (str_is_empty(name))
3737                                         return -EINVAL;
3738
3739                                 acc->type_id = id;
3740                                 acc->idx = access_idx;
3741                                 acc->name = name;
3742                                 spec->len++;
3743                         }
3744
3745                         id = m->type;
3746                 } else if (btf_is_array(t)) {
3747                         const struct btf_array *a = btf_array(t);
3748                         bool flex;
3749
3750                         t = skip_mods_and_typedefs(btf, a->type, &id);
3751                         if (!t)
3752                                 return -EINVAL;
3753
3754                         flex = is_flex_arr(btf, acc - 1, a);
3755                         if (!flex && access_idx >= a->nelems)
3756                                 return -EINVAL;
3757
3758                         spec->spec[spec->len].type_id = id;
3759                         spec->spec[spec->len].idx = access_idx;
3760                         spec->len++;
3761
3762                         sz = btf__resolve_size(btf, id);
3763                         if (sz < 0)
3764                                 return sz;
3765                         spec->bit_offset += access_idx * sz * 8;
3766                 } else {
3767                         pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3768                                 type_id, spec_str, i, id, btf_kind(t));
3769                         return -EINVAL;
3770                 }
3771         }
3772
3773         return 0;
3774 }
3775
3776 static bool bpf_core_is_flavor_sep(const char *s)
3777 {
3778         /* check X___Y name pattern, where X and Y are not underscores */
3779         return s[0] != '_' &&                                 /* X */
3780                s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
3781                s[4] != '_';                                   /* Y */
3782 }
3783
3784 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
3785  * before last triple underscore. Struct name part after last triple
3786  * underscore is ignored by BPF CO-RE relocation during relocation matching.
3787  */
3788 static size_t bpf_core_essential_name_len(const char *name)
3789 {
3790         size_t n = strlen(name);
3791         int i;
3792
3793         for (i = n - 5; i >= 0; i--) {
3794                 if (bpf_core_is_flavor_sep(name + i))
3795                         return i + 1;
3796         }
3797         return n;
3798 }
3799
3800 /* dynamically sized list of type IDs */
3801 struct ids_vec {
3802         __u32 *data;
3803         int len;
3804 };
3805
3806 static void bpf_core_free_cands(struct ids_vec *cand_ids)
3807 {
3808         free(cand_ids->data);
3809         free(cand_ids);
3810 }
3811
3812 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
3813                                            __u32 local_type_id,
3814                                            const struct btf *targ_btf)
3815 {
3816         size_t local_essent_len, targ_essent_len;
3817         const char *local_name, *targ_name;
3818         const struct btf_type *t;
3819         struct ids_vec *cand_ids;
3820         __u32 *new_ids;
3821         int i, err, n;
3822
3823         t = btf__type_by_id(local_btf, local_type_id);
3824         if (!t)
3825                 return ERR_PTR(-EINVAL);
3826
3827         local_name = btf__name_by_offset(local_btf, t->name_off);
3828         if (str_is_empty(local_name))
3829                 return ERR_PTR(-EINVAL);
3830         local_essent_len = bpf_core_essential_name_len(local_name);
3831
3832         cand_ids = calloc(1, sizeof(*cand_ids));
3833         if (!cand_ids)
3834                 return ERR_PTR(-ENOMEM);
3835
3836         n = btf__get_nr_types(targ_btf);
3837         for (i = 1; i <= n; i++) {
3838                 t = btf__type_by_id(targ_btf, i);
3839                 targ_name = btf__name_by_offset(targ_btf, t->name_off);
3840                 if (str_is_empty(targ_name))
3841                         continue;
3842
3843                 targ_essent_len = bpf_core_essential_name_len(targ_name);
3844                 if (targ_essent_len != local_essent_len)
3845                         continue;
3846
3847                 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
3848                         pr_debug("[%d] %s: found candidate [%d] %s\n",
3849                                  local_type_id, local_name, i, targ_name);
3850                         new_ids = realloc(cand_ids->data, cand_ids->len + 1);
3851                         if (!new_ids) {
3852                                 err = -ENOMEM;
3853                                 goto err_out;
3854                         }
3855                         cand_ids->data = new_ids;
3856                         cand_ids->data[cand_ids->len++] = i;
3857                 }
3858         }
3859         return cand_ids;
3860 err_out:
3861         bpf_core_free_cands(cand_ids);
3862         return ERR_PTR(err);
3863 }
3864
3865 /* Check two types for compatibility, skipping const/volatile/restrict and
3866  * typedefs, to ensure we are relocating compatible entities:
3867  *   - any two STRUCTs/UNIONs are compatible and can be mixed;
3868  *   - any two FWDs are compatible, if their names match (modulo flavor suffix);
3869  *   - any two PTRs are always compatible;
3870  *   - for ENUMs, names should be the same (ignoring flavor suffix) or at
3871  *     least one of enums should be anonymous;
3872  *   - for ENUMs, check sizes, names are ignored;
3873  *   - for INT, size and signedness are ignored;
3874  *   - for ARRAY, dimensionality is ignored, element types are checked for
3875  *     compatibility recursively;
3876  *   - everything else shouldn't be ever a target of relocation.
3877  * These rules are not set in stone and probably will be adjusted as we get
3878  * more experience with using BPF CO-RE relocations.
3879  */
3880 static int bpf_core_fields_are_compat(const struct btf *local_btf,
3881                                       __u32 local_id,
3882                                       const struct btf *targ_btf,
3883                                       __u32 targ_id)
3884 {
3885         const struct btf_type *local_type, *targ_type;
3886
3887 recur:
3888         local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
3889         targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3890         if (!local_type || !targ_type)
3891                 return -EINVAL;
3892
3893         if (btf_is_composite(local_type) && btf_is_composite(targ_type))
3894                 return 1;
3895         if (btf_kind(local_type) != btf_kind(targ_type))
3896                 return 0;
3897
3898         switch (btf_kind(local_type)) {
3899         case BTF_KIND_PTR:
3900                 return 1;
3901         case BTF_KIND_FWD:
3902         case BTF_KIND_ENUM: {
3903                 const char *local_name, *targ_name;
3904                 size_t local_len, targ_len;
3905
3906                 local_name = btf__name_by_offset(local_btf,
3907                                                  local_type->name_off);
3908                 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
3909                 local_len = bpf_core_essential_name_len(local_name);
3910                 targ_len = bpf_core_essential_name_len(targ_name);
3911                 /* one of them is anonymous or both w/ same flavor-less names */
3912                 return local_len == 0 || targ_len == 0 ||
3913                        (local_len == targ_len &&
3914                         strncmp(local_name, targ_name, local_len) == 0);
3915         }
3916         case BTF_KIND_INT:
3917                 /* just reject deprecated bitfield-like integers; all other
3918                  * integers are by default compatible between each other
3919                  */
3920                 return btf_int_offset(local_type) == 0 &&
3921                        btf_int_offset(targ_type) == 0;
3922         case BTF_KIND_ARRAY:
3923                 local_id = btf_array(local_type)->type;
3924                 targ_id = btf_array(targ_type)->type;
3925                 goto recur;
3926         default:
3927                 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3928                         btf_kind(local_type), local_id, targ_id);
3929                 return 0;
3930         }
3931 }
3932
3933 /*
3934  * Given single high-level named field accessor in local type, find
3935  * corresponding high-level accessor for a target type. Along the way,
3936  * maintain low-level spec for target as well. Also keep updating target
3937  * bit offset.
3938  *
3939  * Searching is performed through recursive exhaustive enumeration of all
3940  * fields of a struct/union. If there are any anonymous (embedded)
3941  * structs/unions, they are recursively searched as well. If field with
3942  * desired name is found, check compatibility between local and target types,
3943  * before returning result.
3944  *
3945  * 1 is returned, if field is found.
3946  * 0 is returned if no compatible field is found.
3947  * <0 is returned on error.
3948  */
3949 static int bpf_core_match_member(const struct btf *local_btf,
3950                                  const struct bpf_core_accessor *local_acc,
3951                                  const struct btf *targ_btf,
3952                                  __u32 targ_id,
3953                                  struct bpf_core_spec *spec,
3954                                  __u32 *next_targ_id)
3955 {
3956         const struct btf_type *local_type, *targ_type;
3957         const struct btf_member *local_member, *m;
3958         const char *local_name, *targ_name;
3959         __u32 local_id;
3960         int i, n, found;
3961
3962         targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3963         if (!targ_type)
3964                 return -EINVAL;
3965         if (!btf_is_composite(targ_type))
3966                 return 0;
3967
3968         local_id = local_acc->type_id;
3969         local_type = btf__type_by_id(local_btf, local_id);
3970         local_member = btf_members(local_type) + local_acc->idx;
3971         local_name = btf__name_by_offset(local_btf, local_member->name_off);
3972
3973         n = btf_vlen(targ_type);
3974         m = btf_members(targ_type);
3975         for (i = 0; i < n; i++, m++) {
3976                 __u32 bit_offset;
3977
3978                 bit_offset = btf_member_bit_offset(targ_type, i);
3979
3980                 /* too deep struct/union/array nesting */
3981                 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3982                         return -E2BIG;
3983
3984                 /* speculate this member will be the good one */
3985                 spec->bit_offset += bit_offset;
3986                 spec->raw_spec[spec->raw_len++] = i;
3987
3988                 targ_name = btf__name_by_offset(targ_btf, m->name_off);
3989                 if (str_is_empty(targ_name)) {
3990                         /* embedded struct/union, we need to go deeper */
3991                         found = bpf_core_match_member(local_btf, local_acc,
3992                                                       targ_btf, m->type,
3993                                                       spec, next_targ_id);
3994                         if (found) /* either found or error */
3995                                 return found;
3996                 } else if (strcmp(local_name, targ_name) == 0) {
3997                         /* matching named field */
3998                         struct bpf_core_accessor *targ_acc;
3999
4000                         targ_acc = &spec->spec[spec->len++];
4001                         targ_acc->type_id = targ_id;
4002                         targ_acc->idx = i;
4003                         targ_acc->name = targ_name;
4004
4005                         *next_targ_id = m->type;
4006                         found = bpf_core_fields_are_compat(local_btf,
4007                                                            local_member->type,
4008                                                            targ_btf, m->type);
4009                         if (!found)
4010                                 spec->len--; /* pop accessor */
4011                         return found;
4012                 }
4013                 /* member turned out not to be what we looked for */
4014                 spec->bit_offset -= bit_offset;
4015                 spec->raw_len--;
4016         }
4017
4018         return 0;
4019 }
4020
4021 /*
4022  * Try to match local spec to a target type and, if successful, produce full
4023  * target spec (high-level, low-level + bit offset).
4024  */
4025 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
4026                                const struct btf *targ_btf, __u32 targ_id,
4027                                struct bpf_core_spec *targ_spec)
4028 {
4029         const struct btf_type *targ_type;
4030         const struct bpf_core_accessor *local_acc;
4031         struct bpf_core_accessor *targ_acc;
4032         int i, sz, matched;
4033
4034         memset(targ_spec, 0, sizeof(*targ_spec));
4035         targ_spec->btf = targ_btf;
4036
4037         local_acc = &local_spec->spec[0];
4038         targ_acc = &targ_spec->spec[0];
4039
4040         for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
4041                 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
4042                                                    &targ_id);
4043                 if (!targ_type)
4044                         return -EINVAL;
4045
4046                 if (local_acc->name) {
4047                         matched = bpf_core_match_member(local_spec->btf,
4048                                                         local_acc,
4049                                                         targ_btf, targ_id,
4050                                                         targ_spec, &targ_id);
4051                         if (matched <= 0)
4052                                 return matched;
4053                 } else {
4054                         /* for i=0, targ_id is already treated as array element
4055                          * type (because it's the original struct), for others
4056                          * we should find array element type first
4057                          */
4058                         if (i > 0) {
4059                                 const struct btf_array *a;
4060                                 bool flex;
4061
4062                                 if (!btf_is_array(targ_type))
4063                                         return 0;
4064
4065                                 a = btf_array(targ_type);
4066                                 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
4067                                 if (!flex && local_acc->idx >= a->nelems)
4068                                         return 0;
4069                                 if (!skip_mods_and_typedefs(targ_btf, a->type,
4070                                                             &targ_id))
4071                                         return -EINVAL;
4072                         }
4073
4074                         /* too deep struct/union/array nesting */
4075                         if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4076                                 return -E2BIG;
4077
4078                         targ_acc->type_id = targ_id;
4079                         targ_acc->idx = local_acc->idx;
4080                         targ_acc->name = NULL;
4081                         targ_spec->len++;
4082                         targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
4083                         targ_spec->raw_len++;
4084
4085                         sz = btf__resolve_size(targ_btf, targ_id);
4086                         if (sz < 0)
4087                                 return sz;
4088                         targ_spec->bit_offset += local_acc->idx * sz * 8;
4089                 }
4090         }
4091
4092         return 1;
4093 }
4094
4095 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
4096                                     const struct bpf_field_reloc *relo,
4097                                     const struct bpf_core_spec *spec,
4098                                     __u32 *val, bool *validate)
4099 {
4100         const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
4101         const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
4102         __u32 byte_off, byte_sz, bit_off, bit_sz;
4103         const struct btf_member *m;
4104         const struct btf_type *mt;
4105         bool bitfield;
4106         __s64 sz;
4107
4108         /* a[n] accessor needs special handling */
4109         if (!acc->name) {
4110                 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
4111                         *val = spec->bit_offset / 8;
4112                 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
4113                         sz = btf__resolve_size(spec->btf, acc->type_id);
4114                         if (sz < 0)
4115                                 return -EINVAL;
4116                         *val = sz;
4117                 } else {
4118                         pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
4119                                 bpf_program__title(prog, false),
4120                                 relo->kind, relo->insn_off / 8);
4121                         return -EINVAL;
4122                 }
4123                 if (validate)
4124                         *validate = true;
4125                 return 0;
4126         }
4127
4128         m = btf_members(t) + acc->idx;
4129         mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
4130         bit_off = spec->bit_offset;
4131         bit_sz = btf_member_bitfield_size(t, acc->idx);
4132
4133         bitfield = bit_sz > 0;
4134         if (bitfield) {
4135                 byte_sz = mt->size;
4136                 byte_off = bit_off / 8 / byte_sz * byte_sz;
4137                 /* figure out smallest int size necessary for bitfield load */
4138                 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
4139                         if (byte_sz >= 8) {
4140                                 /* bitfield can't be read with 64-bit read */
4141                                 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
4142                                         bpf_program__title(prog, false),
4143                                         relo->kind, relo->insn_off / 8);
4144                                 return -E2BIG;
4145                         }
4146                         byte_sz *= 2;
4147                         byte_off = bit_off / 8 / byte_sz * byte_sz;
4148                 }
4149         } else {
4150                 sz = btf__resolve_size(spec->btf, m->type);
4151                 if (sz < 0)
4152                         return -EINVAL;
4153                 byte_sz = sz;
4154                 byte_off = spec->bit_offset / 8;
4155                 bit_sz = byte_sz * 8;
4156         }
4157
4158         /* for bitfields, all the relocatable aspects are ambiguous and we
4159          * might disagree with compiler, so turn off validation of expected
4160          * value, except for signedness
4161          */
4162         if (validate)
4163                 *validate = !bitfield;
4164
4165         switch (relo->kind) {
4166         case BPF_FIELD_BYTE_OFFSET:
4167                 *val = byte_off;
4168                 break;
4169         case BPF_FIELD_BYTE_SIZE:
4170                 *val = byte_sz;
4171                 break;
4172         case BPF_FIELD_SIGNED:
4173                 /* enums will be assumed unsigned */
4174                 *val = btf_is_enum(mt) ||
4175                        (btf_int_encoding(mt) & BTF_INT_SIGNED);
4176                 if (validate)
4177                         *validate = true; /* signedness is never ambiguous */
4178                 break;
4179         case BPF_FIELD_LSHIFT_U64:
4180 #if __BYTE_ORDER == __LITTLE_ENDIAN
4181                 *val = 64 - (bit_off + bit_sz - byte_off  * 8);
4182 #else
4183                 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
4184 #endif
4185                 break;
4186         case BPF_FIELD_RSHIFT_U64:
4187                 *val = 64 - bit_sz;
4188                 if (validate)
4189                         *validate = true; /* right shift is never ambiguous */
4190                 break;
4191         case BPF_FIELD_EXISTS:
4192         default:
4193                 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
4194                         bpf_program__title(prog, false),
4195                         relo->kind, relo->insn_off / 8);
4196                 return -EINVAL;
4197         }
4198
4199         return 0;
4200 }
4201
4202 /*
4203  * Patch relocatable BPF instruction.
4204  *
4205  * Patched value is determined by relocation kind and target specification.
4206  * For field existence relocation target spec will be NULL if field is not
4207  * found.
4208  * Expected insn->imm value is determined using relocation kind and local
4209  * spec, and is checked before patching instruction. If actual insn->imm value
4210  * is wrong, bail out with error.
4211  *
4212  * Currently three kinds of BPF instructions are supported:
4213  * 1. rX = <imm> (assignment with immediate operand);
4214  * 2. rX += <imm> (arithmetic operations with immediate operand);
4215  */
4216 static int bpf_core_reloc_insn(struct bpf_program *prog,
4217                                const struct bpf_field_reloc *relo,
4218                                const struct bpf_core_spec *local_spec,
4219                                const struct bpf_core_spec *targ_spec)
4220 {
4221         bool failed = false, validate = true;
4222         __u32 orig_val, new_val;
4223         struct bpf_insn *insn;
4224         int insn_idx, err;
4225         __u8 class;
4226
4227         if (relo->insn_off % sizeof(struct bpf_insn))
4228                 return -EINVAL;
4229         insn_idx = relo->insn_off / sizeof(struct bpf_insn);
4230
4231         if (relo->kind == BPF_FIELD_EXISTS) {
4232                 orig_val = 1; /* can't generate EXISTS relo w/o local field */
4233                 new_val = targ_spec ? 1 : 0;
4234         } else if (!targ_spec) {
4235                 failed = true;
4236                 new_val = (__u32)-1;
4237         } else {
4238                 err = bpf_core_calc_field_relo(prog, relo, local_spec,
4239                                                &orig_val, &validate);
4240                 if (err)
4241                         return err;
4242                 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
4243                                                &new_val, NULL);
4244                 if (err)
4245                         return err;
4246         }
4247
4248         insn = &prog->insns[insn_idx];
4249         class = BPF_CLASS(insn->code);
4250
4251         switch (class) {
4252         case BPF_ALU:
4253         case BPF_ALU64:
4254                 if (BPF_SRC(insn->code) != BPF_K)
4255                         return -EINVAL;
4256                 if (!failed && validate && insn->imm != orig_val) {
4257                         pr_warn("prog '%s': unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
4258                                 bpf_program__title(prog, false), insn_idx,
4259                                 insn->imm, orig_val, new_val);
4260                         return -EINVAL;
4261                 }
4262                 orig_val = insn->imm;
4263                 insn->imm = new_val;
4264                 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
4265                          bpf_program__title(prog, false), insn_idx,
4266                          failed ? " w/ failed reloc" : "", orig_val, new_val);
4267                 break;
4268         case BPF_LDX:
4269         case BPF_ST:
4270         case BPF_STX:
4271                 if (!failed && validate && insn->off != orig_val) {
4272                         pr_warn("prog '%s': unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
4273                                 bpf_program__title(prog, false), insn_idx,
4274                                 insn->off, orig_val, new_val);
4275                         return -EINVAL;
4276                 }
4277                 if (new_val > SHRT_MAX) {
4278                         pr_warn("prog '%s': insn #%d (LD/LDX/ST/STX) value too big: %u\n",
4279                                 bpf_program__title(prog, false), insn_idx,
4280                                 new_val);
4281                         return -ERANGE;
4282                 }
4283                 orig_val = insn->off;
4284                 insn->off = new_val;
4285                 pr_debug("prog '%s': patched insn #%d (LD/LDX/ST/STX)%s off %u -> %u\n",
4286                          bpf_program__title(prog, false), insn_idx,
4287                          failed ? " w/ failed reloc" : "", orig_val, new_val);
4288                 break;
4289         default:
4290                 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
4291                         bpf_program__title(prog, false),
4292                         insn_idx, insn->code, insn->src_reg, insn->dst_reg,
4293                         insn->off, insn->imm);
4294                 return -EINVAL;
4295         }
4296
4297         return 0;
4298 }
4299
4300 static struct btf *btf_load_raw(const char *path)
4301 {
4302         struct btf *btf;
4303         size_t read_cnt;
4304         struct stat st;
4305         void *data;
4306         FILE *f;
4307
4308         if (stat(path, &st))
4309                 return ERR_PTR(-errno);
4310
4311         data = malloc(st.st_size);
4312         if (!data)
4313                 return ERR_PTR(-ENOMEM);
4314
4315         f = fopen(path, "rb");
4316         if (!f) {
4317                 btf = ERR_PTR(-errno);
4318                 goto cleanup;
4319         }
4320
4321         read_cnt = fread(data, 1, st.st_size, f);
4322         fclose(f);
4323         if (read_cnt < st.st_size) {
4324                 btf = ERR_PTR(-EBADF);
4325                 goto cleanup;
4326         }
4327
4328         btf = btf__new(data, read_cnt);
4329
4330 cleanup:
4331         free(data);
4332         return btf;
4333 }
4334
4335 /*
4336  * Probe few well-known locations for vmlinux kernel image and try to load BTF
4337  * data out of it to use for target BTF.
4338  */
4339 static struct btf *bpf_find_kernel_btf(void)
4340 {
4341         struct {
4342                 const char *path_fmt;
4343                 bool raw_btf;
4344         } locations[] = {
4345                 /* try canonical vmlinux BTF through sysfs first */
4346                 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
4347                 /* fall back to trying to find vmlinux ELF on disk otherwise */
4348                 { "/boot/vmlinux-%1$s" },
4349                 { "/lib/modules/%1$s/vmlinux-%1$s" },
4350                 { "/lib/modules/%1$s/build/vmlinux" },
4351                 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
4352                 { "/usr/lib/debug/boot/vmlinux-%1$s" },
4353                 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
4354                 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
4355         };
4356         char path[PATH_MAX + 1];
4357         struct utsname buf;
4358         struct btf *btf;
4359         int i;
4360
4361         uname(&buf);
4362
4363         for (i = 0; i < ARRAY_SIZE(locations); i++) {
4364                 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
4365
4366                 if (access(path, R_OK))
4367                         continue;
4368
4369                 if (locations[i].raw_btf)
4370                         btf = btf_load_raw(path);
4371                 else
4372                         btf = btf__parse_elf(path, NULL);
4373
4374                 pr_debug("loading kernel BTF '%s': %ld\n",
4375                          path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
4376                 if (IS_ERR(btf))
4377                         continue;
4378
4379                 return btf;
4380         }
4381
4382         pr_warn("failed to find valid kernel BTF\n");
4383         return ERR_PTR(-ESRCH);
4384 }
4385
4386 /* Output spec definition in the format:
4387  * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
4388  * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
4389  */
4390 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
4391 {
4392         const struct btf_type *t;
4393         const char *s;
4394         __u32 type_id;
4395         int i;
4396
4397         type_id = spec->spec[0].type_id;
4398         t = btf__type_by_id(spec->btf, type_id);
4399         s = btf__name_by_offset(spec->btf, t->name_off);
4400         libbpf_print(level, "[%u] %s + ", type_id, s);
4401
4402         for (i = 0; i < spec->raw_len; i++)
4403                 libbpf_print(level, "%d%s", spec->raw_spec[i],
4404                              i == spec->raw_len - 1 ? " => " : ":");
4405
4406         libbpf_print(level, "%u.%u @ &x",
4407                      spec->bit_offset / 8, spec->bit_offset % 8);
4408
4409         for (i = 0; i < spec->len; i++) {
4410                 if (spec->spec[i].name)
4411                         libbpf_print(level, ".%s", spec->spec[i].name);
4412                 else
4413                         libbpf_print(level, "[%u]", spec->spec[i].idx);
4414         }
4415
4416 }
4417
4418 static size_t bpf_core_hash_fn(const void *key, void *ctx)
4419 {
4420         return (size_t)key;
4421 }
4422
4423 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
4424 {
4425         return k1 == k2;
4426 }
4427
4428 static void *u32_as_hash_key(__u32 x)
4429 {
4430         return (void *)(uintptr_t)x;
4431 }
4432
4433 /*
4434  * CO-RE relocate single instruction.
4435  *
4436  * The outline and important points of the algorithm:
4437  * 1. For given local type, find corresponding candidate target types.
4438  *    Candidate type is a type with the same "essential" name, ignoring
4439  *    everything after last triple underscore (___). E.g., `sample`,
4440  *    `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4441  *    for each other. Names with triple underscore are referred to as
4442  *    "flavors" and are useful, among other things, to allow to
4443  *    specify/support incompatible variations of the same kernel struct, which
4444  *    might differ between different kernel versions and/or build
4445  *    configurations.
4446  *
4447  *    N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4448  *    converter, when deduplicated BTF of a kernel still contains more than
4449  *    one different types with the same name. In that case, ___2, ___3, etc
4450  *    are appended starting from second name conflict. But start flavors are
4451  *    also useful to be defined "locally", in BPF program, to extract same
4452  *    data from incompatible changes between different kernel
4453  *    versions/configurations. For instance, to handle field renames between
4454  *    kernel versions, one can use two flavors of the struct name with the
4455  *    same common name and use conditional relocations to extract that field,
4456  *    depending on target kernel version.
4457  * 2. For each candidate type, try to match local specification to this
4458  *    candidate target type. Matching involves finding corresponding
4459  *    high-level spec accessors, meaning that all named fields should match,
4460  *    as well as all array accesses should be within the actual bounds. Also,
4461  *    types should be compatible (see bpf_core_fields_are_compat for details).
4462  * 3. It is supported and expected that there might be multiple flavors
4463  *    matching the spec. As long as all the specs resolve to the same set of
4464  *    offsets across all candidates, there is no error. If there is any
4465  *    ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4466  *    imprefection of BTF deduplication, which can cause slight duplication of
4467  *    the same BTF type, if some directly or indirectly referenced (by
4468  *    pointer) type gets resolved to different actual types in different
4469  *    object files. If such situation occurs, deduplicated BTF will end up
4470  *    with two (or more) structurally identical types, which differ only in
4471  *    types they refer to through pointer. This should be OK in most cases and
4472  *    is not an error.
4473  * 4. Candidate types search is performed by linearly scanning through all
4474  *    types in target BTF. It is anticipated that this is overall more
4475  *    efficient memory-wise and not significantly worse (if not better)
4476  *    CPU-wise compared to prebuilding a map from all local type names to
4477  *    a list of candidate type names. It's also sped up by caching resolved
4478  *    list of matching candidates per each local "root" type ID, that has at
4479  *    least one bpf_field_reloc associated with it. This list is shared
4480  *    between multiple relocations for the same type ID and is updated as some
4481  *    of the candidates are pruned due to structural incompatibility.
4482  */
4483 static int bpf_core_reloc_field(struct bpf_program *prog,
4484                                  const struct bpf_field_reloc *relo,
4485                                  int relo_idx,
4486                                  const struct btf *local_btf,
4487                                  const struct btf *targ_btf,
4488                                  struct hashmap *cand_cache)
4489 {
4490         const char *prog_name = bpf_program__title(prog, false);
4491         struct bpf_core_spec local_spec, cand_spec, targ_spec;
4492         const void *type_key = u32_as_hash_key(relo->type_id);
4493         const struct btf_type *local_type, *cand_type;
4494         const char *local_name, *cand_name;
4495         struct ids_vec *cand_ids;
4496         __u32 local_id, cand_id;
4497         const char *spec_str;
4498         int i, j, err;
4499
4500         local_id = relo->type_id;
4501         local_type = btf__type_by_id(local_btf, local_id);
4502         if (!local_type)
4503                 return -EINVAL;
4504
4505         local_name = btf__name_by_offset(local_btf, local_type->name_off);
4506         if (str_is_empty(local_name))
4507                 return -EINVAL;
4508
4509         spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4510         if (str_is_empty(spec_str))
4511                 return -EINVAL;
4512
4513         err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4514         if (err) {
4515                 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4516                         prog_name, relo_idx, local_id, local_name, spec_str,
4517                         err);
4518                 return -EINVAL;
4519         }
4520
4521         pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4522                  relo->kind);
4523         bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4524         libbpf_print(LIBBPF_DEBUG, "\n");
4525
4526         if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4527                 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4528                 if (IS_ERR(cand_ids)) {
4529                         pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4530                                 prog_name, relo_idx, local_id, local_name,
4531                                 PTR_ERR(cand_ids));
4532                         return PTR_ERR(cand_ids);
4533                 }
4534                 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4535                 if (err) {
4536                         bpf_core_free_cands(cand_ids);
4537                         return err;
4538                 }
4539         }
4540
4541         for (i = 0, j = 0; i < cand_ids->len; i++) {
4542                 cand_id = cand_ids->data[i];
4543                 cand_type = btf__type_by_id(targ_btf, cand_id);
4544                 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4545
4546                 err = bpf_core_spec_match(&local_spec, targ_btf,
4547                                           cand_id, &cand_spec);
4548                 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4549                          prog_name, relo_idx, i, cand_name);
4550                 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4551                 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4552                 if (err < 0) {
4553                         pr_warn("prog '%s': relo #%d: matching error: %d\n",
4554                                 prog_name, relo_idx, err);
4555                         return err;
4556                 }
4557                 if (err == 0)
4558                         continue;
4559
4560                 if (j == 0) {
4561                         targ_spec = cand_spec;
4562                 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4563                         /* if there are many candidates, they should all
4564                          * resolve to the same bit offset
4565                          */
4566                         pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4567                                 prog_name, relo_idx, cand_spec.bit_offset,
4568                                 targ_spec.bit_offset);
4569                         return -EINVAL;
4570                 }
4571
4572                 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4573         }
4574
4575         /*
4576          * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
4577          * requested, it's expected that we might not find any candidates.
4578          * In this case, if field wasn't found in any candidate, the list of
4579          * candidates shouldn't change at all, we'll just handle relocating
4580          * appropriately, depending on relo's kind.
4581          */
4582         if (j > 0)
4583                 cand_ids->len = j;
4584
4585         if (j == 0 && !prog->obj->relaxed_core_relocs &&
4586             relo->kind != BPF_FIELD_EXISTS) {
4587                 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4588                         prog_name, relo_idx, local_id, local_name, spec_str);
4589                 return -ESRCH;
4590         }
4591
4592         /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4593         err = bpf_core_reloc_insn(prog, relo, &local_spec,
4594                                   j ? &targ_spec : NULL);
4595         if (err) {
4596                 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4597                         prog_name, relo_idx, relo->insn_off, err);
4598                 return -EINVAL;
4599         }
4600
4601         return 0;
4602 }
4603
4604 static int
4605 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4606 {
4607         const struct btf_ext_info_sec *sec;
4608         const struct bpf_field_reloc *rec;
4609         const struct btf_ext_info *seg;
4610         struct hashmap_entry *entry;
4611         struct hashmap *cand_cache = NULL;
4612         struct bpf_program *prog;
4613         struct btf *targ_btf;
4614         const char *sec_name;
4615         int i, err = 0;
4616
4617         if (targ_btf_path)
4618                 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4619         else
4620                 targ_btf = bpf_find_kernel_btf();
4621         if (IS_ERR(targ_btf)) {
4622                 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4623                 return PTR_ERR(targ_btf);
4624         }
4625
4626         cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4627         if (IS_ERR(cand_cache)) {
4628                 err = PTR_ERR(cand_cache);
4629                 goto out;
4630         }
4631
4632         seg = &obj->btf_ext->field_reloc_info;
4633         for_each_btf_ext_sec(seg, sec) {
4634                 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4635                 if (str_is_empty(sec_name)) {
4636                         err = -EINVAL;
4637                         goto out;
4638                 }
4639                 prog = bpf_object__find_program_by_title(obj, sec_name);
4640                 if (!prog) {
4641                         pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4642                                 sec_name);
4643                         err = -EINVAL;
4644                         goto out;
4645                 }
4646
4647                 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4648                          sec_name, sec->num_info);
4649
4650                 for_each_btf_ext_rec(seg, sec, i, rec) {
4651                         err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4652                                                    targ_btf, cand_cache);
4653                         if (err) {
4654                                 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4655                                         sec_name, i, err);
4656                                 goto out;
4657                         }
4658                 }
4659         }
4660
4661 out:
4662         btf__free(targ_btf);
4663         if (!IS_ERR_OR_NULL(cand_cache)) {
4664                 hashmap__for_each_entry(cand_cache, entry, i) {
4665                         bpf_core_free_cands(entry->value);
4666                 }
4667                 hashmap__free(cand_cache);
4668         }
4669         return err;
4670 }
4671
4672 static int
4673 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4674 {
4675         int err = 0;
4676
4677         if (obj->btf_ext->field_reloc_info.len)
4678                 err = bpf_core_reloc_fields(obj, targ_btf_path);
4679
4680         return err;
4681 }
4682
4683 static int
4684 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4685                         struct reloc_desc *relo)
4686 {
4687         struct bpf_insn *insn, *new_insn;
4688         struct bpf_program *text;
4689         size_t new_cnt;
4690         int err;
4691
4692         if (prog->idx == obj->efile.text_shndx) {
4693                 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
4694                         relo->insn_idx, relo->sym_off, relo->sym_off / 8);
4695                 return -LIBBPF_ERRNO__RELOC;
4696         }
4697
4698         if (prog->main_prog_cnt == 0) {
4699                 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4700                 if (!text) {
4701                         pr_warn("no .text section found yet relo into text exist\n");
4702                         return -LIBBPF_ERRNO__RELOC;
4703                 }
4704                 new_cnt = prog->insns_cnt + text->insns_cnt;
4705                 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4706                 if (!new_insn) {
4707                         pr_warn("oom in prog realloc\n");
4708                         return -ENOMEM;
4709                 }
4710                 prog->insns = new_insn;
4711
4712                 if (obj->btf_ext) {
4713                         err = bpf_program_reloc_btf_ext(prog, obj,
4714                                                         text->section_name,
4715                                                         prog->insns_cnt);
4716                         if (err)
4717                                 return err;
4718                 }
4719
4720                 memcpy(new_insn + prog->insns_cnt, text->insns,
4721                        text->insns_cnt * sizeof(*insn));
4722                 prog->main_prog_cnt = prog->insns_cnt;
4723                 prog->insns_cnt = new_cnt;
4724                 pr_debug("added %zd insn from %s to prog %s\n",
4725                          text->insns_cnt, text->section_name,
4726                          prog->section_name);
4727         }
4728         insn = &prog->insns[relo->insn_idx];
4729         insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4730         return 0;
4731 }
4732
4733 static int
4734 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4735 {
4736         int i, err;
4737
4738         if (!prog)
4739                 return 0;
4740
4741         if (obj->btf_ext) {
4742                 err = bpf_program_reloc_btf_ext(prog, obj,
4743                                                 prog->section_name, 0);
4744                 if (err)
4745                         return err;
4746         }
4747
4748         if (!prog->reloc_desc)
4749                 return 0;
4750
4751         for (i = 0; i < prog->nr_reloc; i++) {
4752                 struct reloc_desc *relo = &prog->reloc_desc[i];
4753                 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4754
4755                 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4756                         pr_warn("relocation out of range: '%s'\n",
4757                                 prog->section_name);
4758                         return -LIBBPF_ERRNO__RELOC;
4759                 }
4760
4761                 switch (relo->type) {
4762                 case RELO_LD64:
4763                         insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4764                         insn[0].imm = obj->maps[relo->map_idx].fd;
4765                         break;
4766                 case RELO_DATA:
4767                         insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4768                         insn[1].imm = insn[0].imm + relo->sym_off;
4769                         insn[0].imm = obj->maps[relo->map_idx].fd;
4770                         break;
4771                 case RELO_EXTERN:
4772                         insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4773                         insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
4774                         insn[1].imm = relo->sym_off;
4775                         break;
4776                 case RELO_CALL:
4777                         err = bpf_program__reloc_text(prog, obj, relo);
4778                         if (err)
4779                                 return err;
4780                         break;
4781                 default:
4782                         pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4783                         return -EINVAL;
4784                 }
4785         }
4786
4787         zfree(&prog->reloc_desc);
4788         prog->nr_reloc = 0;
4789         return 0;
4790 }
4791
4792 static int
4793 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4794 {
4795         struct bpf_program *prog;
4796         size_t i;
4797         int err;
4798
4799         if (obj->btf_ext) {
4800                 err = bpf_object__relocate_core(obj, targ_btf_path);
4801                 if (err) {
4802                         pr_warn("failed to perform CO-RE relocations: %d\n",
4803                                 err);
4804                         return err;
4805                 }
4806         }
4807         for (i = 0; i < obj->nr_programs; i++) {
4808                 prog = &obj->programs[i];
4809
4810                 err = bpf_program__relocate(prog, obj);
4811                 if (err) {
4812                         pr_warn("failed to relocate '%s'\n", prog->section_name);
4813                         return err;
4814                 }
4815         }
4816         return 0;
4817 }
4818
4819 static int bpf_object__collect_struct_ops_map_reloc(struct bpf_object *obj,
4820                                                     GElf_Shdr *shdr,
4821                                                     Elf_Data *data);
4822
4823 static int bpf_object__collect_reloc(struct bpf_object *obj)
4824 {
4825         int i, err;
4826
4827         if (!obj_elf_valid(obj)) {
4828                 pr_warn("Internal error: elf object is closed\n");
4829                 return -LIBBPF_ERRNO__INTERNAL;
4830         }
4831
4832         for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
4833                 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
4834                 Elf_Data *data = obj->efile.reloc_sects[i].data;
4835                 int idx = shdr->sh_info;
4836                 struct bpf_program *prog;
4837
4838                 if (shdr->sh_type != SHT_REL) {
4839                         pr_warn("internal error at %d\n", __LINE__);
4840                         return -LIBBPF_ERRNO__INTERNAL;
4841                 }
4842
4843                 if (idx == obj->efile.st_ops_shndx) {
4844                         err = bpf_object__collect_struct_ops_map_reloc(obj,
4845                                                                        shdr,
4846                                                                        data);
4847                         if (err)
4848                                 return err;
4849                         continue;
4850                 }
4851
4852                 prog = bpf_object__find_prog_by_idx(obj, idx);
4853                 if (!prog) {
4854                         pr_warn("relocation failed: no section(%d)\n", idx);
4855                         return -LIBBPF_ERRNO__RELOC;
4856                 }
4857
4858                 err = bpf_program__collect_reloc(prog, shdr, data, obj);
4859                 if (err)
4860                         return err;
4861         }
4862         return 0;
4863 }
4864
4865 static int
4866 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
4867              char *license, __u32 kern_version, int *pfd)
4868 {
4869         struct bpf_load_program_attr load_attr;
4870         char *cp, errmsg[STRERR_BUFSIZE];
4871         int log_buf_size = BPF_LOG_BUF_SIZE;
4872         char *log_buf;
4873         int btf_fd, ret;
4874
4875         if (!insns || !insns_cnt)
4876                 return -EINVAL;
4877
4878         memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
4879         load_attr.prog_type = prog->type;
4880         load_attr.expected_attach_type = prog->expected_attach_type;
4881         if (prog->caps->name)
4882                 load_attr.name = prog->name;
4883         load_attr.insns = insns;
4884         load_attr.insns_cnt = insns_cnt;
4885         load_attr.license = license;
4886         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
4887                 load_attr.attach_btf_id = prog->attach_btf_id;
4888         } else if (prog->type == BPF_PROG_TYPE_TRACING) {
4889                 load_attr.attach_prog_fd = prog->attach_prog_fd;
4890                 load_attr.attach_btf_id = prog->attach_btf_id;
4891         } else {
4892                 load_attr.kern_version = kern_version;
4893                 load_attr.prog_ifindex = prog->prog_ifindex;
4894         }
4895         /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4896         if (prog->obj->btf_ext)
4897                 btf_fd = bpf_object__btf_fd(prog->obj);
4898         else
4899                 btf_fd = -1;
4900         load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
4901         load_attr.func_info = prog->func_info;
4902         load_attr.func_info_rec_size = prog->func_info_rec_size;
4903         load_attr.func_info_cnt = prog->func_info_cnt;
4904         load_attr.line_info = prog->line_info;
4905         load_attr.line_info_rec_size = prog->line_info_rec_size;
4906         load_attr.line_info_cnt = prog->line_info_cnt;
4907         load_attr.log_level = prog->log_level;
4908         load_attr.prog_flags = prog->prog_flags;
4909
4910 retry_load:
4911         log_buf = malloc(log_buf_size);
4912         if (!log_buf)
4913                 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
4914
4915         ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
4916
4917         if (ret >= 0) {
4918                 if (load_attr.log_level)
4919                         pr_debug("verifier log:\n%s", log_buf);
4920                 *pfd = ret;
4921                 ret = 0;
4922                 goto out;
4923         }
4924
4925         if (errno == ENOSPC) {
4926                 log_buf_size <<= 1;
4927                 free(log_buf);
4928                 goto retry_load;
4929         }
4930         ret = -errno;
4931         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4932         pr_warn("load bpf program failed: %s\n", cp);
4933         pr_perm_msg(ret);
4934
4935         if (log_buf && log_buf[0] != '\0') {
4936                 ret = -LIBBPF_ERRNO__VERIFY;
4937                 pr_warn("-- BEGIN DUMP LOG ---\n");
4938                 pr_warn("\n%s\n", log_buf);
4939                 pr_warn("-- END LOG --\n");
4940         } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
4941                 pr_warn("Program too large (%zu insns), at most %d insns\n",
4942                         load_attr.insns_cnt, BPF_MAXINSNS);
4943                 ret = -LIBBPF_ERRNO__PROG2BIG;
4944         } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
4945                 /* Wrong program type? */
4946                 int fd;
4947
4948                 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
4949                 load_attr.expected_attach_type = 0;
4950                 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
4951                 if (fd >= 0) {
4952                         close(fd);
4953                         ret = -LIBBPF_ERRNO__PROGTYPE;
4954                         goto out;
4955                 }
4956         }
4957
4958 out:
4959         free(log_buf);
4960         return ret;
4961 }
4962
4963 static int libbpf_find_attach_btf_id(const char *name,
4964                                      enum bpf_attach_type attach_type,
4965                                      __u32 attach_prog_fd);
4966
4967 int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
4968 {
4969         int err = 0, fd, i, btf_id;
4970
4971         if (prog->type == BPF_PROG_TYPE_TRACING) {
4972                 btf_id = libbpf_find_attach_btf_id(prog->section_name,
4973                                                    prog->expected_attach_type,
4974                                                    prog->attach_prog_fd);
4975                 if (btf_id <= 0)
4976                         return btf_id;
4977                 prog->attach_btf_id = btf_id;
4978         }
4979
4980         if (prog->instances.nr < 0 || !prog->instances.fds) {
4981                 if (prog->preprocessor) {
4982                         pr_warn("Internal error: can't load program '%s'\n",
4983                                 prog->section_name);
4984                         return -LIBBPF_ERRNO__INTERNAL;
4985                 }
4986
4987                 prog->instances.fds = malloc(sizeof(int));
4988                 if (!prog->instances.fds) {
4989                         pr_warn("Not enough memory for BPF fds\n");
4990                         return -ENOMEM;
4991                 }
4992                 prog->instances.nr = 1;
4993                 prog->instances.fds[0] = -1;
4994         }
4995
4996         if (!prog->preprocessor) {
4997                 if (prog->instances.nr != 1) {
4998                         pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4999                                 prog->section_name, prog->instances.nr);
5000                 }
5001                 err = load_program(prog, prog->insns, prog->insns_cnt,
5002                                    license, kern_ver, &fd);
5003                 if (!err)
5004                         prog->instances.fds[0] = fd;
5005                 goto out;
5006         }
5007
5008         for (i = 0; i < prog->instances.nr; i++) {
5009                 struct bpf_prog_prep_result result;
5010                 bpf_program_prep_t preprocessor = prog->preprocessor;
5011
5012                 memset(&result, 0, sizeof(result));
5013                 err = preprocessor(prog, i, prog->insns,
5014                                    prog->insns_cnt, &result);
5015                 if (err) {
5016                         pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
5017                                 i, prog->section_name);
5018                         goto out;
5019                 }
5020
5021                 if (!result.new_insn_ptr || !result.new_insn_cnt) {
5022                         pr_debug("Skip loading the %dth instance of program '%s'\n",
5023                                  i, prog->section_name);
5024                         prog->instances.fds[i] = -1;
5025                         if (result.pfd)
5026                                 *result.pfd = -1;
5027                         continue;
5028                 }
5029
5030                 err = load_program(prog, result.new_insn_ptr,
5031                                    result.new_insn_cnt, license, kern_ver, &fd);
5032                 if (err) {
5033                         pr_warn("Loading the %dth instance of program '%s' failed\n",
5034                                 i, prog->section_name);
5035                         goto out;
5036                 }
5037
5038                 if (result.pfd)
5039                         *result.pfd = fd;
5040                 prog->instances.fds[i] = fd;
5041         }
5042 out:
5043         if (err)
5044                 pr_warn("failed to load program '%s'\n", prog->section_name);
5045         zfree(&prog->insns);
5046         prog->insns_cnt = 0;
5047         return err;
5048 }
5049
5050 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
5051                                              const struct bpf_object *obj)
5052 {
5053         return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
5054 }
5055
5056 static int
5057 bpf_object__load_progs(struct bpf_object *obj, int log_level)
5058 {
5059         size_t i;
5060         int err;
5061
5062         for (i = 0; i < obj->nr_programs; i++) {
5063                 if (bpf_program__is_function_storage(&obj->programs[i], obj))
5064                         continue;
5065                 obj->programs[i].log_level |= log_level;
5066                 err = bpf_program__load(&obj->programs[i],
5067                                         obj->license,
5068                                         obj->kern_version);
5069                 if (err)
5070                         return err;
5071         }
5072         return 0;
5073 }
5074
5075 static struct bpf_object *
5076 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
5077                    const struct bpf_object_open_opts *opts)
5078 {
5079         const char *obj_name, *kconfig;
5080         struct bpf_program *prog;
5081         struct bpf_object *obj;
5082         char tmp_name[64];
5083         int err;
5084
5085         if (elf_version(EV_CURRENT) == EV_NONE) {
5086                 pr_warn("failed to init libelf for %s\n",
5087                         path ? : "(mem buf)");
5088                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
5089         }
5090
5091         if (!OPTS_VALID(opts, bpf_object_open_opts))
5092                 return ERR_PTR(-EINVAL);
5093
5094         obj_name = OPTS_GET(opts, object_name, NULL);
5095         if (obj_buf) {
5096                 if (!obj_name) {
5097                         snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
5098                                  (unsigned long)obj_buf,
5099                                  (unsigned long)obj_buf_sz);
5100                         obj_name = tmp_name;
5101                 }
5102                 path = obj_name;
5103                 pr_debug("loading object '%s' from buffer\n", obj_name);
5104         }
5105
5106         obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
5107         if (IS_ERR(obj))
5108                 return obj;
5109
5110         obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
5111         kconfig = OPTS_GET(opts, kconfig, NULL);
5112         if (kconfig) {
5113                 obj->kconfig = strdup(kconfig);
5114                 if (!obj->kconfig)
5115                         return ERR_PTR(-ENOMEM);
5116         }
5117
5118         err = bpf_object__elf_init(obj);
5119         err = err ? : bpf_object__check_endianness(obj);
5120         err = err ? : bpf_object__elf_collect(obj);
5121         err = err ? : bpf_object__collect_externs(obj);
5122         err = err ? : bpf_object__finalize_btf(obj);
5123         err = err ? : bpf_object__init_maps(obj, opts);
5124         err = err ? : bpf_object__init_prog_names(obj);
5125         err = err ? : bpf_object__collect_reloc(obj);
5126         if (err)
5127                 goto out;
5128         bpf_object__elf_finish(obj);
5129
5130         bpf_object__for_each_program(prog, obj) {
5131                 enum bpf_prog_type prog_type;
5132                 enum bpf_attach_type attach_type;
5133
5134                 if (prog->type != BPF_PROG_TYPE_UNSPEC)
5135                         continue;
5136
5137                 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
5138                                                &attach_type);
5139                 if (err == -ESRCH)
5140                         /* couldn't guess, but user might manually specify */
5141                         continue;
5142                 if (err)
5143                         goto out;
5144
5145                 bpf_program__set_type(prog, prog_type);
5146                 bpf_program__set_expected_attach_type(prog, attach_type);
5147                 if (prog_type == BPF_PROG_TYPE_TRACING)
5148                         prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
5149         }
5150
5151         return obj;
5152 out:
5153         bpf_object__close(obj);
5154         return ERR_PTR(err);
5155 }
5156
5157 static struct bpf_object *
5158 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
5159 {
5160         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5161                 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
5162         );
5163
5164         /* param validation */
5165         if (!attr->file)
5166                 return NULL;
5167
5168         pr_debug("loading %s\n", attr->file);
5169         return __bpf_object__open(attr->file, NULL, 0, &opts);
5170 }
5171
5172 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
5173 {
5174         return __bpf_object__open_xattr(attr, 0);
5175 }
5176
5177 struct bpf_object *bpf_object__open(const char *path)
5178 {
5179         struct bpf_object_open_attr attr = {
5180                 .file           = path,
5181                 .prog_type      = BPF_PROG_TYPE_UNSPEC,
5182         };
5183
5184         return bpf_object__open_xattr(&attr);
5185 }
5186
5187 struct bpf_object *
5188 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
5189 {
5190         if (!path)
5191                 return ERR_PTR(-EINVAL);
5192
5193         pr_debug("loading %s\n", path);
5194
5195         return __bpf_object__open(path, NULL, 0, opts);
5196 }
5197
5198 struct bpf_object *
5199 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
5200                      const struct bpf_object_open_opts *opts)
5201 {
5202         if (!obj_buf || obj_buf_sz == 0)
5203                 return ERR_PTR(-EINVAL);
5204
5205         return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
5206 }
5207
5208 struct bpf_object *
5209 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
5210                         const char *name)
5211 {
5212         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5213                 .object_name = name,
5214                 /* wrong default, but backwards-compatible */
5215                 .relaxed_maps = true,
5216         );
5217
5218         /* returning NULL is wrong, but backwards-compatible */
5219         if (!obj_buf || obj_buf_sz == 0)
5220                 return NULL;
5221
5222         return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
5223 }
5224
5225 int bpf_object__unload(struct bpf_object *obj)
5226 {
5227         size_t i;
5228
5229         if (!obj)
5230                 return -EINVAL;
5231
5232         for (i = 0; i < obj->nr_maps; i++) {
5233                 zclose(obj->maps[i].fd);
5234                 if (obj->maps[i].st_ops)
5235                         zfree(&obj->maps[i].st_ops->kern_vdata);
5236         }
5237
5238         for (i = 0; i < obj->nr_programs; i++)
5239                 bpf_program__unload(&obj->programs[i]);
5240
5241         return 0;
5242 }
5243
5244 static int bpf_object__sanitize_maps(struct bpf_object *obj)
5245 {
5246         struct bpf_map *m;
5247
5248         bpf_object__for_each_map(m, obj) {
5249                 if (!bpf_map__is_internal(m))
5250                         continue;
5251                 if (!obj->caps.global_data) {
5252                         pr_warn("kernel doesn't support global data\n");
5253                         return -ENOTSUP;
5254                 }
5255                 if (!obj->caps.array_mmap)
5256                         m->def.map_flags ^= BPF_F_MMAPABLE;
5257         }
5258
5259         return 0;
5260 }
5261
5262 static int bpf_object__resolve_externs(struct bpf_object *obj,
5263                                        const char *extra_kconfig)
5264 {
5265         bool need_config = false;
5266         struct extern_desc *ext;
5267         int err, i;
5268         void *data;
5269
5270         if (obj->nr_extern == 0)
5271                 return 0;
5272
5273         data = obj->maps[obj->kconfig_map_idx].mmaped;
5274
5275         for (i = 0; i < obj->nr_extern; i++) {
5276                 ext = &obj->externs[i];
5277
5278                 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
5279                         void *ext_val = data + ext->data_off;
5280                         __u32 kver = get_kernel_version();
5281
5282                         if (!kver) {
5283                                 pr_warn("failed to get kernel version\n");
5284                                 return -EINVAL;
5285                         }
5286                         err = set_ext_value_num(ext, ext_val, kver);
5287                         if (err)
5288                                 return err;
5289                         pr_debug("extern %s=0x%x\n", ext->name, kver);
5290                 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
5291                         need_config = true;
5292                 } else {
5293                         pr_warn("unrecognized extern '%s'\n", ext->name);
5294                         return -EINVAL;
5295                 }
5296         }
5297         if (need_config && extra_kconfig) {
5298                 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, data);
5299                 if (err)
5300                         return -EINVAL;
5301                 need_config = false;
5302                 for (i = 0; i < obj->nr_extern; i++) {
5303                         ext = &obj->externs[i];
5304                         if (!ext->is_set) {
5305                                 need_config = true;
5306                                 break;
5307                         }
5308                 }
5309         }
5310         if (need_config) {
5311                 err = bpf_object__read_kconfig_file(obj, data);
5312                 if (err)
5313                         return -EINVAL;
5314         }
5315         for (i = 0; i < obj->nr_extern; i++) {
5316                 ext = &obj->externs[i];
5317
5318                 if (!ext->is_set && !ext->is_weak) {
5319                         pr_warn("extern %s (strong) not resolved\n", ext->name);
5320                         return -ESRCH;
5321                 } else if (!ext->is_set) {
5322                         pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
5323                                  ext->name);
5324                 }
5325         }
5326
5327         return 0;
5328 }
5329
5330 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
5331 {
5332         struct bpf_object *obj;
5333         int err, i;
5334
5335         if (!attr)
5336                 return -EINVAL;
5337         obj = attr->obj;
5338         if (!obj)
5339                 return -EINVAL;
5340
5341         if (obj->loaded) {
5342                 pr_warn("object should not be loaded twice\n");
5343                 return -EINVAL;
5344         }
5345
5346         obj->loaded = true;
5347
5348         err = bpf_object__probe_caps(obj);
5349         err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
5350         err = err ? : bpf_object__sanitize_and_load_btf(obj);
5351         err = err ? : bpf_object__sanitize_maps(obj);
5352         err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
5353         err = err ? : bpf_object__create_maps(obj);
5354         err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
5355         err = err ? : bpf_object__load_progs(obj, attr->log_level);
5356         if (err)
5357                 goto out;
5358
5359         return 0;
5360 out:
5361         /* unpin any maps that were auto-pinned during load */
5362         for (i = 0; i < obj->nr_maps; i++)
5363                 if (obj->maps[i].pinned && !obj->maps[i].reused)
5364                         bpf_map__unpin(&obj->maps[i], NULL);
5365
5366         bpf_object__unload(obj);
5367         pr_warn("failed to load object '%s'\n", obj->path);
5368         return err;
5369 }
5370
5371 int bpf_object__load(struct bpf_object *obj)
5372 {
5373         struct bpf_object_load_attr attr = {
5374                 .obj = obj,
5375         };
5376
5377         return bpf_object__load_xattr(&attr);
5378 }
5379
5380 static int make_parent_dir(const char *path)
5381 {
5382         char *cp, errmsg[STRERR_BUFSIZE];
5383         char *dname, *dir;
5384         int err = 0;
5385
5386         dname = strdup(path);
5387         if (dname == NULL)
5388                 return -ENOMEM;
5389
5390         dir = dirname(dname);
5391         if (mkdir(dir, 0700) && errno != EEXIST)
5392                 err = -errno;
5393
5394         free(dname);
5395         if (err) {
5396                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5397                 pr_warn("failed to mkdir %s: %s\n", path, cp);
5398         }
5399         return err;
5400 }
5401
5402 static int check_path(const char *path)
5403 {
5404         char *cp, errmsg[STRERR_BUFSIZE];
5405         struct statfs st_fs;
5406         char *dname, *dir;
5407         int err = 0;
5408
5409         if (path == NULL)
5410                 return -EINVAL;
5411
5412         dname = strdup(path);
5413         if (dname == NULL)
5414                 return -ENOMEM;
5415
5416         dir = dirname(dname);
5417         if (statfs(dir, &st_fs)) {
5418                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5419                 pr_warn("failed to statfs %s: %s\n", dir, cp);
5420                 err = -errno;
5421         }
5422         free(dname);
5423
5424         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
5425                 pr_warn("specified path %s is not on BPF FS\n", path);
5426                 err = -EINVAL;
5427         }
5428
5429         return err;
5430 }
5431
5432 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
5433                               int instance)
5434 {
5435         char *cp, errmsg[STRERR_BUFSIZE];
5436         int err;
5437
5438         err = make_parent_dir(path);
5439         if (err)
5440                 return err;
5441
5442         err = check_path(path);
5443         if (err)
5444                 return err;
5445
5446         if (prog == NULL) {
5447                 pr_warn("invalid program pointer\n");
5448                 return -EINVAL;
5449         }
5450
5451         if (instance < 0 || instance >= prog->instances.nr) {
5452                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5453                         instance, prog->section_name, prog->instances.nr);
5454                 return -EINVAL;
5455         }
5456
5457         if (bpf_obj_pin(prog->instances.fds[instance], path)) {
5458                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5459                 pr_warn("failed to pin program: %s\n", cp);
5460                 return -errno;
5461         }
5462         pr_debug("pinned program '%s'\n", path);
5463
5464         return 0;
5465 }
5466
5467 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
5468                                 int instance)
5469 {
5470         int err;
5471
5472         err = check_path(path);
5473         if (err)
5474                 return err;
5475
5476         if (prog == NULL) {
5477                 pr_warn("invalid program pointer\n");
5478                 return -EINVAL;
5479         }
5480
5481         if (instance < 0 || instance >= prog->instances.nr) {
5482                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5483                         instance, prog->section_name, prog->instances.nr);
5484                 return -EINVAL;
5485         }
5486
5487         err = unlink(path);
5488         if (err != 0)
5489                 return -errno;
5490         pr_debug("unpinned program '%s'\n", path);
5491
5492         return 0;
5493 }
5494
5495 int bpf_program__pin(struct bpf_program *prog, const char *path)
5496 {
5497         int i, err;
5498
5499         err = make_parent_dir(path);
5500         if (err)
5501                 return err;
5502
5503         err = check_path(path);
5504         if (err)
5505                 return err;
5506
5507         if (prog == NULL) {
5508                 pr_warn("invalid program pointer\n");
5509                 return -EINVAL;
5510         }
5511
5512         if (prog->instances.nr <= 0) {
5513                 pr_warn("no instances of prog %s to pin\n",
5514                            prog->section_name);
5515                 return -EINVAL;
5516         }
5517
5518         if (prog->instances.nr == 1) {
5519                 /* don't create subdirs when pinning single instance */
5520                 return bpf_program__pin_instance(prog, path, 0);
5521         }
5522
5523         for (i = 0; i < prog->instances.nr; i++) {
5524                 char buf[PATH_MAX];
5525                 int len;
5526
5527                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5528                 if (len < 0) {
5529                         err = -EINVAL;
5530                         goto err_unpin;
5531                 } else if (len >= PATH_MAX) {
5532                         err = -ENAMETOOLONG;
5533                         goto err_unpin;
5534                 }
5535
5536                 err = bpf_program__pin_instance(prog, buf, i);
5537                 if (err)
5538                         goto err_unpin;
5539         }
5540
5541         return 0;
5542
5543 err_unpin:
5544         for (i = i - 1; i >= 0; i--) {
5545                 char buf[PATH_MAX];
5546                 int len;
5547
5548                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5549                 if (len < 0)
5550                         continue;
5551                 else if (len >= PATH_MAX)
5552                         continue;
5553
5554                 bpf_program__unpin_instance(prog, buf, i);
5555         }
5556
5557         rmdir(path);
5558
5559         return err;
5560 }
5561
5562 int bpf_program__unpin(struct bpf_program *prog, const char *path)
5563 {
5564         int i, err;
5565
5566         err = check_path(path);
5567         if (err)
5568                 return err;
5569
5570         if (prog == NULL) {
5571                 pr_warn("invalid program pointer\n");
5572                 return -EINVAL;
5573         }
5574
5575         if (prog->instances.nr <= 0) {
5576                 pr_warn("no instances of prog %s to pin\n",
5577                            prog->section_name);
5578                 return -EINVAL;
5579         }
5580
5581         if (prog->instances.nr == 1) {
5582                 /* don't create subdirs when pinning single instance */
5583                 return bpf_program__unpin_instance(prog, path, 0);
5584         }
5585
5586         for (i = 0; i < prog->instances.nr; i++) {
5587                 char buf[PATH_MAX];
5588                 int len;
5589
5590                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5591                 if (len < 0)
5592                         return -EINVAL;
5593                 else if (len >= PATH_MAX)
5594                         return -ENAMETOOLONG;
5595
5596                 err = bpf_program__unpin_instance(prog, buf, i);
5597                 if (err)
5598                         return err;
5599         }
5600
5601         err = rmdir(path);
5602         if (err)
5603                 return -errno;
5604
5605         return 0;
5606 }
5607
5608 int bpf_map__pin(struct bpf_map *map, const char *path)
5609 {
5610         char *cp, errmsg[STRERR_BUFSIZE];
5611         int err;
5612
5613         if (map == NULL) {
5614                 pr_warn("invalid map pointer\n");
5615                 return -EINVAL;
5616         }
5617
5618         if (map->pin_path) {
5619                 if (path && strcmp(path, map->pin_path)) {
5620                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5621                                 bpf_map__name(map), map->pin_path, path);
5622                         return -EINVAL;
5623                 } else if (map->pinned) {
5624                         pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5625                                  bpf_map__name(map), map->pin_path);
5626                         return 0;
5627                 }
5628         } else {
5629                 if (!path) {
5630                         pr_warn("missing a path to pin map '%s' at\n",
5631                                 bpf_map__name(map));
5632                         return -EINVAL;
5633                 } else if (map->pinned) {
5634                         pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5635                         return -EEXIST;
5636                 }
5637
5638                 map->pin_path = strdup(path);
5639                 if (!map->pin_path) {
5640                         err = -errno;
5641                         goto out_err;
5642                 }
5643         }
5644
5645         err = make_parent_dir(map->pin_path);
5646         if (err)
5647                 return err;
5648
5649         err = check_path(map->pin_path);
5650         if (err)
5651                 return err;
5652
5653         if (bpf_obj_pin(map->fd, map->pin_path)) {
5654                 err = -errno;
5655                 goto out_err;
5656         }
5657
5658         map->pinned = true;
5659         pr_debug("pinned map '%s'\n", map->pin_path);
5660
5661         return 0;
5662
5663 out_err:
5664         cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5665         pr_warn("failed to pin map: %s\n", cp);
5666         return err;
5667 }
5668
5669 int bpf_map__unpin(struct bpf_map *map, const char *path)
5670 {
5671         int err;
5672
5673         if (map == NULL) {
5674                 pr_warn("invalid map pointer\n");
5675                 return -EINVAL;
5676         }
5677
5678         if (map->pin_path) {
5679                 if (path && strcmp(path, map->pin_path)) {
5680                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5681                                 bpf_map__name(map), map->pin_path, path);
5682                         return -EINVAL;
5683                 }
5684                 path = map->pin_path;
5685         } else if (!path) {
5686                 pr_warn("no path to unpin map '%s' from\n",
5687                         bpf_map__name(map));
5688                 return -EINVAL;
5689         }
5690
5691         err = check_path(path);
5692         if (err)
5693                 return err;
5694
5695         err = unlink(path);
5696         if (err != 0)
5697                 return -errno;
5698
5699         map->pinned = false;
5700         pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
5701
5702         return 0;
5703 }
5704
5705 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
5706 {
5707         char *new = NULL;
5708
5709         if (path) {
5710                 new = strdup(path);
5711                 if (!new)
5712                         return -errno;
5713         }
5714
5715         free(map->pin_path);
5716         map->pin_path = new;
5717         return 0;
5718 }
5719
5720 const char *bpf_map__get_pin_path(const struct bpf_map *map)
5721 {
5722         return map->pin_path;
5723 }
5724
5725 bool bpf_map__is_pinned(const struct bpf_map *map)
5726 {
5727         return map->pinned;
5728 }
5729
5730 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
5731 {
5732         struct bpf_map *map;
5733         int err;
5734
5735         if (!obj)
5736                 return -ENOENT;
5737
5738         if (!obj->loaded) {
5739                 pr_warn("object not yet loaded; load it first\n");
5740                 return -ENOENT;
5741         }
5742
5743         bpf_object__for_each_map(map, obj) {
5744                 char *pin_path = NULL;
5745                 char buf[PATH_MAX];
5746
5747                 if (path) {
5748                         int len;
5749
5750                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
5751                                        bpf_map__name(map));
5752                         if (len < 0) {
5753                                 err = -EINVAL;
5754                                 goto err_unpin_maps;
5755                         } else if (len >= PATH_MAX) {
5756                                 err = -ENAMETOOLONG;
5757                                 goto err_unpin_maps;
5758                         }
5759                         pin_path = buf;
5760                 } else if (!map->pin_path) {
5761                         continue;
5762                 }
5763
5764                 err = bpf_map__pin(map, pin_path);
5765                 if (err)
5766                         goto err_unpin_maps;
5767         }
5768
5769         return 0;
5770
5771 err_unpin_maps:
5772         while ((map = bpf_map__prev(map, obj))) {
5773                 if (!map->pin_path)
5774                         continue;
5775
5776                 bpf_map__unpin(map, NULL);
5777         }
5778
5779         return err;
5780 }
5781
5782 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
5783 {
5784         struct bpf_map *map;
5785         int err;
5786
5787         if (!obj)
5788                 return -ENOENT;
5789
5790         bpf_object__for_each_map(map, obj) {
5791                 char *pin_path = NULL;
5792                 char buf[PATH_MAX];
5793
5794                 if (path) {
5795                         int len;
5796
5797                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
5798                                        bpf_map__name(map));
5799                         if (len < 0)
5800                                 return -EINVAL;
5801                         else if (len >= PATH_MAX)
5802                                 return -ENAMETOOLONG;
5803                         pin_path = buf;
5804                 } else if (!map->pin_path) {
5805                         continue;
5806                 }
5807
5808                 err = bpf_map__unpin(map, pin_path);
5809                 if (err)
5810                         return err;
5811         }
5812
5813         return 0;
5814 }
5815
5816 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
5817 {
5818         struct bpf_program *prog;
5819         int err;
5820
5821         if (!obj)
5822                 return -ENOENT;
5823
5824         if (!obj->loaded) {
5825                 pr_warn("object not yet loaded; load it first\n");
5826                 return -ENOENT;
5827         }
5828
5829         bpf_object__for_each_program(prog, obj) {
5830                 char buf[PATH_MAX];
5831                 int len;
5832
5833                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5834                                prog->pin_name);
5835                 if (len < 0) {
5836                         err = -EINVAL;
5837                         goto err_unpin_programs;
5838                 } else if (len >= PATH_MAX) {
5839                         err = -ENAMETOOLONG;
5840                         goto err_unpin_programs;
5841                 }
5842
5843                 err = bpf_program__pin(prog, buf);
5844                 if (err)
5845                         goto err_unpin_programs;
5846         }
5847
5848         return 0;
5849
5850 err_unpin_programs:
5851         while ((prog = bpf_program__prev(prog, obj))) {
5852                 char buf[PATH_MAX];
5853                 int len;
5854
5855                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5856                                prog->pin_name);
5857                 if (len < 0)
5858                         continue;
5859                 else if (len >= PATH_MAX)
5860                         continue;
5861
5862                 bpf_program__unpin(prog, buf);
5863         }
5864
5865         return err;
5866 }
5867
5868 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
5869 {
5870         struct bpf_program *prog;
5871         int err;
5872
5873         if (!obj)
5874                 return -ENOENT;
5875
5876         bpf_object__for_each_program(prog, obj) {
5877                 char buf[PATH_MAX];
5878                 int len;
5879
5880                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5881                                prog->pin_name);
5882                 if (len < 0)
5883                         return -EINVAL;
5884                 else if (len >= PATH_MAX)
5885                         return -ENAMETOOLONG;
5886
5887                 err = bpf_program__unpin(prog, buf);
5888                 if (err)
5889                         return err;
5890         }
5891
5892         return 0;
5893 }
5894
5895 int bpf_object__pin(struct bpf_object *obj, const char *path)
5896 {
5897         int err;
5898
5899         err = bpf_object__pin_maps(obj, path);
5900         if (err)
5901                 return err;
5902
5903         err = bpf_object__pin_programs(obj, path);
5904         if (err) {
5905                 bpf_object__unpin_maps(obj, path);
5906                 return err;
5907         }
5908
5909         return 0;
5910 }
5911
5912 void bpf_object__close(struct bpf_object *obj)
5913 {
5914         size_t i;
5915
5916         if (!obj)
5917                 return;
5918
5919         if (obj->clear_priv)
5920                 obj->clear_priv(obj, obj->priv);
5921
5922         bpf_object__elf_finish(obj);
5923         bpf_object__unload(obj);
5924         btf__free(obj->btf);
5925         btf_ext__free(obj->btf_ext);
5926
5927         for (i = 0; i < obj->nr_maps; i++) {
5928                 struct bpf_map *map = &obj->maps[i];
5929
5930                 if (map->clear_priv)
5931                         map->clear_priv(map, map->priv);
5932                 map->priv = NULL;
5933                 map->clear_priv = NULL;
5934
5935                 if (map->mmaped) {
5936                         munmap(map->mmaped, bpf_map_mmap_sz(map));
5937                         map->mmaped = NULL;
5938                 }
5939
5940                 if (map->st_ops) {
5941                         zfree(&map->st_ops->data);
5942                         zfree(&map->st_ops->progs);
5943                         zfree(&map->st_ops->kern_func_off);
5944                         zfree(&map->st_ops);
5945                 }
5946
5947                 zfree(&map->name);
5948                 zfree(&map->pin_path);
5949         }
5950
5951         zfree(&obj->kconfig);
5952         zfree(&obj->externs);
5953         obj->nr_extern = 0;
5954
5955         zfree(&obj->maps);
5956         obj->nr_maps = 0;
5957
5958         if (obj->programs && obj->nr_programs) {
5959                 for (i = 0; i < obj->nr_programs; i++)
5960                         bpf_program__exit(&obj->programs[i]);
5961         }
5962         zfree(&obj->programs);
5963
5964         list_del(&obj->list);
5965         free(obj);
5966 }
5967
5968 struct bpf_object *
5969 bpf_object__next(struct bpf_object *prev)
5970 {
5971         struct bpf_object *next;
5972
5973         if (!prev)
5974                 next = list_first_entry(&bpf_objects_list,
5975                                         struct bpf_object,
5976                                         list);
5977         else
5978                 next = list_next_entry(prev, list);
5979
5980         /* Empty list is noticed here so don't need checking on entry. */
5981         if (&next->list == &bpf_objects_list)
5982                 return NULL;
5983
5984         return next;
5985 }
5986
5987 const char *bpf_object__name(const struct bpf_object *obj)
5988 {
5989         return obj ? obj->name : ERR_PTR(-EINVAL);
5990 }
5991
5992 unsigned int bpf_object__kversion(const struct bpf_object *obj)
5993 {
5994         return obj ? obj->kern_version : 0;
5995 }
5996
5997 struct btf *bpf_object__btf(const struct bpf_object *obj)
5998 {
5999         return obj ? obj->btf : NULL;
6000 }
6001
6002 int bpf_object__btf_fd(const struct bpf_object *obj)
6003 {
6004         return obj->btf ? btf__fd(obj->btf) : -1;
6005 }
6006
6007 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
6008                          bpf_object_clear_priv_t clear_priv)
6009 {
6010         if (obj->priv && obj->clear_priv)
6011                 obj->clear_priv(obj, obj->priv);
6012
6013         obj->priv = priv;
6014         obj->clear_priv = clear_priv;
6015         return 0;
6016 }
6017
6018 void *bpf_object__priv(const struct bpf_object *obj)
6019 {
6020         return obj ? obj->priv : ERR_PTR(-EINVAL);
6021 }
6022
6023 static struct bpf_program *
6024 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
6025                     bool forward)
6026 {
6027         size_t nr_programs = obj->nr_programs;
6028         ssize_t idx;
6029
6030         if (!nr_programs)
6031                 return NULL;
6032
6033         if (!p)
6034                 /* Iter from the beginning */
6035                 return forward ? &obj->programs[0] :
6036                         &obj->programs[nr_programs - 1];
6037
6038         if (p->obj != obj) {
6039                 pr_warn("error: program handler doesn't match object\n");
6040                 return NULL;
6041         }
6042
6043         idx = (p - obj->programs) + (forward ? 1 : -1);
6044         if (idx >= obj->nr_programs || idx < 0)
6045                 return NULL;
6046         return &obj->programs[idx];
6047 }
6048
6049 struct bpf_program *
6050 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
6051 {
6052         struct bpf_program *prog = prev;
6053
6054         do {
6055                 prog = __bpf_program__iter(prog, obj, true);
6056         } while (prog && bpf_program__is_function_storage(prog, obj));
6057
6058         return prog;
6059 }
6060
6061 struct bpf_program *
6062 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
6063 {
6064         struct bpf_program *prog = next;
6065
6066         do {
6067                 prog = __bpf_program__iter(prog, obj, false);
6068         } while (prog && bpf_program__is_function_storage(prog, obj));
6069
6070         return prog;
6071 }
6072
6073 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
6074                           bpf_program_clear_priv_t clear_priv)
6075 {
6076         if (prog->priv && prog->clear_priv)
6077                 prog->clear_priv(prog, prog->priv);
6078
6079         prog->priv = priv;
6080         prog->clear_priv = clear_priv;
6081         return 0;
6082 }
6083
6084 void *bpf_program__priv(const struct bpf_program *prog)
6085 {
6086         return prog ? prog->priv : ERR_PTR(-EINVAL);
6087 }
6088
6089 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
6090 {
6091         prog->prog_ifindex = ifindex;
6092 }
6093
6094 const char *bpf_program__name(const struct bpf_program *prog)
6095 {
6096         return prog->name;
6097 }
6098
6099 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
6100 {
6101         const char *title;
6102
6103         title = prog->section_name;
6104         if (needs_copy) {
6105                 title = strdup(title);
6106                 if (!title) {
6107                         pr_warn("failed to strdup program title\n");
6108                         return ERR_PTR(-ENOMEM);
6109                 }
6110         }
6111
6112         return title;
6113 }
6114
6115 int bpf_program__fd(const struct bpf_program *prog)
6116 {
6117         return bpf_program__nth_fd(prog, 0);
6118 }
6119
6120 size_t bpf_program__size(const struct bpf_program *prog)
6121 {
6122         return prog->insns_cnt * sizeof(struct bpf_insn);
6123 }
6124
6125 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
6126                           bpf_program_prep_t prep)
6127 {
6128         int *instances_fds;
6129
6130         if (nr_instances <= 0 || !prep)
6131                 return -EINVAL;
6132
6133         if (prog->instances.nr > 0 || prog->instances.fds) {
6134                 pr_warn("Can't set pre-processor after loading\n");
6135                 return -EINVAL;
6136         }
6137
6138         instances_fds = malloc(sizeof(int) * nr_instances);
6139         if (!instances_fds) {
6140                 pr_warn("alloc memory failed for fds\n");
6141                 return -ENOMEM;
6142         }
6143
6144         /* fill all fd with -1 */
6145         memset(instances_fds, -1, sizeof(int) * nr_instances);
6146
6147         prog->instances.nr = nr_instances;
6148         prog->instances.fds = instances_fds;
6149         prog->preprocessor = prep;
6150         return 0;
6151 }
6152
6153 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
6154 {
6155         int fd;
6156
6157         if (!prog)
6158                 return -EINVAL;
6159
6160         if (n >= prog->instances.nr || n < 0) {
6161                 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
6162                         n, prog->section_name, prog->instances.nr);
6163                 return -EINVAL;
6164         }
6165
6166         fd = prog->instances.fds[n];
6167         if (fd < 0) {
6168                 pr_warn("%dth instance of program '%s' is invalid\n",
6169                         n, prog->section_name);
6170                 return -ENOENT;
6171         }
6172
6173         return fd;
6174 }
6175
6176 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
6177 {
6178         return prog->type;
6179 }
6180
6181 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
6182 {
6183         prog->type = type;
6184 }
6185
6186 static bool bpf_program__is_type(const struct bpf_program *prog,
6187                                  enum bpf_prog_type type)
6188 {
6189         return prog ? (prog->type == type) : false;
6190 }
6191
6192 #define BPF_PROG_TYPE_FNS(NAME, TYPE)                           \
6193 int bpf_program__set_##NAME(struct bpf_program *prog)           \
6194 {                                                               \
6195         if (!prog)                                              \
6196                 return -EINVAL;                                 \
6197         bpf_program__set_type(prog, TYPE);                      \
6198         return 0;                                               \
6199 }                                                               \
6200                                                                 \
6201 bool bpf_program__is_##NAME(const struct bpf_program *prog)     \
6202 {                                                               \
6203         return bpf_program__is_type(prog, TYPE);                \
6204 }                                                               \
6205
6206 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
6207 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
6208 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
6209 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
6210 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
6211 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
6212 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
6213 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
6214 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
6215 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
6216
6217 enum bpf_attach_type
6218 bpf_program__get_expected_attach_type(struct bpf_program *prog)
6219 {
6220         return prog->expected_attach_type;
6221 }
6222
6223 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
6224                                            enum bpf_attach_type type)
6225 {
6226         prog->expected_attach_type = type;
6227 }
6228
6229 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
6230         { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
6231
6232 /* Programs that can NOT be attached. */
6233 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
6234
6235 /* Programs that can be attached. */
6236 #define BPF_APROG_SEC(string, ptype, atype) \
6237         BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
6238
6239 /* Programs that must specify expected attach type at load time. */
6240 #define BPF_EAPROG_SEC(string, ptype, eatype) \
6241         BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
6242
6243 /* Programs that use BTF to identify attach point */
6244 #define BPF_PROG_BTF(string, ptype, eatype) \
6245         BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
6246
6247 /* Programs that can be attached but attach type can't be identified by section
6248  * name. Kept for backward compatibility.
6249  */
6250 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
6251
6252 #define SEC_DEF(sec_pfx, ptype, ...) {                                      \
6253         .sec = sec_pfx,                                                     \
6254         .len = sizeof(sec_pfx) - 1,                                         \
6255         .prog_type = BPF_PROG_TYPE_##ptype,                                 \
6256         __VA_ARGS__                                                         \
6257 }
6258
6259 struct bpf_sec_def;
6260
6261 typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
6262                                         struct bpf_program *prog);
6263
6264 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6265                                       struct bpf_program *prog);
6266 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6267                                   struct bpf_program *prog);
6268 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6269                                       struct bpf_program *prog);
6270 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6271                                      struct bpf_program *prog);
6272
6273 struct bpf_sec_def {
6274         const char *sec;
6275         size_t len;
6276         enum bpf_prog_type prog_type;
6277         enum bpf_attach_type expected_attach_type;
6278         bool is_attachable;
6279         bool is_attach_btf;
6280         enum bpf_attach_type attach_type;
6281         attach_fn_t attach_fn;
6282 };
6283
6284 static const struct bpf_sec_def section_defs[] = {
6285         BPF_PROG_SEC("socket",                  BPF_PROG_TYPE_SOCKET_FILTER),
6286         BPF_PROG_SEC("sk_reuseport",            BPF_PROG_TYPE_SK_REUSEPORT),
6287         SEC_DEF("kprobe/", KPROBE,
6288                 .attach_fn = attach_kprobe),
6289         BPF_PROG_SEC("uprobe/",                 BPF_PROG_TYPE_KPROBE),
6290         SEC_DEF("kretprobe/", KPROBE,
6291                 .attach_fn = attach_kprobe),
6292         BPF_PROG_SEC("uretprobe/",              BPF_PROG_TYPE_KPROBE),
6293         BPF_PROG_SEC("classifier",              BPF_PROG_TYPE_SCHED_CLS),
6294         BPF_PROG_SEC("action",                  BPF_PROG_TYPE_SCHED_ACT),
6295         SEC_DEF("tracepoint/", TRACEPOINT,
6296                 .attach_fn = attach_tp),
6297         SEC_DEF("tp/", TRACEPOINT,
6298                 .attach_fn = attach_tp),
6299         SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
6300                 .attach_fn = attach_raw_tp),
6301         SEC_DEF("raw_tp/", RAW_TRACEPOINT,
6302                 .attach_fn = attach_raw_tp),
6303         SEC_DEF("tp_btf/", TRACING,
6304                 .expected_attach_type = BPF_TRACE_RAW_TP,
6305                 .is_attach_btf = true,
6306                 .attach_fn = attach_trace),
6307         SEC_DEF("fentry/", TRACING,
6308                 .expected_attach_type = BPF_TRACE_FENTRY,
6309                 .is_attach_btf = true,
6310                 .attach_fn = attach_trace),
6311         SEC_DEF("fexit/", TRACING,
6312                 .expected_attach_type = BPF_TRACE_FEXIT,
6313                 .is_attach_btf = true,
6314                 .attach_fn = attach_trace),
6315         BPF_PROG_SEC("xdp",                     BPF_PROG_TYPE_XDP),
6316         BPF_PROG_SEC("perf_event",              BPF_PROG_TYPE_PERF_EVENT),
6317         BPF_PROG_SEC("lwt_in",                  BPF_PROG_TYPE_LWT_IN),
6318         BPF_PROG_SEC("lwt_out",                 BPF_PROG_TYPE_LWT_OUT),
6319         BPF_PROG_SEC("lwt_xmit",                BPF_PROG_TYPE_LWT_XMIT),
6320         BPF_PROG_SEC("lwt_seg6local",           BPF_PROG_TYPE_LWT_SEG6LOCAL),
6321         BPF_APROG_SEC("cgroup_skb/ingress",     BPF_PROG_TYPE_CGROUP_SKB,
6322                                                 BPF_CGROUP_INET_INGRESS),
6323         BPF_APROG_SEC("cgroup_skb/egress",      BPF_PROG_TYPE_CGROUP_SKB,
6324                                                 BPF_CGROUP_INET_EGRESS),
6325         BPF_APROG_COMPAT("cgroup/skb",          BPF_PROG_TYPE_CGROUP_SKB),
6326         BPF_APROG_SEC("cgroup/sock",            BPF_PROG_TYPE_CGROUP_SOCK,
6327                                                 BPF_CGROUP_INET_SOCK_CREATE),
6328         BPF_EAPROG_SEC("cgroup/post_bind4",     BPF_PROG_TYPE_CGROUP_SOCK,
6329                                                 BPF_CGROUP_INET4_POST_BIND),
6330         BPF_EAPROG_SEC("cgroup/post_bind6",     BPF_PROG_TYPE_CGROUP_SOCK,
6331                                                 BPF_CGROUP_INET6_POST_BIND),
6332         BPF_APROG_SEC("cgroup/dev",             BPF_PROG_TYPE_CGROUP_DEVICE,
6333                                                 BPF_CGROUP_DEVICE),
6334         BPF_APROG_SEC("sockops",                BPF_PROG_TYPE_SOCK_OPS,
6335                                                 BPF_CGROUP_SOCK_OPS),
6336         BPF_APROG_SEC("sk_skb/stream_parser",   BPF_PROG_TYPE_SK_SKB,
6337                                                 BPF_SK_SKB_STREAM_PARSER),
6338         BPF_APROG_SEC("sk_skb/stream_verdict",  BPF_PROG_TYPE_SK_SKB,
6339                                                 BPF_SK_SKB_STREAM_VERDICT),
6340         BPF_APROG_COMPAT("sk_skb",              BPF_PROG_TYPE_SK_SKB),
6341         BPF_APROG_SEC("sk_msg",                 BPF_PROG_TYPE_SK_MSG,
6342                                                 BPF_SK_MSG_VERDICT),
6343         BPF_APROG_SEC("lirc_mode2",             BPF_PROG_TYPE_LIRC_MODE2,
6344                                                 BPF_LIRC_MODE2),
6345         BPF_APROG_SEC("flow_dissector",         BPF_PROG_TYPE_FLOW_DISSECTOR,
6346                                                 BPF_FLOW_DISSECTOR),
6347         BPF_EAPROG_SEC("cgroup/bind4",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6348                                                 BPF_CGROUP_INET4_BIND),
6349         BPF_EAPROG_SEC("cgroup/bind6",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6350                                                 BPF_CGROUP_INET6_BIND),
6351         BPF_EAPROG_SEC("cgroup/connect4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6352                                                 BPF_CGROUP_INET4_CONNECT),
6353         BPF_EAPROG_SEC("cgroup/connect6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6354                                                 BPF_CGROUP_INET6_CONNECT),
6355         BPF_EAPROG_SEC("cgroup/sendmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6356                                                 BPF_CGROUP_UDP4_SENDMSG),
6357         BPF_EAPROG_SEC("cgroup/sendmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6358                                                 BPF_CGROUP_UDP6_SENDMSG),
6359         BPF_EAPROG_SEC("cgroup/recvmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6360                                                 BPF_CGROUP_UDP4_RECVMSG),
6361         BPF_EAPROG_SEC("cgroup/recvmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6362                                                 BPF_CGROUP_UDP6_RECVMSG),
6363         BPF_EAPROG_SEC("cgroup/sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,
6364                                                 BPF_CGROUP_SYSCTL),
6365         BPF_EAPROG_SEC("cgroup/getsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
6366                                                 BPF_CGROUP_GETSOCKOPT),
6367         BPF_EAPROG_SEC("cgroup/setsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
6368                                                 BPF_CGROUP_SETSOCKOPT),
6369         BPF_PROG_SEC("struct_ops",              BPF_PROG_TYPE_STRUCT_OPS),
6370 };
6371
6372 #undef BPF_PROG_SEC_IMPL
6373 #undef BPF_PROG_SEC
6374 #undef BPF_APROG_SEC
6375 #undef BPF_EAPROG_SEC
6376 #undef BPF_APROG_COMPAT
6377 #undef SEC_DEF
6378
6379 #define MAX_TYPE_NAME_SIZE 32
6380
6381 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
6382 {
6383         int i, n = ARRAY_SIZE(section_defs);
6384
6385         for (i = 0; i < n; i++) {
6386                 if (strncmp(sec_name,
6387                             section_defs[i].sec, section_defs[i].len))
6388                         continue;
6389                 return &section_defs[i];
6390         }
6391         return NULL;
6392 }
6393
6394 static char *libbpf_get_type_names(bool attach_type)
6395 {
6396         int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
6397         char *buf;
6398
6399         buf = malloc(len);
6400         if (!buf)
6401                 return NULL;
6402
6403         buf[0] = '\0';
6404         /* Forge string buf with all available names */
6405         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6406                 if (attach_type && !section_defs[i].is_attachable)
6407                         continue;
6408
6409                 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
6410                         free(buf);
6411                         return NULL;
6412                 }
6413                 strcat(buf, " ");
6414                 strcat(buf, section_defs[i].sec);
6415         }
6416
6417         return buf;
6418 }
6419
6420 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
6421                              enum bpf_attach_type *expected_attach_type)
6422 {
6423         const struct bpf_sec_def *sec_def;
6424         char *type_names;
6425
6426         if (!name)
6427                 return -EINVAL;
6428
6429         sec_def = find_sec_def(name);
6430         if (sec_def) {
6431                 *prog_type = sec_def->prog_type;
6432                 *expected_attach_type = sec_def->expected_attach_type;
6433                 return 0;
6434         }
6435
6436         pr_debug("failed to guess program type from ELF section '%s'\n", name);
6437         type_names = libbpf_get_type_names(false);
6438         if (type_names != NULL) {
6439                 pr_debug("supported section(type) names are:%s\n", type_names);
6440                 free(type_names);
6441         }
6442
6443         return -ESRCH;
6444 }
6445
6446 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
6447                                                      size_t offset)
6448 {
6449         struct bpf_map *map;
6450         size_t i;
6451
6452         for (i = 0; i < obj->nr_maps; i++) {
6453                 map = &obj->maps[i];
6454                 if (!bpf_map__is_struct_ops(map))
6455                         continue;
6456                 if (map->sec_offset <= offset &&
6457                     offset - map->sec_offset < map->def.value_size)
6458                         return map;
6459         }
6460
6461         return NULL;
6462 }
6463
6464 /* Collect the reloc from ELF and populate the st_ops->progs[] */
6465 static int bpf_object__collect_struct_ops_map_reloc(struct bpf_object *obj,
6466                                                     GElf_Shdr *shdr,
6467                                                     Elf_Data *data)
6468 {
6469         const struct btf_member *member;
6470         struct bpf_struct_ops *st_ops;
6471         struct bpf_program *prog;
6472         unsigned int shdr_idx;
6473         const struct btf *btf;
6474         struct bpf_map *map;
6475         Elf_Data *symbols;
6476         unsigned int moff;
6477         const char *name;
6478         u32 member_idx;
6479         GElf_Sym sym;
6480         GElf_Rel rel;
6481         int i, nrels;
6482
6483         symbols = obj->efile.symbols;
6484         btf = obj->btf;
6485         nrels = shdr->sh_size / shdr->sh_entsize;
6486         for (i = 0; i < nrels; i++) {
6487                 if (!gelf_getrel(data, i, &rel)) {
6488                         pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
6489                         return -LIBBPF_ERRNO__FORMAT;
6490                 }
6491
6492                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
6493                         pr_warn("struct_ops reloc: symbol %zx not found\n",
6494                                 (size_t)GELF_R_SYM(rel.r_info));
6495                         return -LIBBPF_ERRNO__FORMAT;
6496                 }
6497
6498                 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
6499                                   sym.st_name) ? : "<?>";
6500                 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
6501                 if (!map) {
6502                         pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
6503                                 (size_t)rel.r_offset);
6504                         return -EINVAL;
6505                 }
6506
6507                 moff = rel.r_offset - map->sec_offset;
6508                 shdr_idx = sym.st_shndx;
6509                 st_ops = map->st_ops;
6510                 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",
6511                          map->name,
6512                          (long long)(rel.r_info >> 32),
6513                          (long long)sym.st_value,
6514                          shdr_idx, (size_t)rel.r_offset,
6515                          map->sec_offset, sym.st_name, name);
6516
6517                 if (shdr_idx >= SHN_LORESERVE) {
6518                         pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
6519                                 map->name, (size_t)rel.r_offset, shdr_idx);
6520                         return -LIBBPF_ERRNO__RELOC;
6521                 }
6522
6523                 member = find_member_by_offset(st_ops->type, moff * 8);
6524                 if (!member) {
6525                         pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
6526                                 map->name, moff);
6527                         return -EINVAL;
6528                 }
6529                 member_idx = member - btf_members(st_ops->type);
6530                 name = btf__name_by_offset(btf, member->name_off);
6531
6532                 if (!resolve_func_ptr(btf, member->type, NULL)) {
6533                         pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
6534                                 map->name, name);
6535                         return -EINVAL;
6536                 }
6537
6538                 prog = bpf_object__find_prog_by_idx(obj, shdr_idx);
6539                 if (!prog) {
6540                         pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
6541                                 map->name, shdr_idx, name);
6542                         return -EINVAL;
6543                 }
6544
6545                 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6546                         const struct bpf_sec_def *sec_def;
6547
6548                         sec_def = find_sec_def(prog->section_name);
6549                         if (sec_def &&
6550                             sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
6551                                 /* for pr_warn */
6552                                 prog->type = sec_def->prog_type;
6553                                 goto invalid_prog;
6554                         }
6555
6556                         prog->type = BPF_PROG_TYPE_STRUCT_OPS;
6557                         prog->attach_btf_id = st_ops->type_id;
6558                         prog->expected_attach_type = member_idx;
6559                 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
6560                            prog->attach_btf_id != st_ops->type_id ||
6561                            prog->expected_attach_type != member_idx) {
6562                         goto invalid_prog;
6563                 }
6564                 st_ops->progs[member_idx] = prog;
6565         }
6566
6567         return 0;
6568
6569 invalid_prog:
6570         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",
6571                 map->name, prog->name, prog->section_name, prog->type,
6572                 prog->attach_btf_id, prog->expected_attach_type, name);
6573         return -EINVAL;
6574 }
6575
6576 #define BTF_PREFIX "btf_trace_"
6577 int libbpf_find_vmlinux_btf_id(const char *name,
6578                                enum bpf_attach_type attach_type)
6579 {
6580         struct btf *btf = bpf_find_kernel_btf();
6581         char raw_tp_btf[128] = BTF_PREFIX;
6582         char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
6583         const char *btf_name;
6584         int err = -EINVAL;
6585         __u32 kind;
6586
6587         if (IS_ERR(btf)) {
6588                 pr_warn("vmlinux BTF is not found\n");
6589                 return -EINVAL;
6590         }
6591
6592         if (attach_type == BPF_TRACE_RAW_TP) {
6593                 /* prepend "btf_trace_" prefix per kernel convention */
6594                 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
6595                 btf_name = raw_tp_btf;
6596                 kind = BTF_KIND_TYPEDEF;
6597         } else {
6598                 btf_name = name;
6599                 kind = BTF_KIND_FUNC;
6600         }
6601         err = btf__find_by_name_kind(btf, btf_name, kind);
6602         btf__free(btf);
6603         return err;
6604 }
6605
6606 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
6607 {
6608         struct bpf_prog_info_linear *info_linear;
6609         struct bpf_prog_info *info;
6610         struct btf *btf = NULL;
6611         int err = -EINVAL;
6612
6613         info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
6614         if (IS_ERR_OR_NULL(info_linear)) {
6615                 pr_warn("failed get_prog_info_linear for FD %d\n",
6616                         attach_prog_fd);
6617                 return -EINVAL;
6618         }
6619         info = &info_linear->info;
6620         if (!info->btf_id) {
6621                 pr_warn("The target program doesn't have BTF\n");
6622                 goto out;
6623         }
6624         if (btf__get_from_id(info->btf_id, &btf)) {
6625                 pr_warn("Failed to get BTF of the program\n");
6626                 goto out;
6627         }
6628         err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
6629         btf__free(btf);
6630         if (err <= 0) {
6631                 pr_warn("%s is not found in prog's BTF\n", name);
6632                 goto out;
6633         }
6634 out:
6635         free(info_linear);
6636         return err;
6637 }
6638
6639 static int libbpf_find_attach_btf_id(const char *name,
6640                                      enum bpf_attach_type attach_type,
6641                                      __u32 attach_prog_fd)
6642 {
6643         int i, err;
6644
6645         if (!name)
6646                 return -EINVAL;
6647
6648         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6649                 if (!section_defs[i].is_attach_btf)
6650                         continue;
6651                 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6652                         continue;
6653                 if (attach_prog_fd)
6654                         err = libbpf_find_prog_btf_id(name + section_defs[i].len,
6655                                                       attach_prog_fd);
6656                 else
6657                         err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
6658                                                          attach_type);
6659                 if (err <= 0)
6660                         pr_warn("%s is not found in vmlinux BTF\n", name);
6661                 return err;
6662         }
6663         pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
6664         return -ESRCH;
6665 }
6666
6667 int libbpf_attach_type_by_name(const char *name,
6668                                enum bpf_attach_type *attach_type)
6669 {
6670         char *type_names;
6671         int i;
6672
6673         if (!name)
6674                 return -EINVAL;
6675
6676         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6677                 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
6678                         continue;
6679                 if (!section_defs[i].is_attachable)
6680                         return -EINVAL;
6681                 *attach_type = section_defs[i].attach_type;
6682                 return 0;
6683         }
6684         pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
6685         type_names = libbpf_get_type_names(true);
6686         if (type_names != NULL) {
6687                 pr_debug("attachable section(type) names are:%s\n", type_names);
6688                 free(type_names);
6689         }
6690
6691         return -EINVAL;
6692 }
6693
6694 int bpf_map__fd(const struct bpf_map *map)
6695 {
6696         return map ? map->fd : -EINVAL;
6697 }
6698
6699 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
6700 {
6701         return map ? &map->def : ERR_PTR(-EINVAL);
6702 }
6703
6704 const char *bpf_map__name(const struct bpf_map *map)
6705 {
6706         return map ? map->name : NULL;
6707 }
6708
6709 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
6710 {
6711         return map ? map->btf_key_type_id : 0;
6712 }
6713
6714 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
6715 {
6716         return map ? map->btf_value_type_id : 0;
6717 }
6718
6719 int bpf_map__set_priv(struct bpf_map *map, void *priv,
6720                      bpf_map_clear_priv_t clear_priv)
6721 {
6722         if (!map)
6723                 return -EINVAL;
6724
6725         if (map->priv) {
6726                 if (map->clear_priv)
6727                         map->clear_priv(map, map->priv);
6728         }
6729
6730         map->priv = priv;
6731         map->clear_priv = clear_priv;
6732         return 0;
6733 }
6734
6735 void *bpf_map__priv(const struct bpf_map *map)
6736 {
6737         return map ? map->priv : ERR_PTR(-EINVAL);
6738 }
6739
6740 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
6741 {
6742         return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
6743 }
6744
6745 bool bpf_map__is_internal(const struct bpf_map *map)
6746 {
6747         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
6748 }
6749
6750 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
6751 {
6752         map->map_ifindex = ifindex;
6753 }
6754
6755 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
6756 {
6757         if (!bpf_map_type__is_map_in_map(map->def.type)) {
6758                 pr_warn("error: unsupported map type\n");
6759                 return -EINVAL;
6760         }
6761         if (map->inner_map_fd != -1) {
6762                 pr_warn("error: inner_map_fd already specified\n");
6763                 return -EINVAL;
6764         }
6765         map->inner_map_fd = fd;
6766         return 0;
6767 }
6768
6769 static struct bpf_map *
6770 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
6771 {
6772         ssize_t idx;
6773         struct bpf_map *s, *e;
6774
6775         if (!obj || !obj->maps)
6776                 return NULL;
6777
6778         s = obj->maps;
6779         e = obj->maps + obj->nr_maps;
6780
6781         if ((m < s) || (m >= e)) {
6782                 pr_warn("error in %s: map handler doesn't belong to object\n",
6783                          __func__);
6784                 return NULL;
6785         }
6786
6787         idx = (m - obj->maps) + i;
6788         if (idx >= obj->nr_maps || idx < 0)
6789                 return NULL;
6790         return &obj->maps[idx];
6791 }
6792
6793 struct bpf_map *
6794 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
6795 {
6796         if (prev == NULL)
6797                 return obj->maps;
6798
6799         return __bpf_map__iter(prev, obj, 1);
6800 }
6801
6802 struct bpf_map *
6803 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
6804 {
6805         if (next == NULL) {
6806                 if (!obj->nr_maps)
6807                         return NULL;
6808                 return obj->maps + obj->nr_maps - 1;
6809         }
6810
6811         return __bpf_map__iter(next, obj, -1);
6812 }
6813
6814 struct bpf_map *
6815 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
6816 {
6817         struct bpf_map *pos;
6818
6819         bpf_object__for_each_map(pos, obj) {
6820                 if (pos->name && !strcmp(pos->name, name))
6821                         return pos;
6822         }
6823         return NULL;
6824 }
6825
6826 int
6827 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
6828 {
6829         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
6830 }
6831
6832 struct bpf_map *
6833 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
6834 {
6835         return ERR_PTR(-ENOTSUP);
6836 }
6837
6838 long libbpf_get_error(const void *ptr)
6839 {
6840         return PTR_ERR_OR_ZERO(ptr);
6841 }
6842
6843 int bpf_prog_load(const char *file, enum bpf_prog_type type,
6844                   struct bpf_object **pobj, int *prog_fd)
6845 {
6846         struct bpf_prog_load_attr attr;
6847
6848         memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
6849         attr.file = file;
6850         attr.prog_type = type;
6851         attr.expected_attach_type = 0;
6852
6853         return bpf_prog_load_xattr(&attr, pobj, prog_fd);
6854 }
6855
6856 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
6857                         struct bpf_object **pobj, int *prog_fd)
6858 {
6859         struct bpf_object_open_attr open_attr = {};
6860         struct bpf_program *prog, *first_prog = NULL;
6861         struct bpf_object *obj;
6862         struct bpf_map *map;
6863         int err;
6864
6865         if (!attr)
6866                 return -EINVAL;
6867         if (!attr->file)
6868                 return -EINVAL;
6869
6870         open_attr.file = attr->file;
6871         open_attr.prog_type = attr->prog_type;
6872
6873         obj = bpf_object__open_xattr(&open_attr);
6874         if (IS_ERR_OR_NULL(obj))
6875                 return -ENOENT;
6876
6877         bpf_object__for_each_program(prog, obj) {
6878                 enum bpf_attach_type attach_type = attr->expected_attach_type;
6879                 /*
6880                  * to preserve backwards compatibility, bpf_prog_load treats
6881                  * attr->prog_type, if specified, as an override to whatever
6882                  * bpf_object__open guessed
6883                  */
6884                 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
6885                         bpf_program__set_type(prog, attr->prog_type);
6886                         bpf_program__set_expected_attach_type(prog,
6887                                                               attach_type);
6888                 }
6889                 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
6890                         /*
6891                          * we haven't guessed from section name and user
6892                          * didn't provide a fallback type, too bad...
6893                          */
6894                         bpf_object__close(obj);
6895                         return -EINVAL;
6896                 }
6897
6898                 prog->prog_ifindex = attr->ifindex;
6899                 prog->log_level = attr->log_level;
6900                 prog->prog_flags = attr->prog_flags;
6901                 if (!first_prog)
6902                         first_prog = prog;
6903         }
6904
6905         bpf_object__for_each_map(map, obj) {
6906                 if (!bpf_map__is_offload_neutral(map))
6907                         map->map_ifindex = attr->ifindex;
6908         }
6909
6910         if (!first_prog) {
6911                 pr_warn("object file doesn't contain bpf program\n");
6912                 bpf_object__close(obj);
6913                 return -ENOENT;
6914         }
6915
6916         err = bpf_object__load(obj);
6917         if (err) {
6918                 bpf_object__close(obj);
6919                 return -EINVAL;
6920         }
6921
6922         *pobj = obj;
6923         *prog_fd = bpf_program__fd(first_prog);
6924         return 0;
6925 }
6926
6927 struct bpf_link {
6928         int (*detach)(struct bpf_link *link);
6929         int (*destroy)(struct bpf_link *link);
6930         bool disconnected;
6931 };
6932
6933 /* Release "ownership" of underlying BPF resource (typically, BPF program
6934  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
6935  * link, when destructed through bpf_link__destroy() call won't attempt to
6936  * detach/unregisted that BPF resource. This is useful in situations where,
6937  * say, attached BPF program has to outlive userspace program that attached it
6938  * in the system. Depending on type of BPF program, though, there might be
6939  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
6940  * exit of userspace program doesn't trigger automatic detachment and clean up
6941  * inside the kernel.
6942  */
6943 void bpf_link__disconnect(struct bpf_link *link)
6944 {
6945         link->disconnected = true;
6946 }
6947
6948 int bpf_link__destroy(struct bpf_link *link)
6949 {
6950         int err = 0;
6951
6952         if (!link)
6953                 return 0;
6954
6955         if (!link->disconnected && link->detach)
6956                 err = link->detach(link);
6957         if (link->destroy)
6958                 link->destroy(link);
6959         free(link);
6960
6961         return err;
6962 }
6963
6964 struct bpf_link_fd {
6965         struct bpf_link link; /* has to be at the top of struct */
6966         int fd; /* hook FD */
6967 };
6968
6969 static int bpf_link__detach_perf_event(struct bpf_link *link)
6970 {
6971         struct bpf_link_fd *l = (void *)link;
6972         int err;
6973
6974         err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
6975         if (err)
6976                 err = -errno;
6977
6978         close(l->fd);
6979         return err;
6980 }
6981
6982 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
6983                                                 int pfd)
6984 {
6985         char errmsg[STRERR_BUFSIZE];
6986         struct bpf_link_fd *link;
6987         int prog_fd, err;
6988
6989         if (pfd < 0) {
6990                 pr_warn("program '%s': invalid perf event FD %d\n",
6991                         bpf_program__title(prog, false), pfd);
6992                 return ERR_PTR(-EINVAL);
6993         }
6994         prog_fd = bpf_program__fd(prog);
6995         if (prog_fd < 0) {
6996                 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6997                         bpf_program__title(prog, false));
6998                 return ERR_PTR(-EINVAL);
6999         }
7000
7001         link = calloc(1, sizeof(*link));
7002         if (!link)
7003                 return ERR_PTR(-ENOMEM);
7004         link->link.detach = &bpf_link__detach_perf_event;
7005         link->fd = pfd;
7006
7007         if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
7008                 err = -errno;
7009                 free(link);
7010                 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
7011                         bpf_program__title(prog, false), pfd,
7012                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7013                 return ERR_PTR(err);
7014         }
7015         if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7016                 err = -errno;
7017                 free(link);
7018                 pr_warn("program '%s': failed to enable pfd %d: %s\n",
7019                         bpf_program__title(prog, false), pfd,
7020                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7021                 return ERR_PTR(err);
7022         }
7023         return (struct bpf_link *)link;
7024 }
7025
7026 /*
7027  * this function is expected to parse integer in the range of [0, 2^31-1] from
7028  * given file using scanf format string fmt. If actual parsed value is
7029  * negative, the result might be indistinguishable from error
7030  */
7031 static int parse_uint_from_file(const char *file, const char *fmt)
7032 {
7033         char buf[STRERR_BUFSIZE];
7034         int err, ret;
7035         FILE *f;
7036
7037         f = fopen(file, "r");
7038         if (!f) {
7039                 err = -errno;
7040                 pr_debug("failed to open '%s': %s\n", file,
7041                          libbpf_strerror_r(err, buf, sizeof(buf)));
7042                 return err;
7043         }
7044         err = fscanf(f, fmt, &ret);
7045         if (err != 1) {
7046                 err = err == EOF ? -EIO : -errno;
7047                 pr_debug("failed to parse '%s': %s\n", file,
7048                         libbpf_strerror_r(err, buf, sizeof(buf)));
7049                 fclose(f);
7050                 return err;
7051         }
7052         fclose(f);
7053         return ret;
7054 }
7055
7056 static int determine_kprobe_perf_type(void)
7057 {
7058         const char *file = "/sys/bus/event_source/devices/kprobe/type";
7059
7060         return parse_uint_from_file(file, "%d\n");
7061 }
7062
7063 static int determine_uprobe_perf_type(void)
7064 {
7065         const char *file = "/sys/bus/event_source/devices/uprobe/type";
7066
7067         return parse_uint_from_file(file, "%d\n");
7068 }
7069
7070 static int determine_kprobe_retprobe_bit(void)
7071 {
7072         const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
7073
7074         return parse_uint_from_file(file, "config:%d\n");
7075 }
7076
7077 static int determine_uprobe_retprobe_bit(void)
7078 {
7079         const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
7080
7081         return parse_uint_from_file(file, "config:%d\n");
7082 }
7083
7084 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
7085                                  uint64_t offset, int pid)
7086 {
7087         struct perf_event_attr attr = {};
7088         char errmsg[STRERR_BUFSIZE];
7089         int type, pfd, err;
7090
7091         type = uprobe ? determine_uprobe_perf_type()
7092                       : determine_kprobe_perf_type();
7093         if (type < 0) {
7094                 pr_warn("failed to determine %s perf type: %s\n",
7095                         uprobe ? "uprobe" : "kprobe",
7096                         libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
7097                 return type;
7098         }
7099         if (retprobe) {
7100                 int bit = uprobe ? determine_uprobe_retprobe_bit()
7101                                  : determine_kprobe_retprobe_bit();
7102
7103                 if (bit < 0) {
7104                         pr_warn("failed to determine %s retprobe bit: %s\n",
7105                                 uprobe ? "uprobe" : "kprobe",
7106                                 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
7107                         return bit;
7108                 }
7109                 attr.config |= 1 << bit;
7110         }
7111         attr.size = sizeof(attr);
7112         attr.type = type;
7113         attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
7114         attr.config2 = offset;           /* kprobe_addr or probe_offset */
7115
7116         /* pid filter is meaningful only for uprobes */
7117         pfd = syscall(__NR_perf_event_open, &attr,
7118                       pid < 0 ? -1 : pid /* pid */,
7119                       pid == -1 ? 0 : -1 /* cpu */,
7120                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7121         if (pfd < 0) {
7122                 err = -errno;
7123                 pr_warn("%s perf_event_open() failed: %s\n",
7124                         uprobe ? "uprobe" : "kprobe",
7125                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7126                 return err;
7127         }
7128         return pfd;
7129 }
7130
7131 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
7132                                             bool retprobe,
7133                                             const char *func_name)
7134 {
7135         char errmsg[STRERR_BUFSIZE];
7136         struct bpf_link *link;
7137         int pfd, err;
7138
7139         pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
7140                                     0 /* offset */, -1 /* pid */);
7141         if (pfd < 0) {
7142                 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
7143                         bpf_program__title(prog, false),
7144                         retprobe ? "kretprobe" : "kprobe", func_name,
7145                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7146                 return ERR_PTR(pfd);
7147         }
7148         link = bpf_program__attach_perf_event(prog, pfd);
7149         if (IS_ERR(link)) {
7150                 close(pfd);
7151                 err = PTR_ERR(link);
7152                 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
7153                         bpf_program__title(prog, false),
7154                         retprobe ? "kretprobe" : "kprobe", func_name,
7155                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7156                 return link;
7157         }
7158         return link;
7159 }
7160
7161 static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7162                                       struct bpf_program *prog)
7163 {
7164         const char *func_name;
7165         bool retprobe;
7166
7167         func_name = bpf_program__title(prog, false) + sec->len;
7168         retprobe = strcmp(sec->sec, "kretprobe/") == 0;
7169
7170         return bpf_program__attach_kprobe(prog, retprobe, func_name);
7171 }
7172
7173 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
7174                                             bool retprobe, pid_t pid,
7175                                             const char *binary_path,
7176                                             size_t func_offset)
7177 {
7178         char errmsg[STRERR_BUFSIZE];
7179         struct bpf_link *link;
7180         int pfd, err;
7181
7182         pfd = perf_event_open_probe(true /* uprobe */, retprobe,
7183                                     binary_path, func_offset, pid);
7184         if (pfd < 0) {
7185                 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
7186                         bpf_program__title(prog, false),
7187                         retprobe ? "uretprobe" : "uprobe",
7188                         binary_path, func_offset,
7189                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7190                 return ERR_PTR(pfd);
7191         }
7192         link = bpf_program__attach_perf_event(prog, pfd);
7193         if (IS_ERR(link)) {
7194                 close(pfd);
7195                 err = PTR_ERR(link);
7196                 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
7197                         bpf_program__title(prog, false),
7198                         retprobe ? "uretprobe" : "uprobe",
7199                         binary_path, func_offset,
7200                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7201                 return link;
7202         }
7203         return link;
7204 }
7205
7206 static int determine_tracepoint_id(const char *tp_category,
7207                                    const char *tp_name)
7208 {
7209         char file[PATH_MAX];
7210         int ret;
7211
7212         ret = snprintf(file, sizeof(file),
7213                        "/sys/kernel/debug/tracing/events/%s/%s/id",
7214                        tp_category, tp_name);
7215         if (ret < 0)
7216                 return -errno;
7217         if (ret >= sizeof(file)) {
7218                 pr_debug("tracepoint %s/%s path is too long\n",
7219                          tp_category, tp_name);
7220                 return -E2BIG;
7221         }
7222         return parse_uint_from_file(file, "%d\n");
7223 }
7224
7225 static int perf_event_open_tracepoint(const char *tp_category,
7226                                       const char *tp_name)
7227 {
7228         struct perf_event_attr attr = {};
7229         char errmsg[STRERR_BUFSIZE];
7230         int tp_id, pfd, err;
7231
7232         tp_id = determine_tracepoint_id(tp_category, tp_name);
7233         if (tp_id < 0) {
7234                 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
7235                         tp_category, tp_name,
7236                         libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
7237                 return tp_id;
7238         }
7239
7240         attr.type = PERF_TYPE_TRACEPOINT;
7241         attr.size = sizeof(attr);
7242         attr.config = tp_id;
7243
7244         pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
7245                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7246         if (pfd < 0) {
7247                 err = -errno;
7248                 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
7249                         tp_category, tp_name,
7250                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7251                 return err;
7252         }
7253         return pfd;
7254 }
7255
7256 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
7257                                                 const char *tp_category,
7258                                                 const char *tp_name)
7259 {
7260         char errmsg[STRERR_BUFSIZE];
7261         struct bpf_link *link;
7262         int pfd, err;
7263
7264         pfd = perf_event_open_tracepoint(tp_category, tp_name);
7265         if (pfd < 0) {
7266                 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
7267                         bpf_program__title(prog, false),
7268                         tp_category, tp_name,
7269                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7270                 return ERR_PTR(pfd);
7271         }
7272         link = bpf_program__attach_perf_event(prog, pfd);
7273         if (IS_ERR(link)) {
7274                 close(pfd);
7275                 err = PTR_ERR(link);
7276                 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
7277                         bpf_program__title(prog, false),
7278                         tp_category, tp_name,
7279                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7280                 return link;
7281         }
7282         return link;
7283 }
7284
7285 static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
7286                                   struct bpf_program *prog)
7287 {
7288         char *sec_name, *tp_cat, *tp_name;
7289         struct bpf_link *link;
7290
7291         sec_name = strdup(bpf_program__title(prog, false));
7292         if (!sec_name)
7293                 return ERR_PTR(-ENOMEM);
7294
7295         /* extract "tp/<category>/<name>" */
7296         tp_cat = sec_name + sec->len;
7297         tp_name = strchr(tp_cat, '/');
7298         if (!tp_name) {
7299                 link = ERR_PTR(-EINVAL);
7300                 goto out;
7301         }
7302         *tp_name = '\0';
7303         tp_name++;
7304
7305         link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
7306 out:
7307         free(sec_name);
7308         return link;
7309 }
7310
7311 static int bpf_link__detach_fd(struct bpf_link *link)
7312 {
7313         struct bpf_link_fd *l = (void *)link;
7314
7315         return close(l->fd);
7316 }
7317
7318 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
7319                                                     const char *tp_name)
7320 {
7321         char errmsg[STRERR_BUFSIZE];
7322         struct bpf_link_fd *link;
7323         int prog_fd, pfd;
7324
7325         prog_fd = bpf_program__fd(prog);
7326         if (prog_fd < 0) {
7327                 pr_warn("program '%s': can't attach before loaded\n",
7328                         bpf_program__title(prog, false));
7329                 return ERR_PTR(-EINVAL);
7330         }
7331
7332         link = calloc(1, sizeof(*link));
7333         if (!link)
7334                 return ERR_PTR(-ENOMEM);
7335         link->link.detach = &bpf_link__detach_fd;
7336
7337         pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
7338         if (pfd < 0) {
7339                 pfd = -errno;
7340                 free(link);
7341                 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
7342                         bpf_program__title(prog, false), tp_name,
7343                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7344                 return ERR_PTR(pfd);
7345         }
7346         link->fd = pfd;
7347         return (struct bpf_link *)link;
7348 }
7349
7350 static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
7351                                       struct bpf_program *prog)
7352 {
7353         const char *tp_name = bpf_program__title(prog, false) + sec->len;
7354
7355         return bpf_program__attach_raw_tracepoint(prog, tp_name);
7356 }
7357
7358 struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
7359 {
7360         char errmsg[STRERR_BUFSIZE];
7361         struct bpf_link_fd *link;
7362         int prog_fd, pfd;
7363
7364         prog_fd = bpf_program__fd(prog);
7365         if (prog_fd < 0) {
7366                 pr_warn("program '%s': can't attach before loaded\n",
7367                         bpf_program__title(prog, false));
7368                 return ERR_PTR(-EINVAL);
7369         }
7370
7371         link = calloc(1, sizeof(*link));
7372         if (!link)
7373                 return ERR_PTR(-ENOMEM);
7374         link->link.detach = &bpf_link__detach_fd;
7375
7376         pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
7377         if (pfd < 0) {
7378                 pfd = -errno;
7379                 free(link);
7380                 pr_warn("program '%s': failed to attach to trace: %s\n",
7381                         bpf_program__title(prog, false),
7382                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7383                 return ERR_PTR(pfd);
7384         }
7385         link->fd = pfd;
7386         return (struct bpf_link *)link;
7387 }
7388
7389 static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
7390                                      struct bpf_program *prog)
7391 {
7392         return bpf_program__attach_trace(prog);
7393 }
7394
7395 struct bpf_link *bpf_program__attach(struct bpf_program *prog)
7396 {
7397         const struct bpf_sec_def *sec_def;
7398
7399         sec_def = find_sec_def(bpf_program__title(prog, false));
7400         if (!sec_def || !sec_def->attach_fn)
7401                 return ERR_PTR(-ESRCH);
7402
7403         return sec_def->attach_fn(sec_def, prog);
7404 }
7405
7406 static int bpf_link__detach_struct_ops(struct bpf_link *link)
7407 {
7408         struct bpf_link_fd *l = (void *)link;
7409         __u32 zero = 0;
7410
7411         if (bpf_map_delete_elem(l->fd, &zero))
7412                 return -errno;
7413
7414         return 0;
7415 }
7416
7417 struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
7418 {
7419         struct bpf_struct_ops *st_ops;
7420         struct bpf_link_fd *link;
7421         __u32 i, zero = 0;
7422         int err;
7423
7424         if (!bpf_map__is_struct_ops(map) || map->fd == -1)
7425                 return ERR_PTR(-EINVAL);
7426
7427         link = calloc(1, sizeof(*link));
7428         if (!link)
7429                 return ERR_PTR(-EINVAL);
7430
7431         st_ops = map->st_ops;
7432         for (i = 0; i < btf_vlen(st_ops->type); i++) {
7433                 struct bpf_program *prog = st_ops->progs[i];
7434                 void *kern_data;
7435                 int prog_fd;
7436
7437                 if (!prog)
7438                         continue;
7439
7440                 prog_fd = bpf_program__fd(prog);
7441                 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7442                 *(unsigned long *)kern_data = prog_fd;
7443         }
7444
7445         err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
7446         if (err) {
7447                 err = -errno;
7448                 free(link);
7449                 return ERR_PTR(err);
7450         }
7451
7452         link->link.detach = bpf_link__detach_struct_ops;
7453         link->fd = map->fd;
7454
7455         return (struct bpf_link *)link;
7456 }
7457
7458 enum bpf_perf_event_ret
7459 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
7460                            void **copy_mem, size_t *copy_size,
7461                            bpf_perf_event_print_t fn, void *private_data)
7462 {
7463         struct perf_event_mmap_page *header = mmap_mem;
7464         __u64 data_head = ring_buffer_read_head(header);
7465         __u64 data_tail = header->data_tail;
7466         void *base = ((__u8 *)header) + page_size;
7467         int ret = LIBBPF_PERF_EVENT_CONT;
7468         struct perf_event_header *ehdr;
7469         size_t ehdr_size;
7470
7471         while (data_head != data_tail) {
7472                 ehdr = base + (data_tail & (mmap_size - 1));
7473                 ehdr_size = ehdr->size;
7474
7475                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
7476                         void *copy_start = ehdr;
7477                         size_t len_first = base + mmap_size - copy_start;
7478                         size_t len_secnd = ehdr_size - len_first;
7479
7480                         if (*copy_size < ehdr_size) {
7481                                 free(*copy_mem);
7482                                 *copy_mem = malloc(ehdr_size);
7483                                 if (!*copy_mem) {
7484                                         *copy_size = 0;
7485                                         ret = LIBBPF_PERF_EVENT_ERROR;
7486                                         break;
7487                                 }
7488                                 *copy_size = ehdr_size;
7489                         }
7490
7491                         memcpy(*copy_mem, copy_start, len_first);
7492                         memcpy(*copy_mem + len_first, base, len_secnd);
7493                         ehdr = *copy_mem;
7494                 }
7495
7496                 ret = fn(ehdr, private_data);
7497                 data_tail += ehdr_size;
7498                 if (ret != LIBBPF_PERF_EVENT_CONT)
7499                         break;
7500         }
7501
7502         ring_buffer_write_tail(header, data_tail);
7503         return ret;
7504 }
7505
7506 struct perf_buffer;
7507
7508 struct perf_buffer_params {
7509         struct perf_event_attr *attr;
7510         /* if event_cb is specified, it takes precendence */
7511         perf_buffer_event_fn event_cb;
7512         /* sample_cb and lost_cb are higher-level common-case callbacks */
7513         perf_buffer_sample_fn sample_cb;
7514         perf_buffer_lost_fn lost_cb;
7515         void *ctx;
7516         int cpu_cnt;
7517         int *cpus;
7518         int *map_keys;
7519 };
7520
7521 struct perf_cpu_buf {
7522         struct perf_buffer *pb;
7523         void *base; /* mmap()'ed memory */
7524         void *buf; /* for reconstructing segmented data */
7525         size_t buf_size;
7526         int fd;
7527         int cpu;
7528         int map_key;
7529 };
7530
7531 struct perf_buffer {
7532         perf_buffer_event_fn event_cb;
7533         perf_buffer_sample_fn sample_cb;
7534         perf_buffer_lost_fn lost_cb;
7535         void *ctx; /* passed into callbacks */
7536
7537         size_t page_size;
7538         size_t mmap_size;
7539         struct perf_cpu_buf **cpu_bufs;
7540         struct epoll_event *events;
7541         int cpu_cnt; /* number of allocated CPU buffers */
7542         int epoll_fd; /* perf event FD */
7543         int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
7544 };
7545
7546 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
7547                                       struct perf_cpu_buf *cpu_buf)
7548 {
7549         if (!cpu_buf)
7550                 return;
7551         if (cpu_buf->base &&
7552             munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
7553                 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
7554         if (cpu_buf->fd >= 0) {
7555                 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
7556                 close(cpu_buf->fd);
7557         }
7558         free(cpu_buf->buf);
7559         free(cpu_buf);
7560 }
7561
7562 void perf_buffer__free(struct perf_buffer *pb)
7563 {
7564         int i;
7565
7566         if (!pb)
7567                 return;
7568         if (pb->cpu_bufs) {
7569                 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
7570                         struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
7571
7572                         bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
7573                         perf_buffer__free_cpu_buf(pb, cpu_buf);
7574                 }
7575                 free(pb->cpu_bufs);
7576         }
7577         if (pb->epoll_fd >= 0)
7578                 close(pb->epoll_fd);
7579         free(pb->events);
7580         free(pb);
7581 }
7582
7583 static struct perf_cpu_buf *
7584 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
7585                           int cpu, int map_key)
7586 {
7587         struct perf_cpu_buf *cpu_buf;
7588         char msg[STRERR_BUFSIZE];
7589         int err;
7590
7591         cpu_buf = calloc(1, sizeof(*cpu_buf));
7592         if (!cpu_buf)
7593                 return ERR_PTR(-ENOMEM);
7594
7595         cpu_buf->pb = pb;
7596         cpu_buf->cpu = cpu;
7597         cpu_buf->map_key = map_key;
7598
7599         cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
7600                               -1, PERF_FLAG_FD_CLOEXEC);
7601         if (cpu_buf->fd < 0) {
7602                 err = -errno;
7603                 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
7604                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
7605                 goto error;
7606         }
7607
7608         cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
7609                              PROT_READ | PROT_WRITE, MAP_SHARED,
7610                              cpu_buf->fd, 0);
7611         if (cpu_buf->base == MAP_FAILED) {
7612                 cpu_buf->base = NULL;
7613                 err = -errno;
7614                 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
7615                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
7616                 goto error;
7617         }
7618
7619         if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7620                 err = -errno;
7621                 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
7622                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
7623                 goto error;
7624         }
7625
7626         return cpu_buf;
7627
7628 error:
7629         perf_buffer__free_cpu_buf(pb, cpu_buf);
7630         return (struct perf_cpu_buf *)ERR_PTR(err);
7631 }
7632
7633 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
7634                                               struct perf_buffer_params *p);
7635
7636 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
7637                                      const struct perf_buffer_opts *opts)
7638 {
7639         struct perf_buffer_params p = {};
7640         struct perf_event_attr attr = { 0, };
7641
7642         attr.config = PERF_COUNT_SW_BPF_OUTPUT,
7643         attr.type = PERF_TYPE_SOFTWARE;
7644         attr.sample_type = PERF_SAMPLE_RAW;
7645         attr.sample_period = 1;
7646         attr.wakeup_events = 1;
7647
7648         p.attr = &attr;
7649         p.sample_cb = opts ? opts->sample_cb : NULL;
7650         p.lost_cb = opts ? opts->lost_cb : NULL;
7651         p.ctx = opts ? opts->ctx : NULL;
7652
7653         return __perf_buffer__new(map_fd, page_cnt, &p);
7654 }
7655
7656 struct perf_buffer *
7657 perf_buffer__new_raw(int map_fd, size_t page_cnt,
7658                      const struct perf_buffer_raw_opts *opts)
7659 {
7660         struct perf_buffer_params p = {};
7661
7662         p.attr = opts->attr;
7663         p.event_cb = opts->event_cb;
7664         p.ctx = opts->ctx;
7665         p.cpu_cnt = opts->cpu_cnt;
7666         p.cpus = opts->cpus;
7667         p.map_keys = opts->map_keys;
7668
7669         return __perf_buffer__new(map_fd, page_cnt, &p);
7670 }
7671
7672 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
7673                                               struct perf_buffer_params *p)
7674 {
7675         const char *online_cpus_file = "/sys/devices/system/cpu/online";
7676         struct bpf_map_info map = {};
7677         char msg[STRERR_BUFSIZE];
7678         struct perf_buffer *pb;
7679         bool *online = NULL;
7680         __u32 map_info_len;
7681         int err, i, j, n;
7682
7683         if (page_cnt & (page_cnt - 1)) {
7684                 pr_warn("page count should be power of two, but is %zu\n",
7685                         page_cnt);
7686                 return ERR_PTR(-EINVAL);
7687         }
7688
7689         map_info_len = sizeof(map);
7690         err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
7691         if (err) {
7692                 err = -errno;
7693                 pr_warn("failed to get map info for map FD %d: %s\n",
7694                         map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
7695                 return ERR_PTR(err);
7696         }
7697
7698         if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
7699                 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
7700                         map.name);
7701                 return ERR_PTR(-EINVAL);
7702         }
7703
7704         pb = calloc(1, sizeof(*pb));
7705         if (!pb)
7706                 return ERR_PTR(-ENOMEM);
7707
7708         pb->event_cb = p->event_cb;
7709         pb->sample_cb = p->sample_cb;
7710         pb->lost_cb = p->lost_cb;
7711         pb->ctx = p->ctx;
7712
7713         pb->page_size = getpagesize();
7714         pb->mmap_size = pb->page_size * page_cnt;
7715         pb->map_fd = map_fd;
7716
7717         pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
7718         if (pb->epoll_fd < 0) {
7719                 err = -errno;
7720                 pr_warn("failed to create epoll instance: %s\n",
7721                         libbpf_strerror_r(err, msg, sizeof(msg)));
7722                 goto error;
7723         }
7724
7725         if (p->cpu_cnt > 0) {
7726                 pb->cpu_cnt = p->cpu_cnt;
7727         } else {
7728                 pb->cpu_cnt = libbpf_num_possible_cpus();
7729                 if (pb->cpu_cnt < 0) {
7730                         err = pb->cpu_cnt;
7731                         goto error;
7732                 }
7733                 if (map.max_entries < pb->cpu_cnt)
7734                         pb->cpu_cnt = map.max_entries;
7735         }
7736
7737         pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
7738         if (!pb->events) {
7739                 err = -ENOMEM;
7740                 pr_warn("failed to allocate events: out of memory\n");
7741                 goto error;
7742         }
7743         pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
7744         if (!pb->cpu_bufs) {
7745                 err = -ENOMEM;
7746                 pr_warn("failed to allocate buffers: out of memory\n");
7747                 goto error;
7748         }
7749
7750         err = parse_cpu_mask_file(online_cpus_file, &online, &n);
7751         if (err) {
7752                 pr_warn("failed to get online CPU mask: %d\n", err);
7753                 goto error;
7754         }
7755
7756         for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
7757                 struct perf_cpu_buf *cpu_buf;
7758                 int cpu, map_key;
7759
7760                 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
7761                 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
7762
7763                 /* in case user didn't explicitly requested particular CPUs to
7764                  * be attached to, skip offline/not present CPUs
7765                  */
7766                 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
7767                         continue;
7768
7769                 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
7770                 if (IS_ERR(cpu_buf)) {
7771                         err = PTR_ERR(cpu_buf);
7772                         goto error;
7773                 }
7774
7775                 pb->cpu_bufs[j] = cpu_buf;
7776
7777                 err = bpf_map_update_elem(pb->map_fd, &map_key,
7778                                           &cpu_buf->fd, 0);
7779                 if (err) {
7780                         err = -errno;
7781                         pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7782                                 cpu, map_key, cpu_buf->fd,
7783                                 libbpf_strerror_r(err, msg, sizeof(msg)));
7784                         goto error;
7785                 }
7786
7787                 pb->events[j].events = EPOLLIN;
7788                 pb->events[j].data.ptr = cpu_buf;
7789                 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
7790                               &pb->events[j]) < 0) {
7791                         err = -errno;
7792                         pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7793                                 cpu, cpu_buf->fd,
7794                                 libbpf_strerror_r(err, msg, sizeof(msg)));
7795                         goto error;
7796                 }
7797                 j++;
7798         }
7799         pb->cpu_cnt = j;
7800         free(online);
7801
7802         return pb;
7803
7804 error:
7805         free(online);
7806         if (pb)
7807                 perf_buffer__free(pb);
7808         return ERR_PTR(err);
7809 }
7810
7811 struct perf_sample_raw {
7812         struct perf_event_header header;
7813         uint32_t size;
7814         char data[0];
7815 };
7816
7817 struct perf_sample_lost {
7818         struct perf_event_header header;
7819         uint64_t id;
7820         uint64_t lost;
7821         uint64_t sample_id;
7822 };
7823
7824 static enum bpf_perf_event_ret
7825 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
7826 {
7827         struct perf_cpu_buf *cpu_buf = ctx;
7828         struct perf_buffer *pb = cpu_buf->pb;
7829         void *data = e;
7830
7831         /* user wants full control over parsing perf event */
7832         if (pb->event_cb)
7833                 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
7834
7835         switch (e->type) {
7836         case PERF_RECORD_SAMPLE: {
7837                 struct perf_sample_raw *s = data;
7838
7839                 if (pb->sample_cb)
7840                         pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
7841                 break;
7842         }
7843         case PERF_RECORD_LOST: {
7844                 struct perf_sample_lost *s = data;
7845
7846                 if (pb->lost_cb)
7847                         pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
7848                 break;
7849         }
7850         default:
7851                 pr_warn("unknown perf sample type %d\n", e->type);
7852                 return LIBBPF_PERF_EVENT_ERROR;
7853         }
7854         return LIBBPF_PERF_EVENT_CONT;
7855 }
7856
7857 static int perf_buffer__process_records(struct perf_buffer *pb,
7858                                         struct perf_cpu_buf *cpu_buf)
7859 {
7860         enum bpf_perf_event_ret ret;
7861
7862         ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
7863                                          pb->page_size, &cpu_buf->buf,
7864                                          &cpu_buf->buf_size,
7865                                          perf_buffer__process_record, cpu_buf);
7866         if (ret != LIBBPF_PERF_EVENT_CONT)
7867                 return ret;
7868         return 0;
7869 }
7870
7871 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
7872 {
7873         int i, cnt, err;
7874
7875         cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
7876         for (i = 0; i < cnt; i++) {
7877                 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
7878
7879                 err = perf_buffer__process_records(pb, cpu_buf);
7880                 if (err) {
7881                         pr_warn("error while processing records: %d\n", err);
7882                         return err;
7883                 }
7884         }
7885         return cnt < 0 ? -errno : cnt;
7886 }
7887
7888 struct bpf_prog_info_array_desc {
7889         int     array_offset;   /* e.g. offset of jited_prog_insns */
7890         int     count_offset;   /* e.g. offset of jited_prog_len */
7891         int     size_offset;    /* > 0: offset of rec size,
7892                                  * < 0: fix size of -size_offset
7893                                  */
7894 };
7895
7896 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
7897         [BPF_PROG_INFO_JITED_INSNS] = {
7898                 offsetof(struct bpf_prog_info, jited_prog_insns),
7899                 offsetof(struct bpf_prog_info, jited_prog_len),
7900                 -1,
7901         },
7902         [BPF_PROG_INFO_XLATED_INSNS] = {
7903                 offsetof(struct bpf_prog_info, xlated_prog_insns),
7904                 offsetof(struct bpf_prog_info, xlated_prog_len),
7905                 -1,
7906         },
7907         [BPF_PROG_INFO_MAP_IDS] = {
7908                 offsetof(struct bpf_prog_info, map_ids),
7909                 offsetof(struct bpf_prog_info, nr_map_ids),
7910                 -(int)sizeof(__u32),
7911         },
7912         [BPF_PROG_INFO_JITED_KSYMS] = {
7913                 offsetof(struct bpf_prog_info, jited_ksyms),
7914                 offsetof(struct bpf_prog_info, nr_jited_ksyms),
7915                 -(int)sizeof(__u64),
7916         },
7917         [BPF_PROG_INFO_JITED_FUNC_LENS] = {
7918                 offsetof(struct bpf_prog_info, jited_func_lens),
7919                 offsetof(struct bpf_prog_info, nr_jited_func_lens),
7920                 -(int)sizeof(__u32),
7921         },
7922         [BPF_PROG_INFO_FUNC_INFO] = {
7923                 offsetof(struct bpf_prog_info, func_info),
7924                 offsetof(struct bpf_prog_info, nr_func_info),
7925                 offsetof(struct bpf_prog_info, func_info_rec_size),
7926         },
7927         [BPF_PROG_INFO_LINE_INFO] = {
7928                 offsetof(struct bpf_prog_info, line_info),
7929                 offsetof(struct bpf_prog_info, nr_line_info),
7930                 offsetof(struct bpf_prog_info, line_info_rec_size),
7931         },
7932         [BPF_PROG_INFO_JITED_LINE_INFO] = {
7933                 offsetof(struct bpf_prog_info, jited_line_info),
7934                 offsetof(struct bpf_prog_info, nr_jited_line_info),
7935                 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
7936         },
7937         [BPF_PROG_INFO_PROG_TAGS] = {
7938                 offsetof(struct bpf_prog_info, prog_tags),
7939                 offsetof(struct bpf_prog_info, nr_prog_tags),
7940                 -(int)sizeof(__u8) * BPF_TAG_SIZE,
7941         },
7942
7943 };
7944
7945 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
7946                                            int offset)
7947 {
7948         __u32 *array = (__u32 *)info;
7949
7950         if (offset >= 0)
7951                 return array[offset / sizeof(__u32)];
7952         return -(int)offset;
7953 }
7954
7955 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
7956                                            int offset)
7957 {
7958         __u64 *array = (__u64 *)info;
7959
7960         if (offset >= 0)
7961                 return array[offset / sizeof(__u64)];
7962         return -(int)offset;
7963 }
7964
7965 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
7966                                          __u32 val)
7967 {
7968         __u32 *array = (__u32 *)info;
7969
7970         if (offset >= 0)
7971                 array[offset / sizeof(__u32)] = val;
7972 }
7973
7974 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
7975                                          __u64 val)
7976 {
7977         __u64 *array = (__u64 *)info;
7978
7979         if (offset >= 0)
7980                 array[offset / sizeof(__u64)] = val;
7981 }
7982
7983 struct bpf_prog_info_linear *
7984 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
7985 {
7986         struct bpf_prog_info_linear *info_linear;
7987         struct bpf_prog_info info = {};
7988         __u32 info_len = sizeof(info);
7989         __u32 data_len = 0;
7990         int i, err;
7991         void *ptr;
7992
7993         if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
7994                 return ERR_PTR(-EINVAL);
7995
7996         /* step 1: get array dimensions */
7997         err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
7998         if (err) {
7999                 pr_debug("can't get prog info: %s", strerror(errno));
8000                 return ERR_PTR(-EFAULT);
8001         }
8002
8003         /* step 2: calculate total size of all arrays */
8004         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8005                 bool include_array = (arrays & (1UL << i)) > 0;
8006                 struct bpf_prog_info_array_desc *desc;
8007                 __u32 count, size;
8008
8009                 desc = bpf_prog_info_array_desc + i;
8010
8011                 /* kernel is too old to support this field */
8012                 if (info_len < desc->array_offset + sizeof(__u32) ||
8013                     info_len < desc->count_offset + sizeof(__u32) ||
8014                     (desc->size_offset > 0 && info_len < desc->size_offset))
8015                         include_array = false;
8016
8017                 if (!include_array) {
8018                         arrays &= ~(1UL << i);  /* clear the bit */
8019                         continue;
8020                 }
8021
8022                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8023                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8024
8025                 data_len += count * size;
8026         }
8027
8028         /* step 3: allocate continuous memory */
8029         data_len = roundup(data_len, sizeof(__u64));
8030         info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
8031         if (!info_linear)
8032                 return ERR_PTR(-ENOMEM);
8033
8034         /* step 4: fill data to info_linear->info */
8035         info_linear->arrays = arrays;
8036         memset(&info_linear->info, 0, sizeof(info));
8037         ptr = info_linear->data;
8038
8039         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8040                 struct bpf_prog_info_array_desc *desc;
8041                 __u32 count, size;
8042
8043                 if ((arrays & (1UL << i)) == 0)
8044                         continue;
8045
8046                 desc  = bpf_prog_info_array_desc + i;
8047                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8048                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8049                 bpf_prog_info_set_offset_u32(&info_linear->info,
8050                                              desc->count_offset, count);
8051                 bpf_prog_info_set_offset_u32(&info_linear->info,
8052                                              desc->size_offset, size);
8053                 bpf_prog_info_set_offset_u64(&info_linear->info,
8054                                              desc->array_offset,
8055                                              ptr_to_u64(ptr));
8056                 ptr += count * size;
8057         }
8058
8059         /* step 5: call syscall again to get required arrays */
8060         err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
8061         if (err) {
8062                 pr_debug("can't get prog info: %s", strerror(errno));
8063                 free(info_linear);
8064                 return ERR_PTR(-EFAULT);
8065         }
8066
8067         /* step 6: verify the data */
8068         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8069                 struct bpf_prog_info_array_desc *desc;
8070                 __u32 v1, v2;
8071
8072                 if ((arrays & (1UL << i)) == 0)
8073                         continue;
8074
8075                 desc = bpf_prog_info_array_desc + i;
8076                 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8077                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8078                                                    desc->count_offset);
8079                 if (v1 != v2)
8080                         pr_warn("%s: mismatch in element count\n", __func__);
8081
8082                 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8083                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8084                                                    desc->size_offset);
8085                 if (v1 != v2)
8086                         pr_warn("%s: mismatch in rec size\n", __func__);
8087         }
8088
8089         /* step 7: update info_len and data_len */
8090         info_linear->info_len = sizeof(struct bpf_prog_info);
8091         info_linear->data_len = data_len;
8092
8093         return info_linear;
8094 }
8095
8096 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
8097 {
8098         int i;
8099
8100         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8101                 struct bpf_prog_info_array_desc *desc;
8102                 __u64 addr, offs;
8103
8104                 if ((info_linear->arrays & (1UL << i)) == 0)
8105                         continue;
8106
8107                 desc = bpf_prog_info_array_desc + i;
8108                 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
8109                                                      desc->array_offset);
8110                 offs = addr - ptr_to_u64(info_linear->data);
8111                 bpf_prog_info_set_offset_u64(&info_linear->info,
8112                                              desc->array_offset, offs);
8113         }
8114 }
8115
8116 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
8117 {
8118         int i;
8119
8120         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8121                 struct bpf_prog_info_array_desc *desc;
8122                 __u64 addr, offs;
8123
8124                 if ((info_linear->arrays & (1UL << i)) == 0)
8125                         continue;
8126
8127                 desc = bpf_prog_info_array_desc + i;
8128                 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
8129                                                      desc->array_offset);
8130                 addr = offs + ptr_to_u64(info_linear->data);
8131                 bpf_prog_info_set_offset_u64(&info_linear->info,
8132                                              desc->array_offset, addr);
8133         }
8134 }
8135
8136 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
8137 {
8138         int err = 0, n, len, start, end = -1;
8139         bool *tmp;
8140
8141         *mask = NULL;
8142         *mask_sz = 0;
8143
8144         /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
8145         while (*s) {
8146                 if (*s == ',' || *s == '\n') {
8147                         s++;
8148                         continue;
8149                 }
8150                 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
8151                 if (n <= 0 || n > 2) {
8152                         pr_warn("Failed to get CPU range %s: %d\n", s, n);
8153                         err = -EINVAL;
8154                         goto cleanup;
8155                 } else if (n == 1) {
8156                         end = start;
8157                 }
8158                 if (start < 0 || start > end) {
8159                         pr_warn("Invalid CPU range [%d,%d] in %s\n",
8160                                 start, end, s);
8161                         err = -EINVAL;
8162                         goto cleanup;
8163                 }
8164                 tmp = realloc(*mask, end + 1);
8165                 if (!tmp) {
8166                         err = -ENOMEM;
8167                         goto cleanup;
8168                 }
8169                 *mask = tmp;
8170                 memset(tmp + *mask_sz, 0, start - *mask_sz);
8171                 memset(tmp + start, 1, end - start + 1);
8172                 *mask_sz = end + 1;
8173                 s += len;
8174         }
8175         if (!*mask_sz) {
8176                 pr_warn("Empty CPU range\n");
8177                 return -EINVAL;
8178         }
8179         return 0;
8180 cleanup:
8181         free(*mask);
8182         *mask = NULL;
8183         return err;
8184 }
8185
8186 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
8187 {
8188         int fd, err = 0, len;
8189         char buf[128];
8190
8191         fd = open(fcpu, O_RDONLY);
8192         if (fd < 0) {
8193                 err = -errno;
8194                 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
8195                 return err;
8196         }
8197         len = read(fd, buf, sizeof(buf));
8198         close(fd);
8199         if (len <= 0) {
8200                 err = len ? -errno : -EINVAL;
8201                 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
8202                 return err;
8203         }
8204         if (len >= sizeof(buf)) {
8205                 pr_warn("CPU mask is too big in file %s\n", fcpu);
8206                 return -E2BIG;
8207         }
8208         buf[len] = '\0';
8209
8210         return parse_cpu_mask_str(buf, mask, mask_sz);
8211 }
8212
8213 int libbpf_num_possible_cpus(void)
8214 {
8215         static const char *fcpu = "/sys/devices/system/cpu/possible";
8216         static int cpus;
8217         int err, n, i, tmp_cpus;
8218         bool *mask;
8219
8220         tmp_cpus = READ_ONCE(cpus);
8221         if (tmp_cpus > 0)
8222                 return tmp_cpus;
8223
8224         err = parse_cpu_mask_file(fcpu, &mask, &n);
8225         if (err)
8226                 return err;
8227
8228         tmp_cpus = 0;
8229         for (i = 0; i < n; i++) {
8230                 if (mask[i])
8231                         tmp_cpus++;
8232         }
8233         free(mask);
8234
8235         WRITE_ONCE(cpus, tmp_cpus);
8236         return tmp_cpus;
8237 }
8238
8239 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
8240                               const struct bpf_object_open_opts *opts)
8241 {
8242         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
8243                 .object_name = s->name,
8244         );
8245         struct bpf_object *obj;
8246         int i;
8247
8248         /* Attempt to preserve opts->object_name, unless overriden by user
8249          * explicitly. Overwriting object name for skeletons is discouraged,
8250          * as it breaks global data maps, because they contain object name
8251          * prefix as their own map name prefix. When skeleton is generated,
8252          * bpftool is making an assumption that this name will stay the same.
8253          */
8254         if (opts) {
8255                 memcpy(&skel_opts, opts, sizeof(*opts));
8256                 if (!opts->object_name)
8257                         skel_opts.object_name = s->name;
8258         }
8259
8260         obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
8261         if (IS_ERR(obj)) {
8262                 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
8263                         s->name, PTR_ERR(obj));
8264                 return PTR_ERR(obj);
8265         }
8266
8267         *s->obj = obj;
8268
8269         for (i = 0; i < s->map_cnt; i++) {
8270                 struct bpf_map **map = s->maps[i].map;
8271                 const char *name = s->maps[i].name;
8272                 void **mmaped = s->maps[i].mmaped;
8273
8274                 *map = bpf_object__find_map_by_name(obj, name);
8275                 if (!*map) {
8276                         pr_warn("failed to find skeleton map '%s'\n", name);
8277                         return -ESRCH;
8278                 }
8279
8280                 /* externs shouldn't be pre-setup from user code */
8281                 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
8282                         *mmaped = (*map)->mmaped;
8283         }
8284
8285         for (i = 0; i < s->prog_cnt; i++) {
8286                 struct bpf_program **prog = s->progs[i].prog;
8287                 const char *name = s->progs[i].name;
8288
8289                 *prog = bpf_object__find_program_by_name(obj, name);
8290                 if (!*prog) {
8291                         pr_warn("failed to find skeleton program '%s'\n", name);
8292                         return -ESRCH;
8293                 }
8294         }
8295
8296         return 0;
8297 }
8298
8299 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
8300 {
8301         int i, err;
8302
8303         err = bpf_object__load(*s->obj);
8304         if (err) {
8305                 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
8306                 return err;
8307         }
8308
8309         for (i = 0; i < s->map_cnt; i++) {
8310                 struct bpf_map *map = *s->maps[i].map;
8311                 size_t mmap_sz = bpf_map_mmap_sz(map);
8312                 int prot, map_fd = bpf_map__fd(map);
8313                 void **mmaped = s->maps[i].mmaped;
8314
8315                 if (!mmaped)
8316                         continue;
8317
8318                 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
8319                         *mmaped = NULL;
8320                         continue;
8321                 }
8322
8323                 if (map->def.map_flags & BPF_F_RDONLY_PROG)
8324                         prot = PROT_READ;
8325                 else
8326                         prot = PROT_READ | PROT_WRITE;
8327
8328                 /* Remap anonymous mmap()-ed "map initialization image" as
8329                  * a BPF map-backed mmap()-ed memory, but preserving the same
8330                  * memory address. This will cause kernel to change process'
8331                  * page table to point to a different piece of kernel memory,
8332                  * but from userspace point of view memory address (and its
8333                  * contents, being identical at this point) will stay the
8334                  * same. This mapping will be released by bpf_object__close()
8335                  * as per normal clean up procedure, so we don't need to worry
8336                  * about it from skeleton's clean up perspective.
8337                  */
8338                 *mmaped = mmap(map->mmaped, mmap_sz, prot,
8339                                 MAP_SHARED | MAP_FIXED, map_fd, 0);
8340                 if (*mmaped == MAP_FAILED) {
8341                         err = -errno;
8342                         *mmaped = NULL;
8343                         pr_warn("failed to re-mmap() map '%s': %d\n",
8344                                  bpf_map__name(map), err);
8345                         return err;
8346                 }
8347         }
8348
8349         return 0;
8350 }
8351
8352 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
8353 {
8354         int i;
8355
8356         for (i = 0; i < s->prog_cnt; i++) {
8357                 struct bpf_program *prog = *s->progs[i].prog;
8358                 struct bpf_link **link = s->progs[i].link;
8359                 const struct bpf_sec_def *sec_def;
8360                 const char *sec_name = bpf_program__title(prog, false);
8361
8362                 sec_def = find_sec_def(sec_name);
8363                 if (!sec_def || !sec_def->attach_fn)
8364                         continue;
8365
8366                 *link = sec_def->attach_fn(sec_def, prog);
8367                 if (IS_ERR(*link)) {
8368                         pr_warn("failed to auto-attach program '%s': %ld\n",
8369                                 bpf_program__name(prog), PTR_ERR(*link));
8370                         return PTR_ERR(*link);
8371                 }
8372         }
8373
8374         return 0;
8375 }
8376
8377 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
8378 {
8379         int i;
8380
8381         for (i = 0; i < s->prog_cnt; i++) {
8382                 struct bpf_link **link = s->progs[i].link;
8383
8384                 if (!IS_ERR_OR_NULL(*link))
8385                         bpf_link__destroy(*link);
8386                 *link = NULL;
8387         }
8388 }
8389
8390 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
8391 {
8392         if (s->progs)
8393                 bpf_object__detach_skeleton(s);
8394         if (s->obj)
8395                 bpf_object__close(*s->obj);
8396         free(s->maps);
8397         free(s->progs);
8398         free(s);
8399 }