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