]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/lib/bpf/libbpf.c
30cb08e2eb75da3937b48258ff0636346dea243e
[linux.git] / tools / lib / bpf / libbpf.c
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <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/stat.h>
36 #include <sys/types.h>
37 #include <sys/vfs.h>
38 #include <tools/libc_compat.h>
39 #include <libelf.h>
40 #include <gelf.h>
41
42 #include "libbpf.h"
43 #include "bpf.h"
44 #include "btf.h"
45 #include "str_error.h"
46 #include "libbpf_internal.h"
47
48 #ifndef EM_BPF
49 #define EM_BPF 247
50 #endif
51
52 #ifndef BPF_FS_MAGIC
53 #define BPF_FS_MAGIC            0xcafe4a11
54 #endif
55
56 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
57  * compilation if user enables corresponding warning. Disable it explicitly.
58  */
59 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
60
61 #define __printf(a, b)  __attribute__((format(printf, a, b)))
62
63 static int __base_pr(enum libbpf_print_level level, const char *format,
64                      va_list args)
65 {
66         if (level == LIBBPF_DEBUG)
67                 return 0;
68
69         return vfprintf(stderr, format, args);
70 }
71
72 static libbpf_print_fn_t __libbpf_pr = __base_pr;
73
74 void libbpf_set_print(libbpf_print_fn_t fn)
75 {
76         __libbpf_pr = fn;
77 }
78
79 __printf(2, 3)
80 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
81 {
82         va_list args;
83
84         if (!__libbpf_pr)
85                 return;
86
87         va_start(args, format);
88         __libbpf_pr(level, format, args);
89         va_end(args);
90 }
91
92 #define STRERR_BUFSIZE  128
93
94 #define CHECK_ERR(action, err, out) do {        \
95         err = action;                   \
96         if (err)                        \
97                 goto out;               \
98 } while(0)
99
100
101 /* Copied from tools/perf/util/util.h */
102 #ifndef zfree
103 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
104 #endif
105
106 #ifndef zclose
107 # define zclose(fd) ({                  \
108         int ___err = 0;                 \
109         if ((fd) >= 0)                  \
110                 ___err = close((fd));   \
111         fd = -1;                        \
112         ___err; })
113 #endif
114
115 #ifdef HAVE_LIBELF_MMAP_SUPPORT
116 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
117 #else
118 # define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
119 #endif
120
121 static inline __u64 ptr_to_u64(const void *ptr)
122 {
123         return (__u64) (unsigned long) ptr;
124 }
125
126 struct bpf_capabilities {
127         /* v4.14: kernel support for program & map names. */
128         __u32 name:1;
129         /* v5.2: kernel support for global data sections. */
130         __u32 global_data:1;
131         /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
132         __u32 btf_func:1;
133         /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
134         __u32 btf_datasec:1;
135 };
136
137 /*
138  * bpf_prog should be a better name but it has been used in
139  * linux/filter.h.
140  */
141 struct bpf_program {
142         /* Index in elf obj file, for relocation use. */
143         int idx;
144         char *name;
145         int prog_ifindex;
146         char *section_name;
147         /* section_name with / replaced by _; makes recursive pinning
148          * in bpf_object__pin_programs easier
149          */
150         char *pin_name;
151         struct bpf_insn *insns;
152         size_t insns_cnt, main_prog_cnt;
153         enum bpf_prog_type type;
154
155         struct reloc_desc {
156                 enum {
157                         RELO_LD64,
158                         RELO_CALL,
159                         RELO_DATA,
160                 } type;
161                 int insn_idx;
162                 union {
163                         int map_idx;
164                         int text_off;
165                 };
166         } *reloc_desc;
167         int nr_reloc;
168         int log_level;
169
170         struct {
171                 int nr;
172                 int *fds;
173         } instances;
174         bpf_program_prep_t preprocessor;
175
176         struct bpf_object *obj;
177         void *priv;
178         bpf_program_clear_priv_t clear_priv;
179
180         enum bpf_attach_type expected_attach_type;
181         int btf_fd;
182         void *func_info;
183         __u32 func_info_rec_size;
184         __u32 func_info_cnt;
185
186         struct bpf_capabilities *caps;
187
188         void *line_info;
189         __u32 line_info_rec_size;
190         __u32 line_info_cnt;
191         __u32 prog_flags;
192 };
193
194 enum libbpf_map_type {
195         LIBBPF_MAP_UNSPEC,
196         LIBBPF_MAP_DATA,
197         LIBBPF_MAP_BSS,
198         LIBBPF_MAP_RODATA,
199 };
200
201 static const char * const libbpf_type_to_btf_name[] = {
202         [LIBBPF_MAP_DATA]       = ".data",
203         [LIBBPF_MAP_BSS]        = ".bss",
204         [LIBBPF_MAP_RODATA]     = ".rodata",
205 };
206
207 struct bpf_map {
208         int fd;
209         char *name;
210         size_t offset;
211         int map_ifindex;
212         int inner_map_fd;
213         struct bpf_map_def def;
214         __u32 btf_key_type_id;
215         __u32 btf_value_type_id;
216         void *priv;
217         bpf_map_clear_priv_t clear_priv;
218         enum libbpf_map_type libbpf_type;
219 };
220
221 struct bpf_secdata {
222         void *rodata;
223         void *data;
224 };
225
226 static LIST_HEAD(bpf_objects_list);
227
228 struct bpf_object {
229         char name[BPF_OBJ_NAME_LEN];
230         char license[64];
231         __u32 kern_version;
232
233         struct bpf_program *programs;
234         size_t nr_programs;
235         struct bpf_map *maps;
236         size_t nr_maps;
237         struct bpf_secdata sections;
238
239         bool loaded;
240         bool has_pseudo_calls;
241
242         /*
243          * Information when doing elf related work. Only valid if fd
244          * is valid.
245          */
246         struct {
247                 int fd;
248                 void *obj_buf;
249                 size_t obj_buf_sz;
250                 Elf *elf;
251                 GElf_Ehdr ehdr;
252                 Elf_Data *symbols;
253                 Elf_Data *data;
254                 Elf_Data *rodata;
255                 Elf_Data *bss;
256                 size_t strtabidx;
257                 struct {
258                         GElf_Shdr shdr;
259                         Elf_Data *data;
260                 } *reloc;
261                 int nr_reloc;
262                 int maps_shndx;
263                 int text_shndx;
264                 int data_shndx;
265                 int rodata_shndx;
266                 int bss_shndx;
267         } efile;
268         /*
269          * All loaded bpf_object is linked in a list, which is
270          * hidden to caller. bpf_objects__<func> handlers deal with
271          * all objects.
272          */
273         struct list_head list;
274
275         struct btf *btf;
276         struct btf_ext *btf_ext;
277
278         void *priv;
279         bpf_object_clear_priv_t clear_priv;
280
281         struct bpf_capabilities caps;
282
283         char path[];
284 };
285 #define obj_elf_valid(o)        ((o)->efile.elf)
286
287 void bpf_program__unload(struct bpf_program *prog)
288 {
289         int i;
290
291         if (!prog)
292                 return;
293
294         /*
295          * If the object is opened but the program was never loaded,
296          * it is possible that prog->instances.nr == -1.
297          */
298         if (prog->instances.nr > 0) {
299                 for (i = 0; i < prog->instances.nr; i++)
300                         zclose(prog->instances.fds[i]);
301         } else if (prog->instances.nr != -1) {
302                 pr_warning("Internal error: instances.nr is %d\n",
303                            prog->instances.nr);
304         }
305
306         prog->instances.nr = -1;
307         zfree(&prog->instances.fds);
308
309         zclose(prog->btf_fd);
310         zfree(&prog->func_info);
311         zfree(&prog->line_info);
312 }
313
314 static void bpf_program__exit(struct bpf_program *prog)
315 {
316         if (!prog)
317                 return;
318
319         if (prog->clear_priv)
320                 prog->clear_priv(prog, prog->priv);
321
322         prog->priv = NULL;
323         prog->clear_priv = NULL;
324
325         bpf_program__unload(prog);
326         zfree(&prog->name);
327         zfree(&prog->section_name);
328         zfree(&prog->pin_name);
329         zfree(&prog->insns);
330         zfree(&prog->reloc_desc);
331
332         prog->nr_reloc = 0;
333         prog->insns_cnt = 0;
334         prog->idx = -1;
335 }
336
337 static char *__bpf_program__pin_name(struct bpf_program *prog)
338 {
339         char *name, *p;
340
341         name = p = strdup(prog->section_name);
342         while ((p = strchr(p, '/')))
343                 *p = '_';
344
345         return name;
346 }
347
348 static int
349 bpf_program__init(void *data, size_t size, char *section_name, int idx,
350                   struct bpf_program *prog)
351 {
352         if (size < sizeof(struct bpf_insn)) {
353                 pr_warning("corrupted section '%s'\n", section_name);
354                 return -EINVAL;
355         }
356
357         memset(prog, 0, sizeof(*prog));
358
359         prog->section_name = strdup(section_name);
360         if (!prog->section_name) {
361                 pr_warning("failed to alloc name for prog under section(%d) %s\n",
362                            idx, section_name);
363                 goto errout;
364         }
365
366         prog->pin_name = __bpf_program__pin_name(prog);
367         if (!prog->pin_name) {
368                 pr_warning("failed to alloc pin name for prog under section(%d) %s\n",
369                            idx, section_name);
370                 goto errout;
371         }
372
373         prog->insns = malloc(size);
374         if (!prog->insns) {
375                 pr_warning("failed to alloc insns for prog under section %s\n",
376                            section_name);
377                 goto errout;
378         }
379         prog->insns_cnt = size / sizeof(struct bpf_insn);
380         memcpy(prog->insns, data,
381                prog->insns_cnt * sizeof(struct bpf_insn));
382         prog->idx = idx;
383         prog->instances.fds = NULL;
384         prog->instances.nr = -1;
385         prog->type = BPF_PROG_TYPE_UNSPEC;
386         prog->btf_fd = -1;
387
388         return 0;
389 errout:
390         bpf_program__exit(prog);
391         return -ENOMEM;
392 }
393
394 static int
395 bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
396                         char *section_name, int idx)
397 {
398         struct bpf_program prog, *progs;
399         int nr_progs, err;
400
401         err = bpf_program__init(data, size, section_name, idx, &prog);
402         if (err)
403                 return err;
404
405         prog.caps = &obj->caps;
406         progs = obj->programs;
407         nr_progs = obj->nr_programs;
408
409         progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
410         if (!progs) {
411                 /*
412                  * In this case the original obj->programs
413                  * is still valid, so don't need special treat for
414                  * bpf_close_object().
415                  */
416                 pr_warning("failed to alloc a new program under section '%s'\n",
417                            section_name);
418                 bpf_program__exit(&prog);
419                 return -ENOMEM;
420         }
421
422         pr_debug("found program %s\n", prog.section_name);
423         obj->programs = progs;
424         obj->nr_programs = nr_progs + 1;
425         prog.obj = obj;
426         progs[nr_progs] = prog;
427         return 0;
428 }
429
430 static int
431 bpf_object__init_prog_names(struct bpf_object *obj)
432 {
433         Elf_Data *symbols = obj->efile.symbols;
434         struct bpf_program *prog;
435         size_t pi, si;
436
437         for (pi = 0; pi < obj->nr_programs; pi++) {
438                 const char *name = NULL;
439
440                 prog = &obj->programs[pi];
441
442                 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
443                      si++) {
444                         GElf_Sym sym;
445
446                         if (!gelf_getsym(symbols, si, &sym))
447                                 continue;
448                         if (sym.st_shndx != prog->idx)
449                                 continue;
450                         if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
451                                 continue;
452
453                         name = elf_strptr(obj->efile.elf,
454                                           obj->efile.strtabidx,
455                                           sym.st_name);
456                         if (!name) {
457                                 pr_warning("failed to get sym name string for prog %s\n",
458                                            prog->section_name);
459                                 return -LIBBPF_ERRNO__LIBELF;
460                         }
461                 }
462
463                 if (!name && prog->idx == obj->efile.text_shndx)
464                         name = ".text";
465
466                 if (!name) {
467                         pr_warning("failed to find sym for prog %s\n",
468                                    prog->section_name);
469                         return -EINVAL;
470                 }
471
472                 prog->name = strdup(name);
473                 if (!prog->name) {
474                         pr_warning("failed to allocate memory for prog sym %s\n",
475                                    name);
476                         return -ENOMEM;
477                 }
478         }
479
480         return 0;
481 }
482
483 static struct bpf_object *bpf_object__new(const char *path,
484                                           void *obj_buf,
485                                           size_t obj_buf_sz)
486 {
487         struct bpf_object *obj;
488         char *end;
489
490         obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
491         if (!obj) {
492                 pr_warning("alloc memory failed for %s\n", path);
493                 return ERR_PTR(-ENOMEM);
494         }
495
496         strcpy(obj->path, path);
497         /* Using basename() GNU version which doesn't modify arg. */
498         strncpy(obj->name, basename((void *)path),
499                 sizeof(obj->name) - 1);
500         end = strchr(obj->name, '.');
501         if (end)
502                 *end = 0;
503
504         obj->efile.fd = -1;
505         /*
506          * Caller of this function should also calls
507          * bpf_object__elf_finish() after data collection to return
508          * obj_buf to user. If not, we should duplicate the buffer to
509          * avoid user freeing them before elf finish.
510          */
511         obj->efile.obj_buf = obj_buf;
512         obj->efile.obj_buf_sz = obj_buf_sz;
513         obj->efile.maps_shndx = -1;
514         obj->efile.data_shndx = -1;
515         obj->efile.rodata_shndx = -1;
516         obj->efile.bss_shndx = -1;
517
518         obj->loaded = false;
519
520         INIT_LIST_HEAD(&obj->list);
521         list_add(&obj->list, &bpf_objects_list);
522         return obj;
523 }
524
525 static void bpf_object__elf_finish(struct bpf_object *obj)
526 {
527         if (!obj_elf_valid(obj))
528                 return;
529
530         if (obj->efile.elf) {
531                 elf_end(obj->efile.elf);
532                 obj->efile.elf = NULL;
533         }
534         obj->efile.symbols = NULL;
535         obj->efile.data = NULL;
536         obj->efile.rodata = NULL;
537         obj->efile.bss = NULL;
538
539         zfree(&obj->efile.reloc);
540         obj->efile.nr_reloc = 0;
541         zclose(obj->efile.fd);
542         obj->efile.obj_buf = NULL;
543         obj->efile.obj_buf_sz = 0;
544 }
545
546 static int bpf_object__elf_init(struct bpf_object *obj)
547 {
548         int err = 0;
549         GElf_Ehdr *ep;
550
551         if (obj_elf_valid(obj)) {
552                 pr_warning("elf init: internal error\n");
553                 return -LIBBPF_ERRNO__LIBELF;
554         }
555
556         if (obj->efile.obj_buf_sz > 0) {
557                 /*
558                  * obj_buf should have been validated by
559                  * bpf_object__open_buffer().
560                  */
561                 obj->efile.elf = elf_memory(obj->efile.obj_buf,
562                                             obj->efile.obj_buf_sz);
563         } else {
564                 obj->efile.fd = open(obj->path, O_RDONLY);
565                 if (obj->efile.fd < 0) {
566                         char errmsg[STRERR_BUFSIZE];
567                         char *cp = libbpf_strerror_r(errno, errmsg,
568                                                      sizeof(errmsg));
569
570                         pr_warning("failed to open %s: %s\n", obj->path, cp);
571                         return -errno;
572                 }
573
574                 obj->efile.elf = elf_begin(obj->efile.fd,
575                                 LIBBPF_ELF_C_READ_MMAP,
576                                 NULL);
577         }
578
579         if (!obj->efile.elf) {
580                 pr_warning("failed to open %s as ELF file\n",
581                                 obj->path);
582                 err = -LIBBPF_ERRNO__LIBELF;
583                 goto errout;
584         }
585
586         if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
587                 pr_warning("failed to get EHDR from %s\n",
588                                 obj->path);
589                 err = -LIBBPF_ERRNO__FORMAT;
590                 goto errout;
591         }
592         ep = &obj->efile.ehdr;
593
594         /* Old LLVM set e_machine to EM_NONE */
595         if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
596                 pr_warning("%s is not an eBPF object file\n",
597                         obj->path);
598                 err = -LIBBPF_ERRNO__FORMAT;
599                 goto errout;
600         }
601
602         return 0;
603 errout:
604         bpf_object__elf_finish(obj);
605         return err;
606 }
607
608 static int
609 bpf_object__check_endianness(struct bpf_object *obj)
610 {
611         static unsigned int const endian = 1;
612
613         switch (obj->efile.ehdr.e_ident[EI_DATA]) {
614         case ELFDATA2LSB:
615                 /* We are big endian, BPF obj is little endian. */
616                 if (*(unsigned char const *)&endian != 1)
617                         goto mismatch;
618                 break;
619
620         case ELFDATA2MSB:
621                 /* We are little endian, BPF obj is big endian. */
622                 if (*(unsigned char const *)&endian != 0)
623                         goto mismatch;
624                 break;
625         default:
626                 return -LIBBPF_ERRNO__ENDIAN;
627         }
628
629         return 0;
630
631 mismatch:
632         pr_warning("Error: endianness mismatch.\n");
633         return -LIBBPF_ERRNO__ENDIAN;
634 }
635
636 static int
637 bpf_object__init_license(struct bpf_object *obj,
638                          void *data, size_t size)
639 {
640         memcpy(obj->license, data,
641                min(size, sizeof(obj->license) - 1));
642         pr_debug("license of %s is %s\n", obj->path, obj->license);
643         return 0;
644 }
645
646 static int
647 bpf_object__init_kversion(struct bpf_object *obj,
648                           void *data, size_t size)
649 {
650         __u32 kver;
651
652         if (size != sizeof(kver)) {
653                 pr_warning("invalid kver section in %s\n", obj->path);
654                 return -LIBBPF_ERRNO__FORMAT;
655         }
656         memcpy(&kver, data, sizeof(kver));
657         obj->kern_version = kver;
658         pr_debug("kernel version of %s is %x\n", obj->path,
659                  obj->kern_version);
660         return 0;
661 }
662
663 static int compare_bpf_map(const void *_a, const void *_b)
664 {
665         const struct bpf_map *a = _a;
666         const struct bpf_map *b = _b;
667
668         return a->offset - b->offset;
669 }
670
671 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
672 {
673         if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
674             type == BPF_MAP_TYPE_HASH_OF_MAPS)
675                 return true;
676         return false;
677 }
678
679 static int bpf_object_search_section_size(const struct bpf_object *obj,
680                                           const char *name, size_t *d_size)
681 {
682         const GElf_Ehdr *ep = &obj->efile.ehdr;
683         Elf *elf = obj->efile.elf;
684         Elf_Scn *scn = NULL;
685         int idx = 0;
686
687         while ((scn = elf_nextscn(elf, scn)) != NULL) {
688                 const char *sec_name;
689                 Elf_Data *data;
690                 GElf_Shdr sh;
691
692                 idx++;
693                 if (gelf_getshdr(scn, &sh) != &sh) {
694                         pr_warning("failed to get section(%d) header from %s\n",
695                                    idx, obj->path);
696                         return -EIO;
697                 }
698
699                 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
700                 if (!sec_name) {
701                         pr_warning("failed to get section(%d) name from %s\n",
702                                    idx, obj->path);
703                         return -EIO;
704                 }
705
706                 if (strcmp(name, sec_name))
707                         continue;
708
709                 data = elf_getdata(scn, 0);
710                 if (!data) {
711                         pr_warning("failed to get section(%d) data from %s(%s)\n",
712                                    idx, name, obj->path);
713                         return -EIO;
714                 }
715
716                 *d_size = data->d_size;
717                 return 0;
718         }
719
720         return -ENOENT;
721 }
722
723 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
724                              __u32 *size)
725 {
726         int ret = -ENOENT;
727         size_t d_size;
728
729         *size = 0;
730         if (!name) {
731                 return -EINVAL;
732         } else if (!strcmp(name, ".data")) {
733                 if (obj->efile.data)
734                         *size = obj->efile.data->d_size;
735         } else if (!strcmp(name, ".bss")) {
736                 if (obj->efile.bss)
737                         *size = obj->efile.bss->d_size;
738         } else if (!strcmp(name, ".rodata")) {
739                 if (obj->efile.rodata)
740                         *size = obj->efile.rodata->d_size;
741         } else {
742                 ret = bpf_object_search_section_size(obj, name, &d_size);
743                 if (!ret)
744                         *size = d_size;
745         }
746
747         return *size ? 0 : ret;
748 }
749
750 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
751                                 __u32 *off)
752 {
753         Elf_Data *symbols = obj->efile.symbols;
754         const char *sname;
755         size_t si;
756
757         if (!name || !off)
758                 return -EINVAL;
759
760         for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
761                 GElf_Sym sym;
762
763                 if (!gelf_getsym(symbols, si, &sym))
764                         continue;
765                 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
766                     GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
767                         continue;
768
769                 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
770                                    sym.st_name);
771                 if (!sname) {
772                         pr_warning("failed to get sym name string for var %s\n",
773                                    name);
774                         return -EIO;
775                 }
776                 if (strcmp(name, sname) == 0) {
777                         *off = sym.st_value;
778                         return 0;
779                 }
780         }
781
782         return -ENOENT;
783 }
784
785 static bool bpf_object__has_maps(const struct bpf_object *obj)
786 {
787         return obj->efile.maps_shndx >= 0 ||
788                obj->efile.data_shndx >= 0 ||
789                obj->efile.rodata_shndx >= 0 ||
790                obj->efile.bss_shndx >= 0;
791 }
792
793 static int
794 bpf_object__init_internal_map(struct bpf_object *obj, struct bpf_map *map,
795                               enum libbpf_map_type type, Elf_Data *data,
796                               void **data_buff)
797 {
798         struct bpf_map_def *def = &map->def;
799         char map_name[BPF_OBJ_NAME_LEN];
800
801         map->libbpf_type = type;
802         map->offset = ~(typeof(map->offset))0;
803         snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
804                  libbpf_type_to_btf_name[type]);
805         map->name = strdup(map_name);
806         if (!map->name) {
807                 pr_warning("failed to alloc map name\n");
808                 return -ENOMEM;
809         }
810
811         def->type = BPF_MAP_TYPE_ARRAY;
812         def->key_size = sizeof(int);
813         def->value_size = data->d_size;
814         def->max_entries = 1;
815         def->map_flags = type == LIBBPF_MAP_RODATA ?
816                          BPF_F_RDONLY_PROG : 0;
817         if (data_buff) {
818                 *data_buff = malloc(data->d_size);
819                 if (!*data_buff) {
820                         zfree(&map->name);
821                         pr_warning("failed to alloc map content buffer\n");
822                         return -ENOMEM;
823                 }
824                 memcpy(*data_buff, data->d_buf, data->d_size);
825         }
826
827         pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
828         return 0;
829 }
830
831 static int
832 bpf_object__init_maps(struct bpf_object *obj, int flags)
833 {
834         int i, map_idx, map_def_sz = 0, nr_syms, nr_maps = 0, nr_maps_glob = 0;
835         bool strict = !(flags & MAPS_RELAX_COMPAT);
836         Elf_Data *symbols = obj->efile.symbols;
837         Elf_Data *data = NULL;
838         int ret = 0;
839
840         if (!symbols)
841                 return -EINVAL;
842         nr_syms = symbols->d_size / sizeof(GElf_Sym);
843
844         if (obj->efile.maps_shndx >= 0) {
845                 Elf_Scn *scn = elf_getscn(obj->efile.elf,
846                                           obj->efile.maps_shndx);
847
848                 if (scn)
849                         data = elf_getdata(scn, NULL);
850                 if (!scn || !data) {
851                         pr_warning("failed to get Elf_Data from map section %d\n",
852                                    obj->efile.maps_shndx);
853                         return -EINVAL;
854                 }
855         }
856
857         /*
858          * Count number of maps. Each map has a name.
859          * Array of maps is not supported: only the first element is
860          * considered.
861          *
862          * TODO: Detect array of map and report error.
863          */
864         if (obj->caps.global_data) {
865                 if (obj->efile.data_shndx >= 0)
866                         nr_maps_glob++;
867                 if (obj->efile.rodata_shndx >= 0)
868                         nr_maps_glob++;
869                 if (obj->efile.bss_shndx >= 0)
870                         nr_maps_glob++;
871         }
872
873         for (i = 0; data && i < nr_syms; i++) {
874                 GElf_Sym sym;
875
876                 if (!gelf_getsym(symbols, i, &sym))
877                         continue;
878                 if (sym.st_shndx != obj->efile.maps_shndx)
879                         continue;
880                 nr_maps++;
881         }
882
883         if (!nr_maps && !nr_maps_glob)
884                 return 0;
885
886         /* Assume equally sized map definitions */
887         if (data) {
888                 pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
889                          nr_maps, data->d_size);
890
891                 map_def_sz = data->d_size / nr_maps;
892                 if (!data->d_size || (data->d_size % nr_maps) != 0) {
893                         pr_warning("unable to determine map definition size "
894                                    "section %s, %d maps in %zd bytes\n",
895                                    obj->path, nr_maps, data->d_size);
896                         return -EINVAL;
897                 }
898         }
899
900         nr_maps += nr_maps_glob;
901         obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
902         if (!obj->maps) {
903                 pr_warning("alloc maps for object failed\n");
904                 return -ENOMEM;
905         }
906         obj->nr_maps = nr_maps;
907
908         for (i = 0; i < nr_maps; i++) {
909                 /*
910                  * fill all fd with -1 so won't close incorrect
911                  * fd (fd=0 is stdin) when failure (zclose won't close
912                  * negative fd)).
913                  */
914                 obj->maps[i].fd = -1;
915                 obj->maps[i].inner_map_fd = -1;
916         }
917
918         /*
919          * Fill obj->maps using data in "maps" section.
920          */
921         for (i = 0, map_idx = 0; data && i < nr_syms; i++) {
922                 GElf_Sym sym;
923                 const char *map_name;
924                 struct bpf_map_def *def;
925
926                 if (!gelf_getsym(symbols, i, &sym))
927                         continue;
928                 if (sym.st_shndx != obj->efile.maps_shndx)
929                         continue;
930
931                 map_name = elf_strptr(obj->efile.elf,
932                                       obj->efile.strtabidx,
933                                       sym.st_name);
934
935                 obj->maps[map_idx].libbpf_type = LIBBPF_MAP_UNSPEC;
936                 obj->maps[map_idx].offset = sym.st_value;
937                 if (sym.st_value + map_def_sz > data->d_size) {
938                         pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
939                                    obj->path, map_name);
940                         return -EINVAL;
941                 }
942
943                 obj->maps[map_idx].name = strdup(map_name);
944                 if (!obj->maps[map_idx].name) {
945                         pr_warning("failed to alloc map name\n");
946                         return -ENOMEM;
947                 }
948                 pr_debug("map %d is \"%s\"\n", map_idx,
949                          obj->maps[map_idx].name);
950                 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
951                 /*
952                  * If the definition of the map in the object file fits in
953                  * bpf_map_def, copy it.  Any extra fields in our version
954                  * of bpf_map_def will default to zero as a result of the
955                  * calloc above.
956                  */
957                 if (map_def_sz <= sizeof(struct bpf_map_def)) {
958                         memcpy(&obj->maps[map_idx].def, def, map_def_sz);
959                 } else {
960                         /*
961                          * Here the map structure being read is bigger than what
962                          * we expect, truncate if the excess bits are all zero.
963                          * If they are not zero, reject this map as
964                          * incompatible.
965                          */
966                         char *b;
967                         for (b = ((char *)def) + sizeof(struct bpf_map_def);
968                              b < ((char *)def) + map_def_sz; b++) {
969                                 if (*b != 0) {
970                                         pr_warning("maps section in %s: \"%s\" "
971                                                    "has unrecognized, non-zero "
972                                                    "options\n",
973                                                    obj->path, map_name);
974                                         if (strict)
975                                                 return -EINVAL;
976                                 }
977                         }
978                         memcpy(&obj->maps[map_idx].def, def,
979                                sizeof(struct bpf_map_def));
980                 }
981                 map_idx++;
982         }
983
984         if (!obj->caps.global_data)
985                 goto finalize;
986
987         /*
988          * Populate rest of obj->maps with libbpf internal maps.
989          */
990         if (obj->efile.data_shndx >= 0)
991                 ret = bpf_object__init_internal_map(obj, &obj->maps[map_idx++],
992                                                     LIBBPF_MAP_DATA,
993                                                     obj->efile.data,
994                                                     &obj->sections.data);
995         if (!ret && obj->efile.rodata_shndx >= 0)
996                 ret = bpf_object__init_internal_map(obj, &obj->maps[map_idx++],
997                                                     LIBBPF_MAP_RODATA,
998                                                     obj->efile.rodata,
999                                                     &obj->sections.rodata);
1000         if (!ret && obj->efile.bss_shndx >= 0)
1001                 ret = bpf_object__init_internal_map(obj, &obj->maps[map_idx++],
1002                                                     LIBBPF_MAP_BSS,
1003                                                     obj->efile.bss, NULL);
1004 finalize:
1005         if (!ret)
1006                 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1007                       compare_bpf_map);
1008         return ret;
1009 }
1010
1011 static bool section_have_execinstr(struct bpf_object *obj, int idx)
1012 {
1013         Elf_Scn *scn;
1014         GElf_Shdr sh;
1015
1016         scn = elf_getscn(obj->efile.elf, idx);
1017         if (!scn)
1018                 return false;
1019
1020         if (gelf_getshdr(scn, &sh) != &sh)
1021                 return false;
1022
1023         if (sh.sh_flags & SHF_EXECINSTR)
1024                 return true;
1025
1026         return false;
1027 }
1028
1029 static void bpf_object__sanitize_btf(struct bpf_object *obj)
1030 {
1031         bool has_datasec = obj->caps.btf_datasec;
1032         bool has_func = obj->caps.btf_func;
1033         struct btf *btf = obj->btf;
1034         struct btf_type *t;
1035         int i, j, vlen;
1036         __u16 kind;
1037
1038         if (!obj->btf || (has_func && has_datasec))
1039                 return;
1040
1041         for (i = 1; i <= btf__get_nr_types(btf); i++) {
1042                 t = (struct btf_type *)btf__type_by_id(btf, i);
1043                 kind = BTF_INFO_KIND(t->info);
1044
1045                 if (!has_datasec && kind == BTF_KIND_VAR) {
1046                         /* replace VAR with INT */
1047                         t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1048                         t->size = sizeof(int);
1049                         *(int *)(t+1) = BTF_INT_ENC(0, 0, 32);
1050                 } else if (!has_datasec && kind == BTF_KIND_DATASEC) {
1051                         /* replace DATASEC with STRUCT */
1052                         struct btf_var_secinfo *v = (void *)(t + 1);
1053                         struct btf_member *m = (void *)(t + 1);
1054                         struct btf_type *vt;
1055                         char *name;
1056
1057                         name = (char *)btf__name_by_offset(btf, t->name_off);
1058                         while (*name) {
1059                                 if (*name == '.')
1060                                         *name = '_';
1061                                 name++;
1062                         }
1063
1064                         vlen = BTF_INFO_VLEN(t->info);
1065                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1066                         for (j = 0; j < vlen; j++, v++, m++) {
1067                                 /* order of field assignments is important */
1068                                 m->offset = v->offset * 8;
1069                                 m->type = v->type;
1070                                 /* preserve variable name as member name */
1071                                 vt = (void *)btf__type_by_id(btf, v->type);
1072                                 m->name_off = vt->name_off;
1073                         }
1074                 } else if (!has_func && kind == BTF_KIND_FUNC_PROTO) {
1075                         /* replace FUNC_PROTO with ENUM */
1076                         vlen = BTF_INFO_VLEN(t->info);
1077                         t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1078                         t->size = sizeof(__u32); /* kernel enforced */
1079                 } else if (!has_func && kind == BTF_KIND_FUNC) {
1080                         /* replace FUNC with TYPEDEF */
1081                         t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1082                 }
1083         }
1084 }
1085
1086 static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1087 {
1088         if (!obj->btf_ext)
1089                 return;
1090
1091         if (!obj->caps.btf_func) {
1092                 btf_ext__free(obj->btf_ext);
1093                 obj->btf_ext = NULL;
1094         }
1095 }
1096
1097 static int bpf_object__elf_collect(struct bpf_object *obj, int flags)
1098 {
1099         Elf *elf = obj->efile.elf;
1100         GElf_Ehdr *ep = &obj->efile.ehdr;
1101         Elf_Data *btf_ext_data = NULL;
1102         Elf_Data *btf_data = NULL;
1103         Elf_Scn *scn = NULL;
1104         int idx = 0, err = 0;
1105
1106         /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1107         if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
1108                 pr_warning("failed to get e_shstrndx from %s\n",
1109                            obj->path);
1110                 return -LIBBPF_ERRNO__FORMAT;
1111         }
1112
1113         while ((scn = elf_nextscn(elf, scn)) != NULL) {
1114                 char *name;
1115                 GElf_Shdr sh;
1116                 Elf_Data *data;
1117
1118                 idx++;
1119                 if (gelf_getshdr(scn, &sh) != &sh) {
1120                         pr_warning("failed to get section(%d) header from %s\n",
1121                                    idx, obj->path);
1122                         err = -LIBBPF_ERRNO__FORMAT;
1123                         goto out;
1124                 }
1125
1126                 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1127                 if (!name) {
1128                         pr_warning("failed to get section(%d) name from %s\n",
1129                                    idx, obj->path);
1130                         err = -LIBBPF_ERRNO__FORMAT;
1131                         goto out;
1132                 }
1133
1134                 data = elf_getdata(scn, 0);
1135                 if (!data) {
1136                         pr_warning("failed to get section(%d) data from %s(%s)\n",
1137                                    idx, name, obj->path);
1138                         err = -LIBBPF_ERRNO__FORMAT;
1139                         goto out;
1140                 }
1141                 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1142                          idx, name, (unsigned long)data->d_size,
1143                          (int)sh.sh_link, (unsigned long)sh.sh_flags,
1144                          (int)sh.sh_type);
1145
1146                 if (strcmp(name, "license") == 0) {
1147                         err = bpf_object__init_license(obj,
1148                                                        data->d_buf,
1149                                                        data->d_size);
1150                 } else if (strcmp(name, "version") == 0) {
1151                         err = bpf_object__init_kversion(obj,
1152                                                         data->d_buf,
1153                                                         data->d_size);
1154                 } else if (strcmp(name, "maps") == 0) {
1155                         obj->efile.maps_shndx = idx;
1156                 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
1157                         btf_data = data;
1158                 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
1159                         btf_ext_data = data;
1160                 } else if (sh.sh_type == SHT_SYMTAB) {
1161                         if (obj->efile.symbols) {
1162                                 pr_warning("bpf: multiple SYMTAB in %s\n",
1163                                            obj->path);
1164                                 err = -LIBBPF_ERRNO__FORMAT;
1165                         } else {
1166                                 obj->efile.symbols = data;
1167                                 obj->efile.strtabidx = sh.sh_link;
1168                         }
1169                 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
1170                         if (sh.sh_flags & SHF_EXECINSTR) {
1171                                 if (strcmp(name, ".text") == 0)
1172                                         obj->efile.text_shndx = idx;
1173                                 err = bpf_object__add_program(obj, data->d_buf,
1174                                                               data->d_size, name, idx);
1175                                 if (err) {
1176                                         char errmsg[STRERR_BUFSIZE];
1177                                         char *cp = libbpf_strerror_r(-err, errmsg,
1178                                                                      sizeof(errmsg));
1179
1180                                         pr_warning("failed to alloc program %s (%s): %s",
1181                                                    name, obj->path, cp);
1182                                 }
1183                         } else if (strcmp(name, ".data") == 0) {
1184                                 obj->efile.data = data;
1185                                 obj->efile.data_shndx = idx;
1186                         } else if (strcmp(name, ".rodata") == 0) {
1187                                 obj->efile.rodata = data;
1188                                 obj->efile.rodata_shndx = idx;
1189                         } else {
1190                                 pr_debug("skip section(%d) %s\n", idx, name);
1191                         }
1192                 } else if (sh.sh_type == SHT_REL) {
1193                         void *reloc = obj->efile.reloc;
1194                         int nr_reloc = obj->efile.nr_reloc + 1;
1195                         int sec = sh.sh_info; /* points to other section */
1196
1197                         /* Only do relo for section with exec instructions */
1198                         if (!section_have_execinstr(obj, sec)) {
1199                                 pr_debug("skip relo %s(%d) for section(%d)\n",
1200                                          name, idx, sec);
1201                                 continue;
1202                         }
1203
1204                         reloc = reallocarray(reloc, nr_reloc,
1205                                              sizeof(*obj->efile.reloc));
1206                         if (!reloc) {
1207                                 pr_warning("realloc failed\n");
1208                                 err = -ENOMEM;
1209                         } else {
1210                                 int n = nr_reloc - 1;
1211
1212                                 obj->efile.reloc = reloc;
1213                                 obj->efile.nr_reloc = nr_reloc;
1214
1215                                 obj->efile.reloc[n].shdr = sh;
1216                                 obj->efile.reloc[n].data = data;
1217                         }
1218                 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, ".bss") == 0) {
1219                         obj->efile.bss = data;
1220                         obj->efile.bss_shndx = idx;
1221                 } else {
1222                         pr_debug("skip section(%d) %s\n", idx, name);
1223                 }
1224                 if (err)
1225                         goto out;
1226         }
1227
1228         if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
1229                 pr_warning("Corrupted ELF file: index of strtab invalid\n");
1230                 return LIBBPF_ERRNO__FORMAT;
1231         }
1232         if (btf_data) {
1233                 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1234                 if (IS_ERR(obj->btf)) {
1235                         pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1236                                    BTF_ELF_SEC, PTR_ERR(obj->btf));
1237                         obj->btf = NULL;
1238                 } else {
1239                         err = btf__finalize_data(obj, obj->btf);
1240                         if (!err) {
1241                                 bpf_object__sanitize_btf(obj);
1242                                 err = btf__load(obj->btf);
1243                         }
1244                         if (err) {
1245                                 pr_warning("Error finalizing and loading %s into kernel: %d. Ignored and continue.\n",
1246                                            BTF_ELF_SEC, err);
1247                                 btf__free(obj->btf);
1248                                 obj->btf = NULL;
1249                                 err = 0;
1250                         }
1251                 }
1252         }
1253         if (btf_ext_data) {
1254                 if (!obj->btf) {
1255                         pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1256                                  BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1257                 } else {
1258                         obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1259                                                     btf_ext_data->d_size);
1260                         if (IS_ERR(obj->btf_ext)) {
1261                                 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
1262                                            BTF_EXT_ELF_SEC,
1263                                            PTR_ERR(obj->btf_ext));
1264                                 obj->btf_ext = NULL;
1265                         } else {
1266                                 bpf_object__sanitize_btf_ext(obj);
1267                         }
1268                 }
1269         }
1270         if (bpf_object__has_maps(obj)) {
1271                 err = bpf_object__init_maps(obj, flags);
1272                 if (err)
1273                         goto out;
1274         }
1275         err = bpf_object__init_prog_names(obj);
1276 out:
1277         return err;
1278 }
1279
1280 static struct bpf_program *
1281 bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
1282 {
1283         struct bpf_program *prog;
1284         size_t i;
1285
1286         for (i = 0; i < obj->nr_programs; i++) {
1287                 prog = &obj->programs[i];
1288                 if (prog->idx == idx)
1289                         return prog;
1290         }
1291         return NULL;
1292 }
1293
1294 struct bpf_program *
1295 bpf_object__find_program_by_title(struct bpf_object *obj, const char *title)
1296 {
1297         struct bpf_program *pos;
1298
1299         bpf_object__for_each_program(pos, obj) {
1300                 if (pos->section_name && !strcmp(pos->section_name, title))
1301                         return pos;
1302         }
1303         return NULL;
1304 }
1305
1306 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
1307                                       int shndx)
1308 {
1309         return shndx == obj->efile.data_shndx ||
1310                shndx == obj->efile.bss_shndx ||
1311                shndx == obj->efile.rodata_shndx;
1312 }
1313
1314 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
1315                                       int shndx)
1316 {
1317         return shndx == obj->efile.maps_shndx;
1318 }
1319
1320 static bool bpf_object__relo_in_known_section(const struct bpf_object *obj,
1321                                               int shndx)
1322 {
1323         return shndx == obj->efile.text_shndx ||
1324                bpf_object__shndx_is_maps(obj, shndx) ||
1325                bpf_object__shndx_is_data(obj, shndx);
1326 }
1327
1328 static enum libbpf_map_type
1329 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
1330 {
1331         if (shndx == obj->efile.data_shndx)
1332                 return LIBBPF_MAP_DATA;
1333         else if (shndx == obj->efile.bss_shndx)
1334                 return LIBBPF_MAP_BSS;
1335         else if (shndx == obj->efile.rodata_shndx)
1336                 return LIBBPF_MAP_RODATA;
1337         else
1338                 return LIBBPF_MAP_UNSPEC;
1339 }
1340
1341 static int
1342 bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
1343                            Elf_Data *data, struct bpf_object *obj)
1344 {
1345         Elf_Data *symbols = obj->efile.symbols;
1346         struct bpf_map *maps = obj->maps;
1347         size_t nr_maps = obj->nr_maps;
1348         int i, nrels;
1349
1350         pr_debug("collecting relocating info for: '%s'\n",
1351                  prog->section_name);
1352         nrels = shdr->sh_size / shdr->sh_entsize;
1353
1354         prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
1355         if (!prog->reloc_desc) {
1356                 pr_warning("failed to alloc memory in relocation\n");
1357                 return -ENOMEM;
1358         }
1359         prog->nr_reloc = nrels;
1360
1361         for (i = 0; i < nrels; i++) {
1362                 GElf_Sym sym;
1363                 GElf_Rel rel;
1364                 unsigned int insn_idx;
1365                 unsigned int shdr_idx;
1366                 struct bpf_insn *insns = prog->insns;
1367                 enum libbpf_map_type type;
1368                 const char *name;
1369                 size_t map_idx;
1370
1371                 if (!gelf_getrel(data, i, &rel)) {
1372                         pr_warning("relocation: failed to get %d reloc\n", i);
1373                         return -LIBBPF_ERRNO__FORMAT;
1374                 }
1375
1376                 if (!gelf_getsym(symbols,
1377                                  GELF_R_SYM(rel.r_info),
1378                                  &sym)) {
1379                         pr_warning("relocation: symbol %"PRIx64" not found\n",
1380                                    GELF_R_SYM(rel.r_info));
1381                         return -LIBBPF_ERRNO__FORMAT;
1382                 }
1383
1384                 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1385                                   sym.st_name) ? : "<?>";
1386
1387                 pr_debug("relo for %lld value %lld name %d (\'%s\')\n",
1388                          (long long) (rel.r_info >> 32),
1389                          (long long) sym.st_value, sym.st_name, name);
1390
1391                 shdr_idx = sym.st_shndx;
1392                 if (!bpf_object__relo_in_known_section(obj, shdr_idx)) {
1393                         pr_warning("Program '%s' contains unrecognized relo data pointing to section %u\n",
1394                                    prog->section_name, shdr_idx);
1395                         return -LIBBPF_ERRNO__RELOC;
1396                 }
1397
1398                 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
1399                 pr_debug("relocation: insn_idx=%u\n", insn_idx);
1400
1401                 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
1402                         if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
1403                                 pr_warning("incorrect bpf_call opcode\n");
1404                                 return -LIBBPF_ERRNO__RELOC;
1405                         }
1406                         prog->reloc_desc[i].type = RELO_CALL;
1407                         prog->reloc_desc[i].insn_idx = insn_idx;
1408                         prog->reloc_desc[i].text_off = sym.st_value;
1409                         obj->has_pseudo_calls = true;
1410                         continue;
1411                 }
1412
1413                 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
1414                         pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
1415                                    insn_idx, insns[insn_idx].code);
1416                         return -LIBBPF_ERRNO__RELOC;
1417                 }
1418
1419                 if (bpf_object__shndx_is_maps(obj, shdr_idx) ||
1420                     bpf_object__shndx_is_data(obj, shdr_idx)) {
1421                         type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
1422                         if (type != LIBBPF_MAP_UNSPEC) {
1423                                 if (GELF_ST_BIND(sym.st_info) == STB_GLOBAL) {
1424                                         pr_warning("bpf: relocation: not yet supported relo for non-static global \'%s\' variable found in insns[%d].code 0x%x\n",
1425                                                    name, insn_idx, insns[insn_idx].code);
1426                                         return -LIBBPF_ERRNO__RELOC;
1427                                 }
1428                                 if (!obj->caps.global_data) {
1429                                         pr_warning("bpf: relocation: kernel does not support global \'%s\' variable access in insns[%d]\n",
1430                                                    name, insn_idx);
1431                                         return -LIBBPF_ERRNO__RELOC;
1432                                 }
1433                         }
1434
1435                         for (map_idx = 0; map_idx < nr_maps; map_idx++) {
1436                                 if (maps[map_idx].libbpf_type != type)
1437                                         continue;
1438                                 if (type != LIBBPF_MAP_UNSPEC ||
1439                                     (type == LIBBPF_MAP_UNSPEC &&
1440                                      maps[map_idx].offset == sym.st_value)) {
1441                                         pr_debug("relocation: find map %zd (%s) for insn %u\n",
1442                                                  map_idx, maps[map_idx].name, insn_idx);
1443                                         break;
1444                                 }
1445                         }
1446
1447                         if (map_idx >= nr_maps) {
1448                                 pr_warning("bpf relocation: map_idx %d large than %d\n",
1449                                            (int)map_idx, (int)nr_maps - 1);
1450                                 return -LIBBPF_ERRNO__RELOC;
1451                         }
1452
1453                         prog->reloc_desc[i].type = type != LIBBPF_MAP_UNSPEC ?
1454                                                    RELO_DATA : RELO_LD64;
1455                         prog->reloc_desc[i].insn_idx = insn_idx;
1456                         prog->reloc_desc[i].map_idx = map_idx;
1457                 }
1458         }
1459         return 0;
1460 }
1461
1462 static int bpf_map_find_btf_info(struct bpf_map *map, const struct btf *btf)
1463 {
1464         struct bpf_map_def *def = &map->def;
1465         __u32 key_type_id = 0, value_type_id = 0;
1466         int ret;
1467
1468         if (!bpf_map__is_internal(map)) {
1469                 ret = btf__get_map_kv_tids(btf, map->name, def->key_size,
1470                                            def->value_size, &key_type_id,
1471                                            &value_type_id);
1472         } else {
1473                 /*
1474                  * LLVM annotates global data differently in BTF, that is,
1475                  * only as '.data', '.bss' or '.rodata'.
1476                  */
1477                 ret = btf__find_by_name(btf,
1478                                 libbpf_type_to_btf_name[map->libbpf_type]);
1479         }
1480         if (ret < 0)
1481                 return ret;
1482
1483         map->btf_key_type_id = key_type_id;
1484         map->btf_value_type_id = bpf_map__is_internal(map) ?
1485                                  ret : value_type_id;
1486         return 0;
1487 }
1488
1489 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1490 {
1491         struct bpf_map_info info = {};
1492         __u32 len = sizeof(info);
1493         int new_fd, err;
1494         char *new_name;
1495
1496         err = bpf_obj_get_info_by_fd(fd, &info, &len);
1497         if (err)
1498                 return err;
1499
1500         new_name = strdup(info.name);
1501         if (!new_name)
1502                 return -errno;
1503
1504         new_fd = open("/", O_RDONLY | O_CLOEXEC);
1505         if (new_fd < 0)
1506                 goto err_free_new_name;
1507
1508         new_fd = dup3(fd, new_fd, O_CLOEXEC);
1509         if (new_fd < 0)
1510                 goto err_close_new_fd;
1511
1512         err = zclose(map->fd);
1513         if (err)
1514                 goto err_close_new_fd;
1515         free(map->name);
1516
1517         map->fd = new_fd;
1518         map->name = new_name;
1519         map->def.type = info.type;
1520         map->def.key_size = info.key_size;
1521         map->def.value_size = info.value_size;
1522         map->def.max_entries = info.max_entries;
1523         map->def.map_flags = info.map_flags;
1524         map->btf_key_type_id = info.btf_key_type_id;
1525         map->btf_value_type_id = info.btf_value_type_id;
1526
1527         return 0;
1528
1529 err_close_new_fd:
1530         close(new_fd);
1531 err_free_new_name:
1532         free(new_name);
1533         return -errno;
1534 }
1535
1536 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
1537 {
1538         if (!map || !max_entries)
1539                 return -EINVAL;
1540
1541         /* If map already created, its attributes can't be changed. */
1542         if (map->fd >= 0)
1543                 return -EBUSY;
1544
1545         map->def.max_entries = max_entries;
1546
1547         return 0;
1548 }
1549
1550 static int
1551 bpf_object__probe_name(struct bpf_object *obj)
1552 {
1553         struct bpf_load_program_attr attr;
1554         char *cp, errmsg[STRERR_BUFSIZE];
1555         struct bpf_insn insns[] = {
1556                 BPF_MOV64_IMM(BPF_REG_0, 0),
1557                 BPF_EXIT_INSN(),
1558         };
1559         int ret;
1560
1561         /* make sure basic loading works */
1562
1563         memset(&attr, 0, sizeof(attr));
1564         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1565         attr.insns = insns;
1566         attr.insns_cnt = ARRAY_SIZE(insns);
1567         attr.license = "GPL";
1568
1569         ret = bpf_load_program_xattr(&attr, NULL, 0);
1570         if (ret < 0) {
1571                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1572                 pr_warning("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
1573                            __func__, cp, errno);
1574                 return -errno;
1575         }
1576         close(ret);
1577
1578         /* now try the same program, but with the name */
1579
1580         attr.name = "test";
1581         ret = bpf_load_program_xattr(&attr, NULL, 0);
1582         if (ret >= 0) {
1583                 obj->caps.name = 1;
1584                 close(ret);
1585         }
1586
1587         return 0;
1588 }
1589
1590 static int
1591 bpf_object__probe_global_data(struct bpf_object *obj)
1592 {
1593         struct bpf_load_program_attr prg_attr;
1594         struct bpf_create_map_attr map_attr;
1595         char *cp, errmsg[STRERR_BUFSIZE];
1596         struct bpf_insn insns[] = {
1597                 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
1598                 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
1599                 BPF_MOV64_IMM(BPF_REG_0, 0),
1600                 BPF_EXIT_INSN(),
1601         };
1602         int ret, map;
1603
1604         memset(&map_attr, 0, sizeof(map_attr));
1605         map_attr.map_type = BPF_MAP_TYPE_ARRAY;
1606         map_attr.key_size = sizeof(int);
1607         map_attr.value_size = 32;
1608         map_attr.max_entries = 1;
1609
1610         map = bpf_create_map_xattr(&map_attr);
1611         if (map < 0) {
1612                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1613                 pr_warning("Error in %s():%s(%d). Couldn't create simple array map.\n",
1614                            __func__, cp, errno);
1615                 return -errno;
1616         }
1617
1618         insns[0].imm = map;
1619
1620         memset(&prg_attr, 0, sizeof(prg_attr));
1621         prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1622         prg_attr.insns = insns;
1623         prg_attr.insns_cnt = ARRAY_SIZE(insns);
1624         prg_attr.license = "GPL";
1625
1626         ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
1627         if (ret >= 0) {
1628                 obj->caps.global_data = 1;
1629                 close(ret);
1630         }
1631
1632         close(map);
1633         return 0;
1634 }
1635
1636 static int bpf_object__probe_btf_func(struct bpf_object *obj)
1637 {
1638         const char strs[] = "\0int\0x\0a";
1639         /* void x(int a) {} */
1640         __u32 types[] = {
1641                 /* int */
1642                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
1643                 /* FUNC_PROTO */                                /* [2] */
1644                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
1645                 BTF_PARAM_ENC(7, 1),
1646                 /* FUNC x */                                    /* [3] */
1647                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
1648         };
1649         int res;
1650
1651         res = libbpf__probe_raw_btf((char *)types, sizeof(types),
1652                                     strs, sizeof(strs));
1653         if (res < 0)
1654                 return res;
1655         if (res > 0)
1656                 obj->caps.btf_func = 1;
1657         return 0;
1658 }
1659
1660 static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
1661 {
1662         const char strs[] = "\0x\0.data";
1663         /* static int a; */
1664         __u32 types[] = {
1665                 /* int */
1666                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
1667                 /* VAR x */                                     /* [2] */
1668                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
1669                 BTF_VAR_STATIC,
1670                 /* DATASEC val */                               /* [3] */
1671                 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
1672                 BTF_VAR_SECINFO_ENC(2, 0, 4),
1673         };
1674         int res;
1675
1676         res = libbpf__probe_raw_btf((char *)types, sizeof(types),
1677                                     strs, sizeof(strs));
1678         if (res < 0)
1679                 return res;
1680         if (res > 0)
1681                 obj->caps.btf_datasec = 1;
1682         return 0;
1683 }
1684
1685 static int
1686 bpf_object__probe_caps(struct bpf_object *obj)
1687 {
1688         int (*probe_fn[])(struct bpf_object *obj) = {
1689                 bpf_object__probe_name,
1690                 bpf_object__probe_global_data,
1691                 bpf_object__probe_btf_func,
1692                 bpf_object__probe_btf_datasec,
1693         };
1694         int i, ret;
1695
1696         for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
1697                 ret = probe_fn[i](obj);
1698                 if (ret < 0)
1699                         pr_debug("Probe #%d failed with %d.\n", i, ret);
1700         }
1701
1702         return 0;
1703 }
1704
1705 static int
1706 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
1707 {
1708         char *cp, errmsg[STRERR_BUFSIZE];
1709         int err, zero = 0;
1710         __u8 *data;
1711
1712         /* Nothing to do here since kernel already zero-initializes .bss map. */
1713         if (map->libbpf_type == LIBBPF_MAP_BSS)
1714                 return 0;
1715
1716         data = map->libbpf_type == LIBBPF_MAP_DATA ?
1717                obj->sections.data : obj->sections.rodata;
1718
1719         err = bpf_map_update_elem(map->fd, &zero, data, 0);
1720         /* Freeze .rodata map as read-only from syscall side. */
1721         if (!err && map->libbpf_type == LIBBPF_MAP_RODATA) {
1722                 err = bpf_map_freeze(map->fd);
1723                 if (err) {
1724                         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1725                         pr_warning("Error freezing map(%s) as read-only: %s\n",
1726                                    map->name, cp);
1727                         err = 0;
1728                 }
1729         }
1730         return err;
1731 }
1732
1733 static int
1734 bpf_object__create_maps(struct bpf_object *obj)
1735 {
1736         struct bpf_create_map_attr create_attr = {};
1737         unsigned int i;
1738         int err;
1739
1740         for (i = 0; i < obj->nr_maps; i++) {
1741                 struct bpf_map *map = &obj->maps[i];
1742                 struct bpf_map_def *def = &map->def;
1743                 char *cp, errmsg[STRERR_BUFSIZE];
1744                 int *pfd = &map->fd;
1745
1746                 if (map->fd >= 0) {
1747                         pr_debug("skip map create (preset) %s: fd=%d\n",
1748                                  map->name, map->fd);
1749                         continue;
1750                 }
1751
1752                 if (obj->caps.name)
1753                         create_attr.name = map->name;
1754                 create_attr.map_ifindex = map->map_ifindex;
1755                 create_attr.map_type = def->type;
1756                 create_attr.map_flags = def->map_flags;
1757                 create_attr.key_size = def->key_size;
1758                 create_attr.value_size = def->value_size;
1759                 create_attr.max_entries = def->max_entries;
1760                 create_attr.btf_fd = 0;
1761                 create_attr.btf_key_type_id = 0;
1762                 create_attr.btf_value_type_id = 0;
1763                 if (bpf_map_type__is_map_in_map(def->type) &&
1764                     map->inner_map_fd >= 0)
1765                         create_attr.inner_map_fd = map->inner_map_fd;
1766
1767                 if (obj->btf && !bpf_map_find_btf_info(map, obj->btf)) {
1768                         create_attr.btf_fd = btf__fd(obj->btf);
1769                         create_attr.btf_key_type_id = map->btf_key_type_id;
1770                         create_attr.btf_value_type_id = map->btf_value_type_id;
1771                 }
1772
1773                 *pfd = bpf_create_map_xattr(&create_attr);
1774                 if (*pfd < 0 && create_attr.btf_key_type_id) {
1775                         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1776                         pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
1777                                    map->name, cp, errno);
1778                         create_attr.btf_fd = 0;
1779                         create_attr.btf_key_type_id = 0;
1780                         create_attr.btf_value_type_id = 0;
1781                         map->btf_key_type_id = 0;
1782                         map->btf_value_type_id = 0;
1783                         *pfd = bpf_create_map_xattr(&create_attr);
1784                 }
1785
1786                 if (*pfd < 0) {
1787                         size_t j;
1788
1789                         err = *pfd;
1790 err_out:
1791                         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
1792                         pr_warning("failed to create map (name: '%s'): %s\n",
1793                                    map->name, cp);
1794                         for (j = 0; j < i; j++)
1795                                 zclose(obj->maps[j].fd);
1796                         return err;
1797                 }
1798
1799                 if (bpf_map__is_internal(map)) {
1800                         err = bpf_object__populate_internal_map(obj, map);
1801                         if (err < 0) {
1802                                 zclose(*pfd);
1803                                 goto err_out;
1804                         }
1805                 }
1806
1807                 pr_debug("create map %s: fd=%d\n", map->name, *pfd);
1808         }
1809
1810         return 0;
1811 }
1812
1813 static int
1814 check_btf_ext_reloc_err(struct bpf_program *prog, int err,
1815                         void *btf_prog_info, const char *info_name)
1816 {
1817         if (err != -ENOENT) {
1818                 pr_warning("Error in loading %s for sec %s.\n",
1819                            info_name, prog->section_name);
1820                 return err;
1821         }
1822
1823         /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
1824
1825         if (btf_prog_info) {
1826                 /*
1827                  * Some info has already been found but has problem
1828                  * in the last btf_ext reloc.  Must have to error
1829                  * out.
1830                  */
1831                 pr_warning("Error in relocating %s for sec %s.\n",
1832                            info_name, prog->section_name);
1833                 return err;
1834         }
1835
1836         /*
1837          * Have problem loading the very first info.  Ignore
1838          * the rest.
1839          */
1840         pr_warning("Cannot find %s for main program sec %s. Ignore all %s.\n",
1841                    info_name, prog->section_name, info_name);
1842         return 0;
1843 }
1844
1845 static int
1846 bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
1847                           const char *section_name,  __u32 insn_offset)
1848 {
1849         int err;
1850
1851         if (!insn_offset || prog->func_info) {
1852                 /*
1853                  * !insn_offset => main program
1854                  *
1855                  * For sub prog, the main program's func_info has to
1856                  * be loaded first (i.e. prog->func_info != NULL)
1857                  */
1858                 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
1859                                                section_name, insn_offset,
1860                                                &prog->func_info,
1861                                                &prog->func_info_cnt);
1862                 if (err)
1863                         return check_btf_ext_reloc_err(prog, err,
1864                                                        prog->func_info,
1865                                                        "bpf_func_info");
1866
1867                 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
1868         }
1869
1870         if (!insn_offset || prog->line_info) {
1871                 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
1872                                                section_name, insn_offset,
1873                                                &prog->line_info,
1874                                                &prog->line_info_cnt);
1875                 if (err)
1876                         return check_btf_ext_reloc_err(prog, err,
1877                                                        prog->line_info,
1878                                                        "bpf_line_info");
1879
1880                 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
1881         }
1882
1883         if (!insn_offset)
1884                 prog->btf_fd = btf__fd(obj->btf);
1885
1886         return 0;
1887 }
1888
1889 static int
1890 bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
1891                         struct reloc_desc *relo)
1892 {
1893         struct bpf_insn *insn, *new_insn;
1894         struct bpf_program *text;
1895         size_t new_cnt;
1896         int err;
1897
1898         if (relo->type != RELO_CALL)
1899                 return -LIBBPF_ERRNO__RELOC;
1900
1901         if (prog->idx == obj->efile.text_shndx) {
1902                 pr_warning("relo in .text insn %d into off %d\n",
1903                            relo->insn_idx, relo->text_off);
1904                 return -LIBBPF_ERRNO__RELOC;
1905         }
1906
1907         if (prog->main_prog_cnt == 0) {
1908                 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
1909                 if (!text) {
1910                         pr_warning("no .text section found yet relo into text exist\n");
1911                         return -LIBBPF_ERRNO__RELOC;
1912                 }
1913                 new_cnt = prog->insns_cnt + text->insns_cnt;
1914                 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
1915                 if (!new_insn) {
1916                         pr_warning("oom in prog realloc\n");
1917                         return -ENOMEM;
1918                 }
1919
1920                 if (obj->btf_ext) {
1921                         err = bpf_program_reloc_btf_ext(prog, obj,
1922                                                         text->section_name,
1923                                                         prog->insns_cnt);
1924                         if (err)
1925                                 return err;
1926                 }
1927
1928                 memcpy(new_insn + prog->insns_cnt, text->insns,
1929                        text->insns_cnt * sizeof(*insn));
1930                 prog->insns = new_insn;
1931                 prog->main_prog_cnt = prog->insns_cnt;
1932                 prog->insns_cnt = new_cnt;
1933                 pr_debug("added %zd insn from %s to prog %s\n",
1934                          text->insns_cnt, text->section_name,
1935                          prog->section_name);
1936         }
1937         insn = &prog->insns[relo->insn_idx];
1938         insn->imm += prog->main_prog_cnt - relo->insn_idx;
1939         return 0;
1940 }
1941
1942 static int
1943 bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
1944 {
1945         int i, err;
1946
1947         if (!prog)
1948                 return 0;
1949
1950         if (obj->btf_ext) {
1951                 err = bpf_program_reloc_btf_ext(prog, obj,
1952                                                 prog->section_name, 0);
1953                 if (err)
1954                         return err;
1955         }
1956
1957         if (!prog->reloc_desc)
1958                 return 0;
1959
1960         for (i = 0; i < prog->nr_reloc; i++) {
1961                 if (prog->reloc_desc[i].type == RELO_LD64 ||
1962                     prog->reloc_desc[i].type == RELO_DATA) {
1963                         bool relo_data = prog->reloc_desc[i].type == RELO_DATA;
1964                         struct bpf_insn *insns = prog->insns;
1965                         int insn_idx, map_idx;
1966
1967                         insn_idx = prog->reloc_desc[i].insn_idx;
1968                         map_idx = prog->reloc_desc[i].map_idx;
1969
1970                         if (insn_idx + 1 >= (int)prog->insns_cnt) {
1971                                 pr_warning("relocation out of range: '%s'\n",
1972                                            prog->section_name);
1973                                 return -LIBBPF_ERRNO__RELOC;
1974                         }
1975
1976                         if (!relo_data) {
1977                                 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
1978                         } else {
1979                                 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_VALUE;
1980                                 insns[insn_idx + 1].imm = insns[insn_idx].imm;
1981                         }
1982                         insns[insn_idx].imm = obj->maps[map_idx].fd;
1983                 } else if (prog->reloc_desc[i].type == RELO_CALL) {
1984                         err = bpf_program__reloc_text(prog, obj,
1985                                                       &prog->reloc_desc[i]);
1986                         if (err)
1987                                 return err;
1988                 }
1989         }
1990
1991         zfree(&prog->reloc_desc);
1992         prog->nr_reloc = 0;
1993         return 0;
1994 }
1995
1996
1997 static int
1998 bpf_object__relocate(struct bpf_object *obj)
1999 {
2000         struct bpf_program *prog;
2001         size_t i;
2002         int err;
2003
2004         for (i = 0; i < obj->nr_programs; i++) {
2005                 prog = &obj->programs[i];
2006
2007                 err = bpf_program__relocate(prog, obj);
2008                 if (err) {
2009                         pr_warning("failed to relocate '%s'\n",
2010                                    prog->section_name);
2011                         return err;
2012                 }
2013         }
2014         return 0;
2015 }
2016
2017 static int bpf_object__collect_reloc(struct bpf_object *obj)
2018 {
2019         int i, err;
2020
2021         if (!obj_elf_valid(obj)) {
2022                 pr_warning("Internal error: elf object is closed\n");
2023                 return -LIBBPF_ERRNO__INTERNAL;
2024         }
2025
2026         for (i = 0; i < obj->efile.nr_reloc; i++) {
2027                 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
2028                 Elf_Data *data = obj->efile.reloc[i].data;
2029                 int idx = shdr->sh_info;
2030                 struct bpf_program *prog;
2031
2032                 if (shdr->sh_type != SHT_REL) {
2033                         pr_warning("internal error at %d\n", __LINE__);
2034                         return -LIBBPF_ERRNO__INTERNAL;
2035                 }
2036
2037                 prog = bpf_object__find_prog_by_idx(obj, idx);
2038                 if (!prog) {
2039                         pr_warning("relocation failed: no section(%d)\n", idx);
2040                         return -LIBBPF_ERRNO__RELOC;
2041                 }
2042
2043                 err = bpf_program__collect_reloc(prog,
2044                                                  shdr, data,
2045                                                  obj);
2046                 if (err)
2047                         return err;
2048         }
2049         return 0;
2050 }
2051
2052 static int
2053 load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
2054              char *license, __u32 kern_version, int *pfd)
2055 {
2056         struct bpf_load_program_attr load_attr;
2057         char *cp, errmsg[STRERR_BUFSIZE];
2058         int log_buf_size = BPF_LOG_BUF_SIZE;
2059         char *log_buf;
2060         int ret;
2061
2062         memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
2063         load_attr.prog_type = prog->type;
2064         load_attr.expected_attach_type = prog->expected_attach_type;
2065         if (prog->caps->name)
2066                 load_attr.name = prog->name;
2067         load_attr.insns = insns;
2068         load_attr.insns_cnt = insns_cnt;
2069         load_attr.license = license;
2070         load_attr.kern_version = kern_version;
2071         load_attr.prog_ifindex = prog->prog_ifindex;
2072         load_attr.prog_btf_fd = prog->btf_fd >= 0 ? prog->btf_fd : 0;
2073         load_attr.func_info = prog->func_info;
2074         load_attr.func_info_rec_size = prog->func_info_rec_size;
2075         load_attr.func_info_cnt = prog->func_info_cnt;
2076         load_attr.line_info = prog->line_info;
2077         load_attr.line_info_rec_size = prog->line_info_rec_size;
2078         load_attr.line_info_cnt = prog->line_info_cnt;
2079         load_attr.log_level = prog->log_level;
2080         load_attr.prog_flags = prog->prog_flags;
2081         if (!load_attr.insns || !load_attr.insns_cnt)
2082                 return -EINVAL;
2083
2084 retry_load:
2085         log_buf = malloc(log_buf_size);
2086         if (!log_buf)
2087                 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
2088
2089         ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
2090
2091         if (ret >= 0) {
2092                 if (load_attr.log_level)
2093                         pr_debug("verifier log:\n%s", log_buf);
2094                 *pfd = ret;
2095                 ret = 0;
2096                 goto out;
2097         }
2098
2099         if (errno == ENOSPC) {
2100                 log_buf_size <<= 1;
2101                 free(log_buf);
2102                 goto retry_load;
2103         }
2104         ret = -LIBBPF_ERRNO__LOAD;
2105         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2106         pr_warning("load bpf program failed: %s\n", cp);
2107
2108         if (log_buf && log_buf[0] != '\0') {
2109                 ret = -LIBBPF_ERRNO__VERIFY;
2110                 pr_warning("-- BEGIN DUMP LOG ---\n");
2111                 pr_warning("\n%s\n", log_buf);
2112                 pr_warning("-- END LOG --\n");
2113         } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
2114                 pr_warning("Program too large (%zu insns), at most %d insns\n",
2115                            load_attr.insns_cnt, BPF_MAXINSNS);
2116                 ret = -LIBBPF_ERRNO__PROG2BIG;
2117         } else {
2118                 /* Wrong program type? */
2119                 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
2120                         int fd;
2121
2122                         load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
2123                         load_attr.expected_attach_type = 0;
2124                         fd = bpf_load_program_xattr(&load_attr, NULL, 0);
2125                         if (fd >= 0) {
2126                                 close(fd);
2127                                 ret = -LIBBPF_ERRNO__PROGTYPE;
2128                                 goto out;
2129                         }
2130                 }
2131
2132                 if (log_buf)
2133                         ret = -LIBBPF_ERRNO__KVER;
2134         }
2135
2136 out:
2137         free(log_buf);
2138         return ret;
2139 }
2140
2141 int
2142 bpf_program__load(struct bpf_program *prog,
2143                   char *license, __u32 kern_version)
2144 {
2145         int err = 0, fd, i;
2146
2147         if (prog->instances.nr < 0 || !prog->instances.fds) {
2148                 if (prog->preprocessor) {
2149                         pr_warning("Internal error: can't load program '%s'\n",
2150                                    prog->section_name);
2151                         return -LIBBPF_ERRNO__INTERNAL;
2152                 }
2153
2154                 prog->instances.fds = malloc(sizeof(int));
2155                 if (!prog->instances.fds) {
2156                         pr_warning("Not enough memory for BPF fds\n");
2157                         return -ENOMEM;
2158                 }
2159                 prog->instances.nr = 1;
2160                 prog->instances.fds[0] = -1;
2161         }
2162
2163         if (!prog->preprocessor) {
2164                 if (prog->instances.nr != 1) {
2165                         pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
2166                                    prog->section_name, prog->instances.nr);
2167                 }
2168                 err = load_program(prog, prog->insns, prog->insns_cnt,
2169                                    license, kern_version, &fd);
2170                 if (!err)
2171                         prog->instances.fds[0] = fd;
2172                 goto out;
2173         }
2174
2175         for (i = 0; i < prog->instances.nr; i++) {
2176                 struct bpf_prog_prep_result result;
2177                 bpf_program_prep_t preprocessor = prog->preprocessor;
2178
2179                 memset(&result, 0, sizeof(result));
2180                 err = preprocessor(prog, i, prog->insns,
2181                                    prog->insns_cnt, &result);
2182                 if (err) {
2183                         pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
2184                                    i, prog->section_name);
2185                         goto out;
2186                 }
2187
2188                 if (!result.new_insn_ptr || !result.new_insn_cnt) {
2189                         pr_debug("Skip loading the %dth instance of program '%s'\n",
2190                                  i, prog->section_name);
2191                         prog->instances.fds[i] = -1;
2192                         if (result.pfd)
2193                                 *result.pfd = -1;
2194                         continue;
2195                 }
2196
2197                 err = load_program(prog, result.new_insn_ptr,
2198                                    result.new_insn_cnt,
2199                                    license, kern_version, &fd);
2200
2201                 if (err) {
2202                         pr_warning("Loading the %dth instance of program '%s' failed\n",
2203                                         i, prog->section_name);
2204                         goto out;
2205                 }
2206
2207                 if (result.pfd)
2208                         *result.pfd = fd;
2209                 prog->instances.fds[i] = fd;
2210         }
2211 out:
2212         if (err)
2213                 pr_warning("failed to load program '%s'\n",
2214                            prog->section_name);
2215         zfree(&prog->insns);
2216         prog->insns_cnt = 0;
2217         return err;
2218 }
2219
2220 static bool bpf_program__is_function_storage(struct bpf_program *prog,
2221                                              struct bpf_object *obj)
2222 {
2223         return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
2224 }
2225
2226 static int
2227 bpf_object__load_progs(struct bpf_object *obj, int log_level)
2228 {
2229         size_t i;
2230         int err;
2231
2232         for (i = 0; i < obj->nr_programs; i++) {
2233                 if (bpf_program__is_function_storage(&obj->programs[i], obj))
2234                         continue;
2235                 obj->programs[i].log_level |= log_level;
2236                 err = bpf_program__load(&obj->programs[i],
2237                                         obj->license,
2238                                         obj->kern_version);
2239                 if (err)
2240                         return err;
2241         }
2242         return 0;
2243 }
2244
2245 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
2246 {
2247         switch (type) {
2248         case BPF_PROG_TYPE_SOCKET_FILTER:
2249         case BPF_PROG_TYPE_SCHED_CLS:
2250         case BPF_PROG_TYPE_SCHED_ACT:
2251         case BPF_PROG_TYPE_XDP:
2252         case BPF_PROG_TYPE_CGROUP_SKB:
2253         case BPF_PROG_TYPE_CGROUP_SOCK:
2254         case BPF_PROG_TYPE_LWT_IN:
2255         case BPF_PROG_TYPE_LWT_OUT:
2256         case BPF_PROG_TYPE_LWT_XMIT:
2257         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2258         case BPF_PROG_TYPE_SOCK_OPS:
2259         case BPF_PROG_TYPE_SK_SKB:
2260         case BPF_PROG_TYPE_CGROUP_DEVICE:
2261         case BPF_PROG_TYPE_SK_MSG:
2262         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2263         case BPF_PROG_TYPE_LIRC_MODE2:
2264         case BPF_PROG_TYPE_SK_REUSEPORT:
2265         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2266         case BPF_PROG_TYPE_UNSPEC:
2267         case BPF_PROG_TYPE_TRACEPOINT:
2268         case BPF_PROG_TYPE_RAW_TRACEPOINT:
2269         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2270         case BPF_PROG_TYPE_PERF_EVENT:
2271         case BPF_PROG_TYPE_CGROUP_SYSCTL:
2272                 return false;
2273         case BPF_PROG_TYPE_KPROBE:
2274         default:
2275                 return true;
2276         }
2277 }
2278
2279 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
2280 {
2281         if (needs_kver && obj->kern_version == 0) {
2282                 pr_warning("%s doesn't provide kernel version\n",
2283                            obj->path);
2284                 return -LIBBPF_ERRNO__KVERSION;
2285         }
2286         return 0;
2287 }
2288
2289 static struct bpf_object *
2290 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
2291                    bool needs_kver, int flags)
2292 {
2293         struct bpf_object *obj;
2294         int err;
2295
2296         if (elf_version(EV_CURRENT) == EV_NONE) {
2297                 pr_warning("failed to init libelf for %s\n", path);
2298                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
2299         }
2300
2301         obj = bpf_object__new(path, obj_buf, obj_buf_sz);
2302         if (IS_ERR(obj))
2303                 return obj;
2304
2305         CHECK_ERR(bpf_object__elf_init(obj), err, out);
2306         CHECK_ERR(bpf_object__check_endianness(obj), err, out);
2307         CHECK_ERR(bpf_object__probe_caps(obj), err, out);
2308         CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
2309         CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
2310         CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
2311
2312         bpf_object__elf_finish(obj);
2313         return obj;
2314 out:
2315         bpf_object__close(obj);
2316         return ERR_PTR(err);
2317 }
2318
2319 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
2320                                             int flags)
2321 {
2322         /* param validation */
2323         if (!attr->file)
2324                 return NULL;
2325
2326         pr_debug("loading %s\n", attr->file);
2327
2328         return __bpf_object__open(attr->file, NULL, 0,
2329                                   bpf_prog_type__needs_kver(attr->prog_type),
2330                                   flags);
2331 }
2332
2333 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
2334 {
2335         return __bpf_object__open_xattr(attr, 0);
2336 }
2337
2338 struct bpf_object *bpf_object__open(const char *path)
2339 {
2340         struct bpf_object_open_attr attr = {
2341                 .file           = path,
2342                 .prog_type      = BPF_PROG_TYPE_UNSPEC,
2343         };
2344
2345         return bpf_object__open_xattr(&attr);
2346 }
2347
2348 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
2349                                            size_t obj_buf_sz,
2350                                            const char *name)
2351 {
2352         char tmp_name[64];
2353
2354         /* param validation */
2355         if (!obj_buf || obj_buf_sz <= 0)
2356                 return NULL;
2357
2358         if (!name) {
2359                 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
2360                          (unsigned long)obj_buf,
2361                          (unsigned long)obj_buf_sz);
2362                 tmp_name[sizeof(tmp_name) - 1] = '\0';
2363                 name = tmp_name;
2364         }
2365         pr_debug("loading object '%s' from buffer\n",
2366                  name);
2367
2368         return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
2369 }
2370
2371 int bpf_object__unload(struct bpf_object *obj)
2372 {
2373         size_t i;
2374
2375         if (!obj)
2376                 return -EINVAL;
2377
2378         for (i = 0; i < obj->nr_maps; i++)
2379                 zclose(obj->maps[i].fd);
2380
2381         for (i = 0; i < obj->nr_programs; i++)
2382                 bpf_program__unload(&obj->programs[i]);
2383
2384         return 0;
2385 }
2386
2387 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
2388 {
2389         struct bpf_object *obj;
2390         int err;
2391
2392         if (!attr)
2393                 return -EINVAL;
2394         obj = attr->obj;
2395         if (!obj)
2396                 return -EINVAL;
2397
2398         if (obj->loaded) {
2399                 pr_warning("object should not be loaded twice\n");
2400                 return -EINVAL;
2401         }
2402
2403         obj->loaded = true;
2404
2405         CHECK_ERR(bpf_object__create_maps(obj), err, out);
2406         CHECK_ERR(bpf_object__relocate(obj), err, out);
2407         CHECK_ERR(bpf_object__load_progs(obj, attr->log_level), err, out);
2408
2409         return 0;
2410 out:
2411         bpf_object__unload(obj);
2412         pr_warning("failed to load object '%s'\n", obj->path);
2413         return err;
2414 }
2415
2416 int bpf_object__load(struct bpf_object *obj)
2417 {
2418         struct bpf_object_load_attr attr = {
2419                 .obj = obj,
2420         };
2421
2422         return bpf_object__load_xattr(&attr);
2423 }
2424
2425 static int check_path(const char *path)
2426 {
2427         char *cp, errmsg[STRERR_BUFSIZE];
2428         struct statfs st_fs;
2429         char *dname, *dir;
2430         int err = 0;
2431
2432         if (path == NULL)
2433                 return -EINVAL;
2434
2435         dname = strdup(path);
2436         if (dname == NULL)
2437                 return -ENOMEM;
2438
2439         dir = dirname(dname);
2440         if (statfs(dir, &st_fs)) {
2441                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2442                 pr_warning("failed to statfs %s: %s\n", dir, cp);
2443                 err = -errno;
2444         }
2445         free(dname);
2446
2447         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
2448                 pr_warning("specified path %s is not on BPF FS\n", path);
2449                 err = -EINVAL;
2450         }
2451
2452         return err;
2453 }
2454
2455 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
2456                               int instance)
2457 {
2458         char *cp, errmsg[STRERR_BUFSIZE];
2459         int err;
2460
2461         err = check_path(path);
2462         if (err)
2463                 return err;
2464
2465         if (prog == NULL) {
2466                 pr_warning("invalid program pointer\n");
2467                 return -EINVAL;
2468         }
2469
2470         if (instance < 0 || instance >= prog->instances.nr) {
2471                 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2472                            instance, prog->section_name, prog->instances.nr);
2473                 return -EINVAL;
2474         }
2475
2476         if (bpf_obj_pin(prog->instances.fds[instance], path)) {
2477                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2478                 pr_warning("failed to pin program: %s\n", cp);
2479                 return -errno;
2480         }
2481         pr_debug("pinned program '%s'\n", path);
2482
2483         return 0;
2484 }
2485
2486 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
2487                                 int instance)
2488 {
2489         int err;
2490
2491         err = check_path(path);
2492         if (err)
2493                 return err;
2494
2495         if (prog == NULL) {
2496                 pr_warning("invalid program pointer\n");
2497                 return -EINVAL;
2498         }
2499
2500         if (instance < 0 || instance >= prog->instances.nr) {
2501                 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2502                            instance, prog->section_name, prog->instances.nr);
2503                 return -EINVAL;
2504         }
2505
2506         err = unlink(path);
2507         if (err != 0)
2508                 return -errno;
2509         pr_debug("unpinned program '%s'\n", path);
2510
2511         return 0;
2512 }
2513
2514 static int make_dir(const char *path)
2515 {
2516         char *cp, errmsg[STRERR_BUFSIZE];
2517         int err = 0;
2518
2519         if (mkdir(path, 0700) && errno != EEXIST)
2520                 err = -errno;
2521
2522         if (err) {
2523                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2524                 pr_warning("failed to mkdir %s: %s\n", path, cp);
2525         }
2526         return err;
2527 }
2528
2529 int bpf_program__pin(struct bpf_program *prog, const char *path)
2530 {
2531         int i, err;
2532
2533         err = check_path(path);
2534         if (err)
2535                 return err;
2536
2537         if (prog == NULL) {
2538                 pr_warning("invalid program pointer\n");
2539                 return -EINVAL;
2540         }
2541
2542         if (prog->instances.nr <= 0) {
2543                 pr_warning("no instances of prog %s to pin\n",
2544                            prog->section_name);
2545                 return -EINVAL;
2546         }
2547
2548         if (prog->instances.nr == 1) {
2549                 /* don't create subdirs when pinning single instance */
2550                 return bpf_program__pin_instance(prog, path, 0);
2551         }
2552
2553         err = make_dir(path);
2554         if (err)
2555                 return err;
2556
2557         for (i = 0; i < prog->instances.nr; i++) {
2558                 char buf[PATH_MAX];
2559                 int len;
2560
2561                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2562                 if (len < 0) {
2563                         err = -EINVAL;
2564                         goto err_unpin;
2565                 } else if (len >= PATH_MAX) {
2566                         err = -ENAMETOOLONG;
2567                         goto err_unpin;
2568                 }
2569
2570                 err = bpf_program__pin_instance(prog, buf, i);
2571                 if (err)
2572                         goto err_unpin;
2573         }
2574
2575         return 0;
2576
2577 err_unpin:
2578         for (i = i - 1; i >= 0; i--) {
2579                 char buf[PATH_MAX];
2580                 int len;
2581
2582                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2583                 if (len < 0)
2584                         continue;
2585                 else if (len >= PATH_MAX)
2586                         continue;
2587
2588                 bpf_program__unpin_instance(prog, buf, i);
2589         }
2590
2591         rmdir(path);
2592
2593         return err;
2594 }
2595
2596 int bpf_program__unpin(struct bpf_program *prog, const char *path)
2597 {
2598         int i, err;
2599
2600         err = check_path(path);
2601         if (err)
2602                 return err;
2603
2604         if (prog == NULL) {
2605                 pr_warning("invalid program pointer\n");
2606                 return -EINVAL;
2607         }
2608
2609         if (prog->instances.nr <= 0) {
2610                 pr_warning("no instances of prog %s to pin\n",
2611                            prog->section_name);
2612                 return -EINVAL;
2613         }
2614
2615         if (prog->instances.nr == 1) {
2616                 /* don't create subdirs when pinning single instance */
2617                 return bpf_program__unpin_instance(prog, path, 0);
2618         }
2619
2620         for (i = 0; i < prog->instances.nr; i++) {
2621                 char buf[PATH_MAX];
2622                 int len;
2623
2624                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2625                 if (len < 0)
2626                         return -EINVAL;
2627                 else if (len >= PATH_MAX)
2628                         return -ENAMETOOLONG;
2629
2630                 err = bpf_program__unpin_instance(prog, buf, i);
2631                 if (err)
2632                         return err;
2633         }
2634
2635         err = rmdir(path);
2636         if (err)
2637                 return -errno;
2638
2639         return 0;
2640 }
2641
2642 int bpf_map__pin(struct bpf_map *map, const char *path)
2643 {
2644         char *cp, errmsg[STRERR_BUFSIZE];
2645         int err;
2646
2647         err = check_path(path);
2648         if (err)
2649                 return err;
2650
2651         if (map == NULL) {
2652                 pr_warning("invalid map pointer\n");
2653                 return -EINVAL;
2654         }
2655
2656         if (bpf_obj_pin(map->fd, path)) {
2657                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2658                 pr_warning("failed to pin map: %s\n", cp);
2659                 return -errno;
2660         }
2661
2662         pr_debug("pinned map '%s'\n", path);
2663
2664         return 0;
2665 }
2666
2667 int bpf_map__unpin(struct bpf_map *map, const char *path)
2668 {
2669         int err;
2670
2671         err = check_path(path);
2672         if (err)
2673                 return err;
2674
2675         if (map == NULL) {
2676                 pr_warning("invalid map pointer\n");
2677                 return -EINVAL;
2678         }
2679
2680         err = unlink(path);
2681         if (err != 0)
2682                 return -errno;
2683         pr_debug("unpinned map '%s'\n", path);
2684
2685         return 0;
2686 }
2687
2688 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
2689 {
2690         struct bpf_map *map;
2691         int err;
2692
2693         if (!obj)
2694                 return -ENOENT;
2695
2696         if (!obj->loaded) {
2697                 pr_warning("object not yet loaded; load it first\n");
2698                 return -ENOENT;
2699         }
2700
2701         err = make_dir(path);
2702         if (err)
2703                 return err;
2704
2705         bpf_object__for_each_map(map, obj) {
2706                 char buf[PATH_MAX];
2707                 int len;
2708
2709                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2710                                bpf_map__name(map));
2711                 if (len < 0) {
2712                         err = -EINVAL;
2713                         goto err_unpin_maps;
2714                 } else if (len >= PATH_MAX) {
2715                         err = -ENAMETOOLONG;
2716                         goto err_unpin_maps;
2717                 }
2718
2719                 err = bpf_map__pin(map, buf);
2720                 if (err)
2721                         goto err_unpin_maps;
2722         }
2723
2724         return 0;
2725
2726 err_unpin_maps:
2727         while ((map = bpf_map__prev(map, obj))) {
2728                 char buf[PATH_MAX];
2729                 int len;
2730
2731                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2732                                bpf_map__name(map));
2733                 if (len < 0)
2734                         continue;
2735                 else if (len >= PATH_MAX)
2736                         continue;
2737
2738                 bpf_map__unpin(map, buf);
2739         }
2740
2741         return err;
2742 }
2743
2744 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
2745 {
2746         struct bpf_map *map;
2747         int err;
2748
2749         if (!obj)
2750                 return -ENOENT;
2751
2752         bpf_object__for_each_map(map, obj) {
2753                 char buf[PATH_MAX];
2754                 int len;
2755
2756                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2757                                bpf_map__name(map));
2758                 if (len < 0)
2759                         return -EINVAL;
2760                 else if (len >= PATH_MAX)
2761                         return -ENAMETOOLONG;
2762
2763                 err = bpf_map__unpin(map, buf);
2764                 if (err)
2765                         return err;
2766         }
2767
2768         return 0;
2769 }
2770
2771 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
2772 {
2773         struct bpf_program *prog;
2774         int err;
2775
2776         if (!obj)
2777                 return -ENOENT;
2778
2779         if (!obj->loaded) {
2780                 pr_warning("object not yet loaded; load it first\n");
2781                 return -ENOENT;
2782         }
2783
2784         err = make_dir(path);
2785         if (err)
2786                 return err;
2787
2788         bpf_object__for_each_program(prog, obj) {
2789                 char buf[PATH_MAX];
2790                 int len;
2791
2792                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2793                                prog->pin_name);
2794                 if (len < 0) {
2795                         err = -EINVAL;
2796                         goto err_unpin_programs;
2797                 } else if (len >= PATH_MAX) {
2798                         err = -ENAMETOOLONG;
2799                         goto err_unpin_programs;
2800                 }
2801
2802                 err = bpf_program__pin(prog, buf);
2803                 if (err)
2804                         goto err_unpin_programs;
2805         }
2806
2807         return 0;
2808
2809 err_unpin_programs:
2810         while ((prog = bpf_program__prev(prog, obj))) {
2811                 char buf[PATH_MAX];
2812                 int len;
2813
2814                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2815                                prog->pin_name);
2816                 if (len < 0)
2817                         continue;
2818                 else if (len >= PATH_MAX)
2819                         continue;
2820
2821                 bpf_program__unpin(prog, buf);
2822         }
2823
2824         return err;
2825 }
2826
2827 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
2828 {
2829         struct bpf_program *prog;
2830         int err;
2831
2832         if (!obj)
2833                 return -ENOENT;
2834
2835         bpf_object__for_each_program(prog, obj) {
2836                 char buf[PATH_MAX];
2837                 int len;
2838
2839                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2840                                prog->pin_name);
2841                 if (len < 0)
2842                         return -EINVAL;
2843                 else if (len >= PATH_MAX)
2844                         return -ENAMETOOLONG;
2845
2846                 err = bpf_program__unpin(prog, buf);
2847                 if (err)
2848                         return err;
2849         }
2850
2851         return 0;
2852 }
2853
2854 int bpf_object__pin(struct bpf_object *obj, const char *path)
2855 {
2856         int err;
2857
2858         err = bpf_object__pin_maps(obj, path);
2859         if (err)
2860                 return err;
2861
2862         err = bpf_object__pin_programs(obj, path);
2863         if (err) {
2864                 bpf_object__unpin_maps(obj, path);
2865                 return err;
2866         }
2867
2868         return 0;
2869 }
2870
2871 void bpf_object__close(struct bpf_object *obj)
2872 {
2873         size_t i;
2874
2875         if (!obj)
2876                 return;
2877
2878         if (obj->clear_priv)
2879                 obj->clear_priv(obj, obj->priv);
2880
2881         bpf_object__elf_finish(obj);
2882         bpf_object__unload(obj);
2883         btf__free(obj->btf);
2884         btf_ext__free(obj->btf_ext);
2885
2886         for (i = 0; i < obj->nr_maps; i++) {
2887                 zfree(&obj->maps[i].name);
2888                 if (obj->maps[i].clear_priv)
2889                         obj->maps[i].clear_priv(&obj->maps[i],
2890                                                 obj->maps[i].priv);
2891                 obj->maps[i].priv = NULL;
2892                 obj->maps[i].clear_priv = NULL;
2893         }
2894
2895         zfree(&obj->sections.rodata);
2896         zfree(&obj->sections.data);
2897         zfree(&obj->maps);
2898         obj->nr_maps = 0;
2899
2900         if (obj->programs && obj->nr_programs) {
2901                 for (i = 0; i < obj->nr_programs; i++)
2902                         bpf_program__exit(&obj->programs[i]);
2903         }
2904         zfree(&obj->programs);
2905
2906         list_del(&obj->list);
2907         free(obj);
2908 }
2909
2910 struct bpf_object *
2911 bpf_object__next(struct bpf_object *prev)
2912 {
2913         struct bpf_object *next;
2914
2915         if (!prev)
2916                 next = list_first_entry(&bpf_objects_list,
2917                                         struct bpf_object,
2918                                         list);
2919         else
2920                 next = list_next_entry(prev, list);
2921
2922         /* Empty list is noticed here so don't need checking on entry. */
2923         if (&next->list == &bpf_objects_list)
2924                 return NULL;
2925
2926         return next;
2927 }
2928
2929 const char *bpf_object__name(struct bpf_object *obj)
2930 {
2931         return obj ? obj->path : ERR_PTR(-EINVAL);
2932 }
2933
2934 unsigned int bpf_object__kversion(struct bpf_object *obj)
2935 {
2936         return obj ? obj->kern_version : 0;
2937 }
2938
2939 struct btf *bpf_object__btf(struct bpf_object *obj)
2940 {
2941         return obj ? obj->btf : NULL;
2942 }
2943
2944 int bpf_object__btf_fd(const struct bpf_object *obj)
2945 {
2946         return obj->btf ? btf__fd(obj->btf) : -1;
2947 }
2948
2949 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
2950                          bpf_object_clear_priv_t clear_priv)
2951 {
2952         if (obj->priv && obj->clear_priv)
2953                 obj->clear_priv(obj, obj->priv);
2954
2955         obj->priv = priv;
2956         obj->clear_priv = clear_priv;
2957         return 0;
2958 }
2959
2960 void *bpf_object__priv(struct bpf_object *obj)
2961 {
2962         return obj ? obj->priv : ERR_PTR(-EINVAL);
2963 }
2964
2965 static struct bpf_program *
2966 __bpf_program__iter(struct bpf_program *p, struct bpf_object *obj, bool forward)
2967 {
2968         size_t nr_programs = obj->nr_programs;
2969         ssize_t idx;
2970
2971         if (!nr_programs)
2972                 return NULL;
2973
2974         if (!p)
2975                 /* Iter from the beginning */
2976                 return forward ? &obj->programs[0] :
2977                         &obj->programs[nr_programs - 1];
2978
2979         if (p->obj != obj) {
2980                 pr_warning("error: program handler doesn't match object\n");
2981                 return NULL;
2982         }
2983
2984         idx = (p - obj->programs) + (forward ? 1 : -1);
2985         if (idx >= obj->nr_programs || idx < 0)
2986                 return NULL;
2987         return &obj->programs[idx];
2988 }
2989
2990 struct bpf_program *
2991 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
2992 {
2993         struct bpf_program *prog = prev;
2994
2995         do {
2996                 prog = __bpf_program__iter(prog, obj, true);
2997         } while (prog && bpf_program__is_function_storage(prog, obj));
2998
2999         return prog;
3000 }
3001
3002 struct bpf_program *
3003 bpf_program__prev(struct bpf_program *next, struct bpf_object *obj)
3004 {
3005         struct bpf_program *prog = next;
3006
3007         do {
3008                 prog = __bpf_program__iter(prog, obj, false);
3009         } while (prog && bpf_program__is_function_storage(prog, obj));
3010
3011         return prog;
3012 }
3013
3014 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
3015                           bpf_program_clear_priv_t clear_priv)
3016 {
3017         if (prog->priv && prog->clear_priv)
3018                 prog->clear_priv(prog, prog->priv);
3019
3020         prog->priv = priv;
3021         prog->clear_priv = clear_priv;
3022         return 0;
3023 }
3024
3025 void *bpf_program__priv(struct bpf_program *prog)
3026 {
3027         return prog ? prog->priv : ERR_PTR(-EINVAL);
3028 }
3029
3030 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
3031 {
3032         prog->prog_ifindex = ifindex;
3033 }
3034
3035 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
3036 {
3037         const char *title;
3038
3039         title = prog->section_name;
3040         if (needs_copy) {
3041                 title = strdup(title);
3042                 if (!title) {
3043                         pr_warning("failed to strdup program title\n");
3044                         return ERR_PTR(-ENOMEM);
3045                 }
3046         }
3047
3048         return title;
3049 }
3050
3051 int bpf_program__fd(struct bpf_program *prog)
3052 {
3053         return bpf_program__nth_fd(prog, 0);
3054 }
3055
3056 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
3057                           bpf_program_prep_t prep)
3058 {
3059         int *instances_fds;
3060
3061         if (nr_instances <= 0 || !prep)
3062                 return -EINVAL;
3063
3064         if (prog->instances.nr > 0 || prog->instances.fds) {
3065                 pr_warning("Can't set pre-processor after loading\n");
3066                 return -EINVAL;
3067         }
3068
3069         instances_fds = malloc(sizeof(int) * nr_instances);
3070         if (!instances_fds) {
3071                 pr_warning("alloc memory failed for fds\n");
3072                 return -ENOMEM;
3073         }
3074
3075         /* fill all fd with -1 */
3076         memset(instances_fds, -1, sizeof(int) * nr_instances);
3077
3078         prog->instances.nr = nr_instances;
3079         prog->instances.fds = instances_fds;
3080         prog->preprocessor = prep;
3081         return 0;
3082 }
3083
3084 int bpf_program__nth_fd(struct bpf_program *prog, int n)
3085 {
3086         int fd;
3087
3088         if (!prog)
3089                 return -EINVAL;
3090
3091         if (n >= prog->instances.nr || n < 0) {
3092                 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
3093                            n, prog->section_name, prog->instances.nr);
3094                 return -EINVAL;
3095         }
3096
3097         fd = prog->instances.fds[n];
3098         if (fd < 0) {
3099                 pr_warning("%dth instance of program '%s' is invalid\n",
3100                            n, prog->section_name);
3101                 return -ENOENT;
3102         }
3103
3104         return fd;
3105 }
3106
3107 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
3108 {
3109         prog->type = type;
3110 }
3111
3112 static bool bpf_program__is_type(struct bpf_program *prog,
3113                                  enum bpf_prog_type type)
3114 {
3115         return prog ? (prog->type == type) : false;
3116 }
3117
3118 #define BPF_PROG_TYPE_FNS(NAME, TYPE)                   \
3119 int bpf_program__set_##NAME(struct bpf_program *prog)   \
3120 {                                                       \
3121         if (!prog)                                      \
3122                 return -EINVAL;                         \
3123         bpf_program__set_type(prog, TYPE);              \
3124         return 0;                                       \
3125 }                                                       \
3126                                                         \
3127 bool bpf_program__is_##NAME(struct bpf_program *prog)   \
3128 {                                                       \
3129         return bpf_program__is_type(prog, TYPE);        \
3130 }                                                       \
3131
3132 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
3133 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
3134 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
3135 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
3136 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
3137 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
3138 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
3139 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
3140
3141 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
3142                                            enum bpf_attach_type type)
3143 {
3144         prog->expected_attach_type = type;
3145 }
3146
3147 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
3148         { string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
3149
3150 /* Programs that can NOT be attached. */
3151 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
3152
3153 /* Programs that can be attached. */
3154 #define BPF_APROG_SEC(string, ptype, atype) \
3155         BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
3156
3157 /* Programs that must specify expected attach type at load time. */
3158 #define BPF_EAPROG_SEC(string, ptype, eatype) \
3159         BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
3160
3161 /* Programs that can be attached but attach type can't be identified by section
3162  * name. Kept for backward compatibility.
3163  */
3164 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
3165
3166 static const struct {
3167         const char *sec;
3168         size_t len;
3169         enum bpf_prog_type prog_type;
3170         enum bpf_attach_type expected_attach_type;
3171         int is_attachable;
3172         enum bpf_attach_type attach_type;
3173 } section_names[] = {
3174         BPF_PROG_SEC("socket",                  BPF_PROG_TYPE_SOCKET_FILTER),
3175         BPF_PROG_SEC("kprobe/",                 BPF_PROG_TYPE_KPROBE),
3176         BPF_PROG_SEC("kretprobe/",              BPF_PROG_TYPE_KPROBE),
3177         BPF_PROG_SEC("classifier",              BPF_PROG_TYPE_SCHED_CLS),
3178         BPF_PROG_SEC("action",                  BPF_PROG_TYPE_SCHED_ACT),
3179         BPF_PROG_SEC("tracepoint/",             BPF_PROG_TYPE_TRACEPOINT),
3180         BPF_PROG_SEC("raw_tracepoint/",         BPF_PROG_TYPE_RAW_TRACEPOINT),
3181         BPF_PROG_SEC("xdp",                     BPF_PROG_TYPE_XDP),
3182         BPF_PROG_SEC("perf_event",              BPF_PROG_TYPE_PERF_EVENT),
3183         BPF_PROG_SEC("lwt_in",                  BPF_PROG_TYPE_LWT_IN),
3184         BPF_PROG_SEC("lwt_out",                 BPF_PROG_TYPE_LWT_OUT),
3185         BPF_PROG_SEC("lwt_xmit",                BPF_PROG_TYPE_LWT_XMIT),
3186         BPF_PROG_SEC("lwt_seg6local",           BPF_PROG_TYPE_LWT_SEG6LOCAL),
3187         BPF_APROG_SEC("cgroup_skb/ingress",     BPF_PROG_TYPE_CGROUP_SKB,
3188                                                 BPF_CGROUP_INET_INGRESS),
3189         BPF_APROG_SEC("cgroup_skb/egress",      BPF_PROG_TYPE_CGROUP_SKB,
3190                                                 BPF_CGROUP_INET_EGRESS),
3191         BPF_APROG_COMPAT("cgroup/skb",          BPF_PROG_TYPE_CGROUP_SKB),
3192         BPF_APROG_SEC("cgroup/sock",            BPF_PROG_TYPE_CGROUP_SOCK,
3193                                                 BPF_CGROUP_INET_SOCK_CREATE),
3194         BPF_EAPROG_SEC("cgroup/post_bind4",     BPF_PROG_TYPE_CGROUP_SOCK,
3195                                                 BPF_CGROUP_INET4_POST_BIND),
3196         BPF_EAPROG_SEC("cgroup/post_bind6",     BPF_PROG_TYPE_CGROUP_SOCK,
3197                                                 BPF_CGROUP_INET6_POST_BIND),
3198         BPF_APROG_SEC("cgroup/dev",             BPF_PROG_TYPE_CGROUP_DEVICE,
3199                                                 BPF_CGROUP_DEVICE),
3200         BPF_APROG_SEC("sockops",                BPF_PROG_TYPE_SOCK_OPS,
3201                                                 BPF_CGROUP_SOCK_OPS),
3202         BPF_APROG_SEC("sk_skb/stream_parser",   BPF_PROG_TYPE_SK_SKB,
3203                                                 BPF_SK_SKB_STREAM_PARSER),
3204         BPF_APROG_SEC("sk_skb/stream_verdict",  BPF_PROG_TYPE_SK_SKB,
3205                                                 BPF_SK_SKB_STREAM_VERDICT),
3206         BPF_APROG_COMPAT("sk_skb",              BPF_PROG_TYPE_SK_SKB),
3207         BPF_APROG_SEC("sk_msg",                 BPF_PROG_TYPE_SK_MSG,
3208                                                 BPF_SK_MSG_VERDICT),
3209         BPF_APROG_SEC("lirc_mode2",             BPF_PROG_TYPE_LIRC_MODE2,
3210                                                 BPF_LIRC_MODE2),
3211         BPF_APROG_SEC("flow_dissector",         BPF_PROG_TYPE_FLOW_DISSECTOR,
3212                                                 BPF_FLOW_DISSECTOR),
3213         BPF_EAPROG_SEC("cgroup/bind4",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3214                                                 BPF_CGROUP_INET4_BIND),
3215         BPF_EAPROG_SEC("cgroup/bind6",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3216                                                 BPF_CGROUP_INET6_BIND),
3217         BPF_EAPROG_SEC("cgroup/connect4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3218                                                 BPF_CGROUP_INET4_CONNECT),
3219         BPF_EAPROG_SEC("cgroup/connect6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3220                                                 BPF_CGROUP_INET6_CONNECT),
3221         BPF_EAPROG_SEC("cgroup/sendmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3222                                                 BPF_CGROUP_UDP4_SENDMSG),
3223         BPF_EAPROG_SEC("cgroup/sendmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3224                                                 BPF_CGROUP_UDP6_SENDMSG),
3225         BPF_EAPROG_SEC("cgroup/sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,
3226                                                 BPF_CGROUP_SYSCTL),
3227 };
3228
3229 #undef BPF_PROG_SEC_IMPL
3230 #undef BPF_PROG_SEC
3231 #undef BPF_APROG_SEC
3232 #undef BPF_EAPROG_SEC
3233 #undef BPF_APROG_COMPAT
3234
3235 #define MAX_TYPE_NAME_SIZE 32
3236
3237 static char *libbpf_get_type_names(bool attach_type)
3238 {
3239         int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
3240         char *buf;
3241
3242         buf = malloc(len);
3243         if (!buf)
3244                 return NULL;
3245
3246         buf[0] = '\0';
3247         /* Forge string buf with all available names */
3248         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3249                 if (attach_type && !section_names[i].is_attachable)
3250                         continue;
3251
3252                 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
3253                         free(buf);
3254                         return NULL;
3255                 }
3256                 strcat(buf, " ");
3257                 strcat(buf, section_names[i].sec);
3258         }
3259
3260         return buf;
3261 }
3262
3263 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
3264                              enum bpf_attach_type *expected_attach_type)
3265 {
3266         char *type_names;
3267         int i;
3268
3269         if (!name)
3270                 return -EINVAL;
3271
3272         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3273                 if (strncmp(name, section_names[i].sec, section_names[i].len))
3274                         continue;
3275                 *prog_type = section_names[i].prog_type;
3276                 *expected_attach_type = section_names[i].expected_attach_type;
3277                 return 0;
3278         }
3279         pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
3280         type_names = libbpf_get_type_names(false);
3281         if (type_names != NULL) {
3282                 pr_info("supported section(type) names are:%s\n", type_names);
3283                 free(type_names);
3284         }
3285
3286         return -EINVAL;
3287 }
3288
3289 int libbpf_attach_type_by_name(const char *name,
3290                                enum bpf_attach_type *attach_type)
3291 {
3292         char *type_names;
3293         int i;
3294
3295         if (!name)
3296                 return -EINVAL;
3297
3298         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3299                 if (strncmp(name, section_names[i].sec, section_names[i].len))
3300                         continue;
3301                 if (!section_names[i].is_attachable)
3302                         return -EINVAL;
3303                 *attach_type = section_names[i].attach_type;
3304                 return 0;
3305         }
3306         pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
3307         type_names = libbpf_get_type_names(true);
3308         if (type_names != NULL) {
3309                 pr_info("attachable section(type) names are:%s\n", type_names);
3310                 free(type_names);
3311         }
3312
3313         return -EINVAL;
3314 }
3315
3316 static int
3317 bpf_program__identify_section(struct bpf_program *prog,
3318                               enum bpf_prog_type *prog_type,
3319                               enum bpf_attach_type *expected_attach_type)
3320 {
3321         return libbpf_prog_type_by_name(prog->section_name, prog_type,
3322                                         expected_attach_type);
3323 }
3324
3325 int bpf_map__fd(struct bpf_map *map)
3326 {
3327         return map ? map->fd : -EINVAL;
3328 }
3329
3330 const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
3331 {
3332         return map ? &map->def : ERR_PTR(-EINVAL);
3333 }
3334
3335 const char *bpf_map__name(struct bpf_map *map)
3336 {
3337         return map ? map->name : NULL;
3338 }
3339
3340 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
3341 {
3342         return map ? map->btf_key_type_id : 0;
3343 }
3344
3345 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
3346 {
3347         return map ? map->btf_value_type_id : 0;
3348 }
3349
3350 int bpf_map__set_priv(struct bpf_map *map, void *priv,
3351                      bpf_map_clear_priv_t clear_priv)
3352 {
3353         if (!map)
3354                 return -EINVAL;
3355
3356         if (map->priv) {
3357                 if (map->clear_priv)
3358                         map->clear_priv(map, map->priv);
3359         }
3360
3361         map->priv = priv;
3362         map->clear_priv = clear_priv;
3363         return 0;
3364 }
3365
3366 void *bpf_map__priv(struct bpf_map *map)
3367 {
3368         return map ? map->priv : ERR_PTR(-EINVAL);
3369 }
3370
3371 bool bpf_map__is_offload_neutral(struct bpf_map *map)
3372 {
3373         return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
3374 }
3375
3376 bool bpf_map__is_internal(struct bpf_map *map)
3377 {
3378         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
3379 }
3380
3381 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
3382 {
3383         map->map_ifindex = ifindex;
3384 }
3385
3386 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
3387 {
3388         if (!bpf_map_type__is_map_in_map(map->def.type)) {
3389                 pr_warning("error: unsupported map type\n");
3390                 return -EINVAL;
3391         }
3392         if (map->inner_map_fd != -1) {
3393                 pr_warning("error: inner_map_fd already specified\n");
3394                 return -EINVAL;
3395         }
3396         map->inner_map_fd = fd;
3397         return 0;
3398 }
3399
3400 static struct bpf_map *
3401 __bpf_map__iter(struct bpf_map *m, struct bpf_object *obj, int i)
3402 {
3403         ssize_t idx;
3404         struct bpf_map *s, *e;
3405
3406         if (!obj || !obj->maps)
3407                 return NULL;
3408
3409         s = obj->maps;
3410         e = obj->maps + obj->nr_maps;
3411
3412         if ((m < s) || (m >= e)) {
3413                 pr_warning("error in %s: map handler doesn't belong to object\n",
3414                            __func__);
3415                 return NULL;
3416         }
3417
3418         idx = (m - obj->maps) + i;
3419         if (idx >= obj->nr_maps || idx < 0)
3420                 return NULL;
3421         return &obj->maps[idx];
3422 }
3423
3424 struct bpf_map *
3425 bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
3426 {
3427         if (prev == NULL)
3428                 return obj->maps;
3429
3430         return __bpf_map__iter(prev, obj, 1);
3431 }
3432
3433 struct bpf_map *
3434 bpf_map__prev(struct bpf_map *next, struct bpf_object *obj)
3435 {
3436         if (next == NULL) {
3437                 if (!obj->nr_maps)
3438                         return NULL;
3439                 return obj->maps + obj->nr_maps - 1;
3440         }
3441
3442         return __bpf_map__iter(next, obj, -1);
3443 }
3444
3445 struct bpf_map *
3446 bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
3447 {
3448         struct bpf_map *pos;
3449
3450         bpf_object__for_each_map(pos, obj) {
3451                 if (pos->name && !strcmp(pos->name, name))
3452                         return pos;
3453         }
3454         return NULL;
3455 }
3456
3457 int
3458 bpf_object__find_map_fd_by_name(struct bpf_object *obj, const char *name)
3459 {
3460         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
3461 }
3462
3463 struct bpf_map *
3464 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
3465 {
3466         int i;
3467
3468         for (i = 0; i < obj->nr_maps; i++) {
3469                 if (obj->maps[i].offset == offset)
3470                         return &obj->maps[i];
3471         }
3472         return ERR_PTR(-ENOENT);
3473 }
3474
3475 long libbpf_get_error(const void *ptr)
3476 {
3477         return PTR_ERR_OR_ZERO(ptr);
3478 }
3479
3480 int bpf_prog_load(const char *file, enum bpf_prog_type type,
3481                   struct bpf_object **pobj, int *prog_fd)
3482 {
3483         struct bpf_prog_load_attr attr;
3484
3485         memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
3486         attr.file = file;
3487         attr.prog_type = type;
3488         attr.expected_attach_type = 0;
3489
3490         return bpf_prog_load_xattr(&attr, pobj, prog_fd);
3491 }
3492
3493 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
3494                         struct bpf_object **pobj, int *prog_fd)
3495 {
3496         struct bpf_object_open_attr open_attr = {
3497                 .file           = attr->file,
3498                 .prog_type      = attr->prog_type,
3499         };
3500         struct bpf_program *prog, *first_prog = NULL;
3501         enum bpf_attach_type expected_attach_type;
3502         enum bpf_prog_type prog_type;
3503         struct bpf_object *obj;
3504         struct bpf_map *map;
3505         int err;
3506
3507         if (!attr)
3508                 return -EINVAL;
3509         if (!attr->file)
3510                 return -EINVAL;
3511
3512         obj = bpf_object__open_xattr(&open_attr);
3513         if (IS_ERR_OR_NULL(obj))
3514                 return -ENOENT;
3515
3516         bpf_object__for_each_program(prog, obj) {
3517                 /*
3518                  * If type is not specified, try to guess it based on
3519                  * section name.
3520                  */
3521                 prog_type = attr->prog_type;
3522                 prog->prog_ifindex = attr->ifindex;
3523                 expected_attach_type = attr->expected_attach_type;
3524                 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
3525                         err = bpf_program__identify_section(prog, &prog_type,
3526                                                             &expected_attach_type);
3527                         if (err < 0) {
3528                                 bpf_object__close(obj);
3529                                 return -EINVAL;
3530                         }
3531                 }
3532
3533                 bpf_program__set_type(prog, prog_type);
3534                 bpf_program__set_expected_attach_type(prog,
3535                                                       expected_attach_type);
3536
3537                 prog->log_level = attr->log_level;
3538                 prog->prog_flags = attr->prog_flags;
3539                 if (!first_prog)
3540                         first_prog = prog;
3541         }
3542
3543         bpf_object__for_each_map(map, obj) {
3544                 if (!bpf_map__is_offload_neutral(map))
3545                         map->map_ifindex = attr->ifindex;
3546         }
3547
3548         if (!first_prog) {
3549                 pr_warning("object file doesn't contain bpf program\n");
3550                 bpf_object__close(obj);
3551                 return -ENOENT;
3552         }
3553
3554         err = bpf_object__load(obj);
3555         if (err) {
3556                 bpf_object__close(obj);
3557                 return -EINVAL;
3558         }
3559
3560         *pobj = obj;
3561         *prog_fd = bpf_program__fd(first_prog);
3562         return 0;
3563 }
3564
3565 enum bpf_perf_event_ret
3566 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
3567                            void **copy_mem, size_t *copy_size,
3568                            bpf_perf_event_print_t fn, void *private_data)
3569 {
3570         struct perf_event_mmap_page *header = mmap_mem;
3571         __u64 data_head = ring_buffer_read_head(header);
3572         __u64 data_tail = header->data_tail;
3573         void *base = ((__u8 *)header) + page_size;
3574         int ret = LIBBPF_PERF_EVENT_CONT;
3575         struct perf_event_header *ehdr;
3576         size_t ehdr_size;
3577
3578         while (data_head != data_tail) {
3579                 ehdr = base + (data_tail & (mmap_size - 1));
3580                 ehdr_size = ehdr->size;
3581
3582                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
3583                         void *copy_start = ehdr;
3584                         size_t len_first = base + mmap_size - copy_start;
3585                         size_t len_secnd = ehdr_size - len_first;
3586
3587                         if (*copy_size < ehdr_size) {
3588                                 free(*copy_mem);
3589                                 *copy_mem = malloc(ehdr_size);
3590                                 if (!*copy_mem) {
3591                                         *copy_size = 0;
3592                                         ret = LIBBPF_PERF_EVENT_ERROR;
3593                                         break;
3594                                 }
3595                                 *copy_size = ehdr_size;
3596                         }
3597
3598                         memcpy(*copy_mem, copy_start, len_first);
3599                         memcpy(*copy_mem + len_first, base, len_secnd);
3600                         ehdr = *copy_mem;
3601                 }
3602
3603                 ret = fn(ehdr, private_data);
3604                 data_tail += ehdr_size;
3605                 if (ret != LIBBPF_PERF_EVENT_CONT)
3606                         break;
3607         }
3608
3609         ring_buffer_write_tail(header, data_tail);
3610         return ret;
3611 }
3612
3613 struct bpf_prog_info_array_desc {
3614         int     array_offset;   /* e.g. offset of jited_prog_insns */
3615         int     count_offset;   /* e.g. offset of jited_prog_len */
3616         int     size_offset;    /* > 0: offset of rec size,
3617                                  * < 0: fix size of -size_offset
3618                                  */
3619 };
3620
3621 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
3622         [BPF_PROG_INFO_JITED_INSNS] = {
3623                 offsetof(struct bpf_prog_info, jited_prog_insns),
3624                 offsetof(struct bpf_prog_info, jited_prog_len),
3625                 -1,
3626         },
3627         [BPF_PROG_INFO_XLATED_INSNS] = {
3628                 offsetof(struct bpf_prog_info, xlated_prog_insns),
3629                 offsetof(struct bpf_prog_info, xlated_prog_len),
3630                 -1,
3631         },
3632         [BPF_PROG_INFO_MAP_IDS] = {
3633                 offsetof(struct bpf_prog_info, map_ids),
3634                 offsetof(struct bpf_prog_info, nr_map_ids),
3635                 -(int)sizeof(__u32),
3636         },
3637         [BPF_PROG_INFO_JITED_KSYMS] = {
3638                 offsetof(struct bpf_prog_info, jited_ksyms),
3639                 offsetof(struct bpf_prog_info, nr_jited_ksyms),
3640                 -(int)sizeof(__u64),
3641         },
3642         [BPF_PROG_INFO_JITED_FUNC_LENS] = {
3643                 offsetof(struct bpf_prog_info, jited_func_lens),
3644                 offsetof(struct bpf_prog_info, nr_jited_func_lens),
3645                 -(int)sizeof(__u32),
3646         },
3647         [BPF_PROG_INFO_FUNC_INFO] = {
3648                 offsetof(struct bpf_prog_info, func_info),
3649                 offsetof(struct bpf_prog_info, nr_func_info),
3650                 offsetof(struct bpf_prog_info, func_info_rec_size),
3651         },
3652         [BPF_PROG_INFO_LINE_INFO] = {
3653                 offsetof(struct bpf_prog_info, line_info),
3654                 offsetof(struct bpf_prog_info, nr_line_info),
3655                 offsetof(struct bpf_prog_info, line_info_rec_size),
3656         },
3657         [BPF_PROG_INFO_JITED_LINE_INFO] = {
3658                 offsetof(struct bpf_prog_info, jited_line_info),
3659                 offsetof(struct bpf_prog_info, nr_jited_line_info),
3660                 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
3661         },
3662         [BPF_PROG_INFO_PROG_TAGS] = {
3663                 offsetof(struct bpf_prog_info, prog_tags),
3664                 offsetof(struct bpf_prog_info, nr_prog_tags),
3665                 -(int)sizeof(__u8) * BPF_TAG_SIZE,
3666         },
3667
3668 };
3669
3670 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
3671 {
3672         __u32 *array = (__u32 *)info;
3673
3674         if (offset >= 0)
3675                 return array[offset / sizeof(__u32)];
3676         return -(int)offset;
3677 }
3678
3679 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
3680 {
3681         __u64 *array = (__u64 *)info;
3682
3683         if (offset >= 0)
3684                 return array[offset / sizeof(__u64)];
3685         return -(int)offset;
3686 }
3687
3688 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
3689                                          __u32 val)
3690 {
3691         __u32 *array = (__u32 *)info;
3692
3693         if (offset >= 0)
3694                 array[offset / sizeof(__u32)] = val;
3695 }
3696
3697 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
3698                                          __u64 val)
3699 {
3700         __u64 *array = (__u64 *)info;
3701
3702         if (offset >= 0)
3703                 array[offset / sizeof(__u64)] = val;
3704 }
3705
3706 struct bpf_prog_info_linear *
3707 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
3708 {
3709         struct bpf_prog_info_linear *info_linear;
3710         struct bpf_prog_info info = {};
3711         __u32 info_len = sizeof(info);
3712         __u32 data_len = 0;
3713         int i, err;
3714         void *ptr;
3715
3716         if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
3717                 return ERR_PTR(-EINVAL);
3718
3719         /* step 1: get array dimensions */
3720         err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
3721         if (err) {
3722                 pr_debug("can't get prog info: %s", strerror(errno));
3723                 return ERR_PTR(-EFAULT);
3724         }
3725
3726         /* step 2: calculate total size of all arrays */
3727         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3728                 bool include_array = (arrays & (1UL << i)) > 0;
3729                 struct bpf_prog_info_array_desc *desc;
3730                 __u32 count, size;
3731
3732                 desc = bpf_prog_info_array_desc + i;
3733
3734                 /* kernel is too old to support this field */
3735                 if (info_len < desc->array_offset + sizeof(__u32) ||
3736                     info_len < desc->count_offset + sizeof(__u32) ||
3737                     (desc->size_offset > 0 && info_len < desc->size_offset))
3738                         include_array = false;
3739
3740                 if (!include_array) {
3741                         arrays &= ~(1UL << i);  /* clear the bit */
3742                         continue;
3743                 }
3744
3745                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
3746                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
3747
3748                 data_len += count * size;
3749         }
3750
3751         /* step 3: allocate continuous memory */
3752         data_len = roundup(data_len, sizeof(__u64));
3753         info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
3754         if (!info_linear)
3755                 return ERR_PTR(-ENOMEM);
3756
3757         /* step 4: fill data to info_linear->info */
3758         info_linear->arrays = arrays;
3759         memset(&info_linear->info, 0, sizeof(info));
3760         ptr = info_linear->data;
3761
3762         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3763                 struct bpf_prog_info_array_desc *desc;
3764                 __u32 count, size;
3765
3766                 if ((arrays & (1UL << i)) == 0)
3767                         continue;
3768
3769                 desc  = bpf_prog_info_array_desc + i;
3770                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
3771                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
3772                 bpf_prog_info_set_offset_u32(&info_linear->info,
3773                                              desc->count_offset, count);
3774                 bpf_prog_info_set_offset_u32(&info_linear->info,
3775                                              desc->size_offset, size);
3776                 bpf_prog_info_set_offset_u64(&info_linear->info,
3777                                              desc->array_offset,
3778                                              ptr_to_u64(ptr));
3779                 ptr += count * size;
3780         }
3781
3782         /* step 5: call syscall again to get required arrays */
3783         err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
3784         if (err) {
3785                 pr_debug("can't get prog info: %s", strerror(errno));
3786                 free(info_linear);
3787                 return ERR_PTR(-EFAULT);
3788         }
3789
3790         /* step 6: verify the data */
3791         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3792                 struct bpf_prog_info_array_desc *desc;
3793                 __u32 v1, v2;
3794
3795                 if ((arrays & (1UL << i)) == 0)
3796                         continue;
3797
3798                 desc = bpf_prog_info_array_desc + i;
3799                 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
3800                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
3801                                                    desc->count_offset);
3802                 if (v1 != v2)
3803                         pr_warning("%s: mismatch in element count\n", __func__);
3804
3805                 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
3806                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
3807                                                    desc->size_offset);
3808                 if (v1 != v2)
3809                         pr_warning("%s: mismatch in rec size\n", __func__);
3810         }
3811
3812         /* step 7: update info_len and data_len */
3813         info_linear->info_len = sizeof(struct bpf_prog_info);
3814         info_linear->data_len = data_len;
3815
3816         return info_linear;
3817 }
3818
3819 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
3820 {
3821         int i;
3822
3823         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3824                 struct bpf_prog_info_array_desc *desc;
3825                 __u64 addr, offs;
3826
3827                 if ((info_linear->arrays & (1UL << i)) == 0)
3828                         continue;
3829
3830                 desc = bpf_prog_info_array_desc + i;
3831                 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
3832                                                      desc->array_offset);
3833                 offs = addr - ptr_to_u64(info_linear->data);
3834                 bpf_prog_info_set_offset_u64(&info_linear->info,
3835                                              desc->array_offset, offs);
3836         }
3837 }
3838
3839 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
3840 {
3841         int i;
3842
3843         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3844                 struct bpf_prog_info_array_desc *desc;
3845                 __u64 addr, offs;
3846
3847                 if ((info_linear->arrays & (1UL << i)) == 0)
3848                         continue;
3849
3850                 desc = bpf_prog_info_array_desc + i;
3851                 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
3852                                                      desc->array_offset);
3853                 addr = offs + ptr_to_u64(info_linear->data);
3854                 bpf_prog_info_set_offset_u64(&info_linear->info,
3855                                              desc->array_offset, addr);
3856         }
3857 }