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