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