libbpf: Add support for relocatable bitfields
[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 <string.h>
22 #include <unistd.h>
23 #include <endian.h>
24 #include <fcntl.h>
25 #include <errno.h>
26 #include <asm/unistd.h>
27 #include <linux/err.h>
28 #include <linux/kernel.h>
29 #include <linux/bpf.h>
30 #include <linux/btf.h>
31 #include <linux/filter.h>
32 #include <linux/list.h>
33 #include <linux/limits.h>
34 #include <linux/perf_event.h>
35 #include <linux/ring_buffer.h>
36 #include <linux/version.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <tools/libc_compat.h>
45 #include <libelf.h>
46 #include <gelf.h>
47
48 #include "libbpf.h"
49 #include "bpf.h"
50 #include "btf.h"
51 #include "str_error.h"
52 #include "libbpf_internal.h"
53 #include "hashmap.h"
54
55 #ifndef EM_BPF
56 #define EM_BPF 247
57 #endif
58
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC            0xcafe4a11
61 #endif
62
63 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
64  * compilation if user enables corresponding warning. Disable it explicitly.
65  */
66 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
67
68 #define __printf(a, b)  __attribute__((format(printf, a, b)))
69
70 static int __base_pr(enum libbpf_print_level level, const char *format,
71                      va_list args)
72 {
73         if (level == LIBBPF_DEBUG)
74                 return 0;
75
76         return vfprintf(stderr, format, args);
77 }
78
79 static libbpf_print_fn_t __libbpf_pr = __base_pr;
80
81 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
82 {
83         libbpf_print_fn_t old_print_fn = __libbpf_pr;
84
85         __libbpf_pr = fn;
86         return old_print_fn;
87 }
88
89 __printf(2, 3)
90 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
91 {
92         va_list args;
93
94         if (!__libbpf_pr)
95                 return;
96
97         va_start(args, format);
98         __libbpf_pr(level, format, args);
99         va_end(args);
100 }
101
102 #define STRERR_BUFSIZE  128
103
104 #define CHECK_ERR(action, err, out) do {        \
105         err = action;                   \
106         if (err)                        \
107                 goto out;               \
108 } while(0)
109
110
111 /* Copied from tools/perf/util/util.h */
112 #ifndef zfree
113 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
114 #endif
115
116 #ifndef zclose
117 # define zclose(fd) ({                  \
118         int ___err = 0;                 \
119         if ((fd) >= 0)                  \
120                 ___err = close((fd));   \
121         fd = -1;                        \
122         ___err; })
123 #endif
124
125 #ifdef HAVE_LIBELF_MMAP_SUPPORT
126 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
127 #else
128 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
129 #endif
130
131 static inline __u64 ptr_to_u64(const void *ptr)
132 {
133         return (__u64) (unsigned long) ptr;
134 }
135
136 struct bpf_capabilities {
137         /* v4.14: kernel support for program & map names. */
138         __u32 name:1;
139         /* v5.2: kernel support for global data sections. */
140         __u32 global_data:1;
141         /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
142         __u32 btf_func:1;
143         /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
144         __u32 btf_datasec:1;
145 };
146
147 /*
148  * bpf_prog should be a better name but it has been used in
149  * linux/filter.h.
150  */
151 struct bpf_program {
152         /* Index in elf obj file, for relocation use. */
153         int idx;
154         char *name;
155         int prog_ifindex;
156         char *section_name;
157         /* section_name with / replaced by _; makes recursive pinning
158          * in bpf_object__pin_programs easier
159          */
160         char *pin_name;
161         struct bpf_insn *insns;
162         size_t insns_cnt, main_prog_cnt;
163         enum bpf_prog_type type;
164
165         struct reloc_desc {
166                 enum {
167                         RELO_LD64,
168                         RELO_CALL,
169                         RELO_DATA,
170                 } type;
171                 int insn_idx;
172                 union {
173                         int map_idx;
174                         int text_off;
175                 };
176         } *reloc_desc;
177         int nr_reloc;
178         int log_level;
179
180         struct {
181                 int nr;
182                 int *fds;
183         } instances;
184         bpf_program_prep_t preprocessor;
185
186         struct bpf_object *obj;
187         void *priv;
188         bpf_program_clear_priv_t clear_priv;
189
190         enum bpf_attach_type expected_attach_type;
191         __u32 attach_btf_id;
192         void *func_info;
193         __u32 func_info_rec_size;
194         __u32 func_info_cnt;
195
196         struct bpf_capabilities *caps;
197
198         void *line_info;
199         __u32 line_info_rec_size;
200         __u32 line_info_cnt;
201         __u32 prog_flags;
202 };
203
204 enum libbpf_map_type {
205         LIBBPF_MAP_UNSPEC,
206         LIBBPF_MAP_DATA,
207         LIBBPF_MAP_BSS,
208         LIBBPF_MAP_RODATA,
209 };
210
211 static const char * const libbpf_type_to_btf_name[] = {
212         [LIBBPF_MAP_DATA]       = ".data",
213         [LIBBPF_MAP_BSS]        = ".bss",
214         [LIBBPF_MAP_RODATA]     = ".rodata",
215 };
216
217 struct bpf_map {
218         int fd;
219         char *name;
220         int sec_idx;
221         size_t sec_offset;
222         int map_ifindex;
223         int inner_map_fd;
224         struct bpf_map_def def;
225         __u32 btf_key_type_id;
226         __u32 btf_value_type_id;
227         void *priv;
228         bpf_map_clear_priv_t clear_priv;
229         enum libbpf_map_type libbpf_type;
230         char *pin_path;
231         bool pinned;
232 };
233
234 struct bpf_secdata {
235         void *rodata;
236         void *data;
237 };
238
239 static LIST_HEAD(bpf_objects_list);
240
241 struct bpf_object {
242         char name[BPF_OBJ_NAME_LEN];
243         char license[64];
244         __u32 kern_version;
245
246         struct bpf_program *programs;
247         size_t nr_programs;
248         struct bpf_map *maps;
249         size_t nr_maps;
250         size_t maps_cap;
251         struct bpf_secdata sections;
252
253         bool loaded;
254         bool has_pseudo_calls;
255         bool relaxed_core_relocs;
256
257         /*
258          * Information when doing elf related work. Only valid if fd
259          * is valid.
260          */
261         struct {
262                 int fd;
263                 const void *obj_buf;
264                 size_t obj_buf_sz;
265                 Elf *elf;
266                 GElf_Ehdr ehdr;
267                 Elf_Data *symbols;
268                 Elf_Data *data;
269                 Elf_Data *rodata;
270                 Elf_Data *bss;
271                 size_t strtabidx;
272                 struct {
273                         GElf_Shdr shdr;
274                         Elf_Data *data;
275                 } *reloc;
276                 int nr_reloc;
277                 int maps_shndx;
278                 int btf_maps_shndx;
279                 int text_shndx;
280                 int data_shndx;
281                 int rodata_shndx;
282                 int bss_shndx;
283         } efile;
284         /*
285          * All loaded bpf_object is linked in a list, which is
286          * hidden to caller. bpf_objects__<func> handlers deal with
287          * all objects.
288          */
289         struct list_head list;
290
291         struct btf *btf;
292         struct btf_ext *btf_ext;
293
294         void *priv;
295         bpf_object_clear_priv_t clear_priv;
296
297         struct bpf_capabilities caps;
298
299         char path[];
300 };
301 #define obj_elf_valid(o)        ((o)->efile.elf)
302
303 void bpf_program__unload(struct bpf_program *prog)
304 {
305         int i;
306
307         if (!prog)
308                 return;
309
310         /*
311          * If the object is opened but the program was never loaded,
312          * it is possible that prog->instances.nr == -1.
313          */
314         if (prog->instances.nr > 0) {
315                 for (i = 0; i < prog->instances.nr; i++)
316                         zclose(prog->instances.fds[i]);
317         } else if (prog->instances.nr != -1) {
318                 pr_warn("Internal error: instances.nr is %d\n",
319                         prog->instances.nr);
320         }
321
322         prog->instances.nr = -1;
323         zfree(&prog->instances.fds);
324
325         zfree(&prog->func_info);
326         zfree(&prog->line_info);
327 }
328
329 static void bpf_program__exit(struct bpf_program *prog)
330 {
331         if (!prog)
332                 return;
333
334         if (prog->clear_priv)
335                 prog->clear_priv(prog, prog->priv);
336
337         prog->priv = NULL;
338         prog->clear_priv = NULL;
339
340         bpf_program__unload(prog);
341         zfree(&prog->name);
342         zfree(&prog->section_name);
343         zfree(&prog->pin_name);
344         zfree(&prog->insns);
345         zfree(&prog->reloc_desc);
346
347         prog->nr_reloc = 0;
348         prog->insns_cnt = 0;
349         prog->idx = -1;
350 }
351
352 static char *__bpf_program__pin_name(struct bpf_program *prog)
353 {
354         char *name, *p;
355
356         name = p = strdup(prog->section_name);
357         while ((p = strchr(p, '/')))
358                 *p = '_';
359
360         return name;
361 }
362
363 static int
364 bpf_program__init(void *data, size_t size, char *section_name, int idx,
365                   struct bpf_program *prog)
366 {
367         const size_t bpf_insn_sz = sizeof(struct bpf_insn);
368
369         if (size == 0 || size % bpf_insn_sz) {
370                 pr_warn("corrupted section '%s', size: %zu\n",
371                         section_name, size);
372                 return -EINVAL;
373         }
374
375         memset(prog, 0, sizeof(*prog));
376
377         prog->section_name = strdup(section_name);
378         if (!prog->section_name) {
379                 pr_warn("failed to alloc name for prog under section(%d) %s\n",
380                         idx, section_name);
381                 goto errout;
382         }
383
384         prog->pin_name = __bpf_program__pin_name(prog);
385         if (!prog->pin_name) {
386                 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
387                         idx, section_name);
388                 goto errout;
389         }
390
391         prog->insns = malloc(size);
392         if (!prog->insns) {
393                 pr_warn("failed to alloc insns for prog under section %s\n",
394                         section_name);
395                 goto errout;
396         }
397         prog->insns_cnt = size / bpf_insn_sz;
398         memcpy(prog->insns, data, size);
399         prog->idx = idx;
400         prog->instances.fds = NULL;
401         prog->instances.nr = -1;
402         prog->type = BPF_PROG_TYPE_UNSPEC;
403
404         return 0;
405 errout:
406         bpf_program__exit(prog);
407         return -ENOMEM;
408 }
409
410 static int
411 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
412                         char *section_name, int idx)
413 {
414         struct bpf_program prog, *progs;
415         int nr_progs, err;
416
417         err = bpf_program__init(data, size, section_name, idx, &prog);
418         if (err)
419                 return err;
420
421         prog.caps = &obj->caps;
422         progs = obj->programs;
423         nr_progs = obj->nr_programs;
424
425         progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
426         if (!progs) {
427                 /*
428                  * In this case the original obj->programs
429                  * is still valid, so don't need special treat for
430                  * bpf_close_object().
431                  */
432                 pr_warn("failed to alloc a new program under section '%s'\n",
433                         section_name);
434                 bpf_program__exit(&prog);
435                 return -ENOMEM;
436         }
437
438         pr_debug("found program %s\n", prog.section_name);
439         obj->programs = progs;
440         obj->nr_programs = nr_progs + 1;
441         prog.obj = obj;
442         progs[nr_progs] = prog;
443         return 0;
444 }
445
446 static int
447 bpf_object__init_prog_names(struct bpf_object *obj)
448 {
449         Elf_Data *symbols = obj->efile.symbols;
450         struct bpf_program *prog;
451         size_t pi, si;
452
453         for (pi = 0; pi < obj->nr_programs; pi++) {
454                 const char *name = NULL;
455
456                 prog = &obj->programs[pi];
457
458                 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
459                      si++) {
460                         GElf_Sym sym;
461
462                         if (!gelf_getsym(symbols, si, &sym))
463                                 continue;
464                         if (sym.st_shndx != prog->idx)
465                                 continue;
466                         if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
467                                 continue;
468
469                         name = elf_strptr(obj->efile.elf,
470                                           obj->efile.strtabidx,
471                                           sym.st_name);
472                         if (!name) {
473                                 pr_warn("failed to get sym name string for prog %s\n",
474                                         prog->section_name);
475                                 return -LIBBPF_ERRNO__LIBELF;
476                         }
477                 }
478
479                 if (!name && prog->idx == obj->efile.text_shndx)
480                         name = ".text";
481
482                 if (!name) {
483                         pr_warn("failed to find sym for prog %s\n",
484                                 prog->section_name);
485                         return -EINVAL;
486                 }
487
488                 prog->name = strdup(name);
489                 if (!prog->name) {
490                         pr_warn("failed to allocate memory for prog sym %s\n",
491                                 name);
492                         return -ENOMEM;
493                 }
494         }
495
496         return 0;
497 }
498
499 static __u32 get_kernel_version(void)
500 {
501         __u32 major, minor, patch;
502         struct utsname info;
503
504         uname(&info);
505         if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
506                 return 0;
507         return KERNEL_VERSION(major, minor, patch);
508 }
509
510 static struct bpf_object *bpf_object__new(const char *path,
511                                           const void *obj_buf,
512                                           size_t obj_buf_sz,
513                                           const char *obj_name)
514 {
515         struct bpf_object *obj;
516         char *end;
517
518         obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
519         if (!obj) {
520                 pr_warn("alloc memory failed for %s\n", path);
521                 return ERR_PTR(-ENOMEM);
522         }
523
524         strcpy(obj->path, path);
525         if (obj_name) {
526                 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
527                 obj->name[sizeof(obj->name) - 1] = 0;
528         } else {
529                 /* Using basename() GNU version which doesn't modify arg. */
530                 strncpy(obj->name, basename((void *)path),
531                         sizeof(obj->name) - 1);
532                 end = strchr(obj->name, '.');
533                 if (end)
534                         *end = 0;
535         }
536
537         obj->efile.fd = -1;
538         /*
539          * Caller of this function should also call
540          * bpf_object__elf_finish() after data collection to return
541          * obj_buf to user. If not, we should duplicate the buffer to
542          * avoid user freeing them before elf finish.
543          */
544         obj->efile.obj_buf = obj_buf;
545         obj->efile.obj_buf_sz = obj_buf_sz;
546         obj->efile.maps_shndx = -1;
547         obj->efile.btf_maps_shndx = -1;
548         obj->efile.data_shndx = -1;
549         obj->efile.rodata_shndx = -1;
550         obj->efile.bss_shndx = -1;
551
552         obj->kern_version = get_kernel_version();
553         obj->loaded = false;
554
555         INIT_LIST_HEAD(&obj->list);
556         list_add(&obj->list, &bpf_objects_list);
557         return obj;
558 }
559
560 static void bpf_object__elf_finish(struct bpf_object *obj)
561 {
562         if (!obj_elf_valid(obj))
563                 return;
564
565         if (obj->efile.elf) {
566                 elf_end(obj->efile.elf);
567                 obj->efile.elf = NULL;
568         }
569         obj->efile.symbols = NULL;
570         obj->efile.data = NULL;
571         obj->efile.rodata = NULL;
572         obj->efile.bss = NULL;
573
574         zfree(&obj->efile.reloc);
575         obj->efile.nr_reloc = 0;
576         zclose(obj->efile.fd);
577         obj->efile.obj_buf = NULL;
578         obj->efile.obj_buf_sz = 0;
579 }
580
581 static int bpf_object__elf_init(struct bpf_object *obj)
582 {
583         int err = 0;
584         GElf_Ehdr *ep;
585
586         if (obj_elf_valid(obj)) {
587                 pr_warn("elf init: internal error\n");
588                 return -LIBBPF_ERRNO__LIBELF;
589         }
590
591         if (obj->efile.obj_buf_sz > 0) {
592                 /*
593                  * obj_buf should have been validated by
594                  * bpf_object__open_buffer().
595                  */
596                 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
597                                             obj->efile.obj_buf_sz);
598         } else {
599                 obj->efile.fd = open(obj->path, O_RDONLY);
600                 if (obj->efile.fd < 0) {
601                         char errmsg[STRERR_BUFSIZE], *cp;
602
603                         err = -errno;
604                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
605                         pr_warn("failed to open %s: %s\n", obj->path, cp);
606                         return err;
607                 }
608
609                 obj->efile.elf = elf_begin(obj->efile.fd,
610                                            LIBBPF_ELF_C_READ_MMAP, NULL);
611         }
612
613         if (!obj->efile.elf) {
614                 pr_warn("failed to open %s as ELF file\n", obj->path);
615                 err = -LIBBPF_ERRNO__LIBELF;
616                 goto errout;
617         }
618
619         if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
620                 pr_warn("failed to get EHDR from %s\n", obj->path);
621                 err = -LIBBPF_ERRNO__FORMAT;
622                 goto errout;
623         }
624         ep = &obj->efile.ehdr;
625
626         /* Old LLVM set e_machine to EM_NONE */
627         if (ep->e_type != ET_REL ||
628             (ep->e_machine && ep->e_machine != EM_BPF)) {
629                 pr_warn("%s is not an eBPF object file\n", obj->path);
630                 err = -LIBBPF_ERRNO__FORMAT;
631                 goto errout;
632         }
633
634         return 0;
635 errout:
636         bpf_object__elf_finish(obj);
637         return err;
638 }
639
640 static int bpf_object__check_endianness(struct bpf_object *obj)
641 {
642 #if __BYTE_ORDER == __LITTLE_ENDIAN
643         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
644                 return 0;
645 #elif __BYTE_ORDER == __BIG_ENDIAN
646         if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
647                 return 0;
648 #else
649 # error "Unrecognized __BYTE_ORDER__"
650 #endif
651         pr_warn("endianness mismatch.\n");
652         return -LIBBPF_ERRNO__ENDIAN;
653 }
654
655 static int
656 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
657 {
658         memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
659         pr_debug("license of %s is %s\n", obj->path, obj->license);
660         return 0;
661 }
662
663 static int
664 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
665 {
666         __u32 kver;
667
668         if (size != sizeof(kver)) {
669                 pr_warn("invalid kver section in %s\n", obj->path);
670                 return -LIBBPF_ERRNO__FORMAT;
671         }
672         memcpy(&kver, data, sizeof(kver));
673         obj->kern_version = kver;
674         pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
675         return 0;
676 }
677
678 static int compare_bpf_map(const void *_a, const void *_b)
679 {
680         const struct bpf_map *a = _a;
681         const struct bpf_map *b = _b;
682
683         if (a->sec_idx != b->sec_idx)
684                 return a->sec_idx - b->sec_idx;
685         return a->sec_offset - b->sec_offset;
686 }
687
688 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
689 {
690         if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
691             type == BPF_MAP_TYPE_HASH_OF_MAPS)
692                 return true;
693         return false;
694 }
695
696 static int bpf_object_search_section_size(const struct bpf_object *obj,
697                                           const char *name, size_t *d_size)
698 {
699         const GElf_Ehdr *ep = &obj->efile.ehdr;
700         Elf *elf = obj->efile.elf;
701         Elf_Scn *scn = NULL;
702         int idx = 0;
703
704         while ((scn = elf_nextscn(elf, scn)) != NULL) {
705                 const char *sec_name;
706                 Elf_Data *data;
707                 GElf_Shdr sh;
708
709                 idx++;
710                 if (gelf_getshdr(scn, &sh) != &sh) {
711                         pr_warn("failed to get section(%d) header from %s\n",
712                                 idx, obj->path);
713                         return -EIO;
714                 }
715
716                 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
717                 if (!sec_name) {
718                         pr_warn("failed to get section(%d) name from %s\n",
719                                 idx, obj->path);
720                         return -EIO;
721                 }
722
723                 if (strcmp(name, sec_name))
724                         continue;
725
726                 data = elf_getdata(scn, 0);
727                 if (!data) {
728                         pr_warn("failed to get section(%d) data from %s(%s)\n",
729                                 idx, name, obj->path);
730                         return -EIO;
731                 }
732
733                 *d_size = data->d_size;
734                 return 0;
735         }
736
737         return -ENOENT;
738 }
739
740 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
741                              __u32 *size)
742 {
743         int ret = -ENOENT;
744         size_t d_size;
745
746         *size = 0;
747         if (!name) {
748                 return -EINVAL;
749         } else if (!strcmp(name, ".data")) {
750                 if (obj->efile.data)
751                         *size = obj->efile.data->d_size;
752         } else if (!strcmp(name, ".bss")) {
753                 if (obj->efile.bss)
754                         *size = obj->efile.bss->d_size;
755         } else if (!strcmp(name, ".rodata")) {
756                 if (obj->efile.rodata)
757                         *size = obj->efile.rodata->d_size;
758         } else {
759                 ret = bpf_object_search_section_size(obj, name, &d_size);
760                 if (!ret)
761                         *size = d_size;
762         }
763
764         return *size ? 0 : ret;
765 }
766
767 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
768                                 __u32 *off)
769 {
770         Elf_Data *symbols = obj->efile.symbols;
771         const char *sname;
772         size_t si;
773
774         if (!name || !off)
775                 return -EINVAL;
776
777         for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
778                 GElf_Sym sym;
779
780                 if (!gelf_getsym(symbols, si, &sym))
781                         continue;
782                 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
783                     GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
784                         continue;
785
786                 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
787                                    sym.st_name);
788                 if (!sname) {
789                         pr_warn("failed to get sym name string for var %s\n",
790                                 name);
791                         return -EIO;
792                 }
793                 if (strcmp(name, sname) == 0) {
794                         *off = sym.st_value;
795                         return 0;
796                 }
797         }
798
799         return -ENOENT;
800 }
801
802 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
803 {
804         struct bpf_map *new_maps;
805         size_t new_cap;
806         int i;
807
808         if (obj->nr_maps < obj->maps_cap)
809                 return &obj->maps[obj->nr_maps++];
810
811         new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
812         new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
813         if (!new_maps) {
814                 pr_warn("alloc maps for object failed\n");
815                 return ERR_PTR(-ENOMEM);
816         }
817
818         obj->maps_cap = new_cap;
819         obj->maps = new_maps;
820
821         /* zero out new maps */
822         memset(obj->maps + obj->nr_maps, 0,
823                (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
824         /*
825          * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
826          * when failure (zclose won't close negative fd)).
827          */
828         for (i = obj->nr_maps; i < obj->maps_cap; i++) {
829                 obj->maps[i].fd = -1;
830                 obj->maps[i].inner_map_fd = -1;
831         }
832
833         return &obj->maps[obj->nr_maps++];
834 }
835
836 static int
837 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
838                               int sec_idx, Elf_Data *data, void **data_buff)
839 {
840         char map_name[BPF_OBJ_NAME_LEN];
841         struct bpf_map_def *def;
842         struct bpf_map *map;
843
844         map = bpf_object__add_map(obj);
845         if (IS_ERR(map))
846                 return PTR_ERR(map);
847
848         map->libbpf_type = type;
849         map->sec_idx = sec_idx;
850         map->sec_offset = 0;
851         snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
852                  libbpf_type_to_btf_name[type]);
853         map->name = strdup(map_name);
854         if (!map->name) {
855                 pr_warn("failed to alloc map name\n");
856                 return -ENOMEM;
857         }
858         pr_debug("map '%s' (global data): at sec_idx %d, offset %zu.\n",
859                  map_name, map->sec_idx, map->sec_offset);
860
861         def = &map->def;
862         def->type = BPF_MAP_TYPE_ARRAY;
863         def->key_size = sizeof(int);
864         def->value_size = data->d_size;
865         def->max_entries = 1;
866         def->map_flags = type == LIBBPF_MAP_RODATA ? BPF_F_RDONLY_PROG : 0;
867         if (data_buff) {
868                 *data_buff = malloc(data->d_size);
869                 if (!*data_buff) {
870                         zfree(&map->name);
871                         pr_warn("failed to alloc map content buffer\n");
872                         return -ENOMEM;
873                 }
874                 memcpy(*data_buff, data->d_buf, data->d_size);
875         }
876
877         pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
878         return 0;
879 }
880
881 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
882 {
883         int err;
884
885         if (!obj->caps.global_data)
886                 return 0;
887         /*
888          * Populate obj->maps with libbpf internal maps.
889          */
890         if (obj->efile.data_shndx >= 0) {
891                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
892                                                     obj->efile.data_shndx,
893                                                     obj->efile.data,
894                                                     &obj->sections.data);
895                 if (err)
896                         return err;
897         }
898         if (obj->efile.rodata_shndx >= 0) {
899                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
900                                                     obj->efile.rodata_shndx,
901                                                     obj->efile.rodata,
902                                                     &obj->sections.rodata);
903                 if (err)
904                         return err;
905         }
906         if (obj->efile.bss_shndx >= 0) {
907                 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
908                                                     obj->efile.bss_shndx,
909                                                     obj->efile.bss, NULL);
910                 if (err)
911                         return err;
912         }
913         return 0;
914 }
915
916 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
917 {
918         Elf_Data *symbols = obj->efile.symbols;
919         int i, map_def_sz = 0, nr_maps = 0, nr_syms;
920         Elf_Data *data = NULL;
921         Elf_Scn *scn;
922
923         if (obj->efile.maps_shndx < 0)
924                 return 0;
925
926         if (!symbols)
927                 return -EINVAL;
928
929         scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
930         if (scn)
931                 data = elf_getdata(scn, NULL);
932         if (!scn || !data) {
933                 pr_warn("failed to get Elf_Data from map section %d\n",
934                         obj->efile.maps_shndx);
935                 return -EINVAL;
936         }
937
938         /*
939          * Count number of maps. Each map has a name.
940          * Array of maps is not supported: only the first element is
941          * considered.
942          *
943          * TODO: Detect array of map and report error.
944          */
945         nr_syms = symbols->d_size / sizeof(GElf_Sym);
946         for (i = 0; i < nr_syms; i++) {
947                 GElf_Sym sym;
948
949                 if (!gelf_getsym(symbols, i, &sym))
950                         continue;
951                 if (sym.st_shndx != obj->efile.maps_shndx)
952                         continue;
953                 nr_maps++;
954         }
955         /* Assume equally sized map definitions */
956         pr_debug("maps in %s: %d maps in %zd bytes\n",
957                  obj->path, nr_maps, data->d_size);
958
959         map_def_sz = data->d_size / nr_maps;
960         if (!data->d_size || (data->d_size % nr_maps) != 0) {
961                 pr_warn("unable to determine map definition size "
962                         "section %s, %d maps in %zd bytes\n",
963                         obj->path, nr_maps, data->d_size);
964                 return -EINVAL;
965         }
966
967         /* Fill obj->maps using data in "maps" section.  */
968         for (i = 0; i < nr_syms; i++) {
969                 GElf_Sym sym;
970                 const char *map_name;
971                 struct bpf_map_def *def;
972                 struct bpf_map *map;
973
974                 if (!gelf_getsym(symbols, i, &sym))
975                         continue;
976                 if (sym.st_shndx != obj->efile.maps_shndx)
977                         continue;
978
979                 map = bpf_object__add_map(obj);
980                 if (IS_ERR(map))
981                         return PTR_ERR(map);
982
983                 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
984                                       sym.st_name);
985                 if (!map_name) {
986                         pr_warn("failed to get map #%d name sym string for obj %s\n",
987                                 i, obj->path);
988                         return -LIBBPF_ERRNO__FORMAT;
989                 }
990
991                 map->libbpf_type = LIBBPF_MAP_UNSPEC;
992                 map->sec_idx = sym.st_shndx;
993                 map->sec_offset = sym.st_value;
994                 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
995                          map_name, map->sec_idx, map->sec_offset);
996                 if (sym.st_value + map_def_sz > data->d_size) {
997                         pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
998                                 obj->path, map_name);
999                         return -EINVAL;
1000                 }
1001
1002                 map->name = strdup(map_name);
1003                 if (!map->name) {
1004                         pr_warn("failed to alloc map name\n");
1005                         return -ENOMEM;
1006                 }
1007                 pr_debug("map %d is \"%s\"\n", i, map->name);
1008                 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1009                 /*
1010                  * If the definition of the map in the object file fits in
1011                  * bpf_map_def, copy it.  Any extra fields in our version
1012                  * of bpf_map_def will default to zero as a result of the
1013                  * calloc above.
1014                  */
1015                 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1016                         memcpy(&map->def, def, map_def_sz);
1017                 } else {
1018                         /*
1019                          * Here the map structure being read is bigger than what
1020                          * we expect, truncate if the excess bits are all zero.
1021                          * If they are not zero, reject this map as
1022                          * incompatible.
1023                          */
1024                         char *b;
1025                         for (b = ((char *)def) + sizeof(struct bpf_map_def);
1026                              b < ((char *)def) + map_def_sz; b++) {
1027                                 if (*b != 0) {
1028                                         pr_warn("maps section in %s: \"%s\" "
1029                                                 "has unrecognized, non-zero "
1030                                                 "options\n",
1031                                                 obj->path, map_name);
1032                                         if (strict)
1033                                                 return -EINVAL;
1034                                 }
1035                         }
1036                         memcpy(&map->def, def, sizeof(struct bpf_map_def));
1037                 }
1038         }
1039         return 0;
1040 }
1041
1042 static const struct btf_type *
1043 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1044 {
1045         const struct btf_type *t = btf__type_by_id(btf, id);
1046
1047         if (res_id)
1048                 *res_id = id;
1049
1050         while (btf_is_mod(t) || btf_is_typedef(t)) {
1051                 if (res_id)
1052                         *res_id = t->type;
1053                 t = btf__type_by_id(btf, t->type);
1054         }
1055
1056         return t;
1057 }
1058
1059 /*
1060  * Fetch integer attribute of BTF map definition. Such attributes are
1061  * represented using a pointer to an array, in which dimensionality of array
1062  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1063  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1064  * type definition, while using only sizeof(void *) space in ELF data section.
1065  */
1066 static bool get_map_field_int(const char *map_name, const struct btf *btf,
1067                               const struct btf_type *def,
1068                               const struct btf_member *m, __u32 *res) {
1069         const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1070         const char *name = btf__name_by_offset(btf, m->name_off);
1071         const struct btf_array *arr_info;
1072         const struct btf_type *arr_t;
1073
1074         if (!btf_is_ptr(t)) {
1075                 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1076                         map_name, name, btf_kind(t));
1077                 return false;
1078         }
1079
1080         arr_t = btf__type_by_id(btf, t->type);
1081         if (!arr_t) {
1082                 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1083                         map_name, name, t->type);
1084                 return false;
1085         }
1086         if (!btf_is_array(arr_t)) {
1087                 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1088                         map_name, name, btf_kind(arr_t));
1089                 return false;
1090         }
1091         arr_info = btf_array(arr_t);
1092         *res = arr_info->nelems;
1093         return true;
1094 }
1095
1096 static int build_map_pin_path(struct bpf_map *map, const char *path)
1097 {
1098         char buf[PATH_MAX];
1099         int err, len;
1100
1101         if (!path)
1102                 path = "/sys/fs/bpf";
1103
1104         len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1105         if (len < 0)
1106                 return -EINVAL;
1107         else if (len >= PATH_MAX)
1108                 return -ENAMETOOLONG;
1109
1110         err = bpf_map__set_pin_path(map, buf);
1111         if (err)
1112                 return err;
1113
1114         return 0;
1115 }
1116
1117 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1118                                          const struct btf_type *sec,
1119                                          int var_idx, int sec_idx,
1120                                          const Elf_Data *data, bool strict,
1121                                          const char *pin_root_path)
1122 {
1123         const struct btf_type *var, *def, *t;
1124         const struct btf_var_secinfo *vi;
1125         const struct btf_var *var_extra;
1126         const struct btf_member *m;
1127         const char *map_name;
1128         struct bpf_map *map;
1129         int vlen, i;
1130
1131         vi = btf_var_secinfos(sec) + var_idx;
1132         var = btf__type_by_id(obj->btf, vi->type);
1133         var_extra = btf_var(var);
1134         map_name = btf__name_by_offset(obj->btf, var->name_off);
1135         vlen = btf_vlen(var);
1136
1137         if (map_name == NULL || map_name[0] == '\0') {
1138                 pr_warn("map #%d: empty name.\n", var_idx);
1139                 return -EINVAL;
1140         }
1141         if ((__u64)vi->offset + vi->size > data->d_size) {
1142                 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
1143                 return -EINVAL;
1144         }
1145         if (!btf_is_var(var)) {
1146                 pr_warn("map '%s': unexpected var kind %u.\n",
1147                         map_name, btf_kind(var));
1148                 return -EINVAL;
1149         }
1150         if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1151             var_extra->linkage != BTF_VAR_STATIC) {
1152                 pr_warn("map '%s': unsupported var linkage %u.\n",
1153                         map_name, var_extra->linkage);
1154                 return -EOPNOTSUPP;
1155         }
1156
1157         def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
1158         if (!btf_is_struct(def)) {
1159                 pr_warn("map '%s': unexpected def kind %u.\n",
1160                         map_name, btf_kind(var));
1161                 return -EINVAL;
1162         }
1163         if (def->size > vi->size) {
1164                 pr_warn("map '%s': invalid def size.\n", map_name);
1165                 return -EINVAL;
1166         }
1167
1168         map = bpf_object__add_map(obj);
1169         if (IS_ERR(map))
1170                 return PTR_ERR(map);
1171         map->name = strdup(map_name);
1172         if (!map->name) {
1173                 pr_warn("map '%s': failed to alloc map name.\n", map_name);
1174                 return -ENOMEM;
1175         }
1176         map->libbpf_type = LIBBPF_MAP_UNSPEC;
1177         map->def.type = BPF_MAP_TYPE_UNSPEC;
1178         map->sec_idx = sec_idx;
1179         map->sec_offset = vi->offset;
1180         pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1181                  map_name, map->sec_idx, map->sec_offset);
1182
1183         vlen = btf_vlen(def);
1184         m = btf_members(def);
1185         for (i = 0; i < vlen; i++, m++) {
1186                 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1187
1188                 if (!name) {
1189                         pr_warn("map '%s': invalid field #%d.\n", map_name, i);
1190                         return -EINVAL;
1191                 }
1192                 if (strcmp(name, "type") == 0) {
1193                         if (!get_map_field_int(map_name, obj->btf, def, m,
1194                                                &map->def.type))
1195                                 return -EINVAL;
1196                         pr_debug("map '%s': found type = %u.\n",
1197                                  map_name, map->def.type);
1198                 } else if (strcmp(name, "max_entries") == 0) {
1199                         if (!get_map_field_int(map_name, obj->btf, def, m,
1200                                                &map->def.max_entries))
1201                                 return -EINVAL;
1202                         pr_debug("map '%s': found max_entries = %u.\n",
1203                                  map_name, map->def.max_entries);
1204                 } else if (strcmp(name, "map_flags") == 0) {
1205                         if (!get_map_field_int(map_name, obj->btf, def, m,
1206                                                &map->def.map_flags))
1207                                 return -EINVAL;
1208                         pr_debug("map '%s': found map_flags = %u.\n",
1209                                  map_name, map->def.map_flags);
1210                 } else if (strcmp(name, "key_size") == 0) {
1211                         __u32 sz;
1212
1213                         if (!get_map_field_int(map_name, obj->btf, def, m,
1214                                                &sz))
1215                                 return -EINVAL;
1216                         pr_debug("map '%s': found key_size = %u.\n",
1217                                  map_name, sz);
1218                         if (map->def.key_size && map->def.key_size != sz) {
1219                                 pr_warn("map '%s': conflicting key size %u != %u.\n",
1220                                         map_name, map->def.key_size, sz);
1221                                 return -EINVAL;
1222                         }
1223                         map->def.key_size = sz;
1224                 } else if (strcmp(name, "key") == 0) {
1225                         __s64 sz;
1226
1227                         t = btf__type_by_id(obj->btf, m->type);
1228                         if (!t) {
1229                                 pr_warn("map '%s': key type [%d] not found.\n",
1230                                         map_name, m->type);
1231                                 return -EINVAL;
1232                         }
1233                         if (!btf_is_ptr(t)) {
1234                                 pr_warn("map '%s': key spec is not PTR: %u.\n",
1235                                         map_name, btf_kind(t));
1236                                 return -EINVAL;
1237                         }
1238                         sz = btf__resolve_size(obj->btf, t->type);
1239                         if (sz < 0) {
1240                                 pr_warn("map '%s': can't determine key size for type [%u]: %lld.\n",
1241                                         map_name, t->type, sz);
1242                                 return sz;
1243                         }
1244                         pr_debug("map '%s': found key [%u], sz = %lld.\n",
1245                                  map_name, t->type, sz);
1246                         if (map->def.key_size && map->def.key_size != sz) {
1247                                 pr_warn("map '%s': conflicting key size %u != %lld.\n",
1248                                         map_name, map->def.key_size, sz);
1249                                 return -EINVAL;
1250                         }
1251                         map->def.key_size = sz;
1252                         map->btf_key_type_id = t->type;
1253                 } else if (strcmp(name, "value_size") == 0) {
1254                         __u32 sz;
1255
1256                         if (!get_map_field_int(map_name, obj->btf, def, m,
1257                                                &sz))
1258                                 return -EINVAL;
1259                         pr_debug("map '%s': found value_size = %u.\n",
1260                                  map_name, sz);
1261                         if (map->def.value_size && map->def.value_size != sz) {
1262                                 pr_warn("map '%s': conflicting value size %u != %u.\n",
1263                                         map_name, map->def.value_size, sz);
1264                                 return -EINVAL;
1265                         }
1266                         map->def.value_size = sz;
1267                 } else if (strcmp(name, "value") == 0) {
1268                         __s64 sz;
1269
1270                         t = btf__type_by_id(obj->btf, m->type);
1271                         if (!t) {
1272                                 pr_warn("map '%s': value type [%d] not found.\n",
1273                                         map_name, m->type);
1274                                 return -EINVAL;
1275                         }
1276                         if (!btf_is_ptr(t)) {
1277                                 pr_warn("map '%s': value spec is not PTR: %u.\n",
1278                                         map_name, btf_kind(t));
1279                                 return -EINVAL;
1280                         }
1281                         sz = btf__resolve_size(obj->btf, t->type);
1282                         if (sz < 0) {
1283                                 pr_warn("map '%s': can't determine value size for type [%u]: %lld.\n",
1284                                         map_name, t->type, sz);
1285                                 return sz;
1286                         }
1287                         pr_debug("map '%s': found value [%u], sz = %lld.\n",
1288                                  map_name, t->type, sz);
1289                         if (map->def.value_size && map->def.value_size != sz) {
1290                                 pr_warn("map '%s': conflicting value size %u != %lld.\n",
1291                                         map_name, map->def.value_size, sz);
1292                                 return -EINVAL;
1293                         }
1294                         map->def.value_size = sz;
1295                         map->btf_value_type_id = t->type;
1296                 } else if (strcmp(name, "pinning") == 0) {
1297                         __u32 val;
1298                         int err;
1299
1300                         if (!get_map_field_int(map_name, obj->btf, def, m,
1301                                                &val))
1302                                 return -EINVAL;
1303                         pr_debug("map '%s': found pinning = %u.\n",
1304                                  map_name, val);
1305
1306                         if (val != LIBBPF_PIN_NONE &&
1307                             val != LIBBPF_PIN_BY_NAME) {
1308                                 pr_warn("map '%s': invalid pinning value %u.\n",
1309                                         map_name, val);
1310                                 return -EINVAL;
1311                         }
1312                         if (val == LIBBPF_PIN_BY_NAME) {
1313                                 err = build_map_pin_path(map, pin_root_path);
1314                                 if (err) {
1315                                         pr_warn("map '%s': couldn't build pin path.\n",
1316                                                 map_name);
1317                                         return err;
1318                                 }
1319                         }
1320                 } else {
1321                         if (strict) {
1322                                 pr_warn("map '%s': unknown field '%s'.\n",
1323                                         map_name, name);
1324                                 return -ENOTSUP;
1325                         }
1326                         pr_debug("map '%s': ignoring unknown field '%s'.\n",
1327                                  map_name, name);
1328                 }
1329         }
1330
1331         if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
1332                 pr_warn("map '%s': map type isn't specified.\n", map_name);
1333                 return -EINVAL;
1334         }
1335
1336         return 0;
1337 }
1338
1339 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1340                                           const char *pin_root_path)
1341 {
1342         const struct btf_type *sec = NULL;
1343         int nr_types, i, vlen, err;
1344         const struct btf_type *t;
1345         const char *name;
1346         Elf_Data *data;
1347         Elf_Scn *scn;
1348
1349         if (obj->efile.btf_maps_shndx < 0)
1350                 return 0;
1351
1352         scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1353         if (scn)
1354                 data = elf_getdata(scn, NULL);
1355         if (!scn || !data) {
1356                 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1357                         obj->efile.maps_shndx, MAPS_ELF_SEC);
1358                 return -EINVAL;
1359         }
1360
1361         nr_types = btf__get_nr_types(obj->btf);
1362         for (i = 1; i <= nr_types; i++) {
1363                 t = btf__type_by_id(obj->btf, i);
1364                 if (!btf_is_datasec(t))
1365                         continue;
1366                 name = btf__name_by_offset(obj->btf, t->name_off);
1367                 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1368                         sec = t;
1369                         break;
1370                 }
1371         }
1372
1373         if (!sec) {
1374                 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
1375                 return -ENOENT;
1376         }
1377
1378         vlen = btf_vlen(sec);
1379         for (i = 0; i < vlen; i++) {
1380                 err = bpf_object__init_user_btf_map(obj, sec, i,
1381                                                     obj->efile.btf_maps_shndx,
1382                                                     data, strict, pin_root_path);
1383                 if (err)
1384                         return err;
1385         }
1386
1387         return 0;
1388 }
1389
1390 static int bpf_object__init_maps(struct bpf_object *obj, bool relaxed_maps,
1391                                  const char *pin_root_path)
1392 {
1393         bool strict = !relaxed_maps;
1394         int err;
1395
1396         err = bpf_object__init_user_maps(obj, strict);
1397         if (err)
1398                 return err;
1399
1400         err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1401         if (err)
1402                 return err;
1403
1404         err = bpf_object__init_global_data_maps(obj);
1405         if (err)
1406                 return err;
1407
1408         if (obj->nr_maps) {
1409                 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1410                       compare_bpf_map);
1411         }
1412         return 0;
1413 }
1414
1415 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1416 {
1417         Elf_Scn *scn;
1418         GElf_Shdr sh;
1419
1420         scn = elf_getscn(obj->efile.elf, idx);
1421         if (!scn)
1422                 return false;
1423
1424         if (gelf_getshdr(scn, &sh) != &sh)
1425                 return false;
1426
1427         if (sh.sh_flags & SHF_EXECINSTR)
1428                 return true;
1429
1430         return false;
1431 }
1432
1433 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1434 {
1435         bool has_datasec = obj->caps.btf_datasec;
1436         bool has_func = obj->caps.btf_func;
1437         struct btf *btf = obj->btf;
1438         struct btf_type *t;
1439         int i, j, vlen;
1440
1441         if (!obj->btf || (has_func && has_datasec))
1442                 return;
1443
1444         for (i = 1; i <= btf__get_nr_types(btf); i++) {
1445                 t = (struct btf_type *)btf__type_by_id(btf, i);
1446
1447                 if (!has_datasec && btf_is_var(t)) {
1448                         /* replace VAR with INT */
1449                         t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1450                         /*
1451                          * using size = 1 is the safest choice, 4 will be too
1452                          * big and cause kernel BTF validation failure if
1453                          * original variable took less than 4 bytes
1454                          */
1455                         t->size = 1;
1456                         *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
1457                 } else if (!has_datasec && btf_is_datasec(t)) {
1458                         /* replace DATASEC with STRUCT */
1459                         const struct btf_var_secinfo *v = btf_var_secinfos(t);
1460                         struct btf_member *m = btf_members(t);
1461                         struct btf_type *vt;
1462                         char *name;
1463
1464                         name = (char *)btf__name_by_offset(btf, t->name_off);
1465                         while (*name) {
1466                                 if (*name == '.')
1467                                         *name = '_';
1468                                 name++;
1469                         }
1470
1471                         vlen = btf_vlen(t);
1472                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1473                         for (j = 0; j < vlen; j++, v++, m++) {
1474                                 /* order of field assignments is important */
1475                                 m->offset = v->offset * 8;
1476                                 m->type = v->type;
1477                                 /* preserve variable name as member name */
1478                                 vt = (void *)btf__type_by_id(btf, v->type);
1479                                 m->name_off = vt->name_off;
1480                         }
1481                 } else if (!has_func && btf_is_func_proto(t)) {
1482                         /* replace FUNC_PROTO with ENUM */
1483                         vlen = btf_vlen(t);
1484                         t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1485                         t->size = sizeof(__u32); /* kernel enforced */
1486                 } else if (!has_func && btf_is_func(t)) {
1487                         /* replace FUNC with TYPEDEF */
1488                         t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1489                 }
1490         }
1491 }
1492
1493 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1494 {
1495         if (!obj->btf_ext)
1496                 return;
1497
1498         if (!obj->caps.btf_func) {
1499                 btf_ext__free(obj->btf_ext);
1500                 obj->btf_ext = NULL;
1501         }
1502 }
1503
1504 static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1505 {
1506         return obj->efile.btf_maps_shndx >= 0;
1507 }
1508
1509 static int bpf_object__init_btf(struct bpf_object *obj,
1510                                 Elf_Data *btf_data,
1511                                 Elf_Data *btf_ext_data)
1512 {
1513         bool btf_required = bpf_object__is_btf_mandatory(obj);
1514         int err = 0;
1515
1516         if (btf_data) {
1517                 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1518                 if (IS_ERR(obj->btf)) {
1519                         pr_warn("Error loading ELF section %s: %d.\n",
1520                                 BTF_ELF_SEC, err);
1521                         goto out;
1522                 }
1523                 err = btf__finalize_data(obj, obj->btf);
1524                 if (err) {
1525                         pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1526                         goto out;
1527                 }
1528         }
1529         if (btf_ext_data) {
1530                 if (!obj->btf) {
1531                         pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1532                                  BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1533                         goto out;
1534                 }
1535                 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1536                                             btf_ext_data->d_size);
1537                 if (IS_ERR(obj->btf_ext)) {
1538                         pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1539                                 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
1540                         obj->btf_ext = NULL;
1541                         goto out;
1542                 }
1543         }
1544 out:
1545         if (err || IS_ERR(obj->btf)) {
1546                 if (btf_required)
1547                         err = err ? : PTR_ERR(obj->btf);
1548                 else
1549                         err = 0;
1550                 if (!IS_ERR_OR_NULL(obj->btf))
1551                         btf__free(obj->btf);
1552                 obj->btf = NULL;
1553         }
1554         if (btf_required && !obj->btf) {
1555                 pr_warn("BTF is required, but is missing or corrupted.\n");
1556                 return err == 0 ? -ENOENT : err;
1557         }
1558         return 0;
1559 }
1560
1561 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1562 {
1563         int err = 0;
1564
1565         if (!obj->btf)
1566                 return 0;
1567
1568         bpf_object__sanitize_btf(obj);
1569         bpf_object__sanitize_btf_ext(obj);
1570
1571         err = btf__load(obj->btf);
1572         if (err) {
1573                 pr_warn("Error loading %s into kernel: %d.\n",
1574                         BTF_ELF_SEC, err);
1575                 btf__free(obj->btf);
1576                 obj->btf = NULL;
1577                 /* btf_ext can't exist without btf, so free it as well */
1578                 if (obj->btf_ext) {
1579                         btf_ext__free(obj->btf_ext);
1580                         obj->btf_ext = NULL;
1581                 }
1582
1583                 if (bpf_object__is_btf_mandatory(obj))
1584                         return err;
1585         }
1586         return 0;
1587 }
1588
1589 static int bpf_object__elf_collect(struct bpf_object *obj, bool relaxed_maps,
1590                                    const char *pin_root_path)
1591 {
1592         Elf *elf = obj->efile.elf;
1593         GElf_Ehdr *ep = &obj->efile.ehdr;
1594         Elf_Data *btf_ext_data = NULL;
1595         Elf_Data *btf_data = NULL;
1596         Elf_Scn *scn = NULL;
1597         int idx = 0, err = 0;
1598
1599         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1600         if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1601                 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
1602                 return -LIBBPF_ERRNO__FORMAT;
1603         }
1604
1605         while ((scn = elf_nextscn(elf, scn)) != NULL) {
1606                 char *name;
1607                 GElf_Shdr sh;
1608                 Elf_Data *data;
1609
1610                 idx++;
1611                 if (gelf_getshdr(scn, &sh) != &sh) {
1612                         pr_warn("failed to get section(%d) header from %s\n",
1613                                 idx, obj->path);
1614                         return -LIBBPF_ERRNO__FORMAT;
1615                 }
1616
1617                 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1618                 if (!name) {
1619                         pr_warn("failed to get section(%d) name from %s\n",
1620                                 idx, obj->path);
1621                         return -LIBBPF_ERRNO__FORMAT;
1622                 }
1623
1624                 data = elf_getdata(scn, 0);
1625                 if (!data) {
1626                         pr_warn("failed to get section(%d) data from %s(%s)\n",
1627                                 idx, name, obj->path);
1628                         return -LIBBPF_ERRNO__FORMAT;
1629                 }
1630                 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1631                          idx, name, (unsigned long)data->d_size,
1632                          (int)sh.sh_link, (unsigned long)sh.sh_flags,
1633                          (int)sh.sh_type);
1634
1635                 if (strcmp(name, "license") == 0) {
1636                         err = bpf_object__init_license(obj,
1637                                                        data->d_buf,
1638                                                        data->d_size);
1639                         if (err)
1640                                 return err;
1641                 } else if (strcmp(name, "version") == 0) {
1642                         err = bpf_object__init_kversion(obj,
1643                                                         data->d_buf,
1644                                                         data->d_size);
1645                         if (err)
1646                                 return err;
1647                 } else if (strcmp(name, "maps") == 0) {
1648                         obj->efile.maps_shndx = idx;
1649                 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
1650                         obj->efile.btf_maps_shndx = idx;
1651                 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1652                         btf_data = data;
1653                 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1654                         btf_ext_data = data;
1655                 } else if (sh.sh_type == SHT_SYMTAB) {
1656                         if (obj->efile.symbols) {
1657                                 pr_warn("bpf: multiple SYMTAB in %s\n",
1658                                         obj->path);
1659                                 return -LIBBPF_ERRNO__FORMAT;
1660                         }
1661                         obj->efile.symbols = data;
1662                         obj->efile.strtabidx = sh.sh_link;
1663                 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1664                         if (sh.sh_flags & SHF_EXECINSTR) {
1665                                 if (strcmp(name, ".text") == 0)
1666                                         obj->efile.text_shndx = idx;
1667                                 err = bpf_object__add_program(obj, data->d_buf,
1668                                                               data->d_size, name, idx);
1669                                 if (err) {
1670                                         char errmsg[STRERR_BUFSIZE];
1671                                         char *cp = libbpf_strerror_r(-err, errmsg,
1672                                                                      sizeof(errmsg));
1673
1674                                         pr_warn("failed to alloc program %s (%s): %s",
1675                                                 name, obj->path, cp);
1676                                         return err;
1677                                 }
1678                         } else if (strcmp(name, ".data") == 0) {
1679                                 obj->efile.data = data;
1680                                 obj->efile.data_shndx = idx;
1681                         } else if (strcmp(name, ".rodata") == 0) {
1682                                 obj->efile.rodata = data;
1683                                 obj->efile.rodata_shndx = idx;
1684                         } else {
1685                                 pr_debug("skip section(%d) %s\n", idx, name);
1686                         }
1687                 } else if (sh.sh_type == SHT_REL) {
1688                         int nr_reloc = obj->efile.nr_reloc;
1689                         void *reloc = obj->efile.reloc;
1690                         int sec = sh.sh_info; /* points to other section */
1691
1692                         /* Only do relo for section with exec instructions */
1693                         if (!section_have_execinstr(obj, sec)) {
1694                                 pr_debug("skip relo %s(%d) for section(%d)\n",
1695                                          name, idx, sec);
1696                                 continue;
1697                         }
1698
1699                         reloc = reallocarray(reloc, nr_reloc + 1,
1700                                              sizeof(*obj->efile.reloc));
1701                         if (!reloc) {
1702                                 pr_warn("realloc failed\n");
1703                                 return -ENOMEM;
1704                         }
1705
1706                         obj->efile.reloc = reloc;
1707                         obj->efile.nr_reloc++;
1708
1709                         obj->efile.reloc[nr_reloc].shdr = sh;
1710                         obj->efile.reloc[nr_reloc].data = data;
1711                 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1712                         obj->efile.bss = data;
1713                         obj->efile.bss_shndx = idx;
1714                 } else {
1715                         pr_debug("skip section(%d) %s\n", idx, name);
1716                 }
1717         }
1718
1719         if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
1720                 pr_warn("Corrupted ELF file: index of strtab invalid\n");
1721                 return -LIBBPF_ERRNO__FORMAT;
1722         }
1723         err = bpf_object__init_btf(obj, btf_data, btf_ext_data);
1724         if (!err)
1725                 err = bpf_object__init_maps(obj, relaxed_maps, pin_root_path);
1726         if (!err)
1727                 err = bpf_object__sanitize_and_load_btf(obj);
1728         if (!err)
1729                 err = bpf_object__init_prog_names(obj);
1730         return err;
1731 }
1732
1733 static struct bpf_program *
1734 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1735 {
1736         struct bpf_program *prog;
1737         size_t i;
1738
1739         for (i = 0; i < obj->nr_programs; i++) {
1740                 prog = &obj->programs[i];
1741                 if (prog->idx == idx)
1742                         return prog;
1743         }
1744         return NULL;
1745 }
1746
1747 struct bpf_program *
1748 bpf_object__find_program_by_title(const struct bpf_object *obj,
1749                                   const char *title)
1750 {
1751         struct bpf_program *pos;
1752
1753         bpf_object__for_each_program(pos, obj) {
1754                 if (pos->section_name && !strcmp(pos->section_name, title))
1755                         return pos;
1756         }
1757         return NULL;
1758 }
1759
1760 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1761                                       int shndx)
1762 {
1763         return shndx == obj->efile.data_shndx ||
1764                shndx == obj->efile.bss_shndx ||
1765                shndx == obj->efile.rodata_shndx;
1766 }
1767
1768 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1769                                       int shndx)
1770 {
1771         return shndx == obj->efile.maps_shndx ||
1772                shndx == obj->efile.btf_maps_shndx;
1773 }
1774
1775 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1776                                               int shndx)
1777 {
1778         return shndx == obj->efile.text_shndx ||
1779                bpf_object__shndx_is_maps(obj, shndx) ||
1780                bpf_object__shndx_is_data(obj, shndx);
1781 }
1782
1783 static enum libbpf_map_type
1784 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1785 {
1786         if (shndx == obj->efile.data_shndx)
1787                 return LIBBPF_MAP_DATA;
1788         else if (shndx == obj->efile.bss_shndx)
1789                 return LIBBPF_MAP_BSS;
1790         else if (shndx == obj->efile.rodata_shndx)
1791                 return LIBBPF_MAP_RODATA;
1792         else
1793                 return LIBBPF_MAP_UNSPEC;
1794 }
1795
1796 static int
1797 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1798                            Elf_Data *data, struct bpf_object *obj)
1799 {
1800         Elf_Data *symbols = obj->efile.symbols;
1801         struct bpf_map *maps = obj->maps;
1802         size_t nr_maps = obj->nr_maps;
1803         int i, nrels;
1804
1805         pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
1806         nrels = shdr->sh_size / shdr->sh_entsize;
1807
1808         prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1809         if (!prog->reloc_desc) {
1810                 pr_warn("failed to alloc memory in relocation\n");
1811                 return -ENOMEM;
1812         }
1813         prog->nr_reloc = nrels;
1814
1815         for (i = 0; i < nrels; i++) {
1816                 struct bpf_insn *insns = prog->insns;
1817                 enum libbpf_map_type type;
1818                 unsigned int insn_idx;
1819                 unsigned int shdr_idx;
1820                 const char *name;
1821                 size_t map_idx;
1822                 GElf_Sym sym;
1823                 GElf_Rel rel;
1824
1825                 if (!gelf_getrel(data, i, &rel)) {
1826                         pr_warn("relocation: failed to get %d reloc\n", i);
1827                         return -LIBBPF_ERRNO__FORMAT;
1828                 }
1829
1830                 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
1831                         pr_warn("relocation: symbol %"PRIx64" not found\n",
1832                                 GELF_R_SYM(rel.r_info));
1833                         return -LIBBPF_ERRNO__FORMAT;
1834                 }
1835
1836                 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1837                                   sym.st_name) ? : "<?>";
1838
1839                 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1840                          (long long) (rel.r_info >> 32),
1841                          (long long) sym.st_value, sym.st_name, name);
1842
1843                 shdr_idx = sym.st_shndx;
1844                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1845                 pr_debug("relocation: insn_idx=%u, shdr_idx=%u\n",
1846                          insn_idx, shdr_idx);
1847
1848                 if (shdr_idx >= SHN_LORESERVE) {
1849                         pr_warn("relocation: not yet supported relo for non-static global \'%s\' variable in special section (0x%x) found in insns[%d].code 0x%x\n",
1850                                 name, shdr_idx, insn_idx,
1851                                 insns[insn_idx].code);
1852                         return -LIBBPF_ERRNO__RELOC;
1853                 }
1854                 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1855                         pr_warn("Program '%s' contains unrecognized relo data pointing to section %u\n",
1856                                 prog->section_name, shdr_idx);
1857                         return -LIBBPF_ERRNO__RELOC;
1858                 }
1859
1860                 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1861                         if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1862                                 pr_warn("incorrect bpf_call opcode\n");
1863                                 return -LIBBPF_ERRNO__RELOC;
1864                         }
1865                         prog->reloc_desc[i].type = RELO_CALL;
1866                         prog->reloc_desc[i].insn_idx = insn_idx;
1867                         prog->reloc_desc[i].text_off = sym.st_value;
1868                         obj->has_pseudo_calls = true;
1869                         continue;
1870                 }
1871
1872                 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1873                         pr_warn("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1874                                 insn_idx, insns[insn_idx].code);
1875                         return -LIBBPF_ERRNO__RELOC;
1876                 }
1877
1878                 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1879                     bpf_object__shndx_is_data(obj, shdr_idx)) {
1880                         type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1881                         if (type != LIBBPF_MAP_UNSPEC) {
1882                                 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1883                                         pr_warn("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1884                                                 name, insn_idx, insns[insn_idx].code);
1885                                         return -LIBBPF_ERRNO__RELOC;
1886                                 }
1887                                 if (!obj->caps.global_data) {
1888                                         pr_warn("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1889                                                 name, insn_idx);
1890                                         return -LIBBPF_ERRNO__RELOC;
1891                                 }
1892                         }
1893
1894                         for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1895                                 if (maps[map_idx].libbpf_type != type)
1896                                         continue;
1897                                 if (type != LIBBPF_MAP_UNSPEC ||
1898                                     (maps[map_idx].sec_idx == sym.st_shndx &&
1899                                      maps[map_idx].sec_offset == sym.st_value)) {
1900                                         pr_debug("relocation: found map %zd (%s, sec_idx %d, offset %zu) for insn %u\n",
1901                                                  map_idx, maps[map_idx].name,
1902                                                  maps[map_idx].sec_idx,
1903                                                  maps[map_idx].sec_offset,
1904                                                  insn_idx);
1905                                         break;
1906                                 }
1907                         }
1908
1909                         if (map_idx >= nr_maps) {
1910                                 pr_warn("bpf relocation: map_idx %d larger than %d\n",
1911                                         (int)map_idx, (int)nr_maps - 1);
1912                                 return -LIBBPF_ERRNO__RELOC;
1913                         }
1914
1915                         prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1916                                                    RELO_DATA : RELO_LD64;
1917                         prog->reloc_desc[i].insn_idx = insn_idx;
1918                         prog->reloc_desc[i].map_idx = map_idx;
1919                 }
1920         }
1921         return 0;
1922 }
1923
1924 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
1925 {
1926         struct bpf_map_def *def = &map->def;
1927         __u32 key_type_id = 0, value_type_id = 0;
1928         int ret;
1929
1930         /* if it's BTF-defined map, we don't need to search for type IDs */
1931         if (map->sec_idx == obj->efile.btf_maps_shndx)
1932                 return 0;
1933
1934         if (!bpf_map__is_internal(map)) {
1935                 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
1936                                            def->value_size, &key_type_id,
1937                                            &value_type_id);
1938         } else {
1939                 /*
1940                  * LLVM annotates global data differently in BTF, that is,
1941                  * only as '.data', '.bss' or '.rodata'.
1942                  */
1943                 ret = btf__find_by_name(obj->btf,
1944                                 libbpf_type_to_btf_name[map->libbpf_type]);
1945         }
1946         if (ret < 0)
1947                 return ret;
1948
1949         map->btf_key_type_id = key_type_id;
1950         map->btf_value_type_id = bpf_map__is_internal(map) ?
1951                                  ret : value_type_id;
1952         return 0;
1953 }
1954
1955 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1956 {
1957         struct bpf_map_info info = {};
1958         __u32 len = sizeof(info);
1959         int new_fd, err;
1960         char *new_name;
1961
1962         err = bpf_obj_get_info_by_fd(fd, &info, &len);
1963         if (err)
1964                 return err;
1965
1966         new_name = strdup(info.name);
1967         if (!new_name)
1968                 return -errno;
1969
1970         new_fd = open("/", O_RDONLY | O_CLOEXEC);
1971         if (new_fd < 0) {
1972                 err = -errno;
1973                 goto err_free_new_name;
1974         }
1975
1976         new_fd = dup3(fd, new_fd, O_CLOEXEC);
1977         if (new_fd < 0) {
1978                 err = -errno;
1979                 goto err_close_new_fd;
1980         }
1981
1982         err = zclose(map->fd);
1983         if (err) {
1984                 err = -errno;
1985                 goto err_close_new_fd;
1986         }
1987         free(map->name);
1988
1989         map->fd = new_fd;
1990         map->name = new_name;
1991         map->def.type = info.type;
1992         map->def.key_size = info.key_size;
1993         map->def.value_size = info.value_size;
1994         map->def.max_entries = info.max_entries;
1995         map->def.map_flags = info.map_flags;
1996         map->btf_key_type_id = info.btf_key_type_id;
1997         map->btf_value_type_id = info.btf_value_type_id;
1998
1999         return 0;
2000
2001 err_close_new_fd:
2002         close(new_fd);
2003 err_free_new_name:
2004         free(new_name);
2005         return err;
2006 }
2007
2008 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2009 {
2010         if (!map || !max_entries)
2011                 return -EINVAL;
2012
2013         /* If map already created, its attributes can't be changed. */
2014         if (map->fd >= 0)
2015                 return -EBUSY;
2016
2017         map->def.max_entries = max_entries;
2018
2019         return 0;
2020 }
2021
2022 static int
2023 bpf_object__probe_name(struct bpf_object *obj)
2024 {
2025         struct bpf_load_program_attr attr;
2026         char *cp, errmsg[STRERR_BUFSIZE];
2027         struct bpf_insn insns[] = {
2028                 BPF_MOV64_IMM(BPF_REG_0, 0),
2029                 BPF_EXIT_INSN(),
2030         };
2031         int ret;
2032
2033         /* make sure basic loading works */
2034
2035         memset(&attr, 0, sizeof(attr));
2036         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2037         attr.insns = insns;
2038         attr.insns_cnt = ARRAY_SIZE(insns);
2039         attr.license = "GPL";
2040
2041         ret = bpf_load_program_xattr(&attr, NULL, 0);
2042         if (ret < 0) {
2043                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2044                 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2045                         __func__, cp, errno);
2046                 return -errno;
2047         }
2048         close(ret);
2049
2050         /* now try the same program, but with the name */
2051
2052         attr.name = "test";
2053         ret = bpf_load_program_xattr(&attr, NULL, 0);
2054         if (ret >= 0) {
2055                 obj->caps.name = 1;
2056                 close(ret);
2057         }
2058
2059         return 0;
2060 }
2061
2062 static int
2063 bpf_object__probe_global_data(struct bpf_object *obj)
2064 {
2065         struct bpf_load_program_attr prg_attr;
2066         struct bpf_create_map_attr map_attr;
2067         char *cp, errmsg[STRERR_BUFSIZE];
2068         struct bpf_insn insns[] = {
2069                 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2070                 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2071                 BPF_MOV64_IMM(BPF_REG_0, 0),
2072                 BPF_EXIT_INSN(),
2073         };
2074         int ret, map;
2075
2076         memset(&map_attr, 0, sizeof(map_attr));
2077         map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2078         map_attr.key_size = sizeof(int);
2079         map_attr.value_size = 32;
2080         map_attr.max_entries = 1;
2081
2082         map = bpf_create_map_xattr(&map_attr);
2083         if (map < 0) {
2084                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2085                 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2086                         __func__, cp, errno);
2087                 return -errno;
2088         }
2089
2090         insns[0].imm = map;
2091
2092         memset(&prg_attr, 0, sizeof(prg_attr));
2093         prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2094         prg_attr.insns = insns;
2095         prg_attr.insns_cnt = ARRAY_SIZE(insns);
2096         prg_attr.license = "GPL";
2097
2098         ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2099         if (ret >= 0) {
2100                 obj->caps.global_data = 1;
2101                 close(ret);
2102         }
2103
2104         close(map);
2105         return 0;
2106 }
2107
2108 static int bpf_object__probe_btf_func(struct bpf_object *obj)
2109 {
2110         const char strs[] = "\0int\0x\0a";
2111         /* void x(int a) {} */
2112         __u32 types[] = {
2113                 /* int */
2114                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2115                 /* FUNC_PROTO */                                /* [2] */
2116                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2117                 BTF_PARAM_ENC(7, 1),
2118                 /* FUNC x */                                    /* [3] */
2119                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2120         };
2121         int btf_fd;
2122
2123         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2124                                       strs, sizeof(strs));
2125         if (btf_fd >= 0) {
2126                 obj->caps.btf_func = 1;
2127                 close(btf_fd);
2128                 return 1;
2129         }
2130
2131         return 0;
2132 }
2133
2134 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2135 {
2136         const char strs[] = "\0x\0.data";
2137         /* static int a; */
2138         __u32 types[] = {
2139                 /* int */
2140                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
2141                 /* VAR x */                                     /* [2] */
2142                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2143                 BTF_VAR_STATIC,
2144                 /* DATASEC val */                               /* [3] */
2145                 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2146                 BTF_VAR_SECINFO_ENC(2, 0, 4),
2147         };
2148         int btf_fd;
2149
2150         btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2151                                       strs, sizeof(strs));
2152         if (btf_fd >= 0) {
2153                 obj->caps.btf_datasec = 1;
2154                 close(btf_fd);
2155                 return 1;
2156         }
2157
2158         return 0;
2159 }
2160
2161 static int
2162 bpf_object__probe_caps(struct bpf_object *obj)
2163 {
2164         int (*probe_fn[])(struct bpf_object *obj) = {
2165                 bpf_object__probe_name,
2166                 bpf_object__probe_global_data,
2167                 bpf_object__probe_btf_func,
2168                 bpf_object__probe_btf_datasec,
2169         };
2170         int i, ret;
2171
2172         for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2173                 ret = probe_fn[i](obj);
2174                 if (ret < 0)
2175                         pr_debug("Probe #%d failed with %d.\n", i, ret);
2176         }
2177
2178         return 0;
2179 }
2180
2181 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2182 {
2183         struct bpf_map_info map_info = {};
2184         char msg[STRERR_BUFSIZE];
2185         __u32 map_info_len;
2186
2187         map_info_len = sizeof(map_info);
2188
2189         if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2190                 pr_warn("failed to get map info for map FD %d: %s\n",
2191                         map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2192                 return false;
2193         }
2194
2195         return (map_info.type == map->def.type &&
2196                 map_info.key_size == map->def.key_size &&
2197                 map_info.value_size == map->def.value_size &&
2198                 map_info.max_entries == map->def.max_entries &&
2199                 map_info.map_flags == map->def.map_flags);
2200 }
2201
2202 static int
2203 bpf_object__reuse_map(struct bpf_map *map)
2204 {
2205         char *cp, errmsg[STRERR_BUFSIZE];
2206         int err, pin_fd;
2207
2208         pin_fd = bpf_obj_get(map->pin_path);
2209         if (pin_fd < 0) {
2210                 err = -errno;
2211                 if (err == -ENOENT) {
2212                         pr_debug("found no pinned map to reuse at '%s'\n",
2213                                  map->pin_path);
2214                         return 0;
2215                 }
2216
2217                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2218                 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2219                         map->pin_path, cp);
2220                 return err;
2221         }
2222
2223         if (!map_is_reuse_compat(map, pin_fd)) {
2224                 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2225                         map->pin_path);
2226                 close(pin_fd);
2227                 return -EINVAL;
2228         }
2229
2230         err = bpf_map__reuse_fd(map, pin_fd);
2231         if (err) {
2232                 close(pin_fd);
2233                 return err;
2234         }
2235         map->pinned = true;
2236         pr_debug("reused pinned map at '%s'\n", map->pin_path);
2237
2238         return 0;
2239 }
2240
2241 static int
2242 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2243 {
2244         char *cp, errmsg[STRERR_BUFSIZE];
2245         int err, zero = 0;
2246         __u8 *data;
2247
2248         /* Nothing to do here since kernel already zero-initializes .bss map. */
2249         if (map->libbpf_type == LIBBPF_MAP_BSS)
2250                 return 0;
2251
2252         data = map->libbpf_type == LIBBPF_MAP_DATA ?
2253                obj->sections.data : obj->sections.rodata;
2254
2255         err = bpf_map_update_elem(map->fd, &zero, data, 0);
2256         /* Freeze .rodata map as read-only from syscall side. */
2257         if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
2258                 err = bpf_map_freeze(map->fd);
2259                 if (err) {
2260                         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2261                         pr_warn("Error freezing map(%s) as read-only: %s\n",
2262                                 map->name, cp);
2263                         err = 0;
2264                 }
2265         }
2266         return err;
2267 }
2268
2269 static int
2270 bpf_object__create_maps(struct bpf_object *obj)
2271 {
2272         struct bpf_create_map_attr create_attr = {};
2273         int nr_cpus = 0;
2274         unsigned int i;
2275         int err;
2276
2277         for (i = 0; i < obj->nr_maps; i++) {
2278                 struct bpf_map *map = &obj->maps[i];
2279                 struct bpf_map_def *def = &map->def;
2280                 char *cp, errmsg[STRERR_BUFSIZE];
2281                 int *pfd = &map->fd;
2282
2283                 if (map->pin_path) {
2284                         err = bpf_object__reuse_map(map);
2285                         if (err) {
2286                                 pr_warn("error reusing pinned map %s\n",
2287                                         map->name);
2288                                 return err;
2289                         }
2290                 }
2291
2292                 if (map->fd >= 0) {
2293                         pr_debug("skip map create (preset) %s: fd=%d\n",
2294                                  map->name, map->fd);
2295                         continue;
2296                 }
2297
2298                 if (obj->caps.name)
2299                         create_attr.name = map->name;
2300                 create_attr.map_ifindex = map->map_ifindex;
2301                 create_attr.map_type = def->type;
2302                 create_attr.map_flags = def->map_flags;
2303                 create_attr.key_size = def->key_size;
2304                 create_attr.value_size = def->value_size;
2305                 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2306                     !def->max_entries) {
2307                         if (!nr_cpus)
2308                                 nr_cpus = libbpf_num_possible_cpus();
2309                         if (nr_cpus < 0) {
2310                                 pr_warn("failed to determine number of system CPUs: %d\n",
2311                                         nr_cpus);
2312                                 err = nr_cpus;
2313                                 goto err_out;
2314                         }
2315                         pr_debug("map '%s': setting size to %d\n",
2316                                  map->name, nr_cpus);
2317                         create_attr.max_entries = nr_cpus;
2318                 } else {
2319                         create_attr.max_entries = def->max_entries;
2320                 }
2321                 create_attr.btf_fd = 0;
2322                 create_attr.btf_key_type_id = 0;
2323                 create_attr.btf_value_type_id = 0;
2324                 if (bpf_map_type__is_map_in_map(def->type) &&
2325                     map->inner_map_fd >= 0)
2326                         create_attr.inner_map_fd = map->inner_map_fd;
2327
2328                 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
2329                         create_attr.btf_fd = btf__fd(obj->btf);
2330                         create_attr.btf_key_type_id = map->btf_key_type_id;
2331                         create_attr.btf_value_type_id = map->btf_value_type_id;
2332                 }
2333
2334                 *pfd = bpf_create_map_xattr(&create_attr);
2335                 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2336                                  create_attr.btf_value_type_id)) {
2337                         err = -errno;
2338                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2339                         pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2340                                 map->name, cp, err);
2341                         create_attr.btf_fd = 0;
2342                         create_attr.btf_key_type_id = 0;
2343                         create_attr.btf_value_type_id = 0;
2344                         map->btf_key_type_id = 0;
2345                         map->btf_value_type_id = 0;
2346                         *pfd = bpf_create_map_xattr(&create_attr);
2347                 }
2348
2349                 if (*pfd < 0) {
2350                         size_t j;
2351
2352                         err = -errno;
2353 err_out:
2354                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2355                         pr_warn("failed to create map (name: '%s'): %s(%d)\n",
2356                                 map->name, cp, err);
2357                         for (j = 0; j < i; j++)
2358                                 zclose(obj->maps[j].fd);
2359                         return err;
2360                 }
2361
2362                 if (bpf_map__is_internal(map)) {
2363                         err = bpf_object__populate_internal_map(obj, map);
2364                         if (err < 0) {
2365                                 zclose(*pfd);
2366                                 goto err_out;
2367                         }
2368                 }
2369
2370                 if (map->pin_path && !map->pinned) {
2371                         err = bpf_map__pin(map, NULL);
2372                         if (err) {
2373                                 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
2374                                         map->name, map->pin_path);
2375                                 return err;
2376                         }
2377                 }
2378
2379                 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
2380         }
2381
2382         return 0;
2383 }
2384
2385 static int
2386 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
2387                         void *btf_prog_info, const char *info_name)
2388 {
2389         if (err != -ENOENT) {
2390                 pr_warn("Error in loading %s for sec %s.\n",
2391                         info_name, prog->section_name);
2392                 return err;
2393         }
2394
2395         /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
2396
2397         if (btf_prog_info) {
2398                 /*
2399                  * Some info has already been found but has problem
2400                  * in the last btf_ext reloc. Must have to error out.
2401                  */
2402                 pr_warn("Error in relocating %s for sec %s.\n",
2403                         info_name, prog->section_name);
2404                 return err;
2405         }
2406
2407         /* Have problem loading the very first info. Ignore the rest. */
2408         pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
2409                 info_name, prog->section_name, info_name);
2410         return 0;
2411 }
2412
2413 static int
2414 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
2415                           const char *section_name,  __u32 insn_offset)
2416 {
2417         int err;
2418
2419         if (!insn_offset || prog->func_info) {
2420                 /*
2421                  * !insn_offset => main program
2422                  *
2423                  * For sub prog, the main program's func_info has to
2424                  * be loaded first (i.e. prog->func_info != NULL)
2425                  */
2426                 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
2427                                                section_name, insn_offset,
2428                                                &prog->func_info,
2429                                                &prog->func_info_cnt);
2430                 if (err)
2431                         return check_btf_ext_reloc_err(prog, err,
2432                                                        prog->func_info,
2433                                                        "bpf_func_info");
2434
2435                 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
2436         }
2437
2438         if (!insn_offset || prog->line_info) {
2439                 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
2440                                                section_name, insn_offset,
2441                                                &prog->line_info,
2442                                                &prog->line_info_cnt);
2443                 if (err)
2444                         return check_btf_ext_reloc_err(prog, err,
2445                                                        prog->line_info,
2446                                                        "bpf_line_info");
2447
2448                 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
2449         }
2450
2451         return 0;
2452 }
2453
2454 #define BPF_CORE_SPEC_MAX_LEN 64
2455
2456 /* represents BPF CO-RE field or array element accessor */
2457 struct bpf_core_accessor {
2458         __u32 type_id;          /* struct/union type or array element type */
2459         __u32 idx;              /* field index or array index */
2460         const char *name;       /* field name or NULL for array accessor */
2461 };
2462
2463 struct bpf_core_spec {
2464         const struct btf *btf;
2465         /* high-level spec: named fields and array indices only */
2466         struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
2467         /* high-level spec length */
2468         int len;
2469         /* raw, low-level spec: 1-to-1 with accessor spec string */
2470         int raw_spec[BPF_CORE_SPEC_MAX_LEN];
2471         /* raw spec length */
2472         int raw_len;
2473         /* field bit offset represented by spec */
2474         __u32 bit_offset;
2475 };
2476
2477 static bool str_is_empty(const char *s)
2478 {
2479         return !s || !s[0];
2480 }
2481
2482 /*
2483  * Turn bpf_field_reloc into a low- and high-level spec representation,
2484  * validating correctness along the way, as well as calculating resulting
2485  * field bit offset, specified by accessor string. Low-level spec captures
2486  * every single level of nestedness, including traversing anonymous
2487  * struct/union members. High-level one only captures semantically meaningful
2488  * "turning points": named fields and array indicies.
2489  * E.g., for this case:
2490  *
2491  *   struct sample {
2492  *       int __unimportant;
2493  *       struct {
2494  *           int __1;
2495  *           int __2;
2496  *           int a[7];
2497  *       };
2498  *   };
2499  *
2500  *   struct sample *s = ...;
2501  *
2502  *   int x = &s->a[3]; // access string = '0:1:2:3'
2503  *
2504  * Low-level spec has 1:1 mapping with each element of access string (it's
2505  * just a parsed access string representation): [0, 1, 2, 3].
2506  *
2507  * High-level spec will capture only 3 points:
2508  *   - intial zero-index access by pointer (&s->... is the same as &s[0]...);
2509  *   - field 'a' access (corresponds to '2' in low-level spec);
2510  *   - array element #3 access (corresponds to '3' in low-level spec).
2511  *
2512  */
2513 static int bpf_core_spec_parse(const struct btf *btf,
2514                                __u32 type_id,
2515                                const char *spec_str,
2516                                struct bpf_core_spec *spec)
2517 {
2518         int access_idx, parsed_len, i;
2519         const struct btf_type *t;
2520         const char *name;
2521         __u32 id;
2522         __s64 sz;
2523
2524         if (str_is_empty(spec_str) || *spec_str == ':')
2525                 return -EINVAL;
2526
2527         memset(spec, 0, sizeof(*spec));
2528         spec->btf = btf;
2529
2530         /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
2531         while (*spec_str) {
2532                 if (*spec_str == ':')
2533                         ++spec_str;
2534                 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
2535                         return -EINVAL;
2536                 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2537                         return -E2BIG;
2538                 spec_str += parsed_len;
2539                 spec->raw_spec[spec->raw_len++] = access_idx;
2540         }
2541
2542         if (spec->raw_len == 0)
2543                 return -EINVAL;
2544
2545         /* first spec value is always reloc type array index */
2546         t = skip_mods_and_typedefs(btf, type_id, &id);
2547         if (!t)
2548                 return -EINVAL;
2549
2550         access_idx = spec->raw_spec[0];
2551         spec->spec[0].type_id = id;
2552         spec->spec[0].idx = access_idx;
2553         spec->len++;
2554
2555         sz = btf__resolve_size(btf, id);
2556         if (sz < 0)
2557                 return sz;
2558         spec->bit_offset = access_idx * sz * 8;
2559
2560         for (i = 1; i < spec->raw_len; i++) {
2561                 t = skip_mods_and_typedefs(btf, id, &id);
2562                 if (!t)
2563                         return -EINVAL;
2564
2565                 access_idx = spec->raw_spec[i];
2566
2567                 if (btf_is_composite(t)) {
2568                         const struct btf_member *m;
2569                         __u32 bit_offset;
2570
2571                         if (access_idx >= btf_vlen(t))
2572                                 return -EINVAL;
2573
2574                         bit_offset = btf_member_bit_offset(t, access_idx);
2575                         spec->bit_offset += bit_offset;
2576
2577                         m = btf_members(t) + access_idx;
2578                         if (m->name_off) {
2579                                 name = btf__name_by_offset(btf, m->name_off);
2580                                 if (str_is_empty(name))
2581                                         return -EINVAL;
2582
2583                                 spec->spec[spec->len].type_id = id;
2584                                 spec->spec[spec->len].idx = access_idx;
2585                                 spec->spec[spec->len].name = name;
2586                                 spec->len++;
2587                         }
2588
2589                         id = m->type;
2590                 } else if (btf_is_array(t)) {
2591                         const struct btf_array *a = btf_array(t);
2592
2593                         t = skip_mods_and_typedefs(btf, a->type, &id);
2594                         if (!t || access_idx >= a->nelems)
2595                                 return -EINVAL;
2596
2597                         spec->spec[spec->len].type_id = id;
2598                         spec->spec[spec->len].idx = access_idx;
2599                         spec->len++;
2600
2601                         sz = btf__resolve_size(btf, id);
2602                         if (sz < 0)
2603                                 return sz;
2604                         spec->bit_offset += access_idx * sz * 8;
2605                 } else {
2606                         pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
2607                                 type_id, spec_str, i, id, btf_kind(t));
2608                         return -EINVAL;
2609                 }
2610         }
2611
2612         return 0;
2613 }
2614
2615 static bool bpf_core_is_flavor_sep(const char *s)
2616 {
2617         /* check X___Y name pattern, where X and Y are not underscores */
2618         return s[0] != '_' &&                                 /* X */
2619                s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
2620                s[4] != '_';                                   /* Y */
2621 }
2622
2623 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
2624  * before last triple underscore. Struct name part after last triple
2625  * underscore is ignored by BPF CO-RE relocation during relocation matching.
2626  */
2627 static size_t bpf_core_essential_name_len(const char *name)
2628 {
2629         size_t n = strlen(name);
2630         int i;
2631
2632         for (i = n - 5; i >= 0; i--) {
2633                 if (bpf_core_is_flavor_sep(name + i))
2634                         return i + 1;
2635         }
2636         return n;
2637 }
2638
2639 /* dynamically sized list of type IDs */
2640 struct ids_vec {
2641         __u32 *data;
2642         int len;
2643 };
2644
2645 static void bpf_core_free_cands(struct ids_vec *cand_ids)
2646 {
2647         free(cand_ids->data);
2648         free(cand_ids);
2649 }
2650
2651 static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
2652                                            __u32 local_type_id,
2653                                            const struct btf *targ_btf)
2654 {
2655         size_t local_essent_len, targ_essent_len;
2656         const char *local_name, *targ_name;
2657         const struct btf_type *t;
2658         struct ids_vec *cand_ids;
2659         __u32 *new_ids;
2660         int i, err, n;
2661
2662         t = btf__type_by_id(local_btf, local_type_id);
2663         if (!t)
2664                 return ERR_PTR(-EINVAL);
2665
2666         local_name = btf__name_by_offset(local_btf, t->name_off);
2667         if (str_is_empty(local_name))
2668                 return ERR_PTR(-EINVAL);
2669         local_essent_len = bpf_core_essential_name_len(local_name);
2670
2671         cand_ids = calloc(1, sizeof(*cand_ids));
2672         if (!cand_ids)
2673                 return ERR_PTR(-ENOMEM);
2674
2675         n = btf__get_nr_types(targ_btf);
2676         for (i = 1; i <= n; i++) {
2677                 t = btf__type_by_id(targ_btf, i);
2678                 targ_name = btf__name_by_offset(targ_btf, t->name_off);
2679                 if (str_is_empty(targ_name))
2680                         continue;
2681
2682                 targ_essent_len = bpf_core_essential_name_len(targ_name);
2683                 if (targ_essent_len != local_essent_len)
2684                         continue;
2685
2686                 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
2687                         pr_debug("[%d] %s: found candidate [%d] %s\n",
2688                                  local_type_id, local_name, i, targ_name);
2689                         new_ids = realloc(cand_ids->data, cand_ids->len + 1);
2690                         if (!new_ids) {
2691                                 err = -ENOMEM;
2692                                 goto err_out;
2693                         }
2694                         cand_ids->data = new_ids;
2695                         cand_ids->data[cand_ids->len++] = i;
2696                 }
2697         }
2698         return cand_ids;
2699 err_out:
2700         bpf_core_free_cands(cand_ids);
2701         return ERR_PTR(err);
2702 }
2703
2704 /* Check two types for compatibility, skipping const/volatile/restrict and
2705  * typedefs, to ensure we are relocating compatible entities:
2706  *   - any two STRUCTs/UNIONs are compatible and can be mixed;
2707  *   - any two FWDs are compatible;
2708  *   - any two PTRs are always compatible;
2709  *   - for ENUMs, check sizes, names are ignored;
2710  *   - for INT, size and signedness are ignored;
2711  *   - for ARRAY, dimensionality is ignored, element types are checked for
2712  *     compatibility recursively;
2713  *   - everything else shouldn't be ever a target of relocation.
2714  * These rules are not set in stone and probably will be adjusted as we get
2715  * more experience with using BPF CO-RE relocations.
2716  */
2717 static int bpf_core_fields_are_compat(const struct btf *local_btf,
2718                                       __u32 local_id,
2719                                       const struct btf *targ_btf,
2720                                       __u32 targ_id)
2721 {
2722         const struct btf_type *local_type, *targ_type;
2723
2724 recur:
2725         local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
2726         targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2727         if (!local_type || !targ_type)
2728                 return -EINVAL;
2729
2730         if (btf_is_composite(local_type) && btf_is_composite(targ_type))
2731                 return 1;
2732         if (btf_kind(local_type) != btf_kind(targ_type))
2733                 return 0;
2734
2735         switch (btf_kind(local_type)) {
2736         case BTF_KIND_FWD:
2737         case BTF_KIND_PTR:
2738                 return 1;
2739         case BTF_KIND_ENUM:
2740                 return local_type->size == targ_type->size;
2741         case BTF_KIND_INT:
2742                 /* just reject deprecated bitfield-like integers; all other
2743                  * integers are by default compatible between each other
2744                  */
2745                 return btf_int_offset(local_type) == 0 &&
2746                        btf_int_offset(targ_type) == 0;
2747         case BTF_KIND_ARRAY:
2748                 local_id = btf_array(local_type)->type;
2749                 targ_id = btf_array(targ_type)->type;
2750                 goto recur;
2751         default:
2752                 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
2753                         btf_kind(local_type), local_id, targ_id);
2754                 return 0;
2755         }
2756 }
2757
2758 /*
2759  * Given single high-level named field accessor in local type, find
2760  * corresponding high-level accessor for a target type. Along the way,
2761  * maintain low-level spec for target as well. Also keep updating target
2762  * bit offset.
2763  *
2764  * Searching is performed through recursive exhaustive enumeration of all
2765  * fields of a struct/union. If there are any anonymous (embedded)
2766  * structs/unions, they are recursively searched as well. If field with
2767  * desired name is found, check compatibility between local and target types,
2768  * before returning result.
2769  *
2770  * 1 is returned, if field is found.
2771  * 0 is returned if no compatible field is found.
2772  * <0 is returned on error.
2773  */
2774 static int bpf_core_match_member(const struct btf *local_btf,
2775                                  const struct bpf_core_accessor *local_acc,
2776                                  const struct btf *targ_btf,
2777                                  __u32 targ_id,
2778                                  struct bpf_core_spec *spec,
2779                                  __u32 *next_targ_id)
2780 {
2781         const struct btf_type *local_type, *targ_type;
2782         const struct btf_member *local_member, *m;
2783         const char *local_name, *targ_name;
2784         __u32 local_id;
2785         int i, n, found;
2786
2787         targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
2788         if (!targ_type)
2789                 return -EINVAL;
2790         if (!btf_is_composite(targ_type))
2791                 return 0;
2792
2793         local_id = local_acc->type_id;
2794         local_type = btf__type_by_id(local_btf, local_id);
2795         local_member = btf_members(local_type) + local_acc->idx;
2796         local_name = btf__name_by_offset(local_btf, local_member->name_off);
2797
2798         n = btf_vlen(targ_type);
2799         m = btf_members(targ_type);
2800         for (i = 0; i < n; i++, m++) {
2801                 __u32 bit_offset;
2802
2803                 bit_offset = btf_member_bit_offset(targ_type, i);
2804
2805                 /* too deep struct/union/array nesting */
2806                 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2807                         return -E2BIG;
2808
2809                 /* speculate this member will be the good one */
2810                 spec->bit_offset += bit_offset;
2811                 spec->raw_spec[spec->raw_len++] = i;
2812
2813                 targ_name = btf__name_by_offset(targ_btf, m->name_off);
2814                 if (str_is_empty(targ_name)) {
2815                         /* embedded struct/union, we need to go deeper */
2816                         found = bpf_core_match_member(local_btf, local_acc,
2817                                                       targ_btf, m->type,
2818                                                       spec, next_targ_id);
2819                         if (found) /* either found or error */
2820                                 return found;
2821                 } else if (strcmp(local_name, targ_name) == 0) {
2822                         /* matching named field */
2823                         struct bpf_core_accessor *targ_acc;
2824
2825                         targ_acc = &spec->spec[spec->len++];
2826                         targ_acc->type_id = targ_id;
2827                         targ_acc->idx = i;
2828                         targ_acc->name = targ_name;
2829
2830                         *next_targ_id = m->type;
2831                         found = bpf_core_fields_are_compat(local_btf,
2832                                                            local_member->type,
2833                                                            targ_btf, m->type);
2834                         if (!found)
2835                                 spec->len--; /* pop accessor */
2836                         return found;
2837                 }
2838                 /* member turned out not to be what we looked for */
2839                 spec->bit_offset -= bit_offset;
2840                 spec->raw_len--;
2841         }
2842
2843         return 0;
2844 }
2845
2846 /*
2847  * Try to match local spec to a target type and, if successful, produce full
2848  * target spec (high-level, low-level + bit offset).
2849  */
2850 static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
2851                                const struct btf *targ_btf, __u32 targ_id,
2852                                struct bpf_core_spec *targ_spec)
2853 {
2854         const struct btf_type *targ_type;
2855         const struct bpf_core_accessor *local_acc;
2856         struct bpf_core_accessor *targ_acc;
2857         int i, sz, matched;
2858
2859         memset(targ_spec, 0, sizeof(*targ_spec));
2860         targ_spec->btf = targ_btf;
2861
2862         local_acc = &local_spec->spec[0];
2863         targ_acc = &targ_spec->spec[0];
2864
2865         for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
2866                 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
2867                                                    &targ_id);
2868                 if (!targ_type)
2869                         return -EINVAL;
2870
2871                 if (local_acc->name) {
2872                         matched = bpf_core_match_member(local_spec->btf,
2873                                                         local_acc,
2874                                                         targ_btf, targ_id,
2875                                                         targ_spec, &targ_id);
2876                         if (matched <= 0)
2877                                 return matched;
2878                 } else {
2879                         /* for i=0, targ_id is already treated as array element
2880                          * type (because it's the original struct), for others
2881                          * we should find array element type first
2882                          */
2883                         if (i > 0) {
2884                                 const struct btf_array *a;
2885
2886                                 if (!btf_is_array(targ_type))
2887                                         return 0;
2888
2889                                 a = btf_array(targ_type);
2890                                 if (local_acc->idx >= a->nelems)
2891                                         return 0;
2892                                 if (!skip_mods_and_typedefs(targ_btf, a->type,
2893                                                             &targ_id))
2894                                         return -EINVAL;
2895                         }
2896
2897                         /* too deep struct/union/array nesting */
2898                         if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
2899                                 return -E2BIG;
2900
2901                         targ_acc->type_id = targ_id;
2902                         targ_acc->idx = local_acc->idx;
2903                         targ_acc->name = NULL;
2904                         targ_spec->len++;
2905                         targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
2906                         targ_spec->raw_len++;
2907
2908                         sz = btf__resolve_size(targ_btf, targ_id);
2909                         if (sz < 0)
2910                                 return sz;
2911                         targ_spec->bit_offset += local_acc->idx * sz * 8;
2912                 }
2913         }
2914
2915         return 1;
2916 }
2917
2918 static int bpf_core_calc_field_relo(const struct bpf_program *prog,
2919                                     const struct bpf_field_reloc *relo,
2920                                     const struct bpf_core_spec *spec,
2921                                     __u32 *val, bool *validate)
2922 {
2923         const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
2924         const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
2925         __u32 byte_off, byte_sz, bit_off, bit_sz;
2926         const struct btf_member *m;
2927         const struct btf_type *mt;
2928         bool bitfield;
2929
2930         /* a[n] accessor needs special handling */
2931         if (!acc->name) {
2932                 if (relo->kind != BPF_FIELD_BYTE_OFFSET) {
2933                         pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access'\n",
2934                                 bpf_program__title(prog, false),
2935                                 relo->kind, relo->insn_off / 8);
2936                         return -EINVAL;
2937                 }
2938                 *val = spec->bit_offset / 8;
2939                 if (validate)
2940                         *validate = true;
2941                 return 0;
2942         }
2943
2944         m = btf_members(t) + acc->idx;
2945         mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
2946         bit_off = spec->bit_offset;
2947         bit_sz = btf_member_bitfield_size(t, acc->idx);
2948
2949         bitfield = bit_sz > 0;
2950         if (bitfield) {
2951                 byte_sz = mt->size;
2952                 byte_off = bit_off / 8 / byte_sz * byte_sz;
2953                 /* figure out smallest int size necessary for bitfield load */
2954                 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
2955                         if (byte_sz >= 8) {
2956                                 /* bitfield can't be read with 64-bit read */
2957                                 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
2958                                         bpf_program__title(prog, false),
2959                                         relo->kind, relo->insn_off / 8);
2960                                 return -E2BIG;
2961                         }
2962                         byte_sz *= 2;
2963                         byte_off = bit_off / 8 / byte_sz * byte_sz;
2964                 }
2965         } else {
2966                 byte_sz = mt->size;
2967                 byte_off = spec->bit_offset / 8;
2968                 bit_sz = byte_sz * 8;
2969         }
2970
2971         /* for bitfields, all the relocatable aspects are ambiguous and we
2972          * might disagree with compiler, so turn off validation of expected
2973          * value, except for signedness
2974          */
2975         if (validate)
2976                 *validate = !bitfield;
2977
2978         switch (relo->kind) {
2979         case BPF_FIELD_BYTE_OFFSET:
2980                 *val = byte_off;
2981                 break;
2982         case BPF_FIELD_BYTE_SIZE:
2983                 *val = byte_sz;
2984                 break;
2985         case BPF_FIELD_SIGNED:
2986                 /* enums will be assumed unsigned */
2987                 *val = btf_is_enum(mt) ||
2988                        (btf_int_encoding(mt) & BTF_INT_SIGNED);
2989                 if (validate)
2990                         *validate = true; /* signedness is never ambiguous */
2991                 break;
2992         case BPF_FIELD_LSHIFT_U64:
2993 #if __BYTE_ORDER == __LITTLE_ENDIAN
2994                 *val = 64 - (bit_off + bit_sz - byte_off  * 8);
2995 #else
2996                 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
2997 #endif
2998                 break;
2999         case BPF_FIELD_RSHIFT_U64:
3000                 *val = 64 - bit_sz;
3001                 if (validate)
3002                         *validate = true; /* right shift is never ambiguous */
3003                 break;
3004         case BPF_FIELD_EXISTS:
3005         default:
3006                 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3007                         bpf_program__title(prog, false),
3008                         relo->kind, relo->insn_off / 8);
3009                 return -EINVAL;
3010         }
3011
3012         return 0;
3013 }
3014
3015 /*
3016  * Patch relocatable BPF instruction.
3017  *
3018  * Patched value is determined by relocation kind and target specification.
3019  * For field existence relocation target spec will be NULL if field is not
3020  * found.
3021  * Expected insn->imm value is determined using relocation kind and local
3022  * spec, and is checked before patching instruction. If actual insn->imm value
3023  * is wrong, bail out with error.
3024  *
3025  * Currently three kinds of BPF instructions are supported:
3026  * 1. rX = <imm> (assignment with immediate operand);
3027  * 2. rX += <imm> (arithmetic operations with immediate operand);
3028  */
3029 static int bpf_core_reloc_insn(struct bpf_program *prog,
3030                                const struct bpf_field_reloc *relo,
3031                                const struct bpf_core_spec *local_spec,
3032                                const struct bpf_core_spec *targ_spec)
3033 {
3034         bool failed = false, validate = true;
3035         __u32 orig_val, new_val;
3036         struct bpf_insn *insn;
3037         int insn_idx, err;
3038         __u8 class;
3039
3040         if (relo->insn_off % sizeof(struct bpf_insn))
3041                 return -EINVAL;
3042         insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3043
3044         if (relo->kind == BPF_FIELD_EXISTS) {
3045                 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3046                 new_val = targ_spec ? 1 : 0;
3047         } else if (!targ_spec) {
3048                 failed = true;
3049                 new_val = (__u32)-1;
3050         } else {
3051                 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3052                                                &orig_val, &validate);
3053                 if (err)
3054                         return err;
3055                 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3056                                                &new_val, NULL);
3057                 if (err)
3058                         return err;
3059         }
3060
3061         insn = &prog->insns[insn_idx];
3062         class = BPF_CLASS(insn->code);
3063
3064         if (class == BPF_ALU || class == BPF_ALU64) {
3065                 if (BPF_SRC(insn->code) != BPF_K)
3066                         return -EINVAL;
3067                 if (!failed && validate && insn->imm != orig_val) {
3068                         pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3069                                 bpf_program__title(prog, false), insn_idx,
3070                                 insn->imm, orig_val, new_val);
3071                         return -EINVAL;
3072                 }
3073                 orig_val = insn->imm;
3074                 insn->imm = new_val;
3075                 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3076                          bpf_program__title(prog, false), insn_idx,
3077                          failed ? " w/ failed reloc" : "", orig_val, new_val);
3078         } else {
3079                 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3080                         bpf_program__title(prog, false),
3081                         insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3082                         insn->off, insn->imm);
3083                 return -EINVAL;
3084         }
3085
3086         return 0;
3087 }
3088
3089 static struct btf *btf_load_raw(const char *path)
3090 {
3091         struct btf *btf;
3092         size_t read_cnt;
3093         struct stat st;
3094         void *data;
3095         FILE *f;
3096
3097         if (stat(path, &st))
3098                 return ERR_PTR(-errno);
3099
3100         data = malloc(st.st_size);
3101         if (!data)
3102                 return ERR_PTR(-ENOMEM);
3103
3104         f = fopen(path, "rb");
3105         if (!f) {
3106                 btf = ERR_PTR(-errno);
3107                 goto cleanup;
3108         }
3109
3110         read_cnt = fread(data, 1, st.st_size, f);
3111         fclose(f);
3112         if (read_cnt < st.st_size) {
3113                 btf = ERR_PTR(-EBADF);
3114                 goto cleanup;
3115         }
3116
3117         btf = btf__new(data, read_cnt);
3118
3119 cleanup:
3120         free(data);
3121         return btf;
3122 }
3123
3124 /*
3125  * Probe few well-known locations for vmlinux kernel image and try to load BTF
3126  * data out of it to use for target BTF.
3127  */
3128 static struct btf *bpf_core_find_kernel_btf(void)
3129 {
3130         struct {
3131                 const char *path_fmt;
3132                 bool raw_btf;
3133         } locations[] = {
3134                 /* try canonical vmlinux BTF through sysfs first */
3135                 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3136                 /* fall back to trying to find vmlinux ELF on disk otherwise */
3137                 { "/boot/vmlinux-%1$s" },
3138                 { "/lib/modules/%1$s/vmlinux-%1$s" },
3139                 { "/lib/modules/%1$s/build/vmlinux" },
3140                 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3141                 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3142                 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3143                 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3144         };
3145         char path[PATH_MAX + 1];
3146         struct utsname buf;
3147         struct btf *btf;
3148         int i;
3149
3150         uname(&buf);
3151
3152         for (i = 0; i < ARRAY_SIZE(locations); i++) {
3153                 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3154
3155                 if (access(path, R_OK))
3156                         continue;
3157
3158                 if (locations[i].raw_btf)
3159                         btf = btf_load_raw(path);
3160                 else
3161                         btf = btf__parse_elf(path, NULL);
3162
3163                 pr_debug("loading kernel BTF '%s': %ld\n",
3164                          path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3165                 if (IS_ERR(btf))
3166                         continue;
3167
3168                 return btf;
3169         }
3170
3171         pr_warn("failed to find valid kernel BTF\n");
3172         return ERR_PTR(-ESRCH);
3173 }
3174
3175 /* Output spec definition in the format:
3176  * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3177  * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3178  */
3179 static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3180 {
3181         const struct btf_type *t;
3182         const char *s;
3183         __u32 type_id;
3184         int i;
3185
3186         type_id = spec->spec[0].type_id;
3187         t = btf__type_by_id(spec->btf, type_id);
3188         s = btf__name_by_offset(spec->btf, t->name_off);
3189         libbpf_print(level, "[%u] %s + ", type_id, s);
3190
3191         for (i = 0; i < spec->raw_len; i++)
3192                 libbpf_print(level, "%d%s", spec->raw_spec[i],
3193                              i == spec->raw_len - 1 ? " => " : ":");
3194
3195         libbpf_print(level, "%u.%u @ &x",
3196                      spec->bit_offset / 8, spec->bit_offset % 8);
3197
3198         for (i = 0; i < spec->len; i++) {
3199                 if (spec->spec[i].name)
3200                         libbpf_print(level, ".%s", spec->spec[i].name);
3201                 else
3202                         libbpf_print(level, "[%u]", spec->spec[i].idx);
3203         }
3204
3205 }
3206
3207 static size_t bpf_core_hash_fn(const void *key, void *ctx)
3208 {
3209         return (size_t)key;
3210 }
3211
3212 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3213 {
3214         return k1 == k2;
3215 }
3216
3217 static void *u32_as_hash_key(__u32 x)
3218 {
3219         return (void *)(uintptr_t)x;
3220 }
3221
3222 /*
3223  * CO-RE relocate single instruction.
3224  *
3225  * The outline and important points of the algorithm:
3226  * 1. For given local type, find corresponding candidate target types.
3227  *    Candidate type is a type with the same "essential" name, ignoring
3228  *    everything after last triple underscore (___). E.g., `sample`,
3229  *    `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3230  *    for each other. Names with triple underscore are referred to as
3231  *    "flavors" and are useful, among other things, to allow to
3232  *    specify/support incompatible variations of the same kernel struct, which
3233  *    might differ between different kernel versions and/or build
3234  *    configurations.
3235  *
3236  *    N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3237  *    converter, when deduplicated BTF of a kernel still contains more than
3238  *    one different types with the same name. In that case, ___2, ___3, etc
3239  *    are appended starting from second name conflict. But start flavors are
3240  *    also useful to be defined "locally", in BPF program, to extract same
3241  *    data from incompatible changes between different kernel
3242  *    versions/configurations. For instance, to handle field renames between
3243  *    kernel versions, one can use two flavors of the struct name with the
3244  *    same common name and use conditional relocations to extract that field,
3245  *    depending on target kernel version.
3246  * 2. For each candidate type, try to match local specification to this
3247  *    candidate target type. Matching involves finding corresponding
3248  *    high-level spec accessors, meaning that all named fields should match,
3249  *    as well as all array accesses should be within the actual bounds. Also,
3250  *    types should be compatible (see bpf_core_fields_are_compat for details).
3251  * 3. It is supported and expected that there might be multiple flavors
3252  *    matching the spec. As long as all the specs resolve to the same set of
3253  *    offsets across all candidates, there is no error. If there is any
3254  *    ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3255  *    imprefection of BTF deduplication, which can cause slight duplication of
3256  *    the same BTF type, if some directly or indirectly referenced (by
3257  *    pointer) type gets resolved to different actual types in different
3258  *    object files. If such situation occurs, deduplicated BTF will end up
3259  *    with two (or more) structurally identical types, which differ only in
3260  *    types they refer to through pointer. This should be OK in most cases and
3261  *    is not an error.
3262  * 4. Candidate types search is performed by linearly scanning through all
3263  *    types in target BTF. It is anticipated that this is overall more
3264  *    efficient memory-wise and not significantly worse (if not better)
3265  *    CPU-wise compared to prebuilding a map from all local type names to
3266  *    a list of candidate type names. It's also sped up by caching resolved
3267  *    list of matching candidates per each local "root" type ID, that has at
3268  *    least one bpf_field_reloc associated with it. This list is shared
3269  *    between multiple relocations for the same type ID and is updated as some
3270  *    of the candidates are pruned due to structural incompatibility.
3271  */
3272 static int bpf_core_reloc_field(struct bpf_program *prog,
3273                                  const struct bpf_field_reloc *relo,
3274                                  int relo_idx,
3275                                  const struct btf *local_btf,
3276                                  const struct btf *targ_btf,
3277                                  struct hashmap *cand_cache)
3278 {
3279         const char *prog_name = bpf_program__title(prog, false);
3280         struct bpf_core_spec local_spec, cand_spec, targ_spec;
3281         const void *type_key = u32_as_hash_key(relo->type_id);
3282         const struct btf_type *local_type, *cand_type;
3283         const char *local_name, *cand_name;
3284         struct ids_vec *cand_ids;
3285         __u32 local_id, cand_id;
3286         const char *spec_str;
3287         int i, j, err;
3288
3289         local_id = relo->type_id;
3290         local_type = btf__type_by_id(local_btf, local_id);
3291         if (!local_type)
3292                 return -EINVAL;
3293
3294         local_name = btf__name_by_offset(local_btf, local_type->name_off);
3295         if (str_is_empty(local_name))
3296                 return -EINVAL;
3297
3298         spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
3299         if (str_is_empty(spec_str))
3300                 return -EINVAL;
3301
3302         err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
3303         if (err) {
3304                 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
3305                         prog_name, relo_idx, local_id, local_name, spec_str,
3306                         err);
3307                 return -EINVAL;
3308         }
3309
3310         pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
3311                  relo->kind);
3312         bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
3313         libbpf_print(LIBBPF_DEBUG, "\n");
3314
3315         if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
3316                 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
3317                 if (IS_ERR(cand_ids)) {
3318                         pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
3319                                 prog_name, relo_idx, local_id, local_name,
3320                                 PTR_ERR(cand_ids));
3321                         return PTR_ERR(cand_ids);
3322                 }
3323                 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
3324                 if (err) {
3325                         bpf_core_free_cands(cand_ids);
3326                         return err;
3327                 }
3328         }
3329
3330         for (i = 0, j = 0; i < cand_ids->len; i++) {
3331                 cand_id = cand_ids->data[i];
3332                 cand_type = btf__type_by_id(targ_btf, cand_id);
3333                 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
3334
3335                 err = bpf_core_spec_match(&local_spec, targ_btf,
3336                                           cand_id, &cand_spec);
3337                 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
3338                          prog_name, relo_idx, i, cand_name);
3339                 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
3340                 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
3341                 if (err < 0) {
3342                         pr_warn("prog '%s': relo #%d: matching error: %d\n",
3343                                 prog_name, relo_idx, err);
3344                         return err;
3345                 }
3346                 if (err == 0)
3347                         continue;
3348
3349                 if (j == 0) {
3350                         targ_spec = cand_spec;
3351                 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
3352                         /* if there are many candidates, they should all
3353                          * resolve to the same bit offset
3354                          */
3355                         pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
3356                                 prog_name, relo_idx, cand_spec.bit_offset,
3357                                 targ_spec.bit_offset);
3358                         return -EINVAL;
3359                 }
3360
3361                 cand_ids->data[j++] = cand_spec.spec[0].type_id;
3362         }
3363
3364         /*
3365          * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
3366          * requested, it's expected that we might not find any candidates.
3367          * In this case, if field wasn't found in any candidate, the list of
3368          * candidates shouldn't change at all, we'll just handle relocating
3369          * appropriately, depending on relo's kind.
3370          */
3371         if (j > 0)
3372                 cand_ids->len = j;
3373
3374         if (j == 0 && !prog->obj->relaxed_core_relocs &&
3375             relo->kind != BPF_FIELD_EXISTS) {
3376                 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
3377                         prog_name, relo_idx, local_id, local_name, spec_str);
3378                 return -ESRCH;
3379         }
3380
3381         /* bpf_core_reloc_insn should know how to handle missing targ_spec */
3382         err = bpf_core_reloc_insn(prog, relo, &local_spec,
3383                                   j ? &targ_spec : NULL);
3384         if (err) {
3385                 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
3386                         prog_name, relo_idx, relo->insn_off, err);
3387                 return -EINVAL;
3388         }
3389
3390         return 0;
3391 }
3392
3393 static int
3394 bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
3395 {
3396         const struct btf_ext_info_sec *sec;
3397         const struct bpf_field_reloc *rec;
3398         const struct btf_ext_info *seg;
3399         struct hashmap_entry *entry;
3400         struct hashmap *cand_cache = NULL;
3401         struct bpf_program *prog;
3402         struct btf *targ_btf;
3403         const char *sec_name;
3404         int i, err = 0;
3405
3406         if (targ_btf_path)
3407                 targ_btf = btf__parse_elf(targ_btf_path, NULL);
3408         else
3409                 targ_btf = bpf_core_find_kernel_btf();
3410         if (IS_ERR(targ_btf)) {
3411                 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
3412                 return PTR_ERR(targ_btf);
3413         }
3414
3415         cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
3416         if (IS_ERR(cand_cache)) {
3417                 err = PTR_ERR(cand_cache);
3418                 goto out;
3419         }
3420
3421         seg = &obj->btf_ext->field_reloc_info;
3422         for_each_btf_ext_sec(seg, sec) {
3423                 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3424                 if (str_is_empty(sec_name)) {
3425                         err = -EINVAL;
3426                         goto out;
3427                 }
3428                 prog = bpf_object__find_program_by_title(obj, sec_name);
3429                 if (!prog) {
3430                         pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
3431                                 sec_name);
3432                         err = -EINVAL;
3433                         goto out;
3434                 }
3435
3436                 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
3437                          sec_name, sec->num_info);
3438
3439                 for_each_btf_ext_rec(seg, sec, i, rec) {
3440                         err = bpf_core_reloc_field(prog, rec, i, obj->btf,
3441                                                    targ_btf, cand_cache);
3442                         if (err) {
3443                                 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
3444                                         sec_name, i, err);
3445                                 goto out;
3446                         }
3447                 }
3448         }
3449
3450 out:
3451         btf__free(targ_btf);
3452         if (!IS_ERR_OR_NULL(cand_cache)) {
3453                 hashmap__for_each_entry(cand_cache, entry, i) {
3454                         bpf_core_free_cands(entry->value);
3455                 }
3456                 hashmap__free(cand_cache);
3457         }
3458         return err;
3459 }
3460
3461 static int
3462 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
3463 {
3464         int err = 0;
3465
3466         if (obj->btf_ext->field_reloc_info.len)
3467                 err = bpf_core_reloc_fields(obj, targ_btf_path);
3468
3469         return err;
3470 }
3471
3472 static int
3473 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
3474                         struct reloc_desc *relo)
3475 {
3476         struct bpf_insn *insn, *new_insn;
3477         struct bpf_program *text;
3478         size_t new_cnt;
3479         int err;
3480
3481         if (relo->type != RELO_CALL)
3482                 return -LIBBPF_ERRNO__RELOC;
3483
3484         if (prog->idx == obj->efile.text_shndx) {
3485                 pr_warn("relo in .text insn %d into off %d\n",
3486                         relo->insn_idx, relo->text_off);
3487                 return -LIBBPF_ERRNO__RELOC;
3488         }
3489
3490         if (prog->main_prog_cnt == 0) {
3491                 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
3492                 if (!text) {
3493                         pr_warn("no .text section found yet relo into text exist\n");
3494                         return -LIBBPF_ERRNO__RELOC;
3495                 }
3496                 new_cnt = prog->insns_cnt + text->insns_cnt;
3497                 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
3498                 if (!new_insn) {
3499                         pr_warn("oom in prog realloc\n");
3500                         return -ENOMEM;
3501                 }
3502
3503                 if (obj->btf_ext) {
3504                         err = bpf_program_reloc_btf_ext(prog, obj,
3505                                                         text->section_name,
3506                                                         prog->insns_cnt);
3507                         if (err)
3508                                 return err;
3509                 }
3510
3511                 memcpy(new_insn + prog->insns_cnt, text->insns,
3512                        text->insns_cnt * sizeof(*insn));
3513                 prog->insns = new_insn;
3514                 prog->main_prog_cnt = prog->insns_cnt;
3515                 prog->insns_cnt = new_cnt;
3516                 pr_debug("added %zd insn from %s to prog %s\n",
3517                          text->insns_cnt, text->section_name,
3518                          prog->section_name);
3519         }
3520         insn = &prog->insns[relo->insn_idx];
3521         insn->imm += prog->main_prog_cnt - relo->insn_idx;
3522         return 0;
3523 }
3524
3525 static int
3526 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
3527 {
3528         int i, err;
3529
3530         if (!prog)
3531                 return 0;
3532
3533         if (obj->btf_ext) {
3534                 err = bpf_program_reloc_btf_ext(prog, obj,
3535                                                 prog->section_name, 0);
3536                 if (err)
3537                         return err;
3538         }
3539
3540         if (!prog->reloc_desc)
3541                 return 0;
3542
3543         for (i = 0; i < prog->nr_reloc; i++) {
3544                 if (prog->reloc_desc[i].type == RELO_LD64 ||
3545                     prog->reloc_desc[i].type == RELO_DATA) {
3546                         bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
3547                         struct bpf_insn *insns = prog->insns;
3548                         int insn_idx, map_idx;
3549
3550                         insn_idx = prog->reloc_desc[i].insn_idx;
3551                         map_idx = prog->reloc_desc[i].map_idx;
3552
3553                         if (insn_idx + 1 >= (int)prog->insns_cnt) {
3554                                 pr_warn("relocation out of range: '%s'\n",
3555                                         prog->section_name);
3556                                 return -LIBBPF_ERRNO__RELOC;
3557                         }
3558
3559                         if (!relo_data) {
3560                                 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
3561                         } else {
3562                                 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
3563                                 insns[insn_idx + 1].imm = insns[insn_idx].imm;
3564                         }
3565                         insns[insn_idx].imm = obj->maps[map_idx].fd;
3566                 } else if (prog->reloc_desc[i].type == RELO_CALL) {
3567                         err = bpf_program__reloc_text(prog, obj,
3568                                                       &prog->reloc_desc[i]);
3569                         if (err)
3570                                 return err;
3571                 }
3572         }
3573
3574         zfree(&prog->reloc_desc);
3575         prog->nr_reloc = 0;
3576         return 0;
3577 }
3578
3579 static int
3580 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
3581 {
3582         struct bpf_program *prog;
3583         size_t i;
3584         int err;
3585
3586         if (obj->btf_ext) {
3587                 err = bpf_object__relocate_core(obj, targ_btf_path);
3588                 if (err) {
3589                         pr_warn("failed to perform CO-RE relocations: %d\n",
3590                                 err);
3591                         return err;
3592                 }
3593         }
3594         for (i = 0; i < obj->nr_programs; i++) {
3595                 prog = &obj->programs[i];
3596
3597                 err = bpf_program__relocate(prog, obj);
3598                 if (err) {
3599                         pr_warn("failed to relocate '%s'\n", prog->section_name);
3600                         return err;
3601                 }
3602         }
3603         return 0;
3604 }
3605
3606 static int bpf_object__collect_reloc(struct bpf_object *obj)
3607 {
3608         int i, err;
3609
3610         if (!obj_elf_valid(obj)) {
3611                 pr_warn("Internal error: elf object is closed\n");
3612                 return -LIBBPF_ERRNO__INTERNAL;
3613         }
3614
3615         for (i = 0; i < obj->efile.nr_reloc; i++) {
3616                 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
3617                 Elf_Data *data = obj->efile.reloc[i].data;
3618                 int idx = shdr->sh_info;
3619                 struct bpf_program *prog;
3620
3621                 if (shdr->sh_type != SHT_REL) {
3622                         pr_warn("internal error at %d\n", __LINE__);
3623                         return -LIBBPF_ERRNO__INTERNAL;
3624                 }
3625
3626                 prog = bpf_object__find_prog_by_idx(obj, idx);
3627                 if (!prog) {
3628                         pr_warn("relocation failed: no section(%d)\n", idx);
3629                         return -LIBBPF_ERRNO__RELOC;
3630                 }
3631
3632                 err = bpf_program__collect_reloc(prog, shdr, data, obj);
3633                 if (err)
3634                         return err;
3635         }
3636         return 0;
3637 }
3638
3639 static int
3640 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
3641              char *license, __u32 kern_version, int *pfd)
3642 {
3643         struct bpf_load_program_attr load_attr;
3644         char *cp, errmsg[STRERR_BUFSIZE];
3645         int log_buf_size = BPF_LOG_BUF_SIZE;
3646         char *log_buf;
3647         int btf_fd, ret;
3648
3649         if (!insns || !insns_cnt)
3650                 return -EINVAL;
3651
3652         memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
3653         load_attr.prog_type = prog->type;
3654         load_attr.expected_attach_type = prog->expected_attach_type;
3655         if (prog->caps->name)
3656                 load_attr.name = prog->name;
3657         load_attr.insns = insns;
3658         load_attr.insns_cnt = insns_cnt;
3659         load_attr.license = license;
3660         load_attr.kern_version = kern_version;
3661         load_attr.prog_ifindex = prog->prog_ifindex;
3662         /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
3663         if (prog->obj->btf_ext)
3664                 btf_fd = bpf_object__btf_fd(prog->obj);
3665         else
3666                 btf_fd = -1;
3667         load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
3668         load_attr.func_info = prog->func_info;
3669         load_attr.func_info_rec_size = prog->func_info_rec_size;
3670         load_attr.func_info_cnt = prog->func_info_cnt;
3671         load_attr.line_info = prog->line_info;
3672         load_attr.line_info_rec_size = prog->line_info_rec_size;
3673         load_attr.line_info_cnt = prog->line_info_cnt;
3674         load_attr.log_level = prog->log_level;
3675         load_attr.prog_flags = prog->prog_flags;
3676         load_attr.attach_btf_id = prog->attach_btf_id;
3677
3678 retry_load:
3679         log_buf = malloc(log_buf_size);
3680         if (!log_buf)
3681                 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
3682
3683         ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
3684
3685         if (ret >= 0) {
3686                 if (load_attr.log_level)
3687                         pr_debug("verifier log:\n%s", log_buf);
3688                 *pfd = ret;
3689                 ret = 0;
3690                 goto out;
3691         }
3692
3693         if (errno == ENOSPC) {
3694                 log_buf_size <<= 1;
3695                 free(log_buf);
3696                 goto retry_load;
3697         }
3698         ret = -LIBBPF_ERRNO__LOAD;
3699         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3700         pr_warn("load bpf program failed: %s\n", cp);
3701
3702         if (log_buf && log_buf[0] != '\0') {
3703                 ret = -LIBBPF_ERRNO__VERIFY;
3704                 pr_warn("-- BEGIN DUMP LOG ---\n");
3705                 pr_warn("\n%s\n", log_buf);
3706                 pr_warn("-- END LOG --\n");
3707         } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
3708                 pr_warn("Program too large (%zu insns), at most %d insns\n",
3709                         load_attr.insns_cnt, BPF_MAXINSNS);
3710                 ret = -LIBBPF_ERRNO__PROG2BIG;
3711         } else {
3712                 /* Wrong program type? */
3713                 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
3714                         int fd;
3715
3716                         load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
3717                         load_attr.expected_attach_type = 0;
3718                         fd = bpf_load_program_xattr(&load_attr, NULL, 0);
3719                         if (fd >= 0) {
3720                                 close(fd);
3721                                 ret = -LIBBPF_ERRNO__PROGTYPE;
3722                                 goto out;
3723                         }
3724                 }
3725
3726                 if (log_buf)
3727                         ret = -LIBBPF_ERRNO__KVER;
3728         }
3729
3730 out:
3731         free(log_buf);
3732         return ret;
3733 }
3734
3735 int
3736 bpf_program__load(struct bpf_program *prog,
3737                   char *license, __u32 kern_version)
3738 {
3739         int err = 0, fd, i;
3740
3741         if (prog->instances.nr < 0 || !prog->instances.fds) {
3742                 if (prog->preprocessor) {
3743                         pr_warn("Internal error: can't load program '%s'\n",
3744                                 prog->section_name);
3745                         return -LIBBPF_ERRNO__INTERNAL;
3746                 }
3747
3748                 prog->instances.fds = malloc(sizeof(int));
3749                 if (!prog->instances.fds) {
3750                         pr_warn("Not enough memory for BPF fds\n");
3751                         return -ENOMEM;
3752                 }
3753                 prog->instances.nr = 1;
3754                 prog->instances.fds[0] = -1;
3755         }
3756
3757         if (!prog->preprocessor) {
3758                 if (prog->instances.nr != 1) {
3759                         pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
3760                                 prog->section_name, prog->instances.nr);
3761                 }
3762                 err = load_program(prog, prog->insns, prog->insns_cnt,
3763                                    license, kern_version, &fd);
3764                 if (!err)
3765                         prog->instances.fds[0] = fd;
3766                 goto out;
3767         }
3768
3769         for (i = 0; i < prog->instances.nr; i++) {
3770                 struct bpf_prog_prep_result result;
3771                 bpf_program_prep_t preprocessor = prog->preprocessor;
3772
3773                 memset(&result, 0, sizeof(result));
3774                 err = preprocessor(prog, i, prog->insns,
3775                                    prog->insns_cnt, &result);
3776                 if (err) {
3777                         pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
3778                                 i, prog->section_name);
3779                         goto out;
3780                 }
3781
3782                 if (!result.new_insn_ptr || !result.new_insn_cnt) {
3783                         pr_debug("Skip loading the %dth instance of program '%s'\n",
3784                                  i, prog->section_name);
3785                         prog->instances.fds[i] = -1;
3786                         if (result.pfd)
3787                                 *result.pfd = -1;
3788                         continue;
3789                 }
3790
3791                 err = load_program(prog, result.new_insn_ptr,
3792                                    result.new_insn_cnt,
3793                                    license, kern_version, &fd);
3794
3795                 if (err) {
3796                         pr_warn("Loading the %dth instance of program '%s' failed\n",
3797                                 i, prog->section_name);
3798                         goto out;
3799                 }
3800
3801                 if (result.pfd)
3802                         *result.pfd = fd;
3803                 prog->instances.fds[i] = fd;
3804         }
3805 out:
3806         if (err)
3807                 pr_warn("failed to load program '%s'\n", prog->section_name);
3808         zfree(&prog->insns);
3809         prog->insns_cnt = 0;
3810         return err;
3811 }
3812
3813 static bool bpf_program__is_function_storage(const struct bpf_program *prog,
3814                                              const struct bpf_object *obj)
3815 {
3816         return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
3817 }
3818
3819 static int
3820 bpf_object__load_progs(struct bpf_object *obj, int log_level)
3821 {
3822         size_t i;
3823         int err;
3824
3825         for (i = 0; i < obj->nr_programs; i++) {
3826                 if (bpf_program__is_function_storage(&obj->programs[i], obj))
3827                         continue;
3828                 obj->programs[i].log_level |= log_level;
3829                 err = bpf_program__load(&obj->programs[i],
3830                                         obj->license,
3831                                         obj->kern_version);
3832                 if (err)
3833                         return err;
3834         }
3835         return 0;
3836 }
3837
3838 static int libbpf_attach_btf_id_by_name(const char *name, __u32 *btf_id);
3839
3840 static struct bpf_object *
3841 __bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
3842                    struct bpf_object_open_opts *opts)
3843 {
3844         const char *pin_root_path;
3845         struct bpf_program *prog;
3846         struct bpf_object *obj;
3847         const char *obj_name;
3848         char tmp_name[64];
3849         bool relaxed_maps;
3850         int err;
3851
3852         if (elf_version(EV_CURRENT) == EV_NONE) {
3853                 pr_warn("failed to init libelf for %s\n",
3854                         path ? : "(mem buf)");
3855                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
3856         }
3857
3858         if (!OPTS_VALID(opts, bpf_object_open_opts))
3859                 return ERR_PTR(-EINVAL);
3860
3861         obj_name = OPTS_GET(opts, object_name, path);
3862         if (obj_buf) {
3863                 if (!obj_name) {
3864                         snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
3865                                  (unsigned long)obj_buf,
3866                                  (unsigned long)obj_buf_sz);
3867                         obj_name = tmp_name;
3868                 }
3869                 path = obj_name;
3870                 pr_debug("loading object '%s' from buffer\n", obj_name);
3871         }
3872
3873         obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
3874         if (IS_ERR(obj))
3875                 return obj;
3876
3877         obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
3878         relaxed_maps = OPTS_GET(opts, relaxed_maps, false);
3879         pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3880
3881         CHECK_ERR(bpf_object__elf_init(obj), err, out);
3882         CHECK_ERR(bpf_object__check_endianness(obj), err, out);
3883         CHECK_ERR(bpf_object__probe_caps(obj), err, out);
3884         CHECK_ERR(bpf_object__elf_collect(obj, relaxed_maps, pin_root_path),
3885                   err, out);
3886         CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
3887         bpf_object__elf_finish(obj);
3888
3889         bpf_object__for_each_program(prog, obj) {
3890                 enum bpf_prog_type prog_type;
3891                 enum bpf_attach_type attach_type;
3892                 __u32 btf_id;
3893
3894                 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
3895                                                &attach_type);
3896                 if (err == -ESRCH)
3897                         /* couldn't guess, but user might manually specify */
3898                         continue;
3899                 if (err)
3900                         goto out;
3901
3902                 bpf_program__set_type(prog, prog_type);
3903                 bpf_program__set_expected_attach_type(prog, attach_type);
3904                 if (prog_type == BPF_PROG_TYPE_TRACING) {
3905                         err = libbpf_attach_btf_id_by_name(prog->section_name, &btf_id);
3906                         if (err)
3907                                 goto out;
3908                         prog->attach_btf_id = btf_id;
3909                 }
3910         }
3911
3912         return obj;
3913 out:
3914         bpf_object__close(obj);
3915         return ERR_PTR(err);
3916 }
3917
3918 static struct bpf_object *
3919 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
3920 {
3921         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
3922                 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
3923         );
3924
3925         /* param validation */
3926         if (!attr->file)
3927                 return NULL;
3928
3929         pr_debug("loading %s\n", attr->file);
3930         return __bpf_object__open(attr->file, NULL, 0, &opts);
3931 }
3932
3933 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
3934 {
3935         return __bpf_object__open_xattr(attr, 0);
3936 }
3937
3938 struct bpf_object *bpf_object__open(const char *path)
3939 {
3940         struct bpf_object_open_attr attr = {
3941                 .file           = path,
3942                 .prog_type      = BPF_PROG_TYPE_UNSPEC,
3943         };
3944
3945         return bpf_object__open_xattr(&attr);
3946 }
3947
3948 struct bpf_object *
3949 bpf_object__open_file(const char *path, struct bpf_object_open_opts *opts)
3950 {
3951         if (!path)
3952                 return ERR_PTR(-EINVAL);
3953
3954         pr_debug("loading %s\n", path);
3955
3956         return __bpf_object__open(path, NULL, 0, opts);
3957 }
3958
3959 struct bpf_object *
3960 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
3961                      struct bpf_object_open_opts *opts)
3962 {
3963         if (!obj_buf || obj_buf_sz == 0)
3964                 return ERR_PTR(-EINVAL);
3965
3966         return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
3967 }
3968
3969 struct bpf_object *
3970 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
3971                         const char *name)
3972 {
3973         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
3974                 .object_name = name,
3975                 /* wrong default, but backwards-compatible */
3976                 .relaxed_maps = true,
3977         );
3978
3979         /* returning NULL is wrong, but backwards-compatible */
3980         if (!obj_buf || obj_buf_sz == 0)
3981                 return NULL;
3982
3983         return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
3984 }
3985
3986 int bpf_object__unload(struct bpf_object *obj)
3987 {
3988         size_t i;
3989
3990         if (!obj)
3991                 return -EINVAL;
3992
3993         for (i = 0; i < obj->nr_maps; i++)
3994                 zclose(obj->maps[i].fd);
3995
3996         for (i = 0; i < obj->nr_programs; i++)
3997                 bpf_program__unload(&obj->programs[i]);
3998
3999         return 0;
4000 }
4001
4002 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
4003 {
4004         struct bpf_object *obj;
4005         int err;
4006
4007         if (!attr)
4008                 return -EINVAL;
4009         obj = attr->obj;
4010         if (!obj)
4011                 return -EINVAL;
4012
4013         if (obj->loaded) {
4014                 pr_warn("object should not be loaded twice\n");
4015                 return -EINVAL;
4016         }
4017
4018         obj->loaded = true;
4019
4020         CHECK_ERR(bpf_object__create_maps(obj), err, out);
4021         CHECK_ERR(bpf_object__relocate(obj, attr->target_btf_path), err, out);
4022         CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
4023
4024         return 0;
4025 out:
4026         bpf_object__unload(obj);
4027         pr_warn("failed to load object '%s'\n", obj->path);
4028         return err;
4029 }
4030
4031 int bpf_object__load(struct bpf_object *obj)
4032 {
4033         struct bpf_object_load_attr attr = {
4034                 .obj = obj,
4035         };
4036
4037         return bpf_object__load_xattr(&attr);
4038 }
4039
4040 static int make_parent_dir(const char *path)
4041 {
4042         char *cp, errmsg[STRERR_BUFSIZE];
4043         char *dname, *dir;
4044         int err = 0;
4045
4046         dname = strdup(path);
4047         if (dname == NULL)
4048                 return -ENOMEM;
4049
4050         dir = dirname(dname);
4051         if (mkdir(dir, 0700) && errno != EEXIST)
4052                 err = -errno;
4053
4054         free(dname);
4055         if (err) {
4056                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4057                 pr_warn("failed to mkdir %s: %s\n", path, cp);
4058         }
4059         return err;
4060 }
4061
4062 static int check_path(const char *path)
4063 {
4064         char *cp, errmsg[STRERR_BUFSIZE];
4065         struct statfs st_fs;
4066         char *dname, *dir;
4067         int err = 0;
4068
4069         if (path == NULL)
4070                 return -EINVAL;
4071
4072         dname = strdup(path);
4073         if (dname == NULL)
4074                 return -ENOMEM;
4075
4076         dir = dirname(dname);
4077         if (statfs(dir, &st_fs)) {
4078                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4079                 pr_warn("failed to statfs %s: %s\n", dir, cp);
4080                 err = -errno;
4081         }
4082         free(dname);
4083
4084         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
4085                 pr_warn("specified path %s is not on BPF FS\n", path);
4086                 err = -EINVAL;
4087         }
4088
4089         return err;
4090 }
4091
4092 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4093                               int instance)
4094 {
4095         char *cp, errmsg[STRERR_BUFSIZE];
4096         int err;
4097
4098         err = make_parent_dir(path);
4099         if (err)
4100                 return err;
4101
4102         err = check_path(path);
4103         if (err)
4104                 return err;
4105
4106         if (prog == NULL) {
4107                 pr_warn("invalid program pointer\n");
4108                 return -EINVAL;
4109         }
4110
4111         if (instance < 0 || instance >= prog->instances.nr) {
4112                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4113                         instance, prog->section_name, prog->instances.nr);
4114                 return -EINVAL;
4115         }
4116
4117         if (bpf_obj_pin(prog->instances.fds[instance], path)) {
4118                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
4119                 pr_warn("failed to pin program: %s\n", cp);
4120                 return -errno;
4121         }
4122         pr_debug("pinned program '%s'\n", path);
4123
4124         return 0;
4125 }
4126
4127 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4128                                 int instance)
4129 {
4130         int err;
4131
4132         err = check_path(path);
4133         if (err)
4134                 return err;
4135
4136         if (prog == NULL) {
4137                 pr_warn("invalid program pointer\n");
4138                 return -EINVAL;
4139         }
4140
4141         if (instance < 0 || instance >= prog->instances.nr) {
4142                 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4143                         instance, prog->section_name, prog->instances.nr);
4144                 return -EINVAL;
4145         }
4146
4147         err = unlink(path);
4148         if (err != 0)
4149                 return -errno;
4150         pr_debug("unpinned program '%s'\n", path);
4151
4152         return 0;
4153 }
4154
4155 int bpf_program__pin(struct bpf_program *prog, const char *path)
4156 {
4157         int i, err;
4158
4159         err = make_parent_dir(path);
4160         if (err)
4161                 return err;
4162
4163         err = check_path(path);
4164         if (err)
4165                 return err;
4166
4167         if (prog == NULL) {
4168                 pr_warn("invalid program pointer\n");
4169                 return -EINVAL;
4170         }
4171
4172         if (prog->instances.nr <= 0) {
4173                 pr_warn("no instances of prog %s to pin\n",
4174                            prog->section_name);
4175                 return -EINVAL;
4176         }
4177
4178         if (prog->instances.nr == 1) {
4179                 /* don't create subdirs when pinning single instance */
4180                 return bpf_program__pin_instance(prog, path, 0);
4181         }
4182
4183         for (i = 0; i < prog->instances.nr; i++) {
4184                 char buf[PATH_MAX];
4185                 int len;
4186
4187                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4188                 if (len < 0) {
4189                         err = -EINVAL;
4190                         goto err_unpin;
4191                 } else if (len >= PATH_MAX) {
4192                         err = -ENAMETOOLONG;
4193                         goto err_unpin;
4194                 }
4195
4196                 err = bpf_program__pin_instance(prog, buf, i);
4197                 if (err)
4198                         goto err_unpin;
4199         }
4200
4201         return 0;
4202
4203 err_unpin:
4204         for (i = i - 1; i >= 0; i--) {
4205                 char buf[PATH_MAX];
4206                 int len;
4207
4208                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4209                 if (len < 0)
4210                         continue;
4211                 else if (len >= PATH_MAX)
4212                         continue;
4213
4214                 bpf_program__unpin_instance(prog, buf, i);
4215         }
4216
4217         rmdir(path);
4218
4219         return err;
4220 }
4221
4222 int bpf_program__unpin(struct bpf_program *prog, const char *path)
4223 {
4224         int i, err;
4225
4226         err = check_path(path);
4227         if (err)
4228                 return err;
4229
4230         if (prog == NULL) {
4231                 pr_warn("invalid program pointer\n");
4232                 return -EINVAL;
4233         }
4234
4235         if (prog->instances.nr <= 0) {
4236                 pr_warn("no instances of prog %s to pin\n",
4237                            prog->section_name);
4238                 return -EINVAL;
4239         }
4240
4241         if (prog->instances.nr == 1) {
4242                 /* don't create subdirs when pinning single instance */
4243                 return bpf_program__unpin_instance(prog, path, 0);
4244         }
4245
4246         for (i = 0; i < prog->instances.nr; i++) {
4247                 char buf[PATH_MAX];
4248                 int len;
4249
4250                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
4251                 if (len < 0)
4252                         return -EINVAL;
4253                 else if (len >= PATH_MAX)
4254                         return -ENAMETOOLONG;
4255
4256                 err = bpf_program__unpin_instance(prog, buf, i);
4257                 if (err)
4258                         return err;
4259         }
4260
4261         err = rmdir(path);
4262         if (err)
4263                 return -errno;
4264
4265         return 0;
4266 }
4267
4268 int bpf_map__pin(struct bpf_map *map, const char *path)
4269 {
4270         char *cp, errmsg[STRERR_BUFSIZE];
4271         int err;
4272
4273         if (map == NULL) {
4274                 pr_warn("invalid map pointer\n");
4275                 return -EINVAL;
4276         }
4277
4278         if (map->pin_path) {
4279                 if (path && strcmp(path, map->pin_path)) {
4280                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4281                                 bpf_map__name(map), map->pin_path, path);
4282                         return -EINVAL;
4283                 } else if (map->pinned) {
4284                         pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
4285                                  bpf_map__name(map), map->pin_path);
4286                         return 0;
4287                 }
4288         } else {
4289                 if (!path) {
4290                         pr_warn("missing a path to pin map '%s' at\n",
4291                                 bpf_map__name(map));
4292                         return -EINVAL;
4293                 } else if (map->pinned) {
4294                         pr_warn("map '%s' already pinned\n", bpf_map__name(map));
4295                         return -EEXIST;
4296                 }
4297
4298                 map->pin_path = strdup(path);
4299                 if (!map->pin_path) {
4300                         err = -errno;
4301                         goto out_err;
4302                 }
4303         }
4304
4305         err = make_parent_dir(map->pin_path);
4306         if (err)
4307                 return err;
4308
4309         err = check_path(map->pin_path);
4310         if (err)
4311                 return err;
4312
4313         if (bpf_obj_pin(map->fd, map->pin_path)) {
4314                 err = -errno;
4315                 goto out_err;
4316         }
4317
4318         map->pinned = true;
4319         pr_debug("pinned map '%s'\n", map->pin_path);
4320
4321         return 0;
4322
4323 out_err:
4324         cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4325         pr_warn("failed to pin map: %s\n", cp);
4326         return err;
4327 }
4328
4329 int bpf_map__unpin(struct bpf_map *map, const char *path)
4330 {
4331         int err;
4332
4333         if (map == NULL) {
4334                 pr_warn("invalid map pointer\n");
4335                 return -EINVAL;
4336         }
4337
4338         if (map->pin_path) {
4339                 if (path && strcmp(path, map->pin_path)) {
4340                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
4341                                 bpf_map__name(map), map->pin_path, path);
4342                         return -EINVAL;
4343                 }
4344                 path = map->pin_path;
4345         } else if (!path) {
4346                 pr_warn("no path to unpin map '%s' from\n",
4347                         bpf_map__name(map));
4348                 return -EINVAL;
4349         }
4350
4351         err = check_path(path);
4352         if (err)
4353                 return err;
4354
4355         err = unlink(path);
4356         if (err != 0)
4357                 return -errno;
4358
4359         map->pinned = false;
4360         pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
4361
4362         return 0;
4363 }
4364
4365 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
4366 {
4367         char *new = NULL;
4368
4369         if (path) {
4370                 new = strdup(path);
4371                 if (!new)
4372                         return -errno;
4373         }
4374
4375         free(map->pin_path);
4376         map->pin_path = new;
4377         return 0;
4378 }
4379
4380 const char *bpf_map__get_pin_path(const struct bpf_map *map)
4381 {
4382         return map->pin_path;
4383 }
4384
4385 bool bpf_map__is_pinned(const struct bpf_map *map)
4386 {
4387         return map->pinned;
4388 }
4389
4390 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
4391 {
4392         struct bpf_map *map;
4393         int err;
4394
4395         if (!obj)
4396                 return -ENOENT;
4397
4398         if (!obj->loaded) {
4399                 pr_warn("object not yet loaded; load it first\n");
4400                 return -ENOENT;
4401         }
4402
4403         bpf_object__for_each_map(map, obj) {
4404                 char *pin_path = NULL;
4405                 char buf[PATH_MAX];
4406
4407                 if (path) {
4408                         int len;
4409
4410                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
4411                                        bpf_map__name(map));
4412                         if (len < 0) {
4413                                 err = -EINVAL;
4414                                 goto err_unpin_maps;
4415                         } else if (len >= PATH_MAX) {
4416                                 err = -ENAMETOOLONG;
4417                                 goto err_unpin_maps;
4418                         }
4419                         pin_path = buf;
4420                 } else if (!map->pin_path) {
4421                         continue;
4422                 }
4423
4424                 err = bpf_map__pin(map, pin_path);
4425                 if (err)
4426                         goto err_unpin_maps;
4427         }
4428
4429         return 0;
4430
4431 err_unpin_maps:
4432         while ((map = bpf_map__prev(map, obj))) {
4433                 if (!map->pin_path)
4434                         continue;
4435
4436                 bpf_map__unpin(map, NULL);
4437         }
4438
4439         return err;
4440 }
4441
4442 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
4443 {
4444         struct bpf_map *map;
4445         int err;
4446
4447         if (!obj)
4448                 return -ENOENT;
4449
4450         bpf_object__for_each_map(map, obj) {
4451                 char *pin_path = NULL;
4452                 char buf[PATH_MAX];
4453
4454                 if (path) {
4455                         int len;
4456
4457                         len = snprintf(buf, PATH_MAX, "%s/%s", path,
4458                                        bpf_map__name(map));
4459                         if (len < 0)
4460                                 return -EINVAL;
4461                         else if (len >= PATH_MAX)
4462                                 return -ENAMETOOLONG;
4463                         pin_path = buf;
4464                 } else if (!map->pin_path) {
4465                         continue;
4466                 }
4467
4468                 err = bpf_map__unpin(map, pin_path);
4469                 if (err)
4470                         return err;
4471         }
4472
4473         return 0;
4474 }
4475
4476 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
4477 {
4478         struct bpf_program *prog;
4479         int err;
4480
4481         if (!obj)
4482                 return -ENOENT;
4483
4484         if (!obj->loaded) {
4485                 pr_warn("object not yet loaded; load it first\n");
4486                 return -ENOENT;
4487         }
4488
4489         bpf_object__for_each_program(prog, obj) {
4490                 char buf[PATH_MAX];
4491                 int len;
4492
4493                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4494                                prog->pin_name);
4495                 if (len < 0) {
4496                         err = -EINVAL;
4497                         goto err_unpin_programs;
4498                 } else if (len >= PATH_MAX) {
4499                         err = -ENAMETOOLONG;
4500                         goto err_unpin_programs;
4501                 }
4502
4503                 err = bpf_program__pin(prog, buf);
4504                 if (err)
4505                         goto err_unpin_programs;
4506         }
4507
4508         return 0;
4509
4510 err_unpin_programs:
4511         while ((prog = bpf_program__prev(prog, obj))) {
4512                 char buf[PATH_MAX];
4513                 int len;
4514
4515                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4516                                prog->pin_name);
4517                 if (len < 0)
4518                         continue;
4519                 else if (len >= PATH_MAX)
4520                         continue;
4521
4522                 bpf_program__unpin(prog, buf);
4523         }
4524
4525         return err;
4526 }
4527
4528 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
4529 {
4530         struct bpf_program *prog;
4531         int err;
4532
4533         if (!obj)
4534                 return -ENOENT;
4535
4536         bpf_object__for_each_program(prog, obj) {
4537                 char buf[PATH_MAX];
4538                 int len;
4539
4540                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
4541                                prog->pin_name);
4542                 if (len < 0)
4543                         return -EINVAL;
4544                 else if (len >= PATH_MAX)
4545                         return -ENAMETOOLONG;
4546
4547                 err = bpf_program__unpin(prog, buf);
4548                 if (err)
4549                         return err;
4550         }
4551
4552         return 0;
4553 }
4554
4555 int bpf_object__pin(struct bpf_object *obj, const char *path)
4556 {
4557         int err;
4558
4559         err = bpf_object__pin_maps(obj, path);
4560         if (err)
4561                 return err;
4562
4563         err = bpf_object__pin_programs(obj, path);
4564         if (err) {
4565                 bpf_object__unpin_maps(obj, path);
4566                 return err;
4567         }
4568
4569         return 0;
4570 }
4571
4572 void bpf_object__close(struct bpf_object *obj)
4573 {
4574         size_t i;
4575
4576         if (!obj)
4577                 return;
4578
4579         if (obj->clear_priv)
4580                 obj->clear_priv(obj, obj->priv);
4581
4582         bpf_object__elf_finish(obj);
4583         bpf_object__unload(obj);
4584         btf__free(obj->btf);
4585         btf_ext__free(obj->btf_ext);
4586
4587         for (i = 0; i < obj->nr_maps; i++) {
4588                 zfree(&obj->maps[i].name);
4589                 zfree(&obj->maps[i].pin_path);
4590                 if (obj->maps[i].clear_priv)
4591                         obj->maps[i].clear_priv(&obj->maps[i],
4592                                                 obj->maps[i].priv);
4593                 obj->maps[i].priv = NULL;
4594                 obj->maps[i].clear_priv = NULL;
4595         }
4596
4597         zfree(&obj->sections.rodata);
4598         zfree(&obj->sections.data);
4599         zfree(&obj->maps);
4600         obj->nr_maps = 0;
4601
4602         if (obj->programs && obj->nr_programs) {
4603                 for (i = 0; i < obj->nr_programs; i++)
4604                         bpf_program__exit(&obj->programs[i]);
4605         }
4606         zfree(&obj->programs);
4607
4608         list_del(&obj->list);
4609         free(obj);
4610 }
4611
4612 struct bpf_object *
4613 bpf_object__next(struct bpf_object *prev)
4614 {
4615         struct bpf_object *next;
4616
4617         if (!prev)
4618                 next = list_first_entry(&bpf_objects_list,
4619                                         struct bpf_object,
4620                                         list);
4621         else
4622                 next = list_next_entry(prev, list);
4623
4624         /* Empty list is noticed here so don't need checking on entry. */
4625         if (&next->list == &bpf_objects_list)
4626                 return NULL;
4627
4628         return next;
4629 }
4630
4631 const char *bpf_object__name(const struct bpf_object *obj)
4632 {
4633         return obj ? obj->name : ERR_PTR(-EINVAL);
4634 }
4635
4636 unsigned int bpf_object__kversion(const struct bpf_object *obj)
4637 {
4638         return obj ? obj->kern_version : 0;
4639 }
4640
4641 struct btf *bpf_object__btf(const struct bpf_object *obj)
4642 {
4643         return obj ? obj->btf : NULL;
4644 }
4645
4646 int bpf_object__btf_fd(const struct bpf_object *obj)
4647 {
4648         return obj->btf ? btf__fd(obj->btf) : -1;
4649 }
4650
4651 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
4652                          bpf_object_clear_priv_t clear_priv)
4653 {
4654         if (obj->priv && obj->clear_priv)
4655                 obj->clear_priv(obj, obj->priv);
4656
4657         obj->priv = priv;
4658         obj->clear_priv = clear_priv;
4659         return 0;
4660 }
4661
4662 void *bpf_object__priv(const struct bpf_object *obj)
4663 {
4664         return obj ? obj->priv : ERR_PTR(-EINVAL);
4665 }
4666
4667 static struct bpf_program *
4668 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
4669                     bool forward)
4670 {
4671         size_t nr_programs = obj->nr_programs;
4672         ssize_t idx;
4673
4674         if (!nr_programs)
4675                 return NULL;
4676
4677         if (!p)
4678                 /* Iter from the beginning */
4679                 return forward ? &obj->programs[0] :
4680                         &obj->programs[nr_programs - 1];
4681
4682         if (p->obj != obj) {
4683                 pr_warn("error: program handler doesn't match object\n");
4684                 return NULL;
4685         }
4686
4687         idx = (p - obj->programs) + (forward ? 1 : -1);
4688         if (idx >= obj->nr_programs || idx < 0)
4689                 return NULL;
4690         return &obj->programs[idx];
4691 }
4692
4693 struct bpf_program *
4694 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
4695 {
4696         struct bpf_program *prog = prev;
4697
4698         do {
4699                 prog = __bpf_program__iter(prog, obj, true);
4700         } while (prog && bpf_program__is_function_storage(prog, obj));
4701
4702         return prog;
4703 }
4704
4705 struct bpf_program *
4706 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
4707 {
4708         struct bpf_program *prog = next;
4709
4710         do {
4711                 prog = __bpf_program__iter(prog, obj, false);
4712         } while (prog && bpf_program__is_function_storage(prog, obj));
4713
4714         return prog;
4715 }
4716
4717 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
4718                           bpf_program_clear_priv_t clear_priv)
4719 {
4720         if (prog->priv && prog->clear_priv)
4721                 prog->clear_priv(prog, prog->priv);
4722
4723         prog->priv = priv;
4724         prog->clear_priv = clear_priv;
4725         return 0;
4726 }
4727
4728 void *bpf_program__priv(const struct bpf_program *prog)
4729 {
4730         return prog ? prog->priv : ERR_PTR(-EINVAL);
4731 }
4732
4733 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
4734 {
4735         prog->prog_ifindex = ifindex;
4736 }
4737
4738 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
4739 {
4740         const char *title;
4741
4742         title = prog->section_name;
4743         if (needs_copy) {
4744                 title = strdup(title);
4745                 if (!title) {
4746                         pr_warn("failed to strdup program title\n");
4747                         return ERR_PTR(-ENOMEM);
4748                 }
4749         }
4750
4751         return title;
4752 }
4753
4754 int bpf_program__fd(const struct bpf_program *prog)
4755 {
4756         return bpf_program__nth_fd(prog, 0);
4757 }
4758
4759 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
4760                           bpf_program_prep_t prep)
4761 {
4762         int *instances_fds;
4763
4764         if (nr_instances <= 0 || !prep)
4765                 return -EINVAL;
4766
4767         if (prog->instances.nr > 0 || prog->instances.fds) {
4768                 pr_warn("Can't set pre-processor after loading\n");
4769                 return -EINVAL;
4770         }
4771
4772         instances_fds = malloc(sizeof(int) * nr_instances);
4773         if (!instances_fds) {
4774                 pr_warn("alloc memory failed for fds\n");
4775                 return -ENOMEM;
4776         }
4777
4778         /* fill all fd with -1 */
4779         memset(instances_fds, -1, sizeof(int) * nr_instances);
4780
4781         prog->instances.nr = nr_instances;
4782         prog->instances.fds = instances_fds;
4783         prog->preprocessor = prep;
4784         return 0;
4785 }
4786
4787 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
4788 {
4789         int fd;
4790
4791         if (!prog)
4792                 return -EINVAL;
4793
4794         if (n >= prog->instances.nr || n < 0) {
4795                 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
4796                         n, prog->section_name, prog->instances.nr);
4797                 return -EINVAL;
4798         }
4799
4800         fd = prog->instances.fds[n];
4801         if (fd < 0) {
4802                 pr_warn("%dth instance of program '%s' is invalid\n",
4803                         n, prog->section_name);
4804                 return -ENOENT;
4805         }
4806
4807         return fd;
4808 }
4809
4810 enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
4811 {
4812         return prog->type;
4813 }
4814
4815 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
4816 {
4817         prog->type = type;
4818 }
4819
4820 static bool bpf_program__is_type(const struct bpf_program *prog,
4821                                  enum bpf_prog_type type)
4822 {
4823         return prog ? (prog->type == type) : false;
4824 }
4825
4826 #define BPF_PROG_TYPE_FNS(NAME, TYPE)                           \
4827 int bpf_program__set_##NAME(struct bpf_program *prog)           \
4828 {                                                               \
4829         if (!prog)                                              \
4830                 return -EINVAL;                                 \
4831         bpf_program__set_type(prog, TYPE);                      \
4832         return 0;                                               \
4833 }                                                               \
4834                                                                 \
4835 bool bpf_program__is_##NAME(const struct bpf_program *prog)     \
4836 {                                                               \
4837         return bpf_program__is_type(prog, TYPE);                \
4838 }                                                               \
4839
4840 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
4841 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
4842 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
4843 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
4844 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
4845 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
4846 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
4847 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
4848 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
4849
4850 enum bpf_attach_type
4851 bpf_program__get_expected_attach_type(struct bpf_program *prog)
4852 {
4853         return prog->expected_attach_type;
4854 }
4855
4856 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
4857                                            enum bpf_attach_type type)
4858 {
4859         prog->expected_attach_type = type;
4860 }
4861
4862 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
4863         { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
4864
4865 /* Programs that can NOT be attached. */
4866 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
4867
4868 /* Programs that can be attached. */
4869 #define BPF_APROG_SEC(string, ptype, atype) \
4870         BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
4871
4872 /* Programs that must specify expected attach type at load time. */
4873 #define BPF_EAPROG_SEC(string, ptype, eatype) \
4874         BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
4875
4876 /* Programs that use BTF to identify attach point */
4877 #define BPF_PROG_BTF(string, ptype, eatype) \
4878         BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
4879
4880 /* Programs that can be attached but attach type can't be identified by section
4881  * name. Kept for backward compatibility.
4882  */
4883 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
4884
4885 static const struct {
4886         const char *sec;
4887         size_t len;
4888         enum bpf_prog_type prog_type;
4889         enum bpf_attach_type expected_attach_type;
4890         bool is_attachable;
4891         bool is_attach_btf;
4892         enum bpf_attach_type attach_type;
4893 } section_names[] = {
4894         BPF_PROG_SEC("socket",                  BPF_PROG_TYPE_SOCKET_FILTER),
4895         BPF_PROG_SEC("kprobe/",                 BPF_PROG_TYPE_KPROBE),
4896         BPF_PROG_SEC("uprobe/",                 BPF_PROG_TYPE_KPROBE),
4897         BPF_PROG_SEC("kretprobe/",              BPF_PROG_TYPE_KPROBE),
4898         BPF_PROG_SEC("uretprobe/",              BPF_PROG_TYPE_KPROBE),
4899         BPF_PROG_SEC("classifier",              BPF_PROG_TYPE_SCHED_CLS),
4900         BPF_PROG_SEC("action",                  BPF_PROG_TYPE_SCHED_ACT),
4901         BPF_PROG_SEC("tracepoint/",             BPF_PROG_TYPE_TRACEPOINT),
4902         BPF_PROG_SEC("tp/",                     BPF_PROG_TYPE_TRACEPOINT),
4903         BPF_PROG_SEC("raw_tracepoint/",         BPF_PROG_TYPE_RAW_TRACEPOINT),
4904         BPF_PROG_SEC("raw_tp/",                 BPF_PROG_TYPE_RAW_TRACEPOINT),
4905         BPF_PROG_BTF("tp_btf/",                 BPF_PROG_TYPE_TRACING,
4906                                                 BPF_TRACE_RAW_TP),
4907         BPF_PROG_SEC("xdp",                     BPF_PROG_TYPE_XDP),
4908         BPF_PROG_SEC("perf_event",              BPF_PROG_TYPE_PERF_EVENT),
4909         BPF_PROG_SEC("lwt_in",                  BPF_PROG_TYPE_LWT_IN),
4910         BPF_PROG_SEC("lwt_out",                 BPF_PROG_TYPE_LWT_OUT),
4911         BPF_PROG_SEC("lwt_xmit",                BPF_PROG_TYPE_LWT_XMIT),
4912         BPF_PROG_SEC("lwt_seg6local",           BPF_PROG_TYPE_LWT_SEG6LOCAL),
4913         BPF_APROG_SEC("cgroup_skb/ingress",     BPF_PROG_TYPE_CGROUP_SKB,
4914                                                 BPF_CGROUP_INET_INGRESS),
4915         BPF_APROG_SEC("cgroup_skb/egress",      BPF_PROG_TYPE_CGROUP_SKB,
4916                                                 BPF_CGROUP_INET_EGRESS),
4917         BPF_APROG_COMPAT("cgroup/skb",          BPF_PROG_TYPE_CGROUP_SKB),
4918         BPF_APROG_SEC("cgroup/sock",            BPF_PROG_TYPE_CGROUP_SOCK,
4919                                                 BPF_CGROUP_INET_SOCK_CREATE),
4920         BPF_EAPROG_SEC("cgroup/post_bind4",     BPF_PROG_TYPE_CGROUP_SOCK,
4921                                                 BPF_CGROUP_INET4_POST_BIND),
4922         BPF_EAPROG_SEC("cgroup/post_bind6",     BPF_PROG_TYPE_CGROUP_SOCK,
4923                                                 BPF_CGROUP_INET6_POST_BIND),
4924         BPF_APROG_SEC("cgroup/dev",             BPF_PROG_TYPE_CGROUP_DEVICE,
4925                                                 BPF_CGROUP_DEVICE),
4926         BPF_APROG_SEC("sockops",                BPF_PROG_TYPE_SOCK_OPS,
4927                                                 BPF_CGROUP_SOCK_OPS),
4928         BPF_APROG_SEC("sk_skb/stream_parser",   BPF_PROG_TYPE_SK_SKB,
4929                                                 BPF_SK_SKB_STREAM_PARSER),
4930         BPF_APROG_SEC("sk_skb/stream_verdict",  BPF_PROG_TYPE_SK_SKB,
4931                                                 BPF_SK_SKB_STREAM_VERDICT),
4932         BPF_APROG_COMPAT("sk_skb",              BPF_PROG_TYPE_SK_SKB),
4933         BPF_APROG_SEC("sk_msg",                 BPF_PROG_TYPE_SK_MSG,
4934                                                 BPF_SK_MSG_VERDICT),
4935         BPF_APROG_SEC("lirc_mode2",             BPF_PROG_TYPE_LIRC_MODE2,
4936                                                 BPF_LIRC_MODE2),
4937         BPF_APROG_SEC("flow_dissector",         BPF_PROG_TYPE_FLOW_DISSECTOR,
4938                                                 BPF_FLOW_DISSECTOR),
4939         BPF_EAPROG_SEC("cgroup/bind4",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4940                                                 BPF_CGROUP_INET4_BIND),
4941         BPF_EAPROG_SEC("cgroup/bind6",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4942                                                 BPF_CGROUP_INET6_BIND),
4943         BPF_EAPROG_SEC("cgroup/connect4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4944                                                 BPF_CGROUP_INET4_CONNECT),
4945         BPF_EAPROG_SEC("cgroup/connect6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4946                                                 BPF_CGROUP_INET6_CONNECT),
4947         BPF_EAPROG_SEC("cgroup/sendmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4948                                                 BPF_CGROUP_UDP4_SENDMSG),
4949         BPF_EAPROG_SEC("cgroup/sendmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4950                                                 BPF_CGROUP_UDP6_SENDMSG),
4951         BPF_EAPROG_SEC("cgroup/recvmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4952                                                 BPF_CGROUP_UDP4_RECVMSG),
4953         BPF_EAPROG_SEC("cgroup/recvmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
4954                                                 BPF_CGROUP_UDP6_RECVMSG),
4955         BPF_EAPROG_SEC("cgroup/sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,
4956                                                 BPF_CGROUP_SYSCTL),
4957         BPF_EAPROG_SEC("cgroup/getsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
4958                                                 BPF_CGROUP_GETSOCKOPT),
4959         BPF_EAPROG_SEC("cgroup/setsockopt",     BPF_PROG_TYPE_CGROUP_SOCKOPT,
4960                                                 BPF_CGROUP_SETSOCKOPT),
4961 };
4962
4963 #undef BPF_PROG_SEC_IMPL
4964 #undef BPF_PROG_SEC
4965 #undef BPF_APROG_SEC
4966 #undef BPF_EAPROG_SEC
4967 #undef BPF_APROG_COMPAT
4968
4969 #define MAX_TYPE_NAME_SIZE 32
4970
4971 static char *libbpf_get_type_names(bool attach_type)
4972 {
4973         int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
4974         char *buf;
4975
4976         buf = malloc(len);
4977         if (!buf)
4978                 return NULL;
4979
4980         buf[0] = '\0';
4981         /* Forge string buf with all available names */
4982         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
4983                 if (attach_type && !section_names[i].is_attachable)
4984                         continue;
4985
4986                 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
4987                         free(buf);
4988                         return NULL;
4989                 }
4990                 strcat(buf, " ");
4991                 strcat(buf, section_names[i].sec);
4992         }
4993
4994         return buf;
4995 }
4996
4997 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
4998                              enum bpf_attach_type *expected_attach_type)
4999 {
5000         char *type_names;
5001         int i;
5002
5003         if (!name)
5004                 return -EINVAL;
5005
5006         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5007                 if (strncmp(name, section_names[i].sec, section_names[i].len))
5008                         continue;
5009                 *prog_type = section_names[i].prog_type;
5010                 *expected_attach_type = section_names[i].expected_attach_type;
5011                 return 0;
5012         }
5013         pr_warn("failed to guess program type based on ELF section name '%s'\n", name);
5014         type_names = libbpf_get_type_names(false);
5015         if (type_names != NULL) {
5016                 pr_info("supported section(type) names are:%s\n", type_names);
5017                 free(type_names);
5018         }
5019
5020         return -ESRCH;
5021 }
5022
5023 #define BTF_PREFIX "btf_trace_"
5024 static int libbpf_attach_btf_id_by_name(const char *name, __u32 *btf_id)
5025 {
5026         struct btf *btf = bpf_core_find_kernel_btf();
5027         char raw_tp_btf_name[128] = BTF_PREFIX;
5028         char *dst = raw_tp_btf_name + sizeof(BTF_PREFIX) - 1;
5029         int ret, i, err = -EINVAL;
5030
5031         if (IS_ERR(btf)) {
5032                 pr_warn("vmlinux BTF is not found\n");
5033                 return -EINVAL;
5034         }
5035
5036         if (!name)
5037                 goto out;
5038
5039         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5040                 if (!section_names[i].is_attach_btf)
5041                         continue;
5042                 if (strncmp(name, section_names[i].sec, section_names[i].len))
5043                         continue;
5044                 /* prepend "btf_trace_" prefix per kernel convention */
5045                 strncat(dst, name + section_names[i].len,
5046                         sizeof(raw_tp_btf_name) - sizeof(BTF_PREFIX));
5047                 ret = btf__find_by_name(btf, raw_tp_btf_name);
5048                 if (ret <= 0) {
5049                         pr_warn("%s is not found in vmlinux BTF\n", dst);
5050                         goto out;
5051                 }
5052                 *btf_id = ret;
5053                 err = 0;
5054                 goto out;
5055         }
5056         pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
5057         err = -ESRCH;
5058 out:
5059         btf__free(btf);
5060         return err;
5061 }
5062
5063 int libbpf_attach_type_by_name(const char *name,
5064                                enum bpf_attach_type *attach_type)
5065 {
5066         char *type_names;
5067         int i;
5068
5069         if (!name)
5070                 return -EINVAL;
5071
5072         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
5073                 if (strncmp(name, section_names[i].sec, section_names[i].len))
5074                         continue;
5075                 if (!section_names[i].is_attachable)
5076                         return -EINVAL;
5077                 *attach_type = section_names[i].attach_type;
5078                 return 0;
5079         }
5080         pr_warn("failed to guess attach type based on ELF section name '%s'\n", name);
5081         type_names = libbpf_get_type_names(true);
5082         if (type_names != NULL) {
5083                 pr_info("attachable section(type) names are:%s\n", type_names);
5084                 free(type_names);
5085         }
5086
5087         return -EINVAL;
5088 }
5089
5090 int bpf_map__fd(const struct bpf_map *map)
5091 {
5092         return map ? map->fd : -EINVAL;
5093 }
5094
5095 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
5096 {
5097         return map ? &map->def : ERR_PTR(-EINVAL);
5098 }
5099
5100 const char *bpf_map__name(const struct bpf_map *map)
5101 {
5102         return map ? map->name : NULL;
5103 }
5104
5105 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
5106 {
5107         return map ? map->btf_key_type_id : 0;
5108 }
5109
5110 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
5111 {
5112         return map ? map->btf_value_type_id : 0;
5113 }
5114
5115 int bpf_map__set_priv(struct bpf_map *map, void *priv,
5116                      bpf_map_clear_priv_t clear_priv)
5117 {
5118         if (!map)
5119                 return -EINVAL;
5120
5121         if (map->priv) {
5122                 if (map->clear_priv)
5123                         map->clear_priv(map, map->priv);
5124         }
5125
5126         map->priv = priv;
5127         map->clear_priv = clear_priv;
5128         return 0;
5129 }
5130
5131 void *bpf_map__priv(const struct bpf_map *map)
5132 {
5133         return map ? map->priv : ERR_PTR(-EINVAL);
5134 }
5135
5136 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
5137 {
5138         return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
5139 }
5140
5141 bool bpf_map__is_internal(const struct bpf_map *map)
5142 {
5143         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
5144 }
5145
5146 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
5147 {
5148         map->map_ifindex = ifindex;
5149 }
5150
5151 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
5152 {
5153         if (!bpf_map_type__is_map_in_map(map->def.type)) {
5154                 pr_warn("error: unsupported map type\n");
5155                 return -EINVAL;
5156         }
5157         if (map->inner_map_fd != -1) {
5158                 pr_warn("error: inner_map_fd already specified\n");
5159                 return -EINVAL;
5160         }
5161         map->inner_map_fd = fd;
5162         return 0;
5163 }
5164
5165 static struct bpf_map *
5166 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
5167 {
5168         ssize_t idx;
5169         struct bpf_map *s, *e;
5170
5171         if (!obj || !obj->maps)
5172                 return NULL;
5173
5174         s = obj->maps;
5175         e = obj->maps + obj->nr_maps;
5176
5177         if ((m < s) || (m >= e)) {
5178                 pr_warn("error in %s: map handler doesn't belong to object\n",
5179                          __func__);
5180                 return NULL;
5181         }
5182
5183         idx = (m - obj->maps) + i;
5184         if (idx >= obj->nr_maps || idx < 0)
5185                 return NULL;
5186         return &obj->maps[idx];
5187 }
5188
5189 struct bpf_map *
5190 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
5191 {
5192         if (prev == NULL)
5193                 return obj->maps;
5194
5195         return __bpf_map__iter(prev, obj, 1);
5196 }
5197
5198 struct bpf_map *
5199 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
5200 {
5201         if (next == NULL) {
5202                 if (!obj->nr_maps)
5203                         return NULL;
5204                 return obj->maps + obj->nr_maps - 1;
5205         }
5206
5207         return __bpf_map__iter(next, obj, -1);
5208 }
5209
5210 struct bpf_map *
5211 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
5212 {
5213         struct bpf_map *pos;
5214
5215         bpf_object__for_each_map(pos, obj) {
5216                 if (pos->name && !strcmp(pos->name, name))
5217                         return pos;
5218         }
5219         return NULL;
5220 }
5221
5222 int
5223 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
5224 {
5225         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
5226 }
5227
5228 struct bpf_map *
5229 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
5230 {
5231         return ERR_PTR(-ENOTSUP);
5232 }
5233
5234 long libbpf_get_error(const void *ptr)
5235 {
5236         return PTR_ERR_OR_ZERO(ptr);
5237 }
5238
5239 int bpf_prog_load(const char *file, enum bpf_prog_type type,
5240                   struct bpf_object **pobj, int *prog_fd)
5241 {
5242         struct bpf_prog_load_attr attr;
5243
5244         memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
5245         attr.file = file;
5246         attr.prog_type = type;
5247         attr.expected_attach_type = 0;
5248
5249         return bpf_prog_load_xattr(&attr, pobj, prog_fd);
5250 }
5251
5252 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
5253                         struct bpf_object **pobj, int *prog_fd)
5254 {
5255         struct bpf_object_open_attr open_attr = {};
5256         struct bpf_program *prog, *first_prog = NULL;
5257         struct bpf_object *obj;
5258         struct bpf_map *map;
5259         int err;
5260
5261         if (!attr)
5262                 return -EINVAL;
5263         if (!attr->file)
5264                 return -EINVAL;
5265
5266         open_attr.file = attr->file;
5267         open_attr.prog_type = attr->prog_type;
5268
5269         obj = bpf_object__open_xattr(&open_attr);
5270         if (IS_ERR_OR_NULL(obj))
5271                 return -ENOENT;
5272
5273         bpf_object__for_each_program(prog, obj) {
5274                 enum bpf_attach_type attach_type = attr->expected_attach_type;
5275                 /*
5276                  * to preserve backwards compatibility, bpf_prog_load treats
5277                  * attr->prog_type, if specified, as an override to whatever
5278                  * bpf_object__open guessed
5279                  */
5280                 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
5281                         bpf_program__set_type(prog, attr->prog_type);
5282                         bpf_program__set_expected_attach_type(prog,
5283                                                               attach_type);
5284                 }
5285                 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
5286                         /*
5287                          * we haven't guessed from section name and user
5288                          * didn't provide a fallback type, too bad...
5289                          */
5290                         bpf_object__close(obj);
5291                         return -EINVAL;
5292                 }
5293
5294                 prog->prog_ifindex = attr->ifindex;
5295                 prog->log_level = attr->log_level;
5296                 prog->prog_flags = attr->prog_flags;
5297                 if (!first_prog)
5298                         first_prog = prog;
5299         }
5300
5301         bpf_object__for_each_map(map, obj) {
5302                 if (!bpf_map__is_offload_neutral(map))
5303                         map->map_ifindex = attr->ifindex;
5304         }
5305
5306         if (!first_prog) {
5307                 pr_warn("object file doesn't contain bpf program\n");
5308                 bpf_object__close(obj);
5309                 return -ENOENT;
5310         }
5311
5312         err = bpf_object__load(obj);
5313         if (err) {
5314                 bpf_object__close(obj);
5315                 return -EINVAL;
5316         }
5317
5318         *pobj = obj;
5319         *prog_fd = bpf_program__fd(first_prog);
5320         return 0;
5321 }
5322
5323 struct bpf_link {
5324         int (*destroy)(struct bpf_link *link);
5325 };
5326
5327 int bpf_link__destroy(struct bpf_link *link)
5328 {
5329         int err;
5330
5331         if (!link)
5332                 return 0;
5333
5334         err = link->destroy(link);
5335         free(link);
5336
5337         return err;
5338 }
5339
5340 struct bpf_link_fd {
5341         struct bpf_link link; /* has to be at the top of struct */
5342         int fd; /* hook FD */
5343 };
5344
5345 static int bpf_link__destroy_perf_event(struct bpf_link *link)
5346 {
5347         struct bpf_link_fd *l = (void *)link;
5348         int err;
5349
5350         err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
5351         if (err)
5352                 err = -errno;
5353
5354         close(l->fd);
5355         return err;
5356 }
5357
5358 struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
5359                                                 int pfd)
5360 {
5361         char errmsg[STRERR_BUFSIZE];
5362         struct bpf_link_fd *link;
5363         int prog_fd, err;
5364
5365         if (pfd < 0) {
5366                 pr_warn("program '%s': invalid perf event FD %d\n",
5367                         bpf_program__title(prog, false), pfd);
5368                 return ERR_PTR(-EINVAL);
5369         }
5370         prog_fd = bpf_program__fd(prog);
5371         if (prog_fd < 0) {
5372                 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
5373                         bpf_program__title(prog, false));
5374                 return ERR_PTR(-EINVAL);
5375         }
5376
5377         link = malloc(sizeof(*link));
5378         if (!link)
5379                 return ERR_PTR(-ENOMEM);
5380         link->link.destroy = &bpf_link__destroy_perf_event;
5381         link->fd = pfd;
5382
5383         if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
5384                 err = -errno;
5385                 free(link);
5386                 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
5387                         bpf_program__title(prog, false), pfd,
5388                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5389                 return ERR_PTR(err);
5390         }
5391         if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5392                 err = -errno;
5393                 free(link);
5394                 pr_warn("program '%s': failed to enable pfd %d: %s\n",
5395                         bpf_program__title(prog, false), pfd,
5396                            libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5397                 return ERR_PTR(err);
5398         }
5399         return (struct bpf_link *)link;
5400 }
5401
5402 /*
5403  * this function is expected to parse integer in the range of [0, 2^31-1] from
5404  * given file using scanf format string fmt. If actual parsed value is
5405  * negative, the result might be indistinguishable from error
5406  */
5407 static int parse_uint_from_file(const char *file, const char *fmt)
5408 {
5409         char buf[STRERR_BUFSIZE];
5410         int err, ret;
5411         FILE *f;
5412
5413         f = fopen(file, "r");
5414         if (!f) {
5415                 err = -errno;
5416                 pr_debug("failed to open '%s': %s\n", file,
5417                          libbpf_strerror_r(err, buf, sizeof(buf)));
5418                 return err;
5419         }
5420         err = fscanf(f, fmt, &ret);
5421         if (err != 1) {
5422                 err = err == EOF ? -EIO : -errno;
5423                 pr_debug("failed to parse '%s': %s\n", file,
5424                         libbpf_strerror_r(err, buf, sizeof(buf)));
5425                 fclose(f);
5426                 return err;
5427         }
5428         fclose(f);
5429         return ret;
5430 }
5431
5432 static int determine_kprobe_perf_type(void)
5433 {
5434         const char *file = "/sys/bus/event_source/devices/kprobe/type";
5435
5436         return parse_uint_from_file(file, "%d\n");
5437 }
5438
5439 static int determine_uprobe_perf_type(void)
5440 {
5441         const char *file = "/sys/bus/event_source/devices/uprobe/type";
5442
5443         return parse_uint_from_file(file, "%d\n");
5444 }
5445
5446 static int determine_kprobe_retprobe_bit(void)
5447 {
5448         const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
5449
5450         return parse_uint_from_file(file, "config:%d\n");
5451 }
5452
5453 static int determine_uprobe_retprobe_bit(void)
5454 {
5455         const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
5456
5457         return parse_uint_from_file(file, "config:%d\n");
5458 }
5459
5460 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5461                                  uint64_t offset, int pid)
5462 {
5463         struct perf_event_attr attr = {};
5464         char errmsg[STRERR_BUFSIZE];
5465         int type, pfd, err;
5466
5467         type = uprobe ? determine_uprobe_perf_type()
5468                       : determine_kprobe_perf_type();
5469         if (type < 0) {
5470                 pr_warn("failed to determine %s perf type: %s\n",
5471                         uprobe ? "uprobe" : "kprobe",
5472                         libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
5473                 return type;
5474         }
5475         if (retprobe) {
5476                 int bit = uprobe ? determine_uprobe_retprobe_bit()
5477                                  : determine_kprobe_retprobe_bit();
5478
5479                 if (bit < 0) {
5480                         pr_warn("failed to determine %s retprobe bit: %s\n",
5481                                 uprobe ? "uprobe" : "kprobe",
5482                                 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
5483                         return bit;
5484                 }
5485                 attr.config |= 1 << bit;
5486         }
5487         attr.size = sizeof(attr);
5488         attr.type = type;
5489         attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
5490         attr.config2 = offset;           /* kprobe_addr or probe_offset */
5491
5492         /* pid filter is meaningful only for uprobes */
5493         pfd = syscall(__NR_perf_event_open, &attr,
5494                       pid < 0 ? -1 : pid /* pid */,
5495                       pid == -1 ? 0 : -1 /* cpu */,
5496                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5497         if (pfd < 0) {
5498                 err = -errno;
5499                 pr_warn("%s perf_event_open() failed: %s\n",
5500                         uprobe ? "uprobe" : "kprobe",
5501                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5502                 return err;
5503         }
5504         return pfd;
5505 }
5506
5507 struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
5508                                             bool retprobe,
5509                                             const char *func_name)
5510 {
5511         char errmsg[STRERR_BUFSIZE];
5512         struct bpf_link *link;
5513         int pfd, err;
5514
5515         pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
5516                                     0 /* offset */, -1 /* pid */);
5517         if (pfd < 0) {
5518                 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
5519                         bpf_program__title(prog, false),
5520                         retprobe ? "kretprobe" : "kprobe", func_name,
5521                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5522                 return ERR_PTR(pfd);
5523         }
5524         link = bpf_program__attach_perf_event(prog, pfd);
5525         if (IS_ERR(link)) {
5526                 close(pfd);
5527                 err = PTR_ERR(link);
5528                 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
5529                         bpf_program__title(prog, false),
5530                         retprobe ? "kretprobe" : "kprobe", func_name,
5531                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5532                 return link;
5533         }
5534         return link;
5535 }
5536
5537 struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
5538                                             bool retprobe, pid_t pid,
5539                                             const char *binary_path,
5540                                             size_t func_offset)
5541 {
5542         char errmsg[STRERR_BUFSIZE];
5543         struct bpf_link *link;
5544         int pfd, err;
5545
5546         pfd = perf_event_open_probe(true /* uprobe */, retprobe,
5547                                     binary_path, func_offset, pid);
5548         if (pfd < 0) {
5549                 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
5550                         bpf_program__title(prog, false),
5551                         retprobe ? "uretprobe" : "uprobe",
5552                         binary_path, func_offset,
5553                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5554                 return ERR_PTR(pfd);
5555         }
5556         link = bpf_program__attach_perf_event(prog, pfd);
5557         if (IS_ERR(link)) {
5558                 close(pfd);
5559                 err = PTR_ERR(link);
5560                 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
5561                         bpf_program__title(prog, false),
5562                         retprobe ? "uretprobe" : "uprobe",
5563                         binary_path, func_offset,
5564                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5565                 return link;
5566         }
5567         return link;
5568 }
5569
5570 static int determine_tracepoint_id(const char *tp_category,
5571                                    const char *tp_name)
5572 {
5573         char file[PATH_MAX];
5574         int ret;
5575
5576         ret = snprintf(file, sizeof(file),
5577                        "/sys/kernel/debug/tracing/events/%s/%s/id",
5578                        tp_category, tp_name);
5579         if (ret < 0)
5580                 return -errno;
5581         if (ret >= sizeof(file)) {
5582                 pr_debug("tracepoint %s/%s path is too long\n",
5583                          tp_category, tp_name);
5584                 return -E2BIG;
5585         }
5586         return parse_uint_from_file(file, "%d\n");
5587 }
5588
5589 static int perf_event_open_tracepoint(const char *tp_category,
5590                                       const char *tp_name)
5591 {
5592         struct perf_event_attr attr = {};
5593         char errmsg[STRERR_BUFSIZE];
5594         int tp_id, pfd, err;
5595
5596         tp_id = determine_tracepoint_id(tp_category, tp_name);
5597         if (tp_id < 0) {
5598                 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
5599                         tp_category, tp_name,
5600                         libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
5601                 return tp_id;
5602         }
5603
5604         attr.type = PERF_TYPE_TRACEPOINT;
5605         attr.size = sizeof(attr);
5606         attr.config = tp_id;
5607
5608         pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
5609                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
5610         if (pfd < 0) {
5611                 err = -errno;
5612                 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
5613                         tp_category, tp_name,
5614                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5615                 return err;
5616         }
5617         return pfd;
5618 }
5619
5620 struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
5621                                                 const char *tp_category,
5622                                                 const char *tp_name)
5623 {
5624         char errmsg[STRERR_BUFSIZE];
5625         struct bpf_link *link;
5626         int pfd, err;
5627
5628         pfd = perf_event_open_tracepoint(tp_category, tp_name);
5629         if (pfd < 0) {
5630                 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
5631                         bpf_program__title(prog, false),
5632                         tp_category, tp_name,
5633                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5634                 return ERR_PTR(pfd);
5635         }
5636         link = bpf_program__attach_perf_event(prog, pfd);
5637         if (IS_ERR(link)) {
5638                 close(pfd);
5639                 err = PTR_ERR(link);
5640                 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
5641                         bpf_program__title(prog, false),
5642                         tp_category, tp_name,
5643                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
5644                 return link;
5645         }
5646         return link;
5647 }
5648
5649 static int bpf_link__destroy_fd(struct bpf_link *link)
5650 {
5651         struct bpf_link_fd *l = (void *)link;
5652
5653         return close(l->fd);
5654 }
5655
5656 struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
5657                                                     const char *tp_name)
5658 {
5659         char errmsg[STRERR_BUFSIZE];
5660         struct bpf_link_fd *link;
5661         int prog_fd, pfd;
5662
5663         prog_fd = bpf_program__fd(prog);
5664         if (prog_fd < 0) {
5665                 pr_warn("program '%s': can't attach before loaded\n",
5666                         bpf_program__title(prog, false));
5667                 return ERR_PTR(-EINVAL);
5668         }
5669
5670         link = malloc(sizeof(*link));
5671         if (!link)
5672                 return ERR_PTR(-ENOMEM);
5673         link->link.destroy = &bpf_link__destroy_fd;
5674
5675         pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
5676         if (pfd < 0) {
5677                 pfd = -errno;
5678                 free(link);
5679                 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
5680                         bpf_program__title(prog, false), tp_name,
5681                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
5682                 return ERR_PTR(pfd);
5683         }
5684         link->fd = pfd;
5685         return (struct bpf_link *)link;
5686 }
5687
5688 enum bpf_perf_event_ret
5689 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
5690                            void **copy_mem, size_t *copy_size,
5691                            bpf_perf_event_print_t fn, void *private_data)
5692 {
5693         struct perf_event_mmap_page *header = mmap_mem;
5694         __u64 data_head = ring_buffer_read_head(header);
5695         __u64 data_tail = header->data_tail;
5696         void *base = ((__u8 *)header) + page_size;
5697         int ret = LIBBPF_PERF_EVENT_CONT;
5698         struct perf_event_header *ehdr;
5699         size_t ehdr_size;
5700
5701         while (data_head != data_tail) {
5702                 ehdr = base + (data_tail & (mmap_size - 1));
5703                 ehdr_size = ehdr->size;
5704
5705                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
5706                         void *copy_start = ehdr;
5707                         size_t len_first = base + mmap_size - copy_start;
5708                         size_t len_secnd = ehdr_size - len_first;
5709
5710                         if (*copy_size < ehdr_size) {
5711                                 free(*copy_mem);
5712                                 *copy_mem = malloc(ehdr_size);
5713                                 if (!*copy_mem) {
5714                                         *copy_size = 0;
5715                                         ret = LIBBPF_PERF_EVENT_ERROR;
5716                                         break;
5717                                 }
5718                                 *copy_size = ehdr_size;
5719                         }
5720
5721                         memcpy(*copy_mem, copy_start, len_first);
5722                         memcpy(*copy_mem + len_first, base, len_secnd);
5723                         ehdr = *copy_mem;
5724                 }
5725
5726                 ret = fn(ehdr, private_data);
5727                 data_tail += ehdr_size;
5728                 if (ret != LIBBPF_PERF_EVENT_CONT)
5729                         break;
5730         }
5731
5732         ring_buffer_write_tail(header, data_tail);
5733         return ret;
5734 }
5735
5736 struct perf_buffer;
5737
5738 struct perf_buffer_params {
5739         struct perf_event_attr *attr;
5740         /* if event_cb is specified, it takes precendence */
5741         perf_buffer_event_fn event_cb;
5742         /* sample_cb and lost_cb are higher-level common-case callbacks */
5743         perf_buffer_sample_fn sample_cb;
5744         perf_buffer_lost_fn lost_cb;
5745         void *ctx;
5746         int cpu_cnt;
5747         int *cpus;
5748         int *map_keys;
5749 };
5750
5751 struct perf_cpu_buf {
5752         struct perf_buffer *pb;
5753         void *base; /* mmap()'ed memory */
5754         void *buf; /* for reconstructing segmented data */
5755         size_t buf_size;
5756         int fd;
5757         int cpu;
5758         int map_key;
5759 };
5760
5761 struct perf_buffer {
5762         perf_buffer_event_fn event_cb;
5763         perf_buffer_sample_fn sample_cb;
5764         perf_buffer_lost_fn lost_cb;
5765         void *ctx; /* passed into callbacks */
5766
5767         size_t page_size;
5768         size_t mmap_size;
5769         struct perf_cpu_buf **cpu_bufs;
5770         struct epoll_event *events;
5771         int cpu_cnt;
5772         int epoll_fd; /* perf event FD */
5773         int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
5774 };
5775
5776 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
5777                                       struct perf_cpu_buf *cpu_buf)
5778 {
5779         if (!cpu_buf)
5780                 return;
5781         if (cpu_buf->base &&
5782             munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
5783                 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
5784         if (cpu_buf->fd >= 0) {
5785                 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
5786                 close(cpu_buf->fd);
5787         }
5788         free(cpu_buf->buf);
5789         free(cpu_buf);
5790 }
5791
5792 void perf_buffer__free(struct perf_buffer *pb)
5793 {
5794         int i;
5795
5796         if (!pb)
5797                 return;
5798         if (pb->cpu_bufs) {
5799                 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
5800                         struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
5801
5802                         bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
5803                         perf_buffer__free_cpu_buf(pb, cpu_buf);
5804                 }
5805                 free(pb->cpu_bufs);
5806         }
5807         if (pb->epoll_fd >= 0)
5808                 close(pb->epoll_fd);
5809         free(pb->events);
5810         free(pb);
5811 }
5812
5813 static struct perf_cpu_buf *
5814 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
5815                           int cpu, int map_key)
5816 {
5817         struct perf_cpu_buf *cpu_buf;
5818         char msg[STRERR_BUFSIZE];
5819         int err;
5820
5821         cpu_buf = calloc(1, sizeof(*cpu_buf));
5822         if (!cpu_buf)
5823                 return ERR_PTR(-ENOMEM);
5824
5825         cpu_buf->pb = pb;
5826         cpu_buf->cpu = cpu;
5827         cpu_buf->map_key = map_key;
5828
5829         cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
5830                               -1, PERF_FLAG_FD_CLOEXEC);
5831         if (cpu_buf->fd < 0) {
5832                 err = -errno;
5833                 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
5834                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5835                 goto error;
5836         }
5837
5838         cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
5839                              PROT_READ | PROT_WRITE, MAP_SHARED,
5840                              cpu_buf->fd, 0);
5841         if (cpu_buf->base == MAP_FAILED) {
5842                 cpu_buf->base = NULL;
5843                 err = -errno;
5844                 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
5845                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5846                 goto error;
5847         }
5848
5849         if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
5850                 err = -errno;
5851                 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
5852                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
5853                 goto error;
5854         }
5855
5856         return cpu_buf;
5857
5858 error:
5859         perf_buffer__free_cpu_buf(pb, cpu_buf);
5860         return (struct perf_cpu_buf *)ERR_PTR(err);
5861 }
5862
5863 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5864                                               struct perf_buffer_params *p);
5865
5866 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
5867                                      const struct perf_buffer_opts *opts)
5868 {
5869         struct perf_buffer_params p = {};
5870         struct perf_event_attr attr = { 0, };
5871
5872         attr.config = PERF_COUNT_SW_BPF_OUTPUT,
5873         attr.type = PERF_TYPE_SOFTWARE;
5874         attr.sample_type = PERF_SAMPLE_RAW;
5875         attr.sample_period = 1;
5876         attr.wakeup_events = 1;
5877
5878         p.attr = &attr;
5879         p.sample_cb = opts ? opts->sample_cb : NULL;
5880         p.lost_cb = opts ? opts->lost_cb : NULL;
5881         p.ctx = opts ? opts->ctx : NULL;
5882
5883         return __perf_buffer__new(map_fd, page_cnt, &p);
5884 }
5885
5886 struct perf_buffer *
5887 perf_buffer__new_raw(int map_fd, size_t page_cnt,
5888                      const struct perf_buffer_raw_opts *opts)
5889 {
5890         struct perf_buffer_params p = {};
5891
5892         p.attr = opts->attr;
5893         p.event_cb = opts->event_cb;
5894         p.ctx = opts->ctx;
5895         p.cpu_cnt = opts->cpu_cnt;
5896         p.cpus = opts->cpus;
5897         p.map_keys = opts->map_keys;
5898
5899         return __perf_buffer__new(map_fd, page_cnt, &p);
5900 }
5901
5902 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
5903                                               struct perf_buffer_params *p)
5904 {
5905         struct bpf_map_info map = {};
5906         char msg[STRERR_BUFSIZE];
5907         struct perf_buffer *pb;
5908         __u32 map_info_len;
5909         int err, i;
5910
5911         if (page_cnt & (page_cnt - 1)) {
5912                 pr_warn("page count should be power of two, but is %zu\n",
5913                         page_cnt);
5914                 return ERR_PTR(-EINVAL);
5915         }
5916
5917         map_info_len = sizeof(map);
5918         err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
5919         if (err) {
5920                 err = -errno;
5921                 pr_warn("failed to get map info for map FD %d: %s\n",
5922                         map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
5923                 return ERR_PTR(err);
5924         }
5925
5926         if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
5927                 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
5928                         map.name);
5929                 return ERR_PTR(-EINVAL);
5930         }
5931
5932         pb = calloc(1, sizeof(*pb));
5933         if (!pb)
5934                 return ERR_PTR(-ENOMEM);
5935
5936         pb->event_cb = p->event_cb;
5937         pb->sample_cb = p->sample_cb;
5938         pb->lost_cb = p->lost_cb;
5939         pb->ctx = p->ctx;
5940
5941         pb->page_size = getpagesize();
5942         pb->mmap_size = pb->page_size * page_cnt;
5943         pb->map_fd = map_fd;
5944
5945         pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
5946         if (pb->epoll_fd < 0) {
5947                 err = -errno;
5948                 pr_warn("failed to create epoll instance: %s\n",
5949                         libbpf_strerror_r(err, msg, sizeof(msg)));
5950                 goto error;
5951         }
5952
5953         if (p->cpu_cnt > 0) {
5954                 pb->cpu_cnt = p->cpu_cnt;
5955         } else {
5956                 pb->cpu_cnt = libbpf_num_possible_cpus();
5957                 if (pb->cpu_cnt < 0) {
5958                         err = pb->cpu_cnt;
5959                         goto error;
5960                 }
5961                 if (map.max_entries < pb->cpu_cnt)
5962                         pb->cpu_cnt = map.max_entries;
5963         }
5964
5965         pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
5966         if (!pb->events) {
5967                 err = -ENOMEM;
5968                 pr_warn("failed to allocate events: out of memory\n");
5969                 goto error;
5970         }
5971         pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
5972         if (!pb->cpu_bufs) {
5973                 err = -ENOMEM;
5974                 pr_warn("failed to allocate buffers: out of memory\n");
5975                 goto error;
5976         }
5977
5978         for (i = 0; i < pb->cpu_cnt; i++) {
5979                 struct perf_cpu_buf *cpu_buf;
5980                 int cpu, map_key;
5981
5982                 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
5983                 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
5984
5985                 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
5986                 if (IS_ERR(cpu_buf)) {
5987                         err = PTR_ERR(cpu_buf);
5988                         goto error;
5989                 }
5990
5991                 pb->cpu_bufs[i] = cpu_buf;
5992
5993                 err = bpf_map_update_elem(pb->map_fd, &map_key,
5994                                           &cpu_buf->fd, 0);
5995                 if (err) {
5996                         err = -errno;
5997                         pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
5998                                 cpu, map_key, cpu_buf->fd,
5999                                 libbpf_strerror_r(err, msg, sizeof(msg)));
6000                         goto error;
6001                 }
6002
6003                 pb->events[i].events = EPOLLIN;
6004                 pb->events[i].data.ptr = cpu_buf;
6005                 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
6006                               &pb->events[i]) < 0) {
6007                         err = -errno;
6008                         pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
6009                                 cpu, cpu_buf->fd,
6010                                 libbpf_strerror_r(err, msg, sizeof(msg)));
6011                         goto error;
6012                 }
6013         }
6014
6015         return pb;
6016
6017 error:
6018         if (pb)
6019                 perf_buffer__free(pb);
6020         return ERR_PTR(err);
6021 }
6022
6023 struct perf_sample_raw {
6024         struct perf_event_header header;
6025         uint32_t size;
6026         char data[0];
6027 };
6028
6029 struct perf_sample_lost {
6030         struct perf_event_header header;
6031         uint64_t id;
6032         uint64_t lost;
6033         uint64_t sample_id;
6034 };
6035
6036 static enum bpf_perf_event_ret
6037 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
6038 {
6039         struct perf_cpu_buf *cpu_buf = ctx;
6040         struct perf_buffer *pb = cpu_buf->pb;
6041         void *data = e;
6042
6043         /* user wants full control over parsing perf event */
6044         if (pb->event_cb)
6045                 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
6046
6047         switch (e->type) {
6048         case PERF_RECORD_SAMPLE: {
6049                 struct perf_sample_raw *s = data;
6050
6051                 if (pb->sample_cb)
6052                         pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
6053                 break;
6054         }
6055         case PERF_RECORD_LOST: {
6056                 struct perf_sample_lost *s = data;
6057
6058                 if (pb->lost_cb)
6059                         pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
6060                 break;
6061         }
6062         default:
6063                 pr_warn("unknown perf sample type %d\n", e->type);
6064                 return LIBBPF_PERF_EVENT_ERROR;
6065         }
6066         return LIBBPF_PERF_EVENT_CONT;
6067 }
6068
6069 static int perf_buffer__process_records(struct perf_buffer *pb,
6070                                         struct perf_cpu_buf *cpu_buf)
6071 {
6072         enum bpf_perf_event_ret ret;
6073
6074         ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
6075                                          pb->page_size, &cpu_buf->buf,
6076                                          &cpu_buf->buf_size,
6077                                          perf_buffer__process_record, cpu_buf);
6078         if (ret != LIBBPF_PERF_EVENT_CONT)
6079                 return ret;
6080         return 0;
6081 }
6082
6083 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
6084 {
6085         int i, cnt, err;
6086
6087         cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
6088         for (i = 0; i < cnt; i++) {
6089                 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
6090
6091                 err = perf_buffer__process_records(pb, cpu_buf);
6092                 if (err) {
6093                         pr_warn("error while processing records: %d\n", err);
6094                         return err;
6095                 }
6096         }
6097         return cnt < 0 ? -errno : cnt;
6098 }
6099
6100 struct bpf_prog_info_array_desc {
6101         int     array_offset;   /* e.g. offset of jited_prog_insns */
6102         int     count_offset;   /* e.g. offset of jited_prog_len */
6103         int     size_offset;    /* > 0: offset of rec size,
6104                                  * < 0: fix size of -size_offset
6105                                  */
6106 };
6107
6108 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
6109         [BPF_PROG_INFO_JITED_INSNS] = {
6110                 offsetof(struct bpf_prog_info, jited_prog_insns),
6111                 offsetof(struct bpf_prog_info, jited_prog_len),
6112                 -1,
6113         },
6114         [BPF_PROG_INFO_XLATED_INSNS] = {
6115                 offsetof(struct bpf_prog_info, xlated_prog_insns),
6116                 offsetof(struct bpf_prog_info, xlated_prog_len),
6117                 -1,
6118         },
6119         [BPF_PROG_INFO_MAP_IDS] = {
6120                 offsetof(struct bpf_prog_info, map_ids),
6121                 offsetof(struct bpf_prog_info, nr_map_ids),
6122                 -(int)sizeof(__u32),
6123         },
6124         [BPF_PROG_INFO_JITED_KSYMS] = {
6125                 offsetof(struct bpf_prog_info, jited_ksyms),
6126                 offsetof(struct bpf_prog_info, nr_jited_ksyms),
6127                 -(int)sizeof(__u64),
6128         },
6129         [BPF_PROG_INFO_JITED_FUNC_LENS] = {
6130                 offsetof(struct bpf_prog_info, jited_func_lens),
6131                 offsetof(struct bpf_prog_info, nr_jited_func_lens),
6132                 -(int)sizeof(__u32),
6133         },
6134         [BPF_PROG_INFO_FUNC_INFO] = {
6135                 offsetof(struct bpf_prog_info, func_info),
6136                 offsetof(struct bpf_prog_info, nr_func_info),
6137                 offsetof(struct bpf_prog_info, func_info_rec_size),
6138         },
6139         [BPF_PROG_INFO_LINE_INFO] = {
6140                 offsetof(struct bpf_prog_info, line_info),
6141                 offsetof(struct bpf_prog_info, nr_line_info),
6142                 offsetof(struct bpf_prog_info, line_info_rec_size),
6143         },
6144         [BPF_PROG_INFO_JITED_LINE_INFO] = {
6145                 offsetof(struct bpf_prog_info, jited_line_info),
6146                 offsetof(struct bpf_prog_info, nr_jited_line_info),
6147                 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
6148         },
6149         [BPF_PROG_INFO_PROG_TAGS] = {
6150                 offsetof(struct bpf_prog_info, prog_tags),
6151                 offsetof(struct bpf_prog_info, nr_prog_tags),
6152                 -(int)sizeof(__u8) * BPF_TAG_SIZE,
6153         },
6154
6155 };
6156
6157 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
6158 {
6159         __u32 *array = (__u32 *)info;
6160
6161         if (offset >= 0)
6162                 return array[offset / sizeof(__u32)];
6163         return -(int)offset;
6164 }
6165
6166 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
6167 {
6168         __u64 *array = (__u64 *)info;
6169
6170         if (offset >= 0)
6171                 return array[offset / sizeof(__u64)];
6172         return -(int)offset;
6173 }
6174
6175 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
6176                                          __u32 val)
6177 {
6178         __u32 *array = (__u32 *)info;
6179
6180         if (offset >= 0)
6181                 array[offset / sizeof(__u32)] = val;
6182 }
6183
6184 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
6185                                          __u64 val)
6186 {
6187         __u64 *array = (__u64 *)info;
6188
6189         if (offset >= 0)
6190                 array[offset / sizeof(__u64)] = val;
6191 }
6192
6193 struct bpf_prog_info_linear *
6194 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
6195 {
6196         struct bpf_prog_info_linear *info_linear;
6197         struct bpf_prog_info info = {};
6198         __u32 info_len = sizeof(info);
6199         __u32 data_len = 0;
6200         int i, err;
6201         void *ptr;
6202
6203         if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
6204                 return ERR_PTR(-EINVAL);
6205
6206         /* step 1: get array dimensions */
6207         err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
6208         if (err) {
6209                 pr_debug("can't get prog info: %s", strerror(errno));
6210                 return ERR_PTR(-EFAULT);
6211         }
6212
6213         /* step 2: calculate total size of all arrays */
6214         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6215                 bool include_array = (arrays & (1UL << i)) > 0;
6216                 struct bpf_prog_info_array_desc *desc;
6217                 __u32 count, size;
6218
6219                 desc = bpf_prog_info_array_desc + i;
6220
6221                 /* kernel is too old to support this field */
6222                 if (info_len < desc->array_offset + sizeof(__u32) ||
6223                     info_len < desc->count_offset + sizeof(__u32) ||
6224                     (desc->size_offset > 0 && info_len < desc->size_offset))
6225                         include_array = false;
6226
6227                 if (!include_array) {
6228                         arrays &= ~(1UL << i);  /* clear the bit */
6229                         continue;
6230                 }
6231
6232                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6233                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6234
6235                 data_len += count * size;
6236         }
6237
6238         /* step 3: allocate continuous memory */
6239         data_len = roundup(data_len, sizeof(__u64));
6240         info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
6241         if (!info_linear)
6242                 return ERR_PTR(-ENOMEM);
6243
6244         /* step 4: fill data to info_linear->info */
6245         info_linear->arrays = arrays;
6246         memset(&info_linear->info, 0, sizeof(info));
6247         ptr = info_linear->data;
6248
6249         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6250                 struct bpf_prog_info_array_desc *desc;
6251                 __u32 count, size;
6252
6253                 if ((arrays & (1UL << i)) == 0)
6254                         continue;
6255
6256                 desc  = bpf_prog_info_array_desc + i;
6257                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6258                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6259                 bpf_prog_info_set_offset_u32(&info_linear->info,
6260                                              desc->count_offset, count);
6261                 bpf_prog_info_set_offset_u32(&info_linear->info,
6262                                              desc->size_offset, size);
6263                 bpf_prog_info_set_offset_u64(&info_linear->info,
6264                                              desc->array_offset,
6265                                              ptr_to_u64(ptr));
6266                 ptr += count * size;
6267         }
6268
6269         /* step 5: call syscall again to get required arrays */
6270         err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
6271         if (err) {
6272                 pr_debug("can't get prog info: %s", strerror(errno));
6273                 free(info_linear);
6274                 return ERR_PTR(-EFAULT);
6275         }
6276
6277         /* step 6: verify the data */
6278         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6279                 struct bpf_prog_info_array_desc *desc;
6280                 __u32 v1, v2;
6281
6282                 if ((arrays & (1UL << i)) == 0)
6283                         continue;
6284
6285                 desc = bpf_prog_info_array_desc + i;
6286                 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
6287                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6288                                                    desc->count_offset);
6289                 if (v1 != v2)
6290                         pr_warn("%s: mismatch in element count\n", __func__);
6291
6292                 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
6293                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
6294                                                    desc->size_offset);
6295                 if (v1 != v2)
6296                         pr_warn("%s: mismatch in rec size\n", __func__);
6297         }
6298
6299         /* step 7: update info_len and data_len */
6300         info_linear->info_len = sizeof(struct bpf_prog_info);
6301         info_linear->data_len = data_len;
6302
6303         return info_linear;
6304 }
6305
6306 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
6307 {
6308         int i;
6309
6310         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6311                 struct bpf_prog_info_array_desc *desc;
6312                 __u64 addr, offs;
6313
6314                 if ((info_linear->arrays & (1UL << i)) == 0)
6315                         continue;
6316
6317                 desc = bpf_prog_info_array_desc + i;
6318                 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
6319                                                      desc->array_offset);
6320                 offs = addr - ptr_to_u64(info_linear->data);
6321                 bpf_prog_info_set_offset_u64(&info_linear->info,
6322                                              desc->array_offset, offs);
6323         }
6324 }
6325
6326 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
6327 {
6328         int i;
6329
6330         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
6331                 struct bpf_prog_info_array_desc *desc;
6332                 __u64 addr, offs;
6333
6334                 if ((info_linear->arrays & (1UL << i)) == 0)
6335                         continue;
6336
6337                 desc = bpf_prog_info_array_desc + i;
6338                 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
6339                                                      desc->array_offset);
6340                 addr = offs + ptr_to_u64(info_linear->data);
6341                 bpf_prog_info_set_offset_u64(&info_linear->info,
6342                                              desc->array_offset, addr);
6343         }
6344 }
6345
6346 int libbpf_num_possible_cpus(void)
6347 {
6348         static const char *fcpu = "/sys/devices/system/cpu/possible";
6349         int len = 0, n = 0, il = 0, ir = 0;
6350         unsigned int start = 0, end = 0;
6351         int tmp_cpus = 0;
6352         static int cpus;
6353         char buf[128];
6354         int error = 0;
6355         int fd = -1;
6356
6357         tmp_cpus = READ_ONCE(cpus);
6358         if (tmp_cpus > 0)
6359                 return tmp_cpus;
6360
6361         fd = open(fcpu, O_RDONLY);
6362         if (fd < 0) {
6363                 error = errno;
6364                 pr_warn("Failed to open file %s: %s\n", fcpu, strerror(error));
6365                 return -error;
6366         }
6367         len = read(fd, buf, sizeof(buf));
6368         close(fd);
6369         if (len <= 0) {
6370                 error = len ? errno : EINVAL;
6371                 pr_warn("Failed to read # of possible cpus from %s: %s\n",
6372                         fcpu, strerror(error));
6373                 return -error;
6374         }
6375         if (len == sizeof(buf)) {
6376                 pr_warn("File %s size overflow\n", fcpu);
6377                 return -EOVERFLOW;
6378         }
6379         buf[len] = '\0';
6380
6381         for (ir = 0, tmp_cpus = 0; ir <= len; ir++) {
6382                 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
6383                 if (buf[ir] == ',' || buf[ir] == '\0') {
6384                         buf[ir] = '\0';
6385                         n = sscanf(&buf[il], "%u-%u", &start, &end);
6386                         if (n <= 0) {
6387                                 pr_warn("Failed to get # CPUs from %s\n",
6388                                         &buf[il]);
6389                                 return -EINVAL;
6390                         } else if (n == 1) {
6391                                 end = start;
6392                         }
6393                         tmp_cpus += end - start + 1;
6394                         il = ir + 1;
6395                 }
6396         }
6397         if (tmp_cpus <= 0) {
6398                 pr_warn("Invalid #CPUs %d from %s\n", tmp_cpus, fcpu);
6399                 return -EINVAL;
6400         }
6401
6402         WRITE_ONCE(cpus, tmp_cpus);
6403         return tmp_cpus;
6404 }