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