]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/lib/bpf/libbpf.c
Merge branch 'optimize-zext'
[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)
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                 err = bpf_program__load(&obj->programs[i],
2236                                         obj->license,
2237                                         obj->kern_version);
2238                 if (err)
2239                         return err;
2240         }
2241         return 0;
2242 }
2243
2244 static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
2245 {
2246         switch (type) {
2247         case BPF_PROG_TYPE_SOCKET_FILTER:
2248         case BPF_PROG_TYPE_SCHED_CLS:
2249         case BPF_PROG_TYPE_SCHED_ACT:
2250         case BPF_PROG_TYPE_XDP:
2251         case BPF_PROG_TYPE_CGROUP_SKB:
2252         case BPF_PROG_TYPE_CGROUP_SOCK:
2253         case BPF_PROG_TYPE_LWT_IN:
2254         case BPF_PROG_TYPE_LWT_OUT:
2255         case BPF_PROG_TYPE_LWT_XMIT:
2256         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2257         case BPF_PROG_TYPE_SOCK_OPS:
2258         case BPF_PROG_TYPE_SK_SKB:
2259         case BPF_PROG_TYPE_CGROUP_DEVICE:
2260         case BPF_PROG_TYPE_SK_MSG:
2261         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2262         case BPF_PROG_TYPE_LIRC_MODE2:
2263         case BPF_PROG_TYPE_SK_REUSEPORT:
2264         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2265         case BPF_PROG_TYPE_UNSPEC:
2266         case BPF_PROG_TYPE_TRACEPOINT:
2267         case BPF_PROG_TYPE_RAW_TRACEPOINT:
2268         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2269         case BPF_PROG_TYPE_PERF_EVENT:
2270         case BPF_PROG_TYPE_CGROUP_SYSCTL:
2271                 return false;
2272         case BPF_PROG_TYPE_KPROBE:
2273         default:
2274                 return true;
2275         }
2276 }
2277
2278 static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
2279 {
2280         if (needs_kver && obj->kern_version == 0) {
2281                 pr_warning("%s doesn't provide kernel version\n",
2282                            obj->path);
2283                 return -LIBBPF_ERRNO__KVERSION;
2284         }
2285         return 0;
2286 }
2287
2288 static struct bpf_object *
2289 __bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
2290                    bool needs_kver, int flags)
2291 {
2292         struct bpf_object *obj;
2293         int err;
2294
2295         if (elf_version(EV_CURRENT) == EV_NONE) {
2296                 pr_warning("failed to init libelf for %s\n", path);
2297                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
2298         }
2299
2300         obj = bpf_object__new(path, obj_buf, obj_buf_sz);
2301         if (IS_ERR(obj))
2302                 return obj;
2303
2304         CHECK_ERR(bpf_object__elf_init(obj), err, out);
2305         CHECK_ERR(bpf_object__check_endianness(obj), err, out);
2306         CHECK_ERR(bpf_object__probe_caps(obj), err, out);
2307         CHECK_ERR(bpf_object__elf_collect(obj, flags), err, out);
2308         CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
2309         CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
2310
2311         bpf_object__elf_finish(obj);
2312         return obj;
2313 out:
2314         bpf_object__close(obj);
2315         return ERR_PTR(err);
2316 }
2317
2318 struct bpf_object *__bpf_object__open_xattr(struct bpf_object_open_attr *attr,
2319                                             int flags)
2320 {
2321         /* param validation */
2322         if (!attr->file)
2323                 return NULL;
2324
2325         pr_debug("loading %s\n", attr->file);
2326
2327         return __bpf_object__open(attr->file, NULL, 0,
2328                                   bpf_prog_type__needs_kver(attr->prog_type),
2329                                   flags);
2330 }
2331
2332 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
2333 {
2334         return __bpf_object__open_xattr(attr, 0);
2335 }
2336
2337 struct bpf_object *bpf_object__open(const char *path)
2338 {
2339         struct bpf_object_open_attr attr = {
2340                 .file           = path,
2341                 .prog_type      = BPF_PROG_TYPE_UNSPEC,
2342         };
2343
2344         return bpf_object__open_xattr(&attr);
2345 }
2346
2347 struct bpf_object *bpf_object__open_buffer(void *obj_buf,
2348                                            size_t obj_buf_sz,
2349                                            const char *name)
2350 {
2351         char tmp_name[64];
2352
2353         /* param validation */
2354         if (!obj_buf || obj_buf_sz <= 0)
2355                 return NULL;
2356
2357         if (!name) {
2358                 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
2359                          (unsigned long)obj_buf,
2360                          (unsigned long)obj_buf_sz);
2361                 tmp_name[sizeof(tmp_name) - 1] = '\0';
2362                 name = tmp_name;
2363         }
2364         pr_debug("loading object '%s' from buffer\n",
2365                  name);
2366
2367         return __bpf_object__open(name, obj_buf, obj_buf_sz, true, true);
2368 }
2369
2370 int bpf_object__unload(struct bpf_object *obj)
2371 {
2372         size_t i;
2373
2374         if (!obj)
2375                 return -EINVAL;
2376
2377         for (i = 0; i < obj->nr_maps; i++)
2378                 zclose(obj->maps[i].fd);
2379
2380         for (i = 0; i < obj->nr_programs; i++)
2381                 bpf_program__unload(&obj->programs[i]);
2382
2383         return 0;
2384 }
2385
2386 int bpf_object__load(struct bpf_object *obj)
2387 {
2388         int err;
2389
2390         if (!obj)
2391                 return -EINVAL;
2392
2393         if (obj->loaded) {
2394                 pr_warning("object should not be loaded twice\n");
2395                 return -EINVAL;
2396         }
2397
2398         obj->loaded = true;
2399
2400         CHECK_ERR(bpf_object__create_maps(obj), err, out);
2401         CHECK_ERR(bpf_object__relocate(obj), err, out);
2402         CHECK_ERR(bpf_object__load_progs(obj), err, out);
2403
2404         return 0;
2405 out:
2406         bpf_object__unload(obj);
2407         pr_warning("failed to load object '%s'\n", obj->path);
2408         return err;
2409 }
2410
2411 static int check_path(const char *path)
2412 {
2413         char *cp, errmsg[STRERR_BUFSIZE];
2414         struct statfs st_fs;
2415         char *dname, *dir;
2416         int err = 0;
2417
2418         if (path == NULL)
2419                 return -EINVAL;
2420
2421         dname = strdup(path);
2422         if (dname == NULL)
2423                 return -ENOMEM;
2424
2425         dir = dirname(dname);
2426         if (statfs(dir, &st_fs)) {
2427                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2428                 pr_warning("failed to statfs %s: %s\n", dir, cp);
2429                 err = -errno;
2430         }
2431         free(dname);
2432
2433         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
2434                 pr_warning("specified path %s is not on BPF FS\n", path);
2435                 err = -EINVAL;
2436         }
2437
2438         return err;
2439 }
2440
2441 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
2442                               int instance)
2443 {
2444         char *cp, errmsg[STRERR_BUFSIZE];
2445         int err;
2446
2447         err = check_path(path);
2448         if (err)
2449                 return err;
2450
2451         if (prog == NULL) {
2452                 pr_warning("invalid program pointer\n");
2453                 return -EINVAL;
2454         }
2455
2456         if (instance < 0 || instance >= prog->instances.nr) {
2457                 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2458                            instance, prog->section_name, prog->instances.nr);
2459                 return -EINVAL;
2460         }
2461
2462         if (bpf_obj_pin(prog->instances.fds[instance], path)) {
2463                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2464                 pr_warning("failed to pin program: %s\n", cp);
2465                 return -errno;
2466         }
2467         pr_debug("pinned program '%s'\n", path);
2468
2469         return 0;
2470 }
2471
2472 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
2473                                 int instance)
2474 {
2475         int err;
2476
2477         err = check_path(path);
2478         if (err)
2479                 return err;
2480
2481         if (prog == NULL) {
2482                 pr_warning("invalid program pointer\n");
2483                 return -EINVAL;
2484         }
2485
2486         if (instance < 0 || instance >= prog->instances.nr) {
2487                 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
2488                            instance, prog->section_name, prog->instances.nr);
2489                 return -EINVAL;
2490         }
2491
2492         err = unlink(path);
2493         if (err != 0)
2494                 return -errno;
2495         pr_debug("unpinned program '%s'\n", path);
2496
2497         return 0;
2498 }
2499
2500 static int make_dir(const char *path)
2501 {
2502         char *cp, errmsg[STRERR_BUFSIZE];
2503         int err = 0;
2504
2505         if (mkdir(path, 0700) && errno != EEXIST)
2506                 err = -errno;
2507
2508         if (err) {
2509                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2510                 pr_warning("failed to mkdir %s: %s\n", path, cp);
2511         }
2512         return err;
2513 }
2514
2515 int bpf_program__pin(struct bpf_program *prog, const char *path)
2516 {
2517         int i, err;
2518
2519         err = check_path(path);
2520         if (err)
2521                 return err;
2522
2523         if (prog == NULL) {
2524                 pr_warning("invalid program pointer\n");
2525                 return -EINVAL;
2526         }
2527
2528         if (prog->instances.nr <= 0) {
2529                 pr_warning("no instances of prog %s to pin\n",
2530                            prog->section_name);
2531                 return -EINVAL;
2532         }
2533
2534         if (prog->instances.nr == 1) {
2535                 /* don't create subdirs when pinning single instance */
2536                 return bpf_program__pin_instance(prog, path, 0);
2537         }
2538
2539         err = make_dir(path);
2540         if (err)
2541                 return err;
2542
2543         for (i = 0; i < prog->instances.nr; i++) {
2544                 char buf[PATH_MAX];
2545                 int len;
2546
2547                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2548                 if (len < 0) {
2549                         err = -EINVAL;
2550                         goto err_unpin;
2551                 } else if (len >= PATH_MAX) {
2552                         err = -ENAMETOOLONG;
2553                         goto err_unpin;
2554                 }
2555
2556                 err = bpf_program__pin_instance(prog, buf, i);
2557                 if (err)
2558                         goto err_unpin;
2559         }
2560
2561         return 0;
2562
2563 err_unpin:
2564         for (i = i - 1; i >= 0; i--) {
2565                 char buf[PATH_MAX];
2566                 int len;
2567
2568                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2569                 if (len < 0)
2570                         continue;
2571                 else if (len >= PATH_MAX)
2572                         continue;
2573
2574                 bpf_program__unpin_instance(prog, buf, i);
2575         }
2576
2577         rmdir(path);
2578
2579         return err;
2580 }
2581
2582 int bpf_program__unpin(struct bpf_program *prog, const char *path)
2583 {
2584         int i, err;
2585
2586         err = check_path(path);
2587         if (err)
2588                 return err;
2589
2590         if (prog == NULL) {
2591                 pr_warning("invalid program pointer\n");
2592                 return -EINVAL;
2593         }
2594
2595         if (prog->instances.nr <= 0) {
2596                 pr_warning("no instances of prog %s to pin\n",
2597                            prog->section_name);
2598                 return -EINVAL;
2599         }
2600
2601         if (prog->instances.nr == 1) {
2602                 /* don't create subdirs when pinning single instance */
2603                 return bpf_program__unpin_instance(prog, path, 0);
2604         }
2605
2606         for (i = 0; i < prog->instances.nr; i++) {
2607                 char buf[PATH_MAX];
2608                 int len;
2609
2610                 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
2611                 if (len < 0)
2612                         return -EINVAL;
2613                 else if (len >= PATH_MAX)
2614                         return -ENAMETOOLONG;
2615
2616                 err = bpf_program__unpin_instance(prog, buf, i);
2617                 if (err)
2618                         return err;
2619         }
2620
2621         err = rmdir(path);
2622         if (err)
2623                 return -errno;
2624
2625         return 0;
2626 }
2627
2628 int bpf_map__pin(struct bpf_map *map, const char *path)
2629 {
2630         char *cp, errmsg[STRERR_BUFSIZE];
2631         int err;
2632
2633         err = check_path(path);
2634         if (err)
2635                 return err;
2636
2637         if (map == NULL) {
2638                 pr_warning("invalid map pointer\n");
2639                 return -EINVAL;
2640         }
2641
2642         if (bpf_obj_pin(map->fd, path)) {
2643                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
2644                 pr_warning("failed to pin map: %s\n", cp);
2645                 return -errno;
2646         }
2647
2648         pr_debug("pinned map '%s'\n", path);
2649
2650         return 0;
2651 }
2652
2653 int bpf_map__unpin(struct bpf_map *map, const char *path)
2654 {
2655         int err;
2656
2657         err = check_path(path);
2658         if (err)
2659                 return err;
2660
2661         if (map == NULL) {
2662                 pr_warning("invalid map pointer\n");
2663                 return -EINVAL;
2664         }
2665
2666         err = unlink(path);
2667         if (err != 0)
2668                 return -errno;
2669         pr_debug("unpinned map '%s'\n", path);
2670
2671         return 0;
2672 }
2673
2674 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
2675 {
2676         struct bpf_map *map;
2677         int err;
2678
2679         if (!obj)
2680                 return -ENOENT;
2681
2682         if (!obj->loaded) {
2683                 pr_warning("object not yet loaded; load it first\n");
2684                 return -ENOENT;
2685         }
2686
2687         err = make_dir(path);
2688         if (err)
2689                 return err;
2690
2691         bpf_object__for_each_map(map, obj) {
2692                 char buf[PATH_MAX];
2693                 int len;
2694
2695                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2696                                bpf_map__name(map));
2697                 if (len < 0) {
2698                         err = -EINVAL;
2699                         goto err_unpin_maps;
2700                 } else if (len >= PATH_MAX) {
2701                         err = -ENAMETOOLONG;
2702                         goto err_unpin_maps;
2703                 }
2704
2705                 err = bpf_map__pin(map, buf);
2706                 if (err)
2707                         goto err_unpin_maps;
2708         }
2709
2710         return 0;
2711
2712 err_unpin_maps:
2713         while ((map = bpf_map__prev(map, obj))) {
2714                 char buf[PATH_MAX];
2715                 int len;
2716
2717                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2718                                bpf_map__name(map));
2719                 if (len < 0)
2720                         continue;
2721                 else if (len >= PATH_MAX)
2722                         continue;
2723
2724                 bpf_map__unpin(map, buf);
2725         }
2726
2727         return err;
2728 }
2729
2730 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
2731 {
2732         struct bpf_map *map;
2733         int err;
2734
2735         if (!obj)
2736                 return -ENOENT;
2737
2738         bpf_object__for_each_map(map, obj) {
2739                 char buf[PATH_MAX];
2740                 int len;
2741
2742                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2743                                bpf_map__name(map));
2744                 if (len < 0)
2745                         return -EINVAL;
2746                 else if (len >= PATH_MAX)
2747                         return -ENAMETOOLONG;
2748
2749                 err = bpf_map__unpin(map, buf);
2750                 if (err)
2751                         return err;
2752         }
2753
2754         return 0;
2755 }
2756
2757 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
2758 {
2759         struct bpf_program *prog;
2760         int err;
2761
2762         if (!obj)
2763                 return -ENOENT;
2764
2765         if (!obj->loaded) {
2766                 pr_warning("object not yet loaded; load it first\n");
2767                 return -ENOENT;
2768         }
2769
2770         err = make_dir(path);
2771         if (err)
2772                 return err;
2773
2774         bpf_object__for_each_program(prog, obj) {
2775                 char buf[PATH_MAX];
2776                 int len;
2777
2778                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2779                                prog->pin_name);
2780                 if (len < 0) {
2781                         err = -EINVAL;
2782                         goto err_unpin_programs;
2783                 } else if (len >= PATH_MAX) {
2784                         err = -ENAMETOOLONG;
2785                         goto err_unpin_programs;
2786                 }
2787
2788                 err = bpf_program__pin(prog, buf);
2789                 if (err)
2790                         goto err_unpin_programs;
2791         }
2792
2793         return 0;
2794
2795 err_unpin_programs:
2796         while ((prog = bpf_program__prev(prog, obj))) {
2797                 char buf[PATH_MAX];
2798                 int len;
2799
2800                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2801                                prog->pin_name);
2802                 if (len < 0)
2803                         continue;
2804                 else if (len >= PATH_MAX)
2805                         continue;
2806
2807                 bpf_program__unpin(prog, buf);
2808         }
2809
2810         return err;
2811 }
2812
2813 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
2814 {
2815         struct bpf_program *prog;
2816         int err;
2817
2818         if (!obj)
2819                 return -ENOENT;
2820
2821         bpf_object__for_each_program(prog, obj) {
2822                 char buf[PATH_MAX];
2823                 int len;
2824
2825                 len = snprintf(buf, PATH_MAX, "%s/%s", path,
2826                                prog->pin_name);
2827                 if (len < 0)
2828                         return -EINVAL;
2829                 else if (len >= PATH_MAX)
2830                         return -ENAMETOOLONG;
2831
2832                 err = bpf_program__unpin(prog, buf);
2833                 if (err)
2834                         return err;
2835         }
2836
2837         return 0;
2838 }
2839
2840 int bpf_object__pin(struct bpf_object *obj, const char *path)
2841 {
2842         int err;
2843
2844         err = bpf_object__pin_maps(obj, path);
2845         if (err)
2846                 return err;
2847
2848         err = bpf_object__pin_programs(obj, path);
2849         if (err) {
2850                 bpf_object__unpin_maps(obj, path);
2851                 return err;
2852         }
2853
2854         return 0;
2855 }
2856
2857 void bpf_object__close(struct bpf_object *obj)
2858 {
2859         size_t i;
2860
2861         if (!obj)
2862                 return;
2863
2864         if (obj->clear_priv)
2865                 obj->clear_priv(obj, obj->priv);
2866
2867         bpf_object__elf_finish(obj);
2868         bpf_object__unload(obj);
2869         btf__free(obj->btf);
2870         btf_ext__free(obj->btf_ext);
2871
2872         for (i = 0; i < obj->nr_maps; i++) {
2873                 zfree(&obj->maps[i].name);
2874                 if (obj->maps[i].clear_priv)
2875                         obj->maps[i].clear_priv(&obj->maps[i],
2876                                                 obj->maps[i].priv);
2877                 obj->maps[i].priv = NULL;
2878                 obj->maps[i].clear_priv = NULL;
2879         }
2880
2881         zfree(&obj->sections.rodata);
2882         zfree(&obj->sections.data);
2883         zfree(&obj->maps);
2884         obj->nr_maps = 0;
2885
2886         if (obj->programs && obj->nr_programs) {
2887                 for (i = 0; i < obj->nr_programs; i++)
2888                         bpf_program__exit(&obj->programs[i]);
2889         }
2890         zfree(&obj->programs);
2891
2892         list_del(&obj->list);
2893         free(obj);
2894 }
2895
2896 struct bpf_object *
2897 bpf_object__next(struct bpf_object *prev)
2898 {
2899         struct bpf_object *next;
2900
2901         if (!prev)
2902                 next = list_first_entry(&bpf_objects_list,
2903                                         struct bpf_object,
2904                                         list);
2905         else
2906                 next = list_next_entry(prev, list);
2907
2908         /* Empty list is noticed here so don't need checking on entry. */
2909         if (&next->list == &bpf_objects_list)
2910                 return NULL;
2911
2912         return next;
2913 }
2914
2915 const char *bpf_object__name(struct bpf_object *obj)
2916 {
2917         return obj ? obj->path : ERR_PTR(-EINVAL);
2918 }
2919
2920 unsigned int bpf_object__kversion(struct bpf_object *obj)
2921 {
2922         return obj ? obj->kern_version : 0;
2923 }
2924
2925 struct btf *bpf_object__btf(struct bpf_object *obj)
2926 {
2927         return obj ? obj->btf : NULL;
2928 }
2929
2930 int bpf_object__btf_fd(const struct bpf_object *obj)
2931 {
2932         return obj->btf ? btf__fd(obj->btf) : -1;
2933 }
2934
2935 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
2936                          bpf_object_clear_priv_t clear_priv)
2937 {
2938         if (obj->priv && obj->clear_priv)
2939                 obj->clear_priv(obj, obj->priv);
2940
2941         obj->priv = priv;
2942         obj->clear_priv = clear_priv;
2943         return 0;
2944 }
2945
2946 void *bpf_object__priv(struct bpf_object *obj)
2947 {
2948         return obj ? obj->priv : ERR_PTR(-EINVAL);
2949 }
2950
2951 static struct bpf_program *
2952 __bpf_program__iter(struct bpf_program *p, struct bpf_object *obj, bool forward)
2953 {
2954         size_t nr_programs = obj->nr_programs;
2955         ssize_t idx;
2956
2957         if (!nr_programs)
2958                 return NULL;
2959
2960         if (!p)
2961                 /* Iter from the beginning */
2962                 return forward ? &obj->programs[0] :
2963                         &obj->programs[nr_programs - 1];
2964
2965         if (p->obj != obj) {
2966                 pr_warning("error: program handler doesn't match object\n");
2967                 return NULL;
2968         }
2969
2970         idx = (p - obj->programs) + (forward ? 1 : -1);
2971         if (idx >= obj->nr_programs || idx < 0)
2972                 return NULL;
2973         return &obj->programs[idx];
2974 }
2975
2976 struct bpf_program *
2977 bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
2978 {
2979         struct bpf_program *prog = prev;
2980
2981         do {
2982                 prog = __bpf_program__iter(prog, obj, true);
2983         } while (prog && bpf_program__is_function_storage(prog, obj));
2984
2985         return prog;
2986 }
2987
2988 struct bpf_program *
2989 bpf_program__prev(struct bpf_program *next, struct bpf_object *obj)
2990 {
2991         struct bpf_program *prog = next;
2992
2993         do {
2994                 prog = __bpf_program__iter(prog, obj, false);
2995         } while (prog && bpf_program__is_function_storage(prog, obj));
2996
2997         return prog;
2998 }
2999
3000 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
3001                           bpf_program_clear_priv_t clear_priv)
3002 {
3003         if (prog->priv && prog->clear_priv)
3004                 prog->clear_priv(prog, prog->priv);
3005
3006         prog->priv = priv;
3007         prog->clear_priv = clear_priv;
3008         return 0;
3009 }
3010
3011 void *bpf_program__priv(struct bpf_program *prog)
3012 {
3013         return prog ? prog->priv : ERR_PTR(-EINVAL);
3014 }
3015
3016 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
3017 {
3018         prog->prog_ifindex = ifindex;
3019 }
3020
3021 const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
3022 {
3023         const char *title;
3024
3025         title = prog->section_name;
3026         if (needs_copy) {
3027                 title = strdup(title);
3028                 if (!title) {
3029                         pr_warning("failed to strdup program title\n");
3030                         return ERR_PTR(-ENOMEM);
3031                 }
3032         }
3033
3034         return title;
3035 }
3036
3037 int bpf_program__fd(struct bpf_program *prog)
3038 {
3039         return bpf_program__nth_fd(prog, 0);
3040 }
3041
3042 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
3043                           bpf_program_prep_t prep)
3044 {
3045         int *instances_fds;
3046
3047         if (nr_instances <= 0 || !prep)
3048                 return -EINVAL;
3049
3050         if (prog->instances.nr > 0 || prog->instances.fds) {
3051                 pr_warning("Can't set pre-processor after loading\n");
3052                 return -EINVAL;
3053         }
3054
3055         instances_fds = malloc(sizeof(int) * nr_instances);
3056         if (!instances_fds) {
3057                 pr_warning("alloc memory failed for fds\n");
3058                 return -ENOMEM;
3059         }
3060
3061         /* fill all fd with -1 */
3062         memset(instances_fds, -1, sizeof(int) * nr_instances);
3063
3064         prog->instances.nr = nr_instances;
3065         prog->instances.fds = instances_fds;
3066         prog->preprocessor = prep;
3067         return 0;
3068 }
3069
3070 int bpf_program__nth_fd(struct bpf_program *prog, int n)
3071 {
3072         int fd;
3073
3074         if (!prog)
3075                 return -EINVAL;
3076
3077         if (n >= prog->instances.nr || n < 0) {
3078                 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
3079                            n, prog->section_name, prog->instances.nr);
3080                 return -EINVAL;
3081         }
3082
3083         fd = prog->instances.fds[n];
3084         if (fd < 0) {
3085                 pr_warning("%dth instance of program '%s' is invalid\n",
3086                            n, prog->section_name);
3087                 return -ENOENT;
3088         }
3089
3090         return fd;
3091 }
3092
3093 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
3094 {
3095         prog->type = type;
3096 }
3097
3098 static bool bpf_program__is_type(struct bpf_program *prog,
3099                                  enum bpf_prog_type type)
3100 {
3101         return prog ? (prog->type == type) : false;
3102 }
3103
3104 #define BPF_PROG_TYPE_FNS(NAME, TYPE)                   \
3105 int bpf_program__set_##NAME(struct bpf_program *prog)   \
3106 {                                                       \
3107         if (!prog)                                      \
3108                 return -EINVAL;                         \
3109         bpf_program__set_type(prog, TYPE);              \
3110         return 0;                                       \
3111 }                                                       \
3112                                                         \
3113 bool bpf_program__is_##NAME(struct bpf_program *prog)   \
3114 {                                                       \
3115         return bpf_program__is_type(prog, TYPE);        \
3116 }                                                       \
3117
3118 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
3119 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
3120 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
3121 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
3122 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
3123 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
3124 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
3125 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
3126
3127 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
3128                                            enum bpf_attach_type type)
3129 {
3130         prog->expected_attach_type = type;
3131 }
3132
3133 #define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, atype) \
3134         { string, sizeof(string) - 1, ptype, eatype, is_attachable, atype }
3135
3136 /* Programs that can NOT be attached. */
3137 #define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0)
3138
3139 /* Programs that can be attached. */
3140 #define BPF_APROG_SEC(string, ptype, atype) \
3141         BPF_PROG_SEC_IMPL(string, ptype, 0, 1, atype)
3142
3143 /* Programs that must specify expected attach type at load time. */
3144 #define BPF_EAPROG_SEC(string, ptype, eatype) \
3145         BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, eatype)
3146
3147 /* Programs that can be attached but attach type can't be identified by section
3148  * name. Kept for backward compatibility.
3149  */
3150 #define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
3151
3152 static const struct {
3153         const char *sec;
3154         size_t len;
3155         enum bpf_prog_type prog_type;
3156         enum bpf_attach_type expected_attach_type;
3157         int is_attachable;
3158         enum bpf_attach_type attach_type;
3159 } section_names[] = {
3160         BPF_PROG_SEC("socket",                  BPF_PROG_TYPE_SOCKET_FILTER),
3161         BPF_PROG_SEC("kprobe/",                 BPF_PROG_TYPE_KPROBE),
3162         BPF_PROG_SEC("kretprobe/",              BPF_PROG_TYPE_KPROBE),
3163         BPF_PROG_SEC("classifier",              BPF_PROG_TYPE_SCHED_CLS),
3164         BPF_PROG_SEC("action",                  BPF_PROG_TYPE_SCHED_ACT),
3165         BPF_PROG_SEC("tracepoint/",             BPF_PROG_TYPE_TRACEPOINT),
3166         BPF_PROG_SEC("raw_tracepoint/",         BPF_PROG_TYPE_RAW_TRACEPOINT),
3167         BPF_PROG_SEC("xdp",                     BPF_PROG_TYPE_XDP),
3168         BPF_PROG_SEC("perf_event",              BPF_PROG_TYPE_PERF_EVENT),
3169         BPF_PROG_SEC("lwt_in",                  BPF_PROG_TYPE_LWT_IN),
3170         BPF_PROG_SEC("lwt_out",                 BPF_PROG_TYPE_LWT_OUT),
3171         BPF_PROG_SEC("lwt_xmit",                BPF_PROG_TYPE_LWT_XMIT),
3172         BPF_PROG_SEC("lwt_seg6local",           BPF_PROG_TYPE_LWT_SEG6LOCAL),
3173         BPF_APROG_SEC("cgroup_skb/ingress",     BPF_PROG_TYPE_CGROUP_SKB,
3174                                                 BPF_CGROUP_INET_INGRESS),
3175         BPF_APROG_SEC("cgroup_skb/egress",      BPF_PROG_TYPE_CGROUP_SKB,
3176                                                 BPF_CGROUP_INET_EGRESS),
3177         BPF_APROG_COMPAT("cgroup/skb",          BPF_PROG_TYPE_CGROUP_SKB),
3178         BPF_APROG_SEC("cgroup/sock",            BPF_PROG_TYPE_CGROUP_SOCK,
3179                                                 BPF_CGROUP_INET_SOCK_CREATE),
3180         BPF_EAPROG_SEC("cgroup/post_bind4",     BPF_PROG_TYPE_CGROUP_SOCK,
3181                                                 BPF_CGROUP_INET4_POST_BIND),
3182         BPF_EAPROG_SEC("cgroup/post_bind6",     BPF_PROG_TYPE_CGROUP_SOCK,
3183                                                 BPF_CGROUP_INET6_POST_BIND),
3184         BPF_APROG_SEC("cgroup/dev",             BPF_PROG_TYPE_CGROUP_DEVICE,
3185                                                 BPF_CGROUP_DEVICE),
3186         BPF_APROG_SEC("sockops",                BPF_PROG_TYPE_SOCK_OPS,
3187                                                 BPF_CGROUP_SOCK_OPS),
3188         BPF_APROG_SEC("sk_skb/stream_parser",   BPF_PROG_TYPE_SK_SKB,
3189                                                 BPF_SK_SKB_STREAM_PARSER),
3190         BPF_APROG_SEC("sk_skb/stream_verdict",  BPF_PROG_TYPE_SK_SKB,
3191                                                 BPF_SK_SKB_STREAM_VERDICT),
3192         BPF_APROG_COMPAT("sk_skb",              BPF_PROG_TYPE_SK_SKB),
3193         BPF_APROG_SEC("sk_msg",                 BPF_PROG_TYPE_SK_MSG,
3194                                                 BPF_SK_MSG_VERDICT),
3195         BPF_APROG_SEC("lirc_mode2",             BPF_PROG_TYPE_LIRC_MODE2,
3196                                                 BPF_LIRC_MODE2),
3197         BPF_APROG_SEC("flow_dissector",         BPF_PROG_TYPE_FLOW_DISSECTOR,
3198                                                 BPF_FLOW_DISSECTOR),
3199         BPF_EAPROG_SEC("cgroup/bind4",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3200                                                 BPF_CGROUP_INET4_BIND),
3201         BPF_EAPROG_SEC("cgroup/bind6",          BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3202                                                 BPF_CGROUP_INET6_BIND),
3203         BPF_EAPROG_SEC("cgroup/connect4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3204                                                 BPF_CGROUP_INET4_CONNECT),
3205         BPF_EAPROG_SEC("cgroup/connect6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3206                                                 BPF_CGROUP_INET6_CONNECT),
3207         BPF_EAPROG_SEC("cgroup/sendmsg4",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3208                                                 BPF_CGROUP_UDP4_SENDMSG),
3209         BPF_EAPROG_SEC("cgroup/sendmsg6",       BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
3210                                                 BPF_CGROUP_UDP6_SENDMSG),
3211         BPF_EAPROG_SEC("cgroup/sysctl",         BPF_PROG_TYPE_CGROUP_SYSCTL,
3212                                                 BPF_CGROUP_SYSCTL),
3213 };
3214
3215 #undef BPF_PROG_SEC_IMPL
3216 #undef BPF_PROG_SEC
3217 #undef BPF_APROG_SEC
3218 #undef BPF_EAPROG_SEC
3219 #undef BPF_APROG_COMPAT
3220
3221 #define MAX_TYPE_NAME_SIZE 32
3222
3223 static char *libbpf_get_type_names(bool attach_type)
3224 {
3225         int i, len = ARRAY_SIZE(section_names) * MAX_TYPE_NAME_SIZE;
3226         char *buf;
3227
3228         buf = malloc(len);
3229         if (!buf)
3230                 return NULL;
3231
3232         buf[0] = '\0';
3233         /* Forge string buf with all available names */
3234         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3235                 if (attach_type && !section_names[i].is_attachable)
3236                         continue;
3237
3238                 if (strlen(buf) + strlen(section_names[i].sec) + 2 > len) {
3239                         free(buf);
3240                         return NULL;
3241                 }
3242                 strcat(buf, " ");
3243                 strcat(buf, section_names[i].sec);
3244         }
3245
3246         return buf;
3247 }
3248
3249 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
3250                              enum bpf_attach_type *expected_attach_type)
3251 {
3252         char *type_names;
3253         int i;
3254
3255         if (!name)
3256                 return -EINVAL;
3257
3258         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3259                 if (strncmp(name, section_names[i].sec, section_names[i].len))
3260                         continue;
3261                 *prog_type = section_names[i].prog_type;
3262                 *expected_attach_type = section_names[i].expected_attach_type;
3263                 return 0;
3264         }
3265         pr_warning("failed to guess program type based on ELF section name '%s'\n", name);
3266         type_names = libbpf_get_type_names(false);
3267         if (type_names != NULL) {
3268                 pr_info("supported section(type) names are:%s\n", type_names);
3269                 free(type_names);
3270         }
3271
3272         return -EINVAL;
3273 }
3274
3275 int libbpf_attach_type_by_name(const char *name,
3276                                enum bpf_attach_type *attach_type)
3277 {
3278         char *type_names;
3279         int i;
3280
3281         if (!name)
3282                 return -EINVAL;
3283
3284         for (i = 0; i < ARRAY_SIZE(section_names); i++) {
3285                 if (strncmp(name, section_names[i].sec, section_names[i].len))
3286                         continue;
3287                 if (!section_names[i].is_attachable)
3288                         return -EINVAL;
3289                 *attach_type = section_names[i].attach_type;
3290                 return 0;
3291         }
3292         pr_warning("failed to guess attach type based on ELF section name '%s'\n", name);
3293         type_names = libbpf_get_type_names(true);
3294         if (type_names != NULL) {
3295                 pr_info("attachable section(type) names are:%s\n", type_names);
3296                 free(type_names);
3297         }
3298
3299         return -EINVAL;
3300 }
3301
3302 static int
3303 bpf_program__identify_section(struct bpf_program *prog,
3304                               enum bpf_prog_type *prog_type,
3305                               enum bpf_attach_type *expected_attach_type)
3306 {
3307         return libbpf_prog_type_by_name(prog->section_name, prog_type,
3308                                         expected_attach_type);
3309 }
3310
3311 int bpf_map__fd(struct bpf_map *map)
3312 {
3313         return map ? map->fd : -EINVAL;
3314 }
3315
3316 const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
3317 {
3318         return map ? &map->def : ERR_PTR(-EINVAL);
3319 }
3320
3321 const char *bpf_map__name(struct bpf_map *map)
3322 {
3323         return map ? map->name : NULL;
3324 }
3325
3326 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
3327 {
3328         return map ? map->btf_key_type_id : 0;
3329 }
3330
3331 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
3332 {
3333         return map ? map->btf_value_type_id : 0;
3334 }
3335
3336 int bpf_map__set_priv(struct bpf_map *map, void *priv,
3337                      bpf_map_clear_priv_t clear_priv)
3338 {
3339         if (!map)
3340                 return -EINVAL;
3341
3342         if (map->priv) {
3343                 if (map->clear_priv)
3344                         map->clear_priv(map, map->priv);
3345         }
3346
3347         map->priv = priv;
3348         map->clear_priv = clear_priv;
3349         return 0;
3350 }
3351
3352 void *bpf_map__priv(struct bpf_map *map)
3353 {
3354         return map ? map->priv : ERR_PTR(-EINVAL);
3355 }
3356
3357 bool bpf_map__is_offload_neutral(struct bpf_map *map)
3358 {
3359         return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
3360 }
3361
3362 bool bpf_map__is_internal(struct bpf_map *map)
3363 {
3364         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
3365 }
3366
3367 void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
3368 {
3369         map->map_ifindex = ifindex;
3370 }
3371
3372 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
3373 {
3374         if (!bpf_map_type__is_map_in_map(map->def.type)) {
3375                 pr_warning("error: unsupported map type\n");
3376                 return -EINVAL;
3377         }
3378         if (map->inner_map_fd != -1) {
3379                 pr_warning("error: inner_map_fd already specified\n");
3380                 return -EINVAL;
3381         }
3382         map->inner_map_fd = fd;
3383         return 0;
3384 }
3385
3386 static struct bpf_map *
3387 __bpf_map__iter(struct bpf_map *m, struct bpf_object *obj, int i)
3388 {
3389         ssize_t idx;
3390         struct bpf_map *s, *e;
3391
3392         if (!obj || !obj->maps)
3393                 return NULL;
3394
3395         s = obj->maps;
3396         e = obj->maps + obj->nr_maps;
3397
3398         if ((m < s) || (m >= e)) {
3399                 pr_warning("error in %s: map handler doesn't belong to object\n",
3400                            __func__);
3401                 return NULL;
3402         }
3403
3404         idx = (m - obj->maps) + i;
3405         if (idx >= obj->nr_maps || idx < 0)
3406                 return NULL;
3407         return &obj->maps[idx];
3408 }
3409
3410 struct bpf_map *
3411 bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
3412 {
3413         if (prev == NULL)
3414                 return obj->maps;
3415
3416         return __bpf_map__iter(prev, obj, 1);
3417 }
3418
3419 struct bpf_map *
3420 bpf_map__prev(struct bpf_map *next, struct bpf_object *obj)
3421 {
3422         if (next == NULL) {
3423                 if (!obj->nr_maps)
3424                         return NULL;
3425                 return obj->maps + obj->nr_maps - 1;
3426         }
3427
3428         return __bpf_map__iter(next, obj, -1);
3429 }
3430
3431 struct bpf_map *
3432 bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
3433 {
3434         struct bpf_map *pos;
3435
3436         bpf_object__for_each_map(pos, obj) {
3437                 if (pos->name && !strcmp(pos->name, name))
3438                         return pos;
3439         }
3440         return NULL;
3441 }
3442
3443 int
3444 bpf_object__find_map_fd_by_name(struct bpf_object *obj, const char *name)
3445 {
3446         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
3447 }
3448
3449 struct bpf_map *
3450 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
3451 {
3452         int i;
3453
3454         for (i = 0; i < obj->nr_maps; i++) {
3455                 if (obj->maps[i].offset == offset)
3456                         return &obj->maps[i];
3457         }
3458         return ERR_PTR(-ENOENT);
3459 }
3460
3461 long libbpf_get_error(const void *ptr)
3462 {
3463         if (IS_ERR(ptr))
3464                 return PTR_ERR(ptr);
3465         return 0;
3466 }
3467
3468 int bpf_prog_load(const char *file, enum bpf_prog_type type,
3469                   struct bpf_object **pobj, int *prog_fd)
3470 {
3471         struct bpf_prog_load_attr attr;
3472
3473         memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
3474         attr.file = file;
3475         attr.prog_type = type;
3476         attr.expected_attach_type = 0;
3477
3478         return bpf_prog_load_xattr(&attr, pobj, prog_fd);
3479 }
3480
3481 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
3482                         struct bpf_object **pobj, int *prog_fd)
3483 {
3484         struct bpf_object_open_attr open_attr = {
3485                 .file           = attr->file,
3486                 .prog_type      = attr->prog_type,
3487         };
3488         struct bpf_program *prog, *first_prog = NULL;
3489         enum bpf_attach_type expected_attach_type;
3490         enum bpf_prog_type prog_type;
3491         struct bpf_object *obj;
3492         struct bpf_map *map;
3493         int err;
3494
3495         if (!attr)
3496                 return -EINVAL;
3497         if (!attr->file)
3498                 return -EINVAL;
3499
3500         obj = bpf_object__open_xattr(&open_attr);
3501         if (IS_ERR_OR_NULL(obj))
3502                 return -ENOENT;
3503
3504         bpf_object__for_each_program(prog, obj) {
3505                 /*
3506                  * If type is not specified, try to guess it based on
3507                  * section name.
3508                  */
3509                 prog_type = attr->prog_type;
3510                 prog->prog_ifindex = attr->ifindex;
3511                 expected_attach_type = attr->expected_attach_type;
3512                 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
3513                         err = bpf_program__identify_section(prog, &prog_type,
3514                                                             &expected_attach_type);
3515                         if (err < 0) {
3516                                 bpf_object__close(obj);
3517                                 return -EINVAL;
3518                         }
3519                 }
3520
3521                 bpf_program__set_type(prog, prog_type);
3522                 bpf_program__set_expected_attach_type(prog,
3523                                                       expected_attach_type);
3524
3525                 prog->log_level = attr->log_level;
3526                 prog->prog_flags = attr->prog_flags;
3527                 if (!first_prog)
3528                         first_prog = prog;
3529         }
3530
3531         bpf_object__for_each_map(map, obj) {
3532                 if (!bpf_map__is_offload_neutral(map))
3533                         map->map_ifindex = attr->ifindex;
3534         }
3535
3536         if (!first_prog) {
3537                 pr_warning("object file doesn't contain bpf program\n");
3538                 bpf_object__close(obj);
3539                 return -ENOENT;
3540         }
3541
3542         err = bpf_object__load(obj);
3543         if (err) {
3544                 bpf_object__close(obj);
3545                 return -EINVAL;
3546         }
3547
3548         *pobj = obj;
3549         *prog_fd = bpf_program__fd(first_prog);
3550         return 0;
3551 }
3552
3553 enum bpf_perf_event_ret
3554 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
3555                            void **copy_mem, size_t *copy_size,
3556                            bpf_perf_event_print_t fn, void *private_data)
3557 {
3558         struct perf_event_mmap_page *header = mmap_mem;
3559         __u64 data_head = ring_buffer_read_head(header);
3560         __u64 data_tail = header->data_tail;
3561         void *base = ((__u8 *)header) + page_size;
3562         int ret = LIBBPF_PERF_EVENT_CONT;
3563         struct perf_event_header *ehdr;
3564         size_t ehdr_size;
3565
3566         while (data_head != data_tail) {
3567                 ehdr = base + (data_tail & (mmap_size - 1));
3568                 ehdr_size = ehdr->size;
3569
3570                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
3571                         void *copy_start = ehdr;
3572                         size_t len_first = base + mmap_size - copy_start;
3573                         size_t len_secnd = ehdr_size - len_first;
3574
3575                         if (*copy_size < ehdr_size) {
3576                                 free(*copy_mem);
3577                                 *copy_mem = malloc(ehdr_size);
3578                                 if (!*copy_mem) {
3579                                         *copy_size = 0;
3580                                         ret = LIBBPF_PERF_EVENT_ERROR;
3581                                         break;
3582                                 }
3583                                 *copy_size = ehdr_size;
3584                         }
3585
3586                         memcpy(*copy_mem, copy_start, len_first);
3587                         memcpy(*copy_mem + len_first, base, len_secnd);
3588                         ehdr = *copy_mem;
3589                 }
3590
3591                 ret = fn(ehdr, private_data);
3592                 data_tail += ehdr_size;
3593                 if (ret != LIBBPF_PERF_EVENT_CONT)
3594                         break;
3595         }
3596
3597         ring_buffer_write_tail(header, data_tail);
3598         return ret;
3599 }
3600
3601 struct bpf_prog_info_array_desc {
3602         int     array_offset;   /* e.g. offset of jited_prog_insns */
3603         int     count_offset;   /* e.g. offset of jited_prog_len */
3604         int     size_offset;    /* > 0: offset of rec size,
3605                                  * < 0: fix size of -size_offset
3606                                  */
3607 };
3608
3609 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
3610         [BPF_PROG_INFO_JITED_INSNS] = {
3611                 offsetof(struct bpf_prog_info, jited_prog_insns),
3612                 offsetof(struct bpf_prog_info, jited_prog_len),
3613                 -1,
3614         },
3615         [BPF_PROG_INFO_XLATED_INSNS] = {
3616                 offsetof(struct bpf_prog_info, xlated_prog_insns),
3617                 offsetof(struct bpf_prog_info, xlated_prog_len),
3618                 -1,
3619         },
3620         [BPF_PROG_INFO_MAP_IDS] = {
3621                 offsetof(struct bpf_prog_info, map_ids),
3622                 offsetof(struct bpf_prog_info, nr_map_ids),
3623                 -(int)sizeof(__u32),
3624         },
3625         [BPF_PROG_INFO_JITED_KSYMS] = {
3626                 offsetof(struct bpf_prog_info, jited_ksyms),
3627                 offsetof(struct bpf_prog_info, nr_jited_ksyms),
3628                 -(int)sizeof(__u64),
3629         },
3630         [BPF_PROG_INFO_JITED_FUNC_LENS] = {
3631                 offsetof(struct bpf_prog_info, jited_func_lens),
3632                 offsetof(struct bpf_prog_info, nr_jited_func_lens),
3633                 -(int)sizeof(__u32),
3634         },
3635         [BPF_PROG_INFO_FUNC_INFO] = {
3636                 offsetof(struct bpf_prog_info, func_info),
3637                 offsetof(struct bpf_prog_info, nr_func_info),
3638                 offsetof(struct bpf_prog_info, func_info_rec_size),
3639         },
3640         [BPF_PROG_INFO_LINE_INFO] = {
3641                 offsetof(struct bpf_prog_info, line_info),
3642                 offsetof(struct bpf_prog_info, nr_line_info),
3643                 offsetof(struct bpf_prog_info, line_info_rec_size),
3644         },
3645         [BPF_PROG_INFO_JITED_LINE_INFO] = {
3646                 offsetof(struct bpf_prog_info, jited_line_info),
3647                 offsetof(struct bpf_prog_info, nr_jited_line_info),
3648                 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
3649         },
3650         [BPF_PROG_INFO_PROG_TAGS] = {
3651                 offsetof(struct bpf_prog_info, prog_tags),
3652                 offsetof(struct bpf_prog_info, nr_prog_tags),
3653                 -(int)sizeof(__u8) * BPF_TAG_SIZE,
3654         },
3655
3656 };
3657
3658 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info, int offset)
3659 {
3660         __u32 *array = (__u32 *)info;
3661
3662         if (offset >= 0)
3663                 return array[offset / sizeof(__u32)];
3664         return -(int)offset;
3665 }
3666
3667 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info, int offset)
3668 {
3669         __u64 *array = (__u64 *)info;
3670
3671         if (offset >= 0)
3672                 return array[offset / sizeof(__u64)];
3673         return -(int)offset;
3674 }
3675
3676 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
3677                                          __u32 val)
3678 {
3679         __u32 *array = (__u32 *)info;
3680
3681         if (offset >= 0)
3682                 array[offset / sizeof(__u32)] = val;
3683 }
3684
3685 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
3686                                          __u64 val)
3687 {
3688         __u64 *array = (__u64 *)info;
3689
3690         if (offset >= 0)
3691                 array[offset / sizeof(__u64)] = val;
3692 }
3693
3694 struct bpf_prog_info_linear *
3695 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
3696 {
3697         struct bpf_prog_info_linear *info_linear;
3698         struct bpf_prog_info info = {};
3699         __u32 info_len = sizeof(info);
3700         __u32 data_len = 0;
3701         int i, err;
3702         void *ptr;
3703
3704         if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
3705                 return ERR_PTR(-EINVAL);
3706
3707         /* step 1: get array dimensions */
3708         err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
3709         if (err) {
3710                 pr_debug("can't get prog info: %s", strerror(errno));
3711                 return ERR_PTR(-EFAULT);
3712         }
3713
3714         /* step 2: calculate total size of all arrays */
3715         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3716                 bool include_array = (arrays & (1UL << i)) > 0;
3717                 struct bpf_prog_info_array_desc *desc;
3718                 __u32 count, size;
3719
3720                 desc = bpf_prog_info_array_desc + i;
3721
3722                 /* kernel is too old to support this field */
3723                 if (info_len < desc->array_offset + sizeof(__u32) ||
3724                     info_len < desc->count_offset + sizeof(__u32) ||
3725                     (desc->size_offset > 0 && info_len < desc->size_offset))
3726                         include_array = false;
3727
3728                 if (!include_array) {
3729                         arrays &= ~(1UL << i);  /* clear the bit */
3730                         continue;
3731                 }
3732
3733                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
3734                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
3735
3736                 data_len += count * size;
3737         }
3738
3739         /* step 3: allocate continuous memory */
3740         data_len = roundup(data_len, sizeof(__u64));
3741         info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
3742         if (!info_linear)
3743                 return ERR_PTR(-ENOMEM);
3744
3745         /* step 4: fill data to info_linear->info */
3746         info_linear->arrays = arrays;
3747         memset(&info_linear->info, 0, sizeof(info));
3748         ptr = info_linear->data;
3749
3750         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3751                 struct bpf_prog_info_array_desc *desc;
3752                 __u32 count, size;
3753
3754                 if ((arrays & (1UL << i)) == 0)
3755                         continue;
3756
3757                 desc  = bpf_prog_info_array_desc + i;
3758                 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
3759                 size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
3760                 bpf_prog_info_set_offset_u32(&info_linear->info,
3761                                              desc->count_offset, count);
3762                 bpf_prog_info_set_offset_u32(&info_linear->info,
3763                                              desc->size_offset, size);
3764                 bpf_prog_info_set_offset_u64(&info_linear->info,
3765                                              desc->array_offset,
3766                                              ptr_to_u64(ptr));
3767                 ptr += count * size;
3768         }
3769
3770         /* step 5: call syscall again to get required arrays */
3771         err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
3772         if (err) {
3773                 pr_debug("can't get prog info: %s", strerror(errno));
3774                 free(info_linear);
3775                 return ERR_PTR(-EFAULT);
3776         }
3777
3778         /* step 6: verify the data */
3779         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3780                 struct bpf_prog_info_array_desc *desc;
3781                 __u32 v1, v2;
3782
3783                 if ((arrays & (1UL << i)) == 0)
3784                         continue;
3785
3786                 desc = bpf_prog_info_array_desc + i;
3787                 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
3788                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
3789                                                    desc->count_offset);
3790                 if (v1 != v2)
3791                         pr_warning("%s: mismatch in element count\n", __func__);
3792
3793                 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
3794                 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
3795                                                    desc->size_offset);
3796                 if (v1 != v2)
3797                         pr_warning("%s: mismatch in rec size\n", __func__);
3798         }
3799
3800         /* step 7: update info_len and data_len */
3801         info_linear->info_len = sizeof(struct bpf_prog_info);
3802         info_linear->data_len = data_len;
3803
3804         return info_linear;
3805 }
3806
3807 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
3808 {
3809         int i;
3810
3811         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3812                 struct bpf_prog_info_array_desc *desc;
3813                 __u64 addr, offs;
3814
3815                 if ((info_linear->arrays & (1UL << i)) == 0)
3816                         continue;
3817
3818                 desc = bpf_prog_info_array_desc + i;
3819                 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
3820                                                      desc->array_offset);
3821                 offs = addr - ptr_to_u64(info_linear->data);
3822                 bpf_prog_info_set_offset_u64(&info_linear->info,
3823                                              desc->array_offset, offs);
3824         }
3825 }
3826
3827 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
3828 {
3829         int i;
3830
3831         for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
3832                 struct bpf_prog_info_array_desc *desc;
3833                 __u64 addr, offs;
3834
3835                 if ((info_linear->arrays & (1UL << i)) == 0)
3836                         continue;
3837
3838                 desc = bpf_prog_info_array_desc + i;
3839                 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
3840                                                      desc->array_offset);
3841                 addr = offs + ptr_to_u64(info_linear->data);
3842                 bpf_prog_info_set_offset_u64(&info_linear->info,
3843                                              desc->array_offset, addr);
3844         }
3845 }