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