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