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