tools: libbpf: add bpf_object__find_program_by_title()
[linux-2.6-block.git] / tools / lib / bpf / libbpf.c
CommitLineData
6061a3d6
EL
1// SPDX-License-Identifier: LGPL-2.1
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.
203d1cac
WN
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation;
14 * version 2.1 of the License (not later!)
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Lesser General Public License for more details.
20 *
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this program; if not, see <http://www.gnu.org/licenses>
1b76c13e
WN
23 */
24
531b014e 25#define _GNU_SOURCE
1b76c13e 26#include <stdlib.h>
b3f59d66
WN
27#include <stdio.h>
28#include <stdarg.h>
f367540c 29#include <libgen.h>
34090915 30#include <inttypes.h>
b3f59d66 31#include <string.h>
1b76c13e 32#include <unistd.h>
1a5e3fb1
WN
33#include <fcntl.h>
34#include <errno.h>
d0cabbb0 35#include <perf-sys.h>
1b76c13e 36#include <asm/unistd.h>
e28ff1a8 37#include <linux/err.h>
cb1e5e96 38#include <linux/kernel.h>
1b76c13e 39#include <linux/bpf.h>
9a208eff 40#include <linux/list.h>
f367540c
JS
41#include <linux/limits.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/vfs.h>
531b014e 45#include <tools/libc_compat.h>
1a5e3fb1
WN
46#include <libelf.h>
47#include <gelf.h>
1b76c13e
WN
48
49#include "libbpf.h"
52d3352e 50#include "bpf.h"
8a138aed 51#include "btf.h"
b3f59d66 52
9b16137a
WN
53#ifndef EM_BPF
54#define EM_BPF 247
55#endif
56
f367540c
JS
57#ifndef BPF_FS_MAGIC
58#define BPF_FS_MAGIC 0xcafe4a11
59#endif
60
b3f59d66
WN
61#define __printf(a, b) __attribute__((format(printf, a, b)))
62
63__printf(1, 2)
64static int __base_pr(const char *format, ...)
65{
66 va_list args;
67 int err;
68
69 va_start(args, format);
70 err = vfprintf(stderr, format, args);
71 va_end(args);
72 return err;
73}
74
75static __printf(1, 2) libbpf_print_fn_t __pr_warning = __base_pr;
76static __printf(1, 2) libbpf_print_fn_t __pr_info = __base_pr;
77static __printf(1, 2) libbpf_print_fn_t __pr_debug;
78
79#define __pr(func, fmt, ...) \
80do { \
81 if ((func)) \
82 (func)("libbpf: " fmt, ##__VA_ARGS__); \
83} while (0)
84
85#define pr_warning(fmt, ...) __pr(__pr_warning, fmt, ##__VA_ARGS__)
86#define pr_info(fmt, ...) __pr(__pr_info, fmt, ##__VA_ARGS__)
87#define pr_debug(fmt, ...) __pr(__pr_debug, fmt, ##__VA_ARGS__)
88
89void libbpf_set_print(libbpf_print_fn_t warn,
90 libbpf_print_fn_t info,
91 libbpf_print_fn_t debug)
92{
93 __pr_warning = warn;
94 __pr_info = info;
95 __pr_debug = debug;
96}
1a5e3fb1 97
6371ca3b
WN
98#define STRERR_BUFSIZE 128
99
6371ca3b
WN
100#define CHECK_ERR(action, err, out) do { \
101 err = action; \
102 if (err) \
103 goto out; \
104} while(0)
105
106
1a5e3fb1
WN
107/* Copied from tools/perf/util/util.h */
108#ifndef zfree
109# define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
110#endif
111
112#ifndef zclose
113# define zclose(fd) ({ \
114 int ___err = 0; \
115 if ((fd) >= 0) \
116 ___err = close((fd)); \
117 fd = -1; \
118 ___err; })
119#endif
120
121#ifdef HAVE_LIBELF_MMAP_SUPPORT
122# define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
123#else
124# define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
125#endif
126
a5b8bd47
WN
127/*
128 * bpf_prog should be a better name but it has been used in
129 * linux/filter.h.
130 */
131struct bpf_program {
132 /* Index in elf obj file, for relocation use. */
133 int idx;
88cda1c9 134 char *name;
f0307a7e 135 int prog_ifindex;
a5b8bd47
WN
136 char *section_name;
137 struct bpf_insn *insns;
48cca7e4 138 size_t insns_cnt, main_prog_cnt;
5f44e4c8 139 enum bpf_prog_type type;
34090915 140
48cca7e4
AS
141 struct reloc_desc {
142 enum {
143 RELO_LD64,
144 RELO_CALL,
145 } type;
34090915 146 int insn_idx;
48cca7e4
AS
147 union {
148 int map_idx;
149 int text_off;
150 };
34090915
WN
151 } *reloc_desc;
152 int nr_reloc;
55cffde2 153
b580563e
WN
154 struct {
155 int nr;
156 int *fds;
157 } instances;
158 bpf_program_prep_t preprocessor;
aa9b1ac3
WN
159
160 struct bpf_object *obj;
161 void *priv;
162 bpf_program_clear_priv_t clear_priv;
d7be143b
AI
163
164 enum bpf_attach_type expected_attach_type;
a5b8bd47
WN
165};
166
9d759a9b
WN
167struct bpf_map {
168 int fd;
561bbcca 169 char *name;
4708bbda 170 size_t offset;
f0307a7e 171 int map_ifindex;
9d759a9b 172 struct bpf_map_def def;
61746dbe
MKL
173 uint32_t btf_key_type_id;
174 uint32_t btf_value_type_id;
9d759a9b
WN
175 void *priv;
176 bpf_map_clear_priv_t clear_priv;
177};
178
9a208eff
WN
179static LIST_HEAD(bpf_objects_list);
180
1a5e3fb1 181struct bpf_object {
cb1e5e96
WN
182 char license[64];
183 u32 kern_version;
0b3d1efa 184
a5b8bd47
WN
185 struct bpf_program *programs;
186 size_t nr_programs;
9d759a9b
WN
187 struct bpf_map *maps;
188 size_t nr_maps;
189
52d3352e 190 bool loaded;
9a94f277 191 bool has_pseudo_calls;
a5b8bd47 192
1a5e3fb1
WN
193 /*
194 * Information when doing elf related work. Only valid if fd
195 * is valid.
196 */
197 struct {
198 int fd;
6c956392
WN
199 void *obj_buf;
200 size_t obj_buf_sz;
1a5e3fb1
WN
201 Elf *elf;
202 GElf_Ehdr ehdr;
bec7d68c 203 Elf_Data *symbols;
77ba9a5b 204 size_t strtabidx;
b62f06e8
WN
205 struct {
206 GElf_Shdr shdr;
207 Elf_Data *data;
208 } *reloc;
209 int nr_reloc;
666810e8 210 int maps_shndx;
48cca7e4 211 int text_shndx;
1a5e3fb1 212 } efile;
9a208eff
WN
213 /*
214 * All loaded bpf_object is linked in a list, which is
215 * hidden to caller. bpf_objects__<func> handlers deal with
216 * all objects.
217 */
218 struct list_head list;
10931d24 219
8a138aed
MKL
220 struct btf *btf;
221
10931d24
WN
222 void *priv;
223 bpf_object_clear_priv_t clear_priv;
224
1a5e3fb1
WN
225 char path[];
226};
227#define obj_elf_valid(o) ((o)->efile.elf)
228
55cffde2
WN
229static void bpf_program__unload(struct bpf_program *prog)
230{
b580563e
WN
231 int i;
232
55cffde2
WN
233 if (!prog)
234 return;
235
b580563e
WN
236 /*
237 * If the object is opened but the program was never loaded,
238 * it is possible that prog->instances.nr == -1.
239 */
240 if (prog->instances.nr > 0) {
241 for (i = 0; i < prog->instances.nr; i++)
242 zclose(prog->instances.fds[i]);
243 } else if (prog->instances.nr != -1) {
244 pr_warning("Internal error: instances.nr is %d\n",
245 prog->instances.nr);
246 }
247
248 prog->instances.nr = -1;
249 zfree(&prog->instances.fds);
55cffde2
WN
250}
251
a5b8bd47
WN
252static void bpf_program__exit(struct bpf_program *prog)
253{
254 if (!prog)
255 return;
256
aa9b1ac3
WN
257 if (prog->clear_priv)
258 prog->clear_priv(prog, prog->priv);
259
260 prog->priv = NULL;
261 prog->clear_priv = NULL;
262
55cffde2 263 bpf_program__unload(prog);
88cda1c9 264 zfree(&prog->name);
a5b8bd47
WN
265 zfree(&prog->section_name);
266 zfree(&prog->insns);
34090915
WN
267 zfree(&prog->reloc_desc);
268
269 prog->nr_reloc = 0;
a5b8bd47
WN
270 prog->insns_cnt = 0;
271 prog->idx = -1;
272}
273
274static int
88cda1c9
MKL
275bpf_program__init(void *data, size_t size, char *section_name, int idx,
276 struct bpf_program *prog)
a5b8bd47
WN
277{
278 if (size < sizeof(struct bpf_insn)) {
88cda1c9 279 pr_warning("corrupted section '%s'\n", section_name);
a5b8bd47
WN
280 return -EINVAL;
281 }
282
283 bzero(prog, sizeof(*prog));
284
88cda1c9 285 prog->section_name = strdup(section_name);
a5b8bd47 286 if (!prog->section_name) {
077c066a
JDB
287 pr_warning("failed to alloc name for prog under section(%d) %s\n",
288 idx, section_name);
a5b8bd47
WN
289 goto errout;
290 }
291
292 prog->insns = malloc(size);
293 if (!prog->insns) {
88cda1c9
MKL
294 pr_warning("failed to alloc insns for prog under section %s\n",
295 section_name);
a5b8bd47
WN
296 goto errout;
297 }
298 prog->insns_cnt = size / sizeof(struct bpf_insn);
299 memcpy(prog->insns, data,
300 prog->insns_cnt * sizeof(struct bpf_insn));
301 prog->idx = idx;
b580563e
WN
302 prog->instances.fds = NULL;
303 prog->instances.nr = -1;
5f44e4c8 304 prog->type = BPF_PROG_TYPE_KPROBE;
a5b8bd47
WN
305
306 return 0;
307errout:
308 bpf_program__exit(prog);
309 return -ENOMEM;
310}
311
312static int
313bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
88cda1c9 314 char *section_name, int idx)
a5b8bd47
WN
315{
316 struct bpf_program prog, *progs;
317 int nr_progs, err;
318
88cda1c9 319 err = bpf_program__init(data, size, section_name, idx, &prog);
a5b8bd47
WN
320 if (err)
321 return err;
322
323 progs = obj->programs;
324 nr_progs = obj->nr_programs;
325
531b014e 326 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
a5b8bd47
WN
327 if (!progs) {
328 /*
329 * In this case the original obj->programs
330 * is still valid, so don't need special treat for
331 * bpf_close_object().
332 */
88cda1c9
MKL
333 pr_warning("failed to alloc a new program under section '%s'\n",
334 section_name);
a5b8bd47
WN
335 bpf_program__exit(&prog);
336 return -ENOMEM;
337 }
338
339 pr_debug("found program %s\n", prog.section_name);
340 obj->programs = progs;
341 obj->nr_programs = nr_progs + 1;
aa9b1ac3 342 prog.obj = obj;
a5b8bd47
WN
343 progs[nr_progs] = prog;
344 return 0;
345}
346
88cda1c9
MKL
347static int
348bpf_object__init_prog_names(struct bpf_object *obj)
349{
350 Elf_Data *symbols = obj->efile.symbols;
351 struct bpf_program *prog;
352 size_t pi, si;
353
354 for (pi = 0; pi < obj->nr_programs; pi++) {
48cca7e4 355 const char *name = NULL;
88cda1c9
MKL
356
357 prog = &obj->programs[pi];
358
359 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
360 si++) {
361 GElf_Sym sym;
362
363 if (!gelf_getsym(symbols, si, &sym))
364 continue;
365 if (sym.st_shndx != prog->idx)
366 continue;
fe4d44b2
RG
367 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
368 continue;
88cda1c9
MKL
369
370 name = elf_strptr(obj->efile.elf,
371 obj->efile.strtabidx,
372 sym.st_name);
373 if (!name) {
374 pr_warning("failed to get sym name string for prog %s\n",
375 prog->section_name);
376 return -LIBBPF_ERRNO__LIBELF;
377 }
378 }
379
9a94f277
JK
380 if (!name && prog->idx == obj->efile.text_shndx)
381 name = ".text";
382
88cda1c9
MKL
383 if (!name) {
384 pr_warning("failed to find sym for prog %s\n",
385 prog->section_name);
386 return -EINVAL;
387 }
9a94f277 388
88cda1c9
MKL
389 prog->name = strdup(name);
390 if (!prog->name) {
391 pr_warning("failed to allocate memory for prog sym %s\n",
392 name);
393 return -ENOMEM;
394 }
395 }
396
397 return 0;
398}
399
6c956392
WN
400static struct bpf_object *bpf_object__new(const char *path,
401 void *obj_buf,
402 size_t obj_buf_sz)
1a5e3fb1
WN
403{
404 struct bpf_object *obj;
405
406 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
407 if (!obj) {
408 pr_warning("alloc memory failed for %s\n", path);
6371ca3b 409 return ERR_PTR(-ENOMEM);
1a5e3fb1
WN
410 }
411
412 strcpy(obj->path, path);
413 obj->efile.fd = -1;
6c956392
WN
414
415 /*
416 * Caller of this function should also calls
417 * bpf_object__elf_finish() after data collection to return
418 * obj_buf to user. If not, we should duplicate the buffer to
419 * avoid user freeing them before elf finish.
420 */
421 obj->efile.obj_buf = obj_buf;
422 obj->efile.obj_buf_sz = obj_buf_sz;
666810e8 423 obj->efile.maps_shndx = -1;
6c956392 424
52d3352e 425 obj->loaded = false;
9a208eff
WN
426
427 INIT_LIST_HEAD(&obj->list);
428 list_add(&obj->list, &bpf_objects_list);
1a5e3fb1
WN
429 return obj;
430}
431
432static void bpf_object__elf_finish(struct bpf_object *obj)
433{
434 if (!obj_elf_valid(obj))
435 return;
436
437 if (obj->efile.elf) {
438 elf_end(obj->efile.elf);
439 obj->efile.elf = NULL;
440 }
bec7d68c 441 obj->efile.symbols = NULL;
b62f06e8
WN
442
443 zfree(&obj->efile.reloc);
444 obj->efile.nr_reloc = 0;
1a5e3fb1 445 zclose(obj->efile.fd);
6c956392
WN
446 obj->efile.obj_buf = NULL;
447 obj->efile.obj_buf_sz = 0;
1a5e3fb1
WN
448}
449
450static int bpf_object__elf_init(struct bpf_object *obj)
451{
452 int err = 0;
453 GElf_Ehdr *ep;
454
455 if (obj_elf_valid(obj)) {
456 pr_warning("elf init: internal error\n");
6371ca3b 457 return -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
458 }
459
6c956392
WN
460 if (obj->efile.obj_buf_sz > 0) {
461 /*
462 * obj_buf should have been validated by
463 * bpf_object__open_buffer().
464 */
465 obj->efile.elf = elf_memory(obj->efile.obj_buf,
466 obj->efile.obj_buf_sz);
467 } else {
468 obj->efile.fd = open(obj->path, O_RDONLY);
469 if (obj->efile.fd < 0) {
470 pr_warning("failed to open %s: %s\n", obj->path,
471 strerror(errno));
472 return -errno;
473 }
474
475 obj->efile.elf = elf_begin(obj->efile.fd,
476 LIBBPF_ELF_C_READ_MMAP,
477 NULL);
1a5e3fb1
WN
478 }
479
1a5e3fb1
WN
480 if (!obj->efile.elf) {
481 pr_warning("failed to open %s as ELF file\n",
482 obj->path);
6371ca3b 483 err = -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
484 goto errout;
485 }
486
487 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
488 pr_warning("failed to get EHDR from %s\n",
489 obj->path);
6371ca3b 490 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
491 goto errout;
492 }
493 ep = &obj->efile.ehdr;
494
9b16137a
WN
495 /* Old LLVM set e_machine to EM_NONE */
496 if ((ep->e_type != ET_REL) || (ep->e_machine && (ep->e_machine != EM_BPF))) {
1a5e3fb1
WN
497 pr_warning("%s is not an eBPF object file\n",
498 obj->path);
6371ca3b 499 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
500 goto errout;
501 }
502
503 return 0;
504errout:
505 bpf_object__elf_finish(obj);
506 return err;
507}
508
cc4228d5
WN
509static int
510bpf_object__check_endianness(struct bpf_object *obj)
511{
512 static unsigned int const endian = 1;
513
514 switch (obj->efile.ehdr.e_ident[EI_DATA]) {
515 case ELFDATA2LSB:
516 /* We are big endian, BPF obj is little endian. */
517 if (*(unsigned char const *)&endian != 1)
518 goto mismatch;
519 break;
520
521 case ELFDATA2MSB:
522 /* We are little endian, BPF obj is big endian. */
523 if (*(unsigned char const *)&endian != 0)
524 goto mismatch;
525 break;
526 default:
6371ca3b 527 return -LIBBPF_ERRNO__ENDIAN;
cc4228d5
WN
528 }
529
530 return 0;
531
532mismatch:
533 pr_warning("Error: endianness mismatch.\n");
6371ca3b 534 return -LIBBPF_ERRNO__ENDIAN;
cc4228d5
WN
535}
536
cb1e5e96
WN
537static int
538bpf_object__init_license(struct bpf_object *obj,
539 void *data, size_t size)
540{
541 memcpy(obj->license, data,
542 min(size, sizeof(obj->license) - 1));
543 pr_debug("license of %s is %s\n", obj->path, obj->license);
544 return 0;
545}
546
547static int
548bpf_object__init_kversion(struct bpf_object *obj,
549 void *data, size_t size)
550{
551 u32 kver;
552
553 if (size != sizeof(kver)) {
554 pr_warning("invalid kver section in %s\n", obj->path);
6371ca3b 555 return -LIBBPF_ERRNO__FORMAT;
cb1e5e96
WN
556 }
557 memcpy(&kver, data, sizeof(kver));
558 obj->kern_version = kver;
559 pr_debug("kernel version of %s is %x\n", obj->path,
560 obj->kern_version);
561 return 0;
562}
563
4708bbda
EL
564static int compare_bpf_map(const void *_a, const void *_b)
565{
566 const struct bpf_map *a = _a;
567 const struct bpf_map *b = _b;
9d759a9b 568
4708bbda 569 return a->offset - b->offset;
0b3d1efa
WN
570}
571
973170e6 572static int
4708bbda 573bpf_object__init_maps(struct bpf_object *obj)
561bbcca 574{
b13c5c14 575 int i, map_idx, map_def_sz, nr_maps = 0;
4708bbda
EL
576 Elf_Scn *scn;
577 Elf_Data *data;
561bbcca
WN
578 Elf_Data *symbols = obj->efile.symbols;
579
4708bbda
EL
580 if (obj->efile.maps_shndx < 0)
581 return -EINVAL;
582 if (!symbols)
583 return -EINVAL;
584
585 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
586 if (scn)
587 data = elf_getdata(scn, NULL);
588 if (!scn || !data) {
589 pr_warning("failed to get Elf_Data from map section %d\n",
590 obj->efile.maps_shndx);
973170e6 591 return -EINVAL;
4708bbda 592 }
561bbcca 593
4708bbda
EL
594 /*
595 * Count number of maps. Each map has a name.
596 * Array of maps is not supported: only the first element is
597 * considered.
598 *
599 * TODO: Detect array of map and report error.
600 */
561bbcca
WN
601 for (i = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
602 GElf_Sym sym;
4708bbda
EL
603
604 if (!gelf_getsym(symbols, i, &sym))
605 continue;
606 if (sym.st_shndx != obj->efile.maps_shndx)
607 continue;
608 nr_maps++;
609 }
610
611 /* Alloc obj->maps and fill nr_maps. */
612 pr_debug("maps in %s: %d maps in %zd bytes\n", obj->path,
613 nr_maps, data->d_size);
614
615 if (!nr_maps)
616 return 0;
617
b13c5c14
CG
618 /* Assume equally sized map definitions */
619 map_def_sz = data->d_size / nr_maps;
620 if (!data->d_size || (data->d_size % nr_maps) != 0) {
621 pr_warning("unable to determine map definition size "
622 "section %s, %d maps in %zd bytes\n",
623 obj->path, nr_maps, data->d_size);
624 return -EINVAL;
625 }
626
4708bbda
EL
627 obj->maps = calloc(nr_maps, sizeof(obj->maps[0]));
628 if (!obj->maps) {
629 pr_warning("alloc maps for object failed\n");
630 return -ENOMEM;
631 }
632 obj->nr_maps = nr_maps;
633
634 /*
635 * fill all fd with -1 so won't close incorrect
636 * fd (fd=0 is stdin) when failure (zclose won't close
637 * negative fd)).
638 */
639 for (i = 0; i < nr_maps; i++)
640 obj->maps[i].fd = -1;
641
642 /*
643 * Fill obj->maps using data in "maps" section.
644 */
645 for (i = 0, map_idx = 0; i < symbols->d_size / sizeof(GElf_Sym); i++) {
646 GElf_Sym sym;
561bbcca 647 const char *map_name;
4708bbda 648 struct bpf_map_def *def;
561bbcca
WN
649
650 if (!gelf_getsym(symbols, i, &sym))
651 continue;
666810e8 652 if (sym.st_shndx != obj->efile.maps_shndx)
561bbcca
WN
653 continue;
654
655 map_name = elf_strptr(obj->efile.elf,
77ba9a5b 656 obj->efile.strtabidx,
561bbcca 657 sym.st_name);
4708bbda 658 obj->maps[map_idx].offset = sym.st_value;
b13c5c14 659 if (sym.st_value + map_def_sz > data->d_size) {
4708bbda
EL
660 pr_warning("corrupted maps section in %s: last map \"%s\" too small\n",
661 obj->path, map_name);
662 return -EINVAL;
561bbcca 663 }
4708bbda 664
561bbcca 665 obj->maps[map_idx].name = strdup(map_name);
973170e6
WN
666 if (!obj->maps[map_idx].name) {
667 pr_warning("failed to alloc map name\n");
668 return -ENOMEM;
669 }
4708bbda 670 pr_debug("map %d is \"%s\"\n", map_idx,
561bbcca 671 obj->maps[map_idx].name);
4708bbda 672 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
b13c5c14
CG
673 /*
674 * If the definition of the map in the object file fits in
675 * bpf_map_def, copy it. Any extra fields in our version
676 * of bpf_map_def will default to zero as a result of the
677 * calloc above.
678 */
679 if (map_def_sz <= sizeof(struct bpf_map_def)) {
680 memcpy(&obj->maps[map_idx].def, def, map_def_sz);
681 } else {
682 /*
683 * Here the map structure being read is bigger than what
684 * we expect, truncate if the excess bits are all zero.
685 * If they are not zero, reject this map as
686 * incompatible.
687 */
688 char *b;
689 for (b = ((char *)def) + sizeof(struct bpf_map_def);
690 b < ((char *)def) + map_def_sz; b++) {
691 if (*b != 0) {
692 pr_warning("maps section in %s: \"%s\" "
693 "has unrecognized, non-zero "
694 "options\n",
695 obj->path, map_name);
696 return -EINVAL;
697 }
698 }
699 memcpy(&obj->maps[map_idx].def, def,
700 sizeof(struct bpf_map_def));
701 }
4708bbda 702 map_idx++;
561bbcca 703 }
4708bbda
EL
704
705 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]), compare_bpf_map);
b13c5c14 706 return 0;
561bbcca
WN
707}
708
e3d91b0c
JDB
709static bool section_have_execinstr(struct bpf_object *obj, int idx)
710{
711 Elf_Scn *scn;
712 GElf_Shdr sh;
713
714 scn = elf_getscn(obj->efile.elf, idx);
715 if (!scn)
716 return false;
717
718 if (gelf_getshdr(scn, &sh) != &sh)
719 return false;
720
721 if (sh.sh_flags & SHF_EXECINSTR)
722 return true;
723
724 return false;
725}
726
29603665
WN
727static int bpf_object__elf_collect(struct bpf_object *obj)
728{
729 Elf *elf = obj->efile.elf;
730 GElf_Ehdr *ep = &obj->efile.ehdr;
731 Elf_Scn *scn = NULL;
666810e8 732 int idx = 0, err = 0;
29603665
WN
733
734 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
735 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
736 pr_warning("failed to get e_shstrndx from %s\n",
737 obj->path);
6371ca3b 738 return -LIBBPF_ERRNO__FORMAT;
29603665
WN
739 }
740
741 while ((scn = elf_nextscn(elf, scn)) != NULL) {
742 char *name;
743 GElf_Shdr sh;
744 Elf_Data *data;
745
746 idx++;
747 if (gelf_getshdr(scn, &sh) != &sh) {
077c066a
JDB
748 pr_warning("failed to get section(%d) header from %s\n",
749 idx, obj->path);
6371ca3b 750 err = -LIBBPF_ERRNO__FORMAT;
29603665
WN
751 goto out;
752 }
753
754 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
755 if (!name) {
077c066a
JDB
756 pr_warning("failed to get section(%d) name from %s\n",
757 idx, obj->path);
6371ca3b 758 err = -LIBBPF_ERRNO__FORMAT;
29603665
WN
759 goto out;
760 }
761
762 data = elf_getdata(scn, 0);
763 if (!data) {
077c066a
JDB
764 pr_warning("failed to get section(%d) data from %s(%s)\n",
765 idx, name, obj->path);
6371ca3b 766 err = -LIBBPF_ERRNO__FORMAT;
29603665
WN
767 goto out;
768 }
077c066a
JDB
769 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
770 idx, name, (unsigned long)data->d_size,
29603665
WN
771 (int)sh.sh_link, (unsigned long)sh.sh_flags,
772 (int)sh.sh_type);
cb1e5e96
WN
773
774 if (strcmp(name, "license") == 0)
775 err = bpf_object__init_license(obj,
776 data->d_buf,
777 data->d_size);
778 else if (strcmp(name, "version") == 0)
779 err = bpf_object__init_kversion(obj,
780 data->d_buf,
781 data->d_size);
4708bbda 782 else if (strcmp(name, "maps") == 0)
666810e8 783 obj->efile.maps_shndx = idx;
8a138aed
MKL
784 else if (strcmp(name, BTF_ELF_SEC) == 0) {
785 obj->btf = btf__new(data->d_buf, data->d_size,
786 __pr_debug);
787 if (IS_ERR(obj->btf)) {
788 pr_warning("Error loading ELF section %s: %ld. Ignored and continue.\n",
789 BTF_ELF_SEC, PTR_ERR(obj->btf));
790 obj->btf = NULL;
791 }
792 } else if (sh.sh_type == SHT_SYMTAB) {
bec7d68c
WN
793 if (obj->efile.symbols) {
794 pr_warning("bpf: multiple SYMTAB in %s\n",
795 obj->path);
6371ca3b 796 err = -LIBBPF_ERRNO__FORMAT;
77ba9a5b 797 } else {
bec7d68c 798 obj->efile.symbols = data;
77ba9a5b
WN
799 obj->efile.strtabidx = sh.sh_link;
800 }
a5b8bd47
WN
801 } else if ((sh.sh_type == SHT_PROGBITS) &&
802 (sh.sh_flags & SHF_EXECINSTR) &&
803 (data->d_size > 0)) {
48cca7e4
AS
804 if (strcmp(name, ".text") == 0)
805 obj->efile.text_shndx = idx;
a5b8bd47
WN
806 err = bpf_object__add_program(obj, data->d_buf,
807 data->d_size, name, idx);
808 if (err) {
6371ca3b
WN
809 char errmsg[STRERR_BUFSIZE];
810
a5b8bd47
WN
811 strerror_r(-err, errmsg, sizeof(errmsg));
812 pr_warning("failed to alloc program %s (%s): %s",
813 name, obj->path, errmsg);
814 }
b62f06e8
WN
815 } else if (sh.sh_type == SHT_REL) {
816 void *reloc = obj->efile.reloc;
817 int nr_reloc = obj->efile.nr_reloc + 1;
e3d91b0c
JDB
818 int sec = sh.sh_info; /* points to other section */
819
820 /* Only do relo for section with exec instructions */
821 if (!section_have_execinstr(obj, sec)) {
822 pr_debug("skip relo %s(%d) for section(%d)\n",
823 name, idx, sec);
824 continue;
825 }
b62f06e8 826
531b014e
JK
827 reloc = reallocarray(reloc, nr_reloc,
828 sizeof(*obj->efile.reloc));
b62f06e8
WN
829 if (!reloc) {
830 pr_warning("realloc failed\n");
831 err = -ENOMEM;
832 } else {
833 int n = nr_reloc - 1;
834
835 obj->efile.reloc = reloc;
836 obj->efile.nr_reloc = nr_reloc;
837
838 obj->efile.reloc[n].shdr = sh;
839 obj->efile.reloc[n].data = data;
840 }
077c066a
JDB
841 } else {
842 pr_debug("skip section(%d) %s\n", idx, name);
bec7d68c 843 }
cb1e5e96
WN
844 if (err)
845 goto out;
29603665 846 }
561bbcca 847
77ba9a5b
WN
848 if (!obj->efile.strtabidx || obj->efile.strtabidx >= idx) {
849 pr_warning("Corrupted ELF file: index of strtab invalid\n");
850 return LIBBPF_ERRNO__FORMAT;
851 }
88cda1c9 852 if (obj->efile.maps_shndx >= 0) {
4708bbda 853 err = bpf_object__init_maps(obj);
88cda1c9
MKL
854 if (err)
855 goto out;
856 }
857 err = bpf_object__init_prog_names(obj);
29603665
WN
858out:
859 return err;
860}
861
34090915
WN
862static struct bpf_program *
863bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
864{
865 struct bpf_program *prog;
866 size_t i;
867
868 for (i = 0; i < obj->nr_programs; i++) {
869 prog = &obj->programs[i];
870 if (prog->idx == idx)
871 return prog;
872 }
873 return NULL;
874}
875
6d4b198b
JK
876struct bpf_program *
877bpf_object__find_program_by_title(struct bpf_object *obj, const char *title)
878{
879 struct bpf_program *pos;
880
881 bpf_object__for_each_program(pos, obj) {
882 if (pos->section_name && !strcmp(pos->section_name, title))
883 return pos;
884 }
885 return NULL;
886}
887
34090915 888static int
48cca7e4
AS
889bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
890 Elf_Data *data, struct bpf_object *obj)
34090915 891{
48cca7e4
AS
892 Elf_Data *symbols = obj->efile.symbols;
893 int text_shndx = obj->efile.text_shndx;
894 int maps_shndx = obj->efile.maps_shndx;
895 struct bpf_map *maps = obj->maps;
896 size_t nr_maps = obj->nr_maps;
34090915
WN
897 int i, nrels;
898
899 pr_debug("collecting relocating info for: '%s'\n",
900 prog->section_name);
901 nrels = shdr->sh_size / shdr->sh_entsize;
902
903 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
904 if (!prog->reloc_desc) {
905 pr_warning("failed to alloc memory in relocation\n");
906 return -ENOMEM;
907 }
908 prog->nr_reloc = nrels;
909
910 for (i = 0; i < nrels; i++) {
911 GElf_Sym sym;
912 GElf_Rel rel;
913 unsigned int insn_idx;
914 struct bpf_insn *insns = prog->insns;
915 size_t map_idx;
916
917 if (!gelf_getrel(data, i, &rel)) {
918 pr_warning("relocation: failed to get %d reloc\n", i);
6371ca3b 919 return -LIBBPF_ERRNO__FORMAT;
34090915
WN
920 }
921
34090915
WN
922 if (!gelf_getsym(symbols,
923 GELF_R_SYM(rel.r_info),
924 &sym)) {
925 pr_warning("relocation: symbol %"PRIx64" not found\n",
926 GELF_R_SYM(rel.r_info));
6371ca3b 927 return -LIBBPF_ERRNO__FORMAT;
34090915 928 }
7d9890ef
DM
929 pr_debug("relo for %lld value %lld name %d\n",
930 (long long) (rel.r_info >> 32),
931 (long long) sym.st_value, sym.st_name);
34090915 932
48cca7e4 933 if (sym.st_shndx != maps_shndx && sym.st_shndx != text_shndx) {
666810e8
WN
934 pr_warning("Program '%s' contains non-map related relo data pointing to section %u\n",
935 prog->section_name, sym.st_shndx);
936 return -LIBBPF_ERRNO__RELOC;
937 }
938
939 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
940 pr_debug("relocation: insn_idx=%u\n", insn_idx);
941
48cca7e4
AS
942 if (insns[insn_idx].code == (BPF_JMP | BPF_CALL)) {
943 if (insns[insn_idx].src_reg != BPF_PSEUDO_CALL) {
944 pr_warning("incorrect bpf_call opcode\n");
945 return -LIBBPF_ERRNO__RELOC;
946 }
947 prog->reloc_desc[i].type = RELO_CALL;
948 prog->reloc_desc[i].insn_idx = insn_idx;
949 prog->reloc_desc[i].text_off = sym.st_value;
9a94f277 950 obj->has_pseudo_calls = true;
48cca7e4
AS
951 continue;
952 }
953
34090915
WN
954 if (insns[insn_idx].code != (BPF_LD | BPF_IMM | BPF_DW)) {
955 pr_warning("bpf: relocation: invalid relo for insns[%d].code 0x%x\n",
956 insn_idx, insns[insn_idx].code);
6371ca3b 957 return -LIBBPF_ERRNO__RELOC;
34090915
WN
958 }
959
94e5adec
JS
960 /* TODO: 'maps' is sorted. We can use bsearch to make it faster. */
961 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
962 if (maps[map_idx].offset == sym.st_value) {
963 pr_debug("relocation: find map %zd (%s) for insn %u\n",
964 map_idx, maps[map_idx].name, insn_idx);
965 break;
966 }
967 }
968
34090915
WN
969 if (map_idx >= nr_maps) {
970 pr_warning("bpf relocation: map_idx %d large than %d\n",
971 (int)map_idx, (int)nr_maps - 1);
6371ca3b 972 return -LIBBPF_ERRNO__RELOC;
34090915
WN
973 }
974
48cca7e4 975 prog->reloc_desc[i].type = RELO_LD64;
34090915
WN
976 prog->reloc_desc[i].insn_idx = insn_idx;
977 prog->reloc_desc[i].map_idx = map_idx;
978 }
979 return 0;
980}
981
8a138aed
MKL
982static int bpf_map_find_btf_info(struct bpf_map *map, const struct btf *btf)
983{
984 struct bpf_map_def *def = &map->def;
985 const size_t max_name = 256;
986 int64_t key_size, value_size;
987 int32_t key_id, value_id;
988 char name[max_name];
989
990 /* Find key type by name from BTF */
991 if (snprintf(name, max_name, "%s_key", map->name) == max_name) {
992 pr_warning("map:%s length of BTF key_type:%s_key is too long\n",
993 map->name, map->name);
994 return -EINVAL;
995 }
996
997 key_id = btf__find_by_name(btf, name);
998 if (key_id < 0) {
999 pr_debug("map:%s key_type:%s cannot be found in BTF\n",
1000 map->name, name);
1001 return key_id;
1002 }
1003
1004 key_size = btf__resolve_size(btf, key_id);
1005 if (key_size < 0) {
1006 pr_warning("map:%s key_type:%s cannot get the BTF type_size\n",
1007 map->name, name);
1008 return key_size;
1009 }
1010
1011 if (def->key_size != key_size) {
a1c81810
SB
1012 pr_warning("map:%s key_type:%s has BTF type_size:%u != key_size:%u\n",
1013 map->name, name, (unsigned int)key_size, def->key_size);
8a138aed
MKL
1014 return -EINVAL;
1015 }
1016
1017 /* Find value type from BTF */
1018 if (snprintf(name, max_name, "%s_value", map->name) == max_name) {
1019 pr_warning("map:%s length of BTF value_type:%s_value is too long\n",
1020 map->name, map->name);
1021 return -EINVAL;
1022 }
1023
1024 value_id = btf__find_by_name(btf, name);
1025 if (value_id < 0) {
1026 pr_debug("map:%s value_type:%s cannot be found in BTF\n",
1027 map->name, name);
1028 return value_id;
1029 }
1030
1031 value_size = btf__resolve_size(btf, value_id);
1032 if (value_size < 0) {
1033 pr_warning("map:%s value_type:%s cannot get the BTF type_size\n",
1034 map->name, name);
1035 return value_size;
1036 }
1037
1038 if (def->value_size != value_size) {
a1c81810
SB
1039 pr_warning("map:%s value_type:%s has BTF type_size:%u != value_size:%u\n",
1040 map->name, name, (unsigned int)value_size, def->value_size);
8a138aed
MKL
1041 return -EINVAL;
1042 }
1043
61746dbe
MKL
1044 map->btf_key_type_id = key_id;
1045 map->btf_value_type_id = value_id;
8a138aed
MKL
1046
1047 return 0;
1048}
1049
26736eb9
JK
1050int bpf_map__reuse_fd(struct bpf_map *map, int fd)
1051{
1052 struct bpf_map_info info = {};
1053 __u32 len = sizeof(info);
1054 int new_fd, err;
1055 char *new_name;
1056
1057 err = bpf_obj_get_info_by_fd(fd, &info, &len);
1058 if (err)
1059 return err;
1060
1061 new_name = strdup(info.name);
1062 if (!new_name)
1063 return -errno;
1064
1065 new_fd = open("/", O_RDONLY | O_CLOEXEC);
1066 if (new_fd < 0)
1067 goto err_free_new_name;
1068
1069 new_fd = dup3(fd, new_fd, O_CLOEXEC);
1070 if (new_fd < 0)
1071 goto err_close_new_fd;
1072
1073 err = zclose(map->fd);
1074 if (err)
1075 goto err_close_new_fd;
1076 free(map->name);
1077
1078 map->fd = new_fd;
1079 map->name = new_name;
1080 map->def.type = info.type;
1081 map->def.key_size = info.key_size;
1082 map->def.value_size = info.value_size;
1083 map->def.max_entries = info.max_entries;
1084 map->def.map_flags = info.map_flags;
1085 map->btf_key_type_id = info.btf_key_type_id;
1086 map->btf_value_type_id = info.btf_value_type_id;
1087
1088 return 0;
1089
1090err_close_new_fd:
1091 close(new_fd);
1092err_free_new_name:
1093 free(new_name);
1094 return -errno;
1095}
1096
52d3352e
WN
1097static int
1098bpf_object__create_maps(struct bpf_object *obj)
1099{
8a138aed 1100 struct bpf_create_map_attr create_attr = {};
52d3352e 1101 unsigned int i;
8a138aed 1102 int err;
52d3352e 1103
9d759a9b 1104 for (i = 0; i < obj->nr_maps; i++) {
8a138aed
MKL
1105 struct bpf_map *map = &obj->maps[i];
1106 struct bpf_map_def *def = &map->def;
1107 int *pfd = &map->fd;
1108
26736eb9
JK
1109 if (map->fd >= 0) {
1110 pr_debug("skip map create (preset) %s: fd=%d\n",
1111 map->name, map->fd);
1112 continue;
1113 }
1114
8a138aed 1115 create_attr.name = map->name;
f0307a7e 1116 create_attr.map_ifindex = map->map_ifindex;
8a138aed
MKL
1117 create_attr.map_type = def->type;
1118 create_attr.map_flags = def->map_flags;
1119 create_attr.key_size = def->key_size;
1120 create_attr.value_size = def->value_size;
1121 create_attr.max_entries = def->max_entries;
1122 create_attr.btf_fd = 0;
61746dbe
MKL
1123 create_attr.btf_key_type_id = 0;
1124 create_attr.btf_value_type_id = 0;
8a138aed
MKL
1125
1126 if (obj->btf && !bpf_map_find_btf_info(map, obj->btf)) {
1127 create_attr.btf_fd = btf__fd(obj->btf);
61746dbe
MKL
1128 create_attr.btf_key_type_id = map->btf_key_type_id;
1129 create_attr.btf_value_type_id = map->btf_value_type_id;
8a138aed
MKL
1130 }
1131
1132 *pfd = bpf_create_map_xattr(&create_attr);
61746dbe 1133 if (*pfd < 0 && create_attr.btf_key_type_id) {
8a138aed
MKL
1134 pr_warning("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
1135 map->name, strerror(errno), errno);
1136 create_attr.btf_fd = 0;
61746dbe
MKL
1137 create_attr.btf_key_type_id = 0;
1138 create_attr.btf_value_type_id = 0;
1139 map->btf_key_type_id = 0;
1140 map->btf_value_type_id = 0;
8a138aed
MKL
1141 *pfd = bpf_create_map_xattr(&create_attr);
1142 }
1143
52d3352e
WN
1144 if (*pfd < 0) {
1145 size_t j;
52d3352e 1146
8a138aed 1147 err = *pfd;
49bf4b36 1148 pr_warning("failed to create map (name: '%s'): %s\n",
8a138aed 1149 map->name,
52d3352e
WN
1150 strerror(errno));
1151 for (j = 0; j < i; j++)
9d759a9b 1152 zclose(obj->maps[j].fd);
52d3352e
WN
1153 return err;
1154 }
8a138aed 1155 pr_debug("create map %s: fd=%d\n", map->name, *pfd);
52d3352e
WN
1156 }
1157
52d3352e
WN
1158 return 0;
1159}
1160
48cca7e4
AS
1161static int
1162bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
1163 struct reloc_desc *relo)
1164{
1165 struct bpf_insn *insn, *new_insn;
1166 struct bpf_program *text;
1167 size_t new_cnt;
1168
1169 if (relo->type != RELO_CALL)
1170 return -LIBBPF_ERRNO__RELOC;
1171
1172 if (prog->idx == obj->efile.text_shndx) {
1173 pr_warning("relo in .text insn %d into off %d\n",
1174 relo->insn_idx, relo->text_off);
1175 return -LIBBPF_ERRNO__RELOC;
1176 }
1177
1178 if (prog->main_prog_cnt == 0) {
1179 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
1180 if (!text) {
1181 pr_warning("no .text section found yet relo into text exist\n");
1182 return -LIBBPF_ERRNO__RELOC;
1183 }
1184 new_cnt = prog->insns_cnt + text->insns_cnt;
531b014e 1185 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
48cca7e4
AS
1186 if (!new_insn) {
1187 pr_warning("oom in prog realloc\n");
1188 return -ENOMEM;
1189 }
1190 memcpy(new_insn + prog->insns_cnt, text->insns,
1191 text->insns_cnt * sizeof(*insn));
1192 prog->insns = new_insn;
1193 prog->main_prog_cnt = prog->insns_cnt;
1194 prog->insns_cnt = new_cnt;
b1a2ce82
JC
1195 pr_debug("added %zd insn from %s to prog %s\n",
1196 text->insns_cnt, text->section_name,
1197 prog->section_name);
48cca7e4
AS
1198 }
1199 insn = &prog->insns[relo->insn_idx];
1200 insn->imm += prog->main_prog_cnt - relo->insn_idx;
48cca7e4
AS
1201 return 0;
1202}
1203
8a47a6c5 1204static int
9d759a9b 1205bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
8a47a6c5 1206{
48cca7e4 1207 int i, err;
8a47a6c5
WN
1208
1209 if (!prog || !prog->reloc_desc)
1210 return 0;
1211
1212 for (i = 0; i < prog->nr_reloc; i++) {
48cca7e4
AS
1213 if (prog->reloc_desc[i].type == RELO_LD64) {
1214 struct bpf_insn *insns = prog->insns;
1215 int insn_idx, map_idx;
8a47a6c5 1216
48cca7e4
AS
1217 insn_idx = prog->reloc_desc[i].insn_idx;
1218 map_idx = prog->reloc_desc[i].map_idx;
8a47a6c5 1219
48cca7e4
AS
1220 if (insn_idx >= (int)prog->insns_cnt) {
1221 pr_warning("relocation out of range: '%s'\n",
1222 prog->section_name);
1223 return -LIBBPF_ERRNO__RELOC;
1224 }
1225 insns[insn_idx].src_reg = BPF_PSEUDO_MAP_FD;
1226 insns[insn_idx].imm = obj->maps[map_idx].fd;
1227 } else {
1228 err = bpf_program__reloc_text(prog, obj,
1229 &prog->reloc_desc[i]);
1230 if (err)
1231 return err;
8a47a6c5 1232 }
8a47a6c5
WN
1233 }
1234
1235 zfree(&prog->reloc_desc);
1236 prog->nr_reloc = 0;
1237 return 0;
1238}
1239
1240
1241static int
1242bpf_object__relocate(struct bpf_object *obj)
1243{
1244 struct bpf_program *prog;
1245 size_t i;
1246 int err;
1247
1248 for (i = 0; i < obj->nr_programs; i++) {
1249 prog = &obj->programs[i];
1250
9d759a9b 1251 err = bpf_program__relocate(prog, obj);
8a47a6c5
WN
1252 if (err) {
1253 pr_warning("failed to relocate '%s'\n",
1254 prog->section_name);
1255 return err;
1256 }
1257 }
1258 return 0;
1259}
1260
34090915
WN
1261static int bpf_object__collect_reloc(struct bpf_object *obj)
1262{
1263 int i, err;
1264
1265 if (!obj_elf_valid(obj)) {
1266 pr_warning("Internal error: elf object is closed\n");
6371ca3b 1267 return -LIBBPF_ERRNO__INTERNAL;
34090915
WN
1268 }
1269
1270 for (i = 0; i < obj->efile.nr_reloc; i++) {
1271 GElf_Shdr *shdr = &obj->efile.reloc[i].shdr;
1272 Elf_Data *data = obj->efile.reloc[i].data;
1273 int idx = shdr->sh_info;
1274 struct bpf_program *prog;
34090915
WN
1275
1276 if (shdr->sh_type != SHT_REL) {
1277 pr_warning("internal error at %d\n", __LINE__);
6371ca3b 1278 return -LIBBPF_ERRNO__INTERNAL;
34090915
WN
1279 }
1280
1281 prog = bpf_object__find_prog_by_idx(obj, idx);
1282 if (!prog) {
077c066a 1283 pr_warning("relocation failed: no section(%d)\n", idx);
6371ca3b 1284 return -LIBBPF_ERRNO__RELOC;
34090915
WN
1285 }
1286
48cca7e4 1287 err = bpf_program__collect_reloc(prog,
34090915 1288 shdr, data,
48cca7e4 1289 obj);
34090915 1290 if (err)
6371ca3b 1291 return err;
34090915
WN
1292 }
1293 return 0;
1294}
1295
55cffde2 1296static int
d7be143b
AI
1297load_program(enum bpf_prog_type type, enum bpf_attach_type expected_attach_type,
1298 const char *name, struct bpf_insn *insns, int insns_cnt,
f0307a7e 1299 char *license, u32 kern_version, int *pfd, int prog_ifindex)
55cffde2 1300{
d7be143b 1301 struct bpf_load_program_attr load_attr;
55cffde2 1302 char *log_buf;
d7be143b 1303 int ret;
55cffde2 1304
d7be143b
AI
1305 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
1306 load_attr.prog_type = type;
1307 load_attr.expected_attach_type = expected_attach_type;
1308 load_attr.name = name;
1309 load_attr.insns = insns;
1310 load_attr.insns_cnt = insns_cnt;
1311 load_attr.license = license;
1312 load_attr.kern_version = kern_version;
f0307a7e 1313 load_attr.prog_ifindex = prog_ifindex;
d7be143b
AI
1314
1315 if (!load_attr.insns || !load_attr.insns_cnt)
55cffde2
WN
1316 return -EINVAL;
1317
1318 log_buf = malloc(BPF_LOG_BUF_SIZE);
1319 if (!log_buf)
1320 pr_warning("Alloc log buffer for bpf loader error, continue without log\n");
1321
d7be143b 1322 ret = bpf_load_program_xattr(&load_attr, log_buf, BPF_LOG_BUF_SIZE);
55cffde2
WN
1323
1324 if (ret >= 0) {
1325 *pfd = ret;
1326 ret = 0;
1327 goto out;
1328 }
1329
6371ca3b 1330 ret = -LIBBPF_ERRNO__LOAD;
55cffde2
WN
1331 pr_warning("load bpf program failed: %s\n", strerror(errno));
1332
6371ca3b
WN
1333 if (log_buf && log_buf[0] != '\0') {
1334 ret = -LIBBPF_ERRNO__VERIFY;
55cffde2
WN
1335 pr_warning("-- BEGIN DUMP LOG ---\n");
1336 pr_warning("\n%s\n", log_buf);
1337 pr_warning("-- END LOG --\n");
d7be143b
AI
1338 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
1339 pr_warning("Program too large (%zu insns), at most %d insns\n",
1340 load_attr.insns_cnt, BPF_MAXINSNS);
705fa219 1341 ret = -LIBBPF_ERRNO__PROG2BIG;
6371ca3b 1342 } else {
705fa219 1343 /* Wrong program type? */
d7be143b 1344 if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
705fa219
WN
1345 int fd;
1346
d7be143b
AI
1347 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
1348 load_attr.expected_attach_type = 0;
1349 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
705fa219
WN
1350 if (fd >= 0) {
1351 close(fd);
1352 ret = -LIBBPF_ERRNO__PROGTYPE;
1353 goto out;
1354 }
6371ca3b 1355 }
705fa219
WN
1356
1357 if (log_buf)
1358 ret = -LIBBPF_ERRNO__KVER;
55cffde2
WN
1359 }
1360
1361out:
1362 free(log_buf);
1363 return ret;
1364}
1365
1366static int
1367bpf_program__load(struct bpf_program *prog,
1368 char *license, u32 kern_version)
1369{
b580563e 1370 int err = 0, fd, i;
55cffde2 1371
b580563e
WN
1372 if (prog->instances.nr < 0 || !prog->instances.fds) {
1373 if (prog->preprocessor) {
1374 pr_warning("Internal error: can't load program '%s'\n",
1375 prog->section_name);
1376 return -LIBBPF_ERRNO__INTERNAL;
1377 }
55cffde2 1378
b580563e
WN
1379 prog->instances.fds = malloc(sizeof(int));
1380 if (!prog->instances.fds) {
1381 pr_warning("Not enough memory for BPF fds\n");
1382 return -ENOMEM;
1383 }
1384 prog->instances.nr = 1;
1385 prog->instances.fds[0] = -1;
1386 }
1387
1388 if (!prog->preprocessor) {
1389 if (prog->instances.nr != 1) {
1390 pr_warning("Program '%s' is inconsistent: nr(%d) != 1\n",
1391 prog->section_name, prog->instances.nr);
1392 }
d7be143b
AI
1393 err = load_program(prog->type, prog->expected_attach_type,
1394 prog->name, prog->insns, prog->insns_cnt,
f0307a7e
DB
1395 license, kern_version, &fd,
1396 prog->prog_ifindex);
b580563e
WN
1397 if (!err)
1398 prog->instances.fds[0] = fd;
1399 goto out;
1400 }
1401
1402 for (i = 0; i < prog->instances.nr; i++) {
1403 struct bpf_prog_prep_result result;
1404 bpf_program_prep_t preprocessor = prog->preprocessor;
1405
1406 bzero(&result, sizeof(result));
1407 err = preprocessor(prog, i, prog->insns,
1408 prog->insns_cnt, &result);
1409 if (err) {
1410 pr_warning("Preprocessing the %dth instance of program '%s' failed\n",
1411 i, prog->section_name);
1412 goto out;
1413 }
1414
1415 if (!result.new_insn_ptr || !result.new_insn_cnt) {
1416 pr_debug("Skip loading the %dth instance of program '%s'\n",
1417 i, prog->section_name);
1418 prog->instances.fds[i] = -1;
1419 if (result.pfd)
1420 *result.pfd = -1;
1421 continue;
1422 }
1423
d7be143b
AI
1424 err = load_program(prog->type, prog->expected_attach_type,
1425 prog->name, result.new_insn_ptr,
b580563e 1426 result.new_insn_cnt,
f0307a7e
DB
1427 license, kern_version, &fd,
1428 prog->prog_ifindex);
b580563e
WN
1429
1430 if (err) {
1431 pr_warning("Loading the %dth instance of program '%s' failed\n",
1432 i, prog->section_name);
1433 goto out;
1434 }
1435
1436 if (result.pfd)
1437 *result.pfd = fd;
1438 prog->instances.fds[i] = fd;
1439 }
1440out:
55cffde2
WN
1441 if (err)
1442 pr_warning("failed to load program '%s'\n",
1443 prog->section_name);
1444 zfree(&prog->insns);
1445 prog->insns_cnt = 0;
1446 return err;
1447}
1448
9a94f277
JK
1449static bool bpf_program__is_function_storage(struct bpf_program *prog,
1450 struct bpf_object *obj)
1451{
1452 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
1453}
1454
55cffde2
WN
1455static int
1456bpf_object__load_progs(struct bpf_object *obj)
1457{
1458 size_t i;
1459 int err;
1460
1461 for (i = 0; i < obj->nr_programs; i++) {
9a94f277 1462 if (bpf_program__is_function_storage(&obj->programs[i], obj))
48cca7e4 1463 continue;
55cffde2
WN
1464 err = bpf_program__load(&obj->programs[i],
1465 obj->license,
1466 obj->kern_version);
1467 if (err)
1468 return err;
1469 }
1470 return 0;
1471}
1472
17387dd5
JK
1473static bool bpf_prog_type__needs_kver(enum bpf_prog_type type)
1474{
1475 switch (type) {
1476 case BPF_PROG_TYPE_SOCKET_FILTER:
1477 case BPF_PROG_TYPE_SCHED_CLS:
1478 case BPF_PROG_TYPE_SCHED_ACT:
1479 case BPF_PROG_TYPE_XDP:
1480 case BPF_PROG_TYPE_CGROUP_SKB:
1481 case BPF_PROG_TYPE_CGROUP_SOCK:
1482 case BPF_PROG_TYPE_LWT_IN:
1483 case BPF_PROG_TYPE_LWT_OUT:
1484 case BPF_PROG_TYPE_LWT_XMIT:
004d4b27 1485 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
17387dd5
JK
1486 case BPF_PROG_TYPE_SOCK_OPS:
1487 case BPF_PROG_TYPE_SK_SKB:
1488 case BPF_PROG_TYPE_CGROUP_DEVICE:
1489 case BPF_PROG_TYPE_SK_MSG:
1490 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
6bdd533c 1491 case BPF_PROG_TYPE_LIRC_MODE2:
17387dd5
JK
1492 return false;
1493 case BPF_PROG_TYPE_UNSPEC:
1494 case BPF_PROG_TYPE_KPROBE:
1495 case BPF_PROG_TYPE_TRACEPOINT:
1496 case BPF_PROG_TYPE_PERF_EVENT:
1497 case BPF_PROG_TYPE_RAW_TRACEPOINT:
1498 default:
1499 return true;
1500 }
1501}
1502
1503static int bpf_object__validate(struct bpf_object *obj, bool needs_kver)
cb1e5e96 1504{
17387dd5 1505 if (needs_kver && obj->kern_version == 0) {
cb1e5e96
WN
1506 pr_warning("%s doesn't provide kernel version\n",
1507 obj->path);
6371ca3b 1508 return -LIBBPF_ERRNO__KVERSION;
cb1e5e96
WN
1509 }
1510 return 0;
1511}
1512
1a5e3fb1 1513static struct bpf_object *
17387dd5
JK
1514__bpf_object__open(const char *path, void *obj_buf, size_t obj_buf_sz,
1515 bool needs_kver)
1a5e3fb1
WN
1516{
1517 struct bpf_object *obj;
6371ca3b 1518 int err;
1a5e3fb1
WN
1519
1520 if (elf_version(EV_CURRENT) == EV_NONE) {
1521 pr_warning("failed to init libelf for %s\n", path);
6371ca3b 1522 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1a5e3fb1
WN
1523 }
1524
6c956392 1525 obj = bpf_object__new(path, obj_buf, obj_buf_sz);
6371ca3b
WN
1526 if (IS_ERR(obj))
1527 return obj;
1a5e3fb1 1528
6371ca3b
WN
1529 CHECK_ERR(bpf_object__elf_init(obj), err, out);
1530 CHECK_ERR(bpf_object__check_endianness(obj), err, out);
1531 CHECK_ERR(bpf_object__elf_collect(obj), err, out);
1532 CHECK_ERR(bpf_object__collect_reloc(obj), err, out);
17387dd5 1533 CHECK_ERR(bpf_object__validate(obj, needs_kver), err, out);
1a5e3fb1
WN
1534
1535 bpf_object__elf_finish(obj);
1536 return obj;
1537out:
1538 bpf_object__close(obj);
6371ca3b 1539 return ERR_PTR(err);
1a5e3fb1
WN
1540}
1541
07f2d4ea 1542struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
1a5e3fb1
WN
1543{
1544 /* param validation */
07f2d4ea 1545 if (!attr->file)
1a5e3fb1
WN
1546 return NULL;
1547
07f2d4ea
JK
1548 pr_debug("loading %s\n", attr->file);
1549
1550 return __bpf_object__open(attr->file, NULL, 0,
1551 bpf_prog_type__needs_kver(attr->prog_type));
1552}
1553
1554struct bpf_object *bpf_object__open(const char *path)
1555{
1556 struct bpf_object_open_attr attr = {
1557 .file = path,
1558 .prog_type = BPF_PROG_TYPE_UNSPEC,
1559 };
1a5e3fb1 1560
07f2d4ea 1561 return bpf_object__open_xattr(&attr);
6c956392
WN
1562}
1563
1564struct bpf_object *bpf_object__open_buffer(void *obj_buf,
acf860ae
WN
1565 size_t obj_buf_sz,
1566 const char *name)
6c956392 1567{
acf860ae
WN
1568 char tmp_name[64];
1569
6c956392
WN
1570 /* param validation */
1571 if (!obj_buf || obj_buf_sz <= 0)
1572 return NULL;
1573
acf860ae
WN
1574 if (!name) {
1575 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
1576 (unsigned long)obj_buf,
1577 (unsigned long)obj_buf_sz);
1578 tmp_name[sizeof(tmp_name) - 1] = '\0';
1579 name = tmp_name;
1580 }
1581 pr_debug("loading object '%s' from buffer\n",
1582 name);
6c956392 1583
17387dd5 1584 return __bpf_object__open(name, obj_buf, obj_buf_sz, true);
1a5e3fb1
WN
1585}
1586
52d3352e
WN
1587int bpf_object__unload(struct bpf_object *obj)
1588{
1589 size_t i;
1590
1591 if (!obj)
1592 return -EINVAL;
1593
9d759a9b
WN
1594 for (i = 0; i < obj->nr_maps; i++)
1595 zclose(obj->maps[i].fd);
52d3352e 1596
55cffde2
WN
1597 for (i = 0; i < obj->nr_programs; i++)
1598 bpf_program__unload(&obj->programs[i]);
1599
52d3352e
WN
1600 return 0;
1601}
1602
1603int bpf_object__load(struct bpf_object *obj)
1604{
6371ca3b
WN
1605 int err;
1606
52d3352e
WN
1607 if (!obj)
1608 return -EINVAL;
1609
1610 if (obj->loaded) {
1611 pr_warning("object should not be loaded twice\n");
1612 return -EINVAL;
1613 }
1614
1615 obj->loaded = true;
6371ca3b
WN
1616
1617 CHECK_ERR(bpf_object__create_maps(obj), err, out);
1618 CHECK_ERR(bpf_object__relocate(obj), err, out);
1619 CHECK_ERR(bpf_object__load_progs(obj), err, out);
52d3352e
WN
1620
1621 return 0;
1622out:
1623 bpf_object__unload(obj);
1624 pr_warning("failed to load object '%s'\n", obj->path);
6371ca3b 1625 return err;
52d3352e
WN
1626}
1627
f367540c
JS
1628static int check_path(const char *path)
1629{
1630 struct statfs st_fs;
1631 char *dname, *dir;
1632 int err = 0;
1633
1634 if (path == NULL)
1635 return -EINVAL;
1636
1637 dname = strdup(path);
1638 if (dname == NULL)
1639 return -ENOMEM;
1640
1641 dir = dirname(dname);
1642 if (statfs(dir, &st_fs)) {
1643 pr_warning("failed to statfs %s: %s\n", dir, strerror(errno));
1644 err = -errno;
1645 }
1646 free(dname);
1647
1648 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
1649 pr_warning("specified path %s is not on BPF FS\n", path);
1650 err = -EINVAL;
1651 }
1652
1653 return err;
1654}
1655
1656int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
1657 int instance)
1658{
1659 int err;
1660
1661 err = check_path(path);
1662 if (err)
1663 return err;
1664
1665 if (prog == NULL) {
1666 pr_warning("invalid program pointer\n");
1667 return -EINVAL;
1668 }
1669
1670 if (instance < 0 || instance >= prog->instances.nr) {
1671 pr_warning("invalid prog instance %d of prog %s (max %d)\n",
1672 instance, prog->section_name, prog->instances.nr);
1673 return -EINVAL;
1674 }
1675
1676 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
1677 pr_warning("failed to pin program: %s\n", strerror(errno));
1678 return -errno;
1679 }
1680 pr_debug("pinned program '%s'\n", path);
1681
1682 return 0;
1683}
1684
1685static int make_dir(const char *path)
1686{
1687 int err = 0;
1688
1689 if (mkdir(path, 0700) && errno != EEXIST)
1690 err = -errno;
1691
1692 if (err)
1693 pr_warning("failed to mkdir %s: %s\n", path, strerror(-err));
1694 return err;
1695}
1696
1697int bpf_program__pin(struct bpf_program *prog, const char *path)
1698{
1699 int i, err;
1700
1701 err = check_path(path);
1702 if (err)
1703 return err;
1704
1705 if (prog == NULL) {
1706 pr_warning("invalid program pointer\n");
1707 return -EINVAL;
1708 }
1709
1710 if (prog->instances.nr <= 0) {
1711 pr_warning("no instances of prog %s to pin\n",
1712 prog->section_name);
1713 return -EINVAL;
1714 }
1715
1716 err = make_dir(path);
1717 if (err)
1718 return err;
1719
1720 for (i = 0; i < prog->instances.nr; i++) {
1721 char buf[PATH_MAX];
1722 int len;
1723
1724 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
1725 if (len < 0)
1726 return -EINVAL;
1727 else if (len >= PATH_MAX)
1728 return -ENAMETOOLONG;
1729
1730 err = bpf_program__pin_instance(prog, buf, i);
1731 if (err)
1732 return err;
1733 }
1734
1735 return 0;
1736}
1737
b6989f35
JS
1738int bpf_map__pin(struct bpf_map *map, const char *path)
1739{
1740 int err;
1741
1742 err = check_path(path);
1743 if (err)
1744 return err;
1745
1746 if (map == NULL) {
1747 pr_warning("invalid map pointer\n");
1748 return -EINVAL;
1749 }
1750
1751 if (bpf_obj_pin(map->fd, path)) {
1752 pr_warning("failed to pin map: %s\n", strerror(errno));
1753 return -errno;
1754 }
1755
1756 pr_debug("pinned map '%s'\n", path);
1757 return 0;
1758}
1759
d5148d85
JS
1760int bpf_object__pin(struct bpf_object *obj, const char *path)
1761{
1762 struct bpf_program *prog;
1763 struct bpf_map *map;
1764 int err;
1765
1766 if (!obj)
1767 return -ENOENT;
1768
1769 if (!obj->loaded) {
1770 pr_warning("object not yet loaded; load it first\n");
1771 return -ENOENT;
1772 }
1773
1774 err = make_dir(path);
1775 if (err)
1776 return err;
1777
1778 bpf_map__for_each(map, obj) {
1779 char buf[PATH_MAX];
1780 int len;
1781
1782 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1783 bpf_map__name(map));
1784 if (len < 0)
1785 return -EINVAL;
1786 else if (len >= PATH_MAX)
1787 return -ENAMETOOLONG;
1788
1789 err = bpf_map__pin(map, buf);
1790 if (err)
1791 return err;
1792 }
1793
1794 bpf_object__for_each_program(prog, obj) {
1795 char buf[PATH_MAX];
1796 int len;
1797
1798 len = snprintf(buf, PATH_MAX, "%s/%s", path,
1799 prog->section_name);
1800 if (len < 0)
1801 return -EINVAL;
1802 else if (len >= PATH_MAX)
1803 return -ENAMETOOLONG;
1804
1805 err = bpf_program__pin(prog, buf);
1806 if (err)
1807 return err;
1808 }
1809
1810 return 0;
1811}
1812
1a5e3fb1
WN
1813void bpf_object__close(struct bpf_object *obj)
1814{
a5b8bd47
WN
1815 size_t i;
1816
1a5e3fb1
WN
1817 if (!obj)
1818 return;
1819
10931d24
WN
1820 if (obj->clear_priv)
1821 obj->clear_priv(obj, obj->priv);
1822
1a5e3fb1 1823 bpf_object__elf_finish(obj);
52d3352e 1824 bpf_object__unload(obj);
8a138aed 1825 btf__free(obj->btf);
1a5e3fb1 1826
9d759a9b 1827 for (i = 0; i < obj->nr_maps; i++) {
561bbcca 1828 zfree(&obj->maps[i].name);
9d759a9b
WN
1829 if (obj->maps[i].clear_priv)
1830 obj->maps[i].clear_priv(&obj->maps[i],
1831 obj->maps[i].priv);
1832 obj->maps[i].priv = NULL;
1833 obj->maps[i].clear_priv = NULL;
1834 }
1835 zfree(&obj->maps);
1836 obj->nr_maps = 0;
a5b8bd47
WN
1837
1838 if (obj->programs && obj->nr_programs) {
1839 for (i = 0; i < obj->nr_programs; i++)
1840 bpf_program__exit(&obj->programs[i]);
1841 }
1842 zfree(&obj->programs);
1843
9a208eff 1844 list_del(&obj->list);
1a5e3fb1
WN
1845 free(obj);
1846}
aa9b1ac3 1847
9a208eff
WN
1848struct bpf_object *
1849bpf_object__next(struct bpf_object *prev)
1850{
1851 struct bpf_object *next;
1852
1853 if (!prev)
1854 next = list_first_entry(&bpf_objects_list,
1855 struct bpf_object,
1856 list);
1857 else
1858 next = list_next_entry(prev, list);
1859
1860 /* Empty list is noticed here so don't need checking on entry. */
1861 if (&next->list == &bpf_objects_list)
1862 return NULL;
1863
1864 return next;
1865}
1866
a7fe0450 1867const char *bpf_object__name(struct bpf_object *obj)
acf860ae 1868{
a7fe0450 1869 return obj ? obj->path : ERR_PTR(-EINVAL);
acf860ae
WN
1870}
1871
a7fe0450 1872unsigned int bpf_object__kversion(struct bpf_object *obj)
45825d8a 1873{
a7fe0450 1874 return obj ? obj->kern_version : 0;
45825d8a
WN
1875}
1876
8a138aed
MKL
1877int bpf_object__btf_fd(const struct bpf_object *obj)
1878{
1879 return obj->btf ? btf__fd(obj->btf) : -1;
1880}
1881
10931d24
WN
1882int bpf_object__set_priv(struct bpf_object *obj, void *priv,
1883 bpf_object_clear_priv_t clear_priv)
1884{
1885 if (obj->priv && obj->clear_priv)
1886 obj->clear_priv(obj, obj->priv);
1887
1888 obj->priv = priv;
1889 obj->clear_priv = clear_priv;
1890 return 0;
1891}
1892
1893void *bpf_object__priv(struct bpf_object *obj)
1894{
1895 return obj ? obj->priv : ERR_PTR(-EINVAL);
1896}
1897
eac7d845
JK
1898static struct bpf_program *
1899__bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
aa9b1ac3
WN
1900{
1901 size_t idx;
1902
1903 if (!obj->programs)
1904 return NULL;
1905 /* First handler */
1906 if (prev == NULL)
1907 return &obj->programs[0];
1908
1909 if (prev->obj != obj) {
1910 pr_warning("error: program handler doesn't match object\n");
1911 return NULL;
1912 }
1913
1914 idx = (prev - obj->programs) + 1;
1915 if (idx >= obj->nr_programs)
1916 return NULL;
1917 return &obj->programs[idx];
1918}
1919
eac7d845
JK
1920struct bpf_program *
1921bpf_program__next(struct bpf_program *prev, struct bpf_object *obj)
1922{
1923 struct bpf_program *prog = prev;
1924
1925 do {
1926 prog = __bpf_program__next(prog, obj);
1927 } while (prog && bpf_program__is_function_storage(prog, obj));
1928
1929 return prog;
1930}
1931
edb13ed4
ACM
1932int bpf_program__set_priv(struct bpf_program *prog, void *priv,
1933 bpf_program_clear_priv_t clear_priv)
aa9b1ac3
WN
1934{
1935 if (prog->priv && prog->clear_priv)
1936 prog->clear_priv(prog, prog->priv);
1937
1938 prog->priv = priv;
1939 prog->clear_priv = clear_priv;
1940 return 0;
1941}
1942
be834ffb 1943void *bpf_program__priv(struct bpf_program *prog)
aa9b1ac3 1944{
be834ffb 1945 return prog ? prog->priv : ERR_PTR(-EINVAL);
aa9b1ac3
WN
1946}
1947
9aba3613
JK
1948void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
1949{
1950 prog->prog_ifindex = ifindex;
1951}
1952
715f8db9 1953const char *bpf_program__title(struct bpf_program *prog, bool needs_copy)
aa9b1ac3
WN
1954{
1955 const char *title;
1956
1957 title = prog->section_name;
715f8db9 1958 if (needs_copy) {
aa9b1ac3
WN
1959 title = strdup(title);
1960 if (!title) {
1961 pr_warning("failed to strdup program title\n");
6371ca3b 1962 return ERR_PTR(-ENOMEM);
aa9b1ac3
WN
1963 }
1964 }
1965
1966 return title;
1967}
1968
1969int bpf_program__fd(struct bpf_program *prog)
1970{
b580563e
WN
1971 return bpf_program__nth_fd(prog, 0);
1972}
1973
1974int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
1975 bpf_program_prep_t prep)
1976{
1977 int *instances_fds;
1978
1979 if (nr_instances <= 0 || !prep)
1980 return -EINVAL;
1981
1982 if (prog->instances.nr > 0 || prog->instances.fds) {
1983 pr_warning("Can't set pre-processor after loading\n");
1984 return -EINVAL;
1985 }
1986
1987 instances_fds = malloc(sizeof(int) * nr_instances);
1988 if (!instances_fds) {
1989 pr_warning("alloc memory failed for fds\n");
1990 return -ENOMEM;
1991 }
1992
1993 /* fill all fd with -1 */
1994 memset(instances_fds, -1, sizeof(int) * nr_instances);
1995
1996 prog->instances.nr = nr_instances;
1997 prog->instances.fds = instances_fds;
1998 prog->preprocessor = prep;
1999 return 0;
2000}
2001
2002int bpf_program__nth_fd(struct bpf_program *prog, int n)
2003{
2004 int fd;
2005
1e960043
JK
2006 if (!prog)
2007 return -EINVAL;
2008
b580563e
WN
2009 if (n >= prog->instances.nr || n < 0) {
2010 pr_warning("Can't get the %dth fd from program %s: only %d instances\n",
2011 n, prog->section_name, prog->instances.nr);
2012 return -EINVAL;
2013 }
2014
2015 fd = prog->instances.fds[n];
2016 if (fd < 0) {
2017 pr_warning("%dth instance of program '%s' is invalid\n",
2018 n, prog->section_name);
2019 return -ENOENT;
2020 }
2021
2022 return fd;
aa9b1ac3 2023}
9d759a9b 2024
dd26b7f5 2025void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5f44e4c8
WN
2026{
2027 prog->type = type;
2028}
2029
5f44e4c8
WN
2030static bool bpf_program__is_type(struct bpf_program *prog,
2031 enum bpf_prog_type type)
2032{
2033 return prog ? (prog->type == type) : false;
2034}
2035
ed794073
JS
2036#define BPF_PROG_TYPE_FNS(NAME, TYPE) \
2037int bpf_program__set_##NAME(struct bpf_program *prog) \
2038{ \
2039 if (!prog) \
2040 return -EINVAL; \
2041 bpf_program__set_type(prog, TYPE); \
2042 return 0; \
2043} \
2044 \
2045bool bpf_program__is_##NAME(struct bpf_program *prog) \
2046{ \
2047 return bpf_program__is_type(prog, TYPE); \
2048} \
2049
7803ba73 2050BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
ed794073 2051BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7803ba73
JS
2052BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
2053BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
ed794073 2054BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
e14c93fd 2055BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7803ba73
JS
2056BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
2057BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
5f44e4c8 2058
16962b24
JF
2059void bpf_program__set_expected_attach_type(struct bpf_program *prog,
2060 enum bpf_attach_type type)
d7be143b
AI
2061{
2062 prog->expected_attach_type = type;
2063}
2064
2065#define BPF_PROG_SEC_FULL(string, ptype, atype) \
2066 { string, sizeof(string) - 1, ptype, atype }
2067
2068#define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_FULL(string, ptype, 0)
2069
81efee75
AI
2070#define BPF_S_PROG_SEC(string, ptype) \
2071 BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK, ptype)
2072
e50b0a6f
AI
2073#define BPF_SA_PROG_SEC(string, ptype) \
2074 BPF_PROG_SEC_FULL(string, BPF_PROG_TYPE_CGROUP_SOCK_ADDR, ptype)
2075
583c9009
RG
2076static const struct {
2077 const char *sec;
2078 size_t len;
2079 enum bpf_prog_type prog_type;
d7be143b 2080 enum bpf_attach_type expected_attach_type;
583c9009
RG
2081} section_names[] = {
2082 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
2083 BPF_PROG_SEC("kprobe/", BPF_PROG_TYPE_KPROBE),
2084 BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
0badd331
QM
2085 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
2086 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
583c9009 2087 BPF_PROG_SEC("tracepoint/", BPF_PROG_TYPE_TRACEPOINT),
e14c93fd 2088 BPF_PROG_SEC("raw_tracepoint/", BPF_PROG_TYPE_RAW_TRACEPOINT),
583c9009
RG
2089 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
2090 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
2091 BPF_PROG_SEC("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
2092 BPF_PROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK),
2093 BPF_PROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE),
0badd331
QM
2094 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
2095 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
2096 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
d9b683d7 2097 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
583c9009
RG
2098 BPF_PROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS),
2099 BPF_PROG_SEC("sk_skb", BPF_PROG_TYPE_SK_SKB),
4c4c3c27 2100 BPF_PROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG),
d9b683d7 2101 BPF_PROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2),
e50b0a6f
AI
2102 BPF_SA_PROG_SEC("cgroup/bind4", BPF_CGROUP_INET4_BIND),
2103 BPF_SA_PROG_SEC("cgroup/bind6", BPF_CGROUP_INET6_BIND),
622adafb
AI
2104 BPF_SA_PROG_SEC("cgroup/connect4", BPF_CGROUP_INET4_CONNECT),
2105 BPF_SA_PROG_SEC("cgroup/connect6", BPF_CGROUP_INET6_CONNECT),
72481f39
AI
2106 BPF_SA_PROG_SEC("cgroup/sendmsg4", BPF_CGROUP_UDP4_SENDMSG),
2107 BPF_SA_PROG_SEC("cgroup/sendmsg6", BPF_CGROUP_UDP6_SENDMSG),
81efee75
AI
2108 BPF_S_PROG_SEC("cgroup/post_bind4", BPF_CGROUP_INET4_POST_BIND),
2109 BPF_S_PROG_SEC("cgroup/post_bind6", BPF_CGROUP_INET6_POST_BIND),
583c9009 2110};
d7be143b 2111
583c9009 2112#undef BPF_PROG_SEC
d7be143b 2113#undef BPF_PROG_SEC_FULL
81efee75 2114#undef BPF_S_PROG_SEC
e50b0a6f 2115#undef BPF_SA_PROG_SEC
583c9009 2116
b60df2a0
JK
2117int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
2118 enum bpf_attach_type *expected_attach_type)
583c9009
RG
2119{
2120 int i;
2121
b60df2a0
JK
2122 if (!name)
2123 return -EINVAL;
583c9009 2124
b60df2a0
JK
2125 for (i = 0; i < ARRAY_SIZE(section_names); i++) {
2126 if (strncmp(name, section_names[i].sec, section_names[i].len))
2127 continue;
2128 *prog_type = section_names[i].prog_type;
2129 *expected_attach_type = section_names[i].expected_attach_type;
2130 return 0;
2131 }
2132 return -EINVAL;
2133}
583c9009 2134
b60df2a0
JK
2135static int
2136bpf_program__identify_section(struct bpf_program *prog,
2137 enum bpf_prog_type *prog_type,
2138 enum bpf_attach_type *expected_attach_type)
2139{
2140 return libbpf_prog_type_by_name(prog->section_name, prog_type,
2141 expected_attach_type);
583c9009
RG
2142}
2143
6e009e65 2144int bpf_map__fd(struct bpf_map *map)
9d759a9b 2145{
6e009e65 2146 return map ? map->fd : -EINVAL;
9d759a9b
WN
2147}
2148
53897a78 2149const struct bpf_map_def *bpf_map__def(struct bpf_map *map)
9d759a9b 2150{
53897a78 2151 return map ? &map->def : ERR_PTR(-EINVAL);
9d759a9b
WN
2152}
2153
009ad5d5 2154const char *bpf_map__name(struct bpf_map *map)
561bbcca 2155{
009ad5d5 2156 return map ? map->name : NULL;
561bbcca
WN
2157}
2158
61746dbe 2159uint32_t bpf_map__btf_key_type_id(const struct bpf_map *map)
8a138aed 2160{
61746dbe 2161 return map ? map->btf_key_type_id : 0;
8a138aed
MKL
2162}
2163
61746dbe 2164uint32_t bpf_map__btf_value_type_id(const struct bpf_map *map)
8a138aed 2165{
61746dbe 2166 return map ? map->btf_value_type_id : 0;
8a138aed
MKL
2167}
2168
edb13ed4
ACM
2169int bpf_map__set_priv(struct bpf_map *map, void *priv,
2170 bpf_map_clear_priv_t clear_priv)
9d759a9b
WN
2171{
2172 if (!map)
2173 return -EINVAL;
2174
2175 if (map->priv) {
2176 if (map->clear_priv)
2177 map->clear_priv(map, map->priv);
2178 }
2179
2180 map->priv = priv;
2181 map->clear_priv = clear_priv;
2182 return 0;
2183}
2184
b4cbfa56 2185void *bpf_map__priv(struct bpf_map *map)
9d759a9b 2186{
b4cbfa56 2187 return map ? map->priv : ERR_PTR(-EINVAL);
9d759a9b
WN
2188}
2189
f83fb22c
JK
2190bool bpf_map__is_offload_neutral(struct bpf_map *map)
2191{
2192 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
2193}
2194
9aba3613
JK
2195void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
2196{
2197 map->map_ifindex = ifindex;
2198}
2199
9d759a9b
WN
2200struct bpf_map *
2201bpf_map__next(struct bpf_map *prev, struct bpf_object *obj)
2202{
2203 size_t idx;
2204 struct bpf_map *s, *e;
2205
2206 if (!obj || !obj->maps)
2207 return NULL;
2208
2209 s = obj->maps;
2210 e = obj->maps + obj->nr_maps;
2211
2212 if (prev == NULL)
2213 return s;
2214
2215 if ((prev < s) || (prev >= e)) {
2216 pr_warning("error in %s: map handler doesn't belong to object\n",
2217 __func__);
2218 return NULL;
2219 }
2220
2221 idx = (prev - obj->maps) + 1;
2222 if (idx >= obj->nr_maps)
2223 return NULL;
2224 return &obj->maps[idx];
2225}
561bbcca
WN
2226
2227struct bpf_map *
a7fe0450 2228bpf_object__find_map_by_name(struct bpf_object *obj, const char *name)
561bbcca
WN
2229{
2230 struct bpf_map *pos;
2231
2232 bpf_map__for_each(pos, obj) {
973170e6 2233 if (pos->name && !strcmp(pos->name, name))
561bbcca
WN
2234 return pos;
2235 }
2236 return NULL;
2237}
5a6acad1
WN
2238
2239struct bpf_map *
2240bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
2241{
2242 int i;
2243
2244 for (i = 0; i < obj->nr_maps; i++) {
2245 if (obj->maps[i].offset == offset)
2246 return &obj->maps[i];
2247 }
2248 return ERR_PTR(-ENOENT);
2249}
e28ff1a8
JS
2250
2251long libbpf_get_error(const void *ptr)
2252{
2253 if (IS_ERR(ptr))
2254 return PTR_ERR(ptr);
2255 return 0;
2256}
6f6d33f3
JF
2257
2258int bpf_prog_load(const char *file, enum bpf_prog_type type,
2259 struct bpf_object **pobj, int *prog_fd)
d7be143b
AI
2260{
2261 struct bpf_prog_load_attr attr;
2262
2263 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
2264 attr.file = file;
2265 attr.prog_type = type;
2266 attr.expected_attach_type = 0;
2267
2268 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
2269}
2270
2271int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
2272 struct bpf_object **pobj, int *prog_fd)
6f6d33f3 2273{
07f2d4ea
JK
2274 struct bpf_object_open_attr open_attr = {
2275 .file = attr->file,
2276 .prog_type = attr->prog_type,
2277 };
48cca7e4 2278 struct bpf_program *prog, *first_prog = NULL;
d7be143b
AI
2279 enum bpf_attach_type expected_attach_type;
2280 enum bpf_prog_type prog_type;
6f6d33f3 2281 struct bpf_object *obj;
f0307a7e 2282 struct bpf_map *map;
6f6d33f3
JF
2283 int err;
2284
d7be143b
AI
2285 if (!attr)
2286 return -EINVAL;
17387dd5
JK
2287 if (!attr->file)
2288 return -EINVAL;
d7be143b 2289
07f2d4ea 2290 obj = bpf_object__open_xattr(&open_attr);
3597683c 2291 if (IS_ERR_OR_NULL(obj))
6f6d33f3
JF
2292 return -ENOENT;
2293
48cca7e4
AS
2294 bpf_object__for_each_program(prog, obj) {
2295 /*
2296 * If type is not specified, try to guess it based on
2297 * section name.
2298 */
d7be143b 2299 prog_type = attr->prog_type;
f0307a7e 2300 prog->prog_ifindex = attr->ifindex;
d7be143b
AI
2301 expected_attach_type = attr->expected_attach_type;
2302 if (prog_type == BPF_PROG_TYPE_UNSPEC) {
b60df2a0
JK
2303 err = bpf_program__identify_section(prog, &prog_type,
2304 &expected_attach_type);
2305 if (err < 0) {
2306 pr_warning("failed to guess program type based on section name %s\n",
2307 prog->section_name);
48cca7e4
AS
2308 bpf_object__close(obj);
2309 return -EINVAL;
2310 }
583c9009 2311 }
48cca7e4 2312
d7be143b
AI
2313 bpf_program__set_type(prog, prog_type);
2314 bpf_program__set_expected_attach_type(prog,
2315 expected_attach_type);
2316
9a94f277 2317 if (!bpf_program__is_function_storage(prog, obj) && !first_prog)
48cca7e4
AS
2318 first_prog = prog;
2319 }
2320
f0307a7e 2321 bpf_map__for_each(map, obj) {
f83fb22c
JK
2322 if (!bpf_map__is_offload_neutral(map))
2323 map->map_ifindex = attr->ifindex;
f0307a7e
DB
2324 }
2325
48cca7e4
AS
2326 if (!first_prog) {
2327 pr_warning("object file doesn't contain bpf program\n");
2328 bpf_object__close(obj);
2329 return -ENOENT;
583c9009
RG
2330 }
2331
6f6d33f3
JF
2332 err = bpf_object__load(obj);
2333 if (err) {
2334 bpf_object__close(obj);
2335 return -EINVAL;
2336 }
2337
2338 *pobj = obj;
48cca7e4 2339 *prog_fd = bpf_program__fd(first_prog);
6f6d33f3
JF
2340 return 0;
2341}
d0cabbb0
JK
2342
2343enum bpf_perf_event_ret
2344bpf_perf_event_read_simple(void *mem, unsigned long size,
2345 unsigned long page_size, void **buf, size_t *buf_len,
2346 bpf_perf_event_print_t fn, void *priv)
2347{
2348 volatile struct perf_event_mmap_page *header = mem;
2349 __u64 data_tail = header->data_tail;
2350 __u64 data_head = header->data_head;
2351 void *base, *begin, *end;
2352 int ret;
2353
2354 asm volatile("" ::: "memory"); /* in real code it should be smp_rmb() */
2355 if (data_head == data_tail)
2356 return LIBBPF_PERF_EVENT_CONT;
2357
2358 base = ((char *)header) + page_size;
2359
2360 begin = base + data_tail % size;
2361 end = base + data_head % size;
2362
2363 while (begin != end) {
2364 struct perf_event_header *ehdr;
2365
2366 ehdr = begin;
2367 if (begin + ehdr->size > base + size) {
2368 long len = base + size - begin;
2369
2370 if (*buf_len < ehdr->size) {
2371 free(*buf);
2372 *buf = malloc(ehdr->size);
2373 if (!*buf) {
2374 ret = LIBBPF_PERF_EVENT_ERROR;
2375 break;
2376 }
2377 *buf_len = ehdr->size;
2378 }
2379
2380 memcpy(*buf, begin, len);
2381 memcpy(*buf + len, base, ehdr->size - len);
2382 ehdr = (void *)*buf;
2383 begin = base + ehdr->size - len;
2384 } else if (begin + ehdr->size == base + size) {
2385 begin = base;
2386 } else {
2387 begin += ehdr->size;
2388 }
2389
2390 ret = fn(ehdr, priv);
2391 if (ret != LIBBPF_PERF_EVENT_CONT)
2392 break;
2393
2394 data_tail += ehdr->size;
2395 }
2396
2397 __sync_synchronize(); /* smp_mb() */
2398 header->data_tail = data_tail;
2399
2400 return ret;
2401}