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