Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3/*
4 * Common eBPF ELF object loading operations.
5 *
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
9 * Copyright (C) 2017 Nicira, Inc.
10 * Copyright (C) 2019 Isovalent, Inc.
11 */
12
13#ifndef _GNU_SOURCE
14#define _GNU_SOURCE
15#endif
16#include <stdlib.h>
17#include <stdio.h>
18#include <stdarg.h>
19#include <libgen.h>
20#include <inttypes.h>
21#include <limits.h>
22#include <string.h>
23#include <unistd.h>
24#include <endian.h>
25#include <fcntl.h>
26#include <errno.h>
27#include <ctype.h>
28#include <asm/unistd.h>
29#include <linux/err.h>
30#include <linux/kernel.h>
31#include <linux/bpf.h>
32#include <linux/btf.h>
33#include <linux/filter.h>
34#include <linux/list.h>
35#include <linux/limits.h>
36#include <linux/perf_event.h>
37#include <linux/ring_buffer.h>
38#include <linux/version.h>
39#include <sys/epoll.h>
40#include <sys/ioctl.h>
41#include <sys/mman.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/vfs.h>
45#include <sys/utsname.h>
46#include <sys/resource.h>
47#include <tools/libc_compat.h>
48#include <libelf.h>
49#include <gelf.h>
50#include <zlib.h>
51
52#include "libbpf.h"
53#include "bpf.h"
54#include "btf.h"
55#include "str_error.h"
56#include "libbpf_internal.h"
57#include "hashmap.h"
58
59/* make sure libbpf doesn't use kernel-only integer typedefs */
60#pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
61
62#ifndef EM_BPF
63#define EM_BPF 247
64#endif
65
66#ifndef BPF_FS_MAGIC
67#define BPF_FS_MAGIC 0xcafe4a11
68#endif
69
70/* vsprintf() in __base_pr() uses nonliteral format string. It may break
71 * compilation if user enables corresponding warning. Disable it explicitly.
72 */
73#pragma GCC diagnostic ignored "-Wformat-nonliteral"
74
75#define __printf(a, b) __attribute__((format(printf, a, b)))
76
77static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
78static struct bpf_program *bpf_object__find_prog_by_idx(struct bpf_object *obj,
79 int idx);
80static const struct btf_type *
81skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
82
83static int __base_pr(enum libbpf_print_level level, const char *format,
84 va_list args)
85{
86 if (level == LIBBPF_DEBUG)
87 return 0;
88
89 return vfprintf(stderr, format, args);
90}
91
92static libbpf_print_fn_t __libbpf_pr = __base_pr;
93
94libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
95{
96 libbpf_print_fn_t old_print_fn = __libbpf_pr;
97
98 __libbpf_pr = fn;
99 return old_print_fn;
100}
101
102__printf(2, 3)
103void libbpf_print(enum libbpf_print_level level, const char *format, ...)
104{
105 va_list args;
106
107 if (!__libbpf_pr)
108 return;
109
110 va_start(args, format);
111 __libbpf_pr(level, format, args);
112 va_end(args);
113}
114
115static void pr_perm_msg(int err)
116{
117 struct rlimit limit;
118 char buf[100];
119
120 if (err != -EPERM || geteuid() != 0)
121 return;
122
123 err = getrlimit(RLIMIT_MEMLOCK, &limit);
124 if (err)
125 return;
126
127 if (limit.rlim_cur == RLIM_INFINITY)
128 return;
129
130 if (limit.rlim_cur < 1024)
131 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
132 else if (limit.rlim_cur < 1024*1024)
133 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
134 else
135 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
136
137 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
138 buf);
139}
140
141#define STRERR_BUFSIZE 128
142
143/* Copied from tools/perf/util/util.h */
144#ifndef zfree
145# define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
146#endif
147
148#ifndef zclose
149# define zclose(fd) ({ \
150 int ___err = 0; \
151 if ((fd) >= 0) \
152 ___err = close((fd)); \
153 fd = -1; \
154 ___err; })
155#endif
156
157#ifdef HAVE_LIBELF_MMAP_SUPPORT
158# define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
159#else
160# define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
161#endif
162
163static inline __u64 ptr_to_u64(const void *ptr)
164{
165 return (__u64) (unsigned long) ptr;
166}
167
168struct bpf_capabilities {
169 /* v4.14: kernel support for program & map names. */
170 __u32 name:1;
171 /* v5.2: kernel support for global data sections. */
172 __u32 global_data:1;
173 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
174 __u32 btf_func:1;
175 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
176 __u32 btf_datasec:1;
177 /* BPF_F_MMAPABLE is supported for arrays */
178 __u32 array_mmap:1;
179 /* BTF_FUNC_GLOBAL is supported */
180 __u32 btf_func_global:1;
181 /* kernel support for expected_attach_type in BPF_PROG_LOAD */
182 __u32 exp_attach_type:1;
183};
184
185enum reloc_type {
186 RELO_LD64,
187 RELO_CALL,
188 RELO_DATA,
189 RELO_EXTERN,
190};
191
192struct reloc_desc {
193 enum reloc_type type;
194 int insn_idx;
195 int map_idx;
196 int sym_off;
197};
198
199struct bpf_sec_def;
200
201typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
202 struct bpf_program *prog);
203
204struct bpf_sec_def {
205 const char *sec;
206 size_t len;
207 enum bpf_prog_type prog_type;
208 enum bpf_attach_type expected_attach_type;
209 bool is_exp_attach_type_optional;
210 bool is_attachable;
211 bool is_attach_btf;
212 attach_fn_t attach_fn;
213};
214
215/*
216 * bpf_prog should be a better name but it has been used in
217 * linux/filter.h.
218 */
219struct bpf_program {
220 /* Index in elf obj file, for relocation use. */
221 int idx;
222 char *name;
223 int prog_ifindex;
224 char *section_name;
225 const struct bpf_sec_def *sec_def;
226 /* section_name with / replaced by _; makes recursive pinning
227 * in bpf_object__pin_programs easier
228 */
229 char *pin_name;
230 struct bpf_insn *insns;
231 size_t insns_cnt, main_prog_cnt;
232 enum bpf_prog_type type;
233
234 struct reloc_desc *reloc_desc;
235 int nr_reloc;
236 int log_level;
237
238 struct {
239 int nr;
240 int *fds;
241 } instances;
242 bpf_program_prep_t preprocessor;
243
244 struct bpf_object *obj;
245 void *priv;
246 bpf_program_clear_priv_t clear_priv;
247
248 enum bpf_attach_type expected_attach_type;
249 __u32 attach_btf_id;
250 __u32 attach_prog_fd;
251 void *func_info;
252 __u32 func_info_rec_size;
253 __u32 func_info_cnt;
254
255 struct bpf_capabilities *caps;
256
257 void *line_info;
258 __u32 line_info_rec_size;
259 __u32 line_info_cnt;
260 __u32 prog_flags;
261};
262
263struct bpf_struct_ops {
264 const char *tname;
265 const struct btf_type *type;
266 struct bpf_program **progs;
267 __u32 *kern_func_off;
268 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
269 void *data;
270 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
271 * btf_vmlinux's format.
272 * struct bpf_struct_ops_tcp_congestion_ops {
273 * [... some other kernel fields ...]
274 * struct tcp_congestion_ops data;
275 * }
276 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
277 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
278 * from "data".
279 */
280 void *kern_vdata;
281 __u32 type_id;
282};
283
284#define DATA_SEC ".data"
285#define BSS_SEC ".bss"
286#define RODATA_SEC ".rodata"
287#define KCONFIG_SEC ".kconfig"
288#define STRUCT_OPS_SEC ".struct_ops"
289
290enum libbpf_map_type {
291 LIBBPF_MAP_UNSPEC,
292 LIBBPF_MAP_DATA,
293 LIBBPF_MAP_BSS,
294 LIBBPF_MAP_RODATA,
295 LIBBPF_MAP_KCONFIG,
296};
297
298static const char * const libbpf_type_to_btf_name[] = {
299 [LIBBPF_MAP_DATA] = DATA_SEC,
300 [LIBBPF_MAP_BSS] = BSS_SEC,
301 [LIBBPF_MAP_RODATA] = RODATA_SEC,
302 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
303};
304
305struct bpf_map {
306 char *name;
307 int fd;
308 int sec_idx;
309 size_t sec_offset;
310 int map_ifindex;
311 int inner_map_fd;
312 struct bpf_map_def def;
313 __u32 btf_var_idx;
314 __u32 btf_key_type_id;
315 __u32 btf_value_type_id;
316 __u32 btf_vmlinux_value_type_id;
317 void *priv;
318 bpf_map_clear_priv_t clear_priv;
319 enum libbpf_map_type libbpf_type;
320 void *mmaped;
321 struct bpf_struct_ops *st_ops;
322 struct bpf_map *inner_map;
323 void **init_slots;
324 int init_slots_sz;
325 char *pin_path;
326 bool pinned;
327 bool reused;
328};
329
330enum extern_type {
331 EXT_UNKNOWN,
332 EXT_CHAR,
333 EXT_BOOL,
334 EXT_INT,
335 EXT_TRISTATE,
336 EXT_CHAR_ARR,
337};
338
339struct extern_desc {
340 const char *name;
341 int sym_idx;
342 int btf_id;
343 enum extern_type type;
344 int sz;
345 int align;
346 int data_off;
347 bool is_signed;
348 bool is_weak;
349 bool is_set;
350};
351
352static LIST_HEAD(bpf_objects_list);
353
354struct bpf_object {
355 char name[BPF_OBJ_NAME_LEN];
356 char license[64];
357 __u32 kern_version;
358
359 struct bpf_program *programs;
360 size_t nr_programs;
361 struct bpf_map *maps;
362 size_t nr_maps;
363 size_t maps_cap;
364
365 char *kconfig;
366 struct extern_desc *externs;
367 int nr_extern;
368 int kconfig_map_idx;
369
370 bool loaded;
371 bool has_pseudo_calls;
372
373 /*
374 * Information when doing elf related work. Only valid if fd
375 * is valid.
376 */
377 struct {
378 int fd;
379 const void *obj_buf;
380 size_t obj_buf_sz;
381 Elf *elf;
382 GElf_Ehdr ehdr;
383 Elf_Data *symbols;
384 Elf_Data *data;
385 Elf_Data *rodata;
386 Elf_Data *bss;
387 Elf_Data *st_ops_data;
388 size_t strtabidx;
389 struct {
390 GElf_Shdr shdr;
391 Elf_Data *data;
392 } *reloc_sects;
393 int nr_reloc_sects;
394 int maps_shndx;
395 int btf_maps_shndx;
396 __u32 btf_maps_sec_btf_id;
397 int text_shndx;
398 int symbols_shndx;
399 int data_shndx;
400 int rodata_shndx;
401 int bss_shndx;
402 int st_ops_shndx;
403 } efile;
404 /*
405 * All loaded bpf_object is linked in a list, which is
406 * hidden to caller. bpf_objects__<func> handlers deal with
407 * all objects.
408 */
409 struct list_head list;
410
411 struct btf *btf;
412 /* Parse and load BTF vmlinux if any of the programs in the object need
413 * it at load time.
414 */
415 struct btf *btf_vmlinux;
416 struct btf_ext *btf_ext;
417
418 void *priv;
419 bpf_object_clear_priv_t clear_priv;
420
421 struct bpf_capabilities caps;
422
423 char path[];
424};
425#define obj_elf_valid(o) ((o)->efile.elf)
426
427void bpf_program__unload(struct bpf_program *prog)
428{
429 int i;
430
431 if (!prog)
432 return;
433
434 /*
435 * If the object is opened but the program was never loaded,
436 * it is possible that prog->instances.nr == -1.
437 */
438 if (prog->instances.nr > 0) {
439 for (i = 0; i < prog->instances.nr; i++)
440 zclose(prog->instances.fds[i]);
441 } else if (prog->instances.nr != -1) {
442 pr_warn("Internal error: instances.nr is %d\n",
443 prog->instances.nr);
444 }
445
446 prog->instances.nr = -1;
447 zfree(&prog->instances.fds);
448
449 zfree(&prog->func_info);
450 zfree(&prog->line_info);
451}
452
453static void bpf_program__exit(struct bpf_program *prog)
454{
455 if (!prog)
456 return;
457
458 if (prog->clear_priv)
459 prog->clear_priv(prog, prog->priv);
460
461 prog->priv = NULL;
462 prog->clear_priv = NULL;
463
464 bpf_program__unload(prog);
465 zfree(&prog->name);
466 zfree(&prog->section_name);
467 zfree(&prog->pin_name);
468 zfree(&prog->insns);
469 zfree(&prog->reloc_desc);
470
471 prog->nr_reloc = 0;
472 prog->insns_cnt = 0;
473 prog->idx = -1;
474}
475
476static char *__bpf_program__pin_name(struct bpf_program *prog)
477{
478 char *name, *p;
479
480 name = p = strdup(prog->section_name);
481 while ((p = strchr(p, '/')))
482 *p = '_';
483
484 return name;
485}
486
487static int
488bpf_program__init(void *data, size_t size, char *section_name, int idx,
489 struct bpf_program *prog)
490{
491 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
492
493 if (size == 0 || size % bpf_insn_sz) {
494 pr_warn("corrupted section '%s', size: %zu\n",
495 section_name, size);
496 return -EINVAL;
497 }
498
499 memset(prog, 0, sizeof(*prog));
500
501 prog->section_name = strdup(section_name);
502 if (!prog->section_name) {
503 pr_warn("failed to alloc name for prog under section(%d) %s\n",
504 idx, section_name);
505 goto errout;
506 }
507
508 prog->pin_name = __bpf_program__pin_name(prog);
509 if (!prog->pin_name) {
510 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
511 idx, section_name);
512 goto errout;
513 }
514
515 prog->insns = malloc(size);
516 if (!prog->insns) {
517 pr_warn("failed to alloc insns for prog under section %s\n",
518 section_name);
519 goto errout;
520 }
521 prog->insns_cnt = size / bpf_insn_sz;
522 memcpy(prog->insns, data, size);
523 prog->idx = idx;
524 prog->instances.fds = NULL;
525 prog->instances.nr = -1;
526 prog->type = BPF_PROG_TYPE_UNSPEC;
527
528 return 0;
529errout:
530 bpf_program__exit(prog);
531 return -ENOMEM;
532}
533
534static int
535bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
536 char *section_name, int idx)
537{
538 struct bpf_program prog, *progs;
539 int nr_progs, err;
540
541 err = bpf_program__init(data, size, section_name, idx, &prog);
542 if (err)
543 return err;
544
545 prog.caps = &obj->caps;
546 progs = obj->programs;
547 nr_progs = obj->nr_programs;
548
549 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
550 if (!progs) {
551 /*
552 * In this case the original obj->programs
553 * is still valid, so don't need special treat for
554 * bpf_close_object().
555 */
556 pr_warn("failed to alloc a new program under section '%s'\n",
557 section_name);
558 bpf_program__exit(&prog);
559 return -ENOMEM;
560 }
561
562 pr_debug("found program %s\n", prog.section_name);
563 obj->programs = progs;
564 obj->nr_programs = nr_progs + 1;
565 prog.obj = obj;
566 progs[nr_progs] = prog;
567 return 0;
568}
569
570static int
571bpf_object__init_prog_names(struct bpf_object *obj)
572{
573 Elf_Data *symbols = obj->efile.symbols;
574 struct bpf_program *prog;
575 size_t pi, si;
576
577 for (pi = 0; pi < obj->nr_programs; pi++) {
578 const char *name = NULL;
579
580 prog = &obj->programs[pi];
581
582 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
583 si++) {
584 GElf_Sym sym;
585
586 if (!gelf_getsym(symbols, si, &sym))
587 continue;
588 if (sym.st_shndx != prog->idx)
589 continue;
590 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
591 continue;
592
593 name = elf_strptr(obj->efile.elf,
594 obj->efile.strtabidx,
595 sym.st_name);
596 if (!name) {
597 pr_warn("failed to get sym name string for prog %s\n",
598 prog->section_name);
599 return -LIBBPF_ERRNO__LIBELF;
600 }
601 }
602
603 if (!name && prog->idx == obj->efile.text_shndx)
604 name = ".text";
605
606 if (!name) {
607 pr_warn("failed to find sym for prog %s\n",
608 prog->section_name);
609 return -EINVAL;
610 }
611
612 prog->name = strdup(name);
613 if (!prog->name) {
614 pr_warn("failed to allocate memory for prog sym %s\n",
615 name);
616 return -ENOMEM;
617 }
618 }
619
620 return 0;
621}
622
623static __u32 get_kernel_version(void)
624{
625 __u32 major, minor, patch;
626 struct utsname info;
627
628 uname(&info);
629 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
630 return 0;
631 return KERNEL_VERSION(major, minor, patch);
632}
633
634static const struct btf_member *
635find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
636{
637 struct btf_member *m;
638 int i;
639
640 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
641 if (btf_member_bit_offset(t, i) == bit_offset)
642 return m;
643 }
644
645 return NULL;
646}
647
648static const struct btf_member *
649find_member_by_name(const struct btf *btf, const struct btf_type *t,
650 const char *name)
651{
652 struct btf_member *m;
653 int i;
654
655 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
656 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
657 return m;
658 }
659
660 return NULL;
661}
662
663#define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
664static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
665 const char *name, __u32 kind);
666
667static int
668find_struct_ops_kern_types(const struct btf *btf, const char *tname,
669 const struct btf_type **type, __u32 *type_id,
670 const struct btf_type **vtype, __u32 *vtype_id,
671 const struct btf_member **data_member)
672{
673 const struct btf_type *kern_type, *kern_vtype;
674 const struct btf_member *kern_data_member;
675 __s32 kern_vtype_id, kern_type_id;
676 __u32 i;
677
678 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
679 if (kern_type_id < 0) {
680 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
681 tname);
682 return kern_type_id;
683 }
684 kern_type = btf__type_by_id(btf, kern_type_id);
685
686 /* Find the corresponding "map_value" type that will be used
687 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
688 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
689 * btf_vmlinux.
690 */
691 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
692 tname, BTF_KIND_STRUCT);
693 if (kern_vtype_id < 0) {
694 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
695 STRUCT_OPS_VALUE_PREFIX, tname);
696 return kern_vtype_id;
697 }
698 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
699
700 /* Find "struct tcp_congestion_ops" from
701 * struct bpf_struct_ops_tcp_congestion_ops {
702 * [ ... ]
703 * struct tcp_congestion_ops data;
704 * }
705 */
706 kern_data_member = btf_members(kern_vtype);
707 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
708 if (kern_data_member->type == kern_type_id)
709 break;
710 }
711 if (i == btf_vlen(kern_vtype)) {
712 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
713 tname, STRUCT_OPS_VALUE_PREFIX, tname);
714 return -EINVAL;
715 }
716
717 *type = kern_type;
718 *type_id = kern_type_id;
719 *vtype = kern_vtype;
720 *vtype_id = kern_vtype_id;
721 *data_member = kern_data_member;
722
723 return 0;
724}
725
726static bool bpf_map__is_struct_ops(const struct bpf_map *map)
727{
728 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
729}
730
731/* Init the map's fields that depend on kern_btf */
732static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
733 const struct btf *btf,
734 const struct btf *kern_btf)
735{
736 const struct btf_member *member, *kern_member, *kern_data_member;
737 const struct btf_type *type, *kern_type, *kern_vtype;
738 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
739 struct bpf_struct_ops *st_ops;
740 void *data, *kern_data;
741 const char *tname;
742 int err;
743
744 st_ops = map->st_ops;
745 type = st_ops->type;
746 tname = st_ops->tname;
747 err = find_struct_ops_kern_types(kern_btf, tname,
748 &kern_type, &kern_type_id,
749 &kern_vtype, &kern_vtype_id,
750 &kern_data_member);
751 if (err)
752 return err;
753
754 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
755 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
756
757 map->def.value_size = kern_vtype->size;
758 map->btf_vmlinux_value_type_id = kern_vtype_id;
759
760 st_ops->kern_vdata = calloc(1, kern_vtype->size);
761 if (!st_ops->kern_vdata)
762 return -ENOMEM;
763
764 data = st_ops->data;
765 kern_data_off = kern_data_member->offset / 8;
766 kern_data = st_ops->kern_vdata + kern_data_off;
767
768 member = btf_members(type);
769 for (i = 0; i < btf_vlen(type); i++, member++) {
770 const struct btf_type *mtype, *kern_mtype;
771 __u32 mtype_id, kern_mtype_id;
772 void *mdata, *kern_mdata;
773 __s64 msize, kern_msize;
774 __u32 moff, kern_moff;
775 __u32 kern_member_idx;
776 const char *mname;
777
778 mname = btf__name_by_offset(btf, member->name_off);
779 kern_member = find_member_by_name(kern_btf, kern_type, mname);
780 if (!kern_member) {
781 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
782 map->name, mname);
783 return -ENOTSUP;
784 }
785
786 kern_member_idx = kern_member - btf_members(kern_type);
787 if (btf_member_bitfield_size(type, i) ||
788 btf_member_bitfield_size(kern_type, kern_member_idx)) {
789 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
790 map->name, mname);
791 return -ENOTSUP;
792 }
793
794 moff = member->offset / 8;
795 kern_moff = kern_member->offset / 8;
796
797 mdata = data + moff;
798 kern_mdata = kern_data + kern_moff;
799
800 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
801 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
802 &kern_mtype_id);
803 if (BTF_INFO_KIND(mtype->info) !=
804 BTF_INFO_KIND(kern_mtype->info)) {
805 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
806 map->name, mname, BTF_INFO_KIND(mtype->info),
807 BTF_INFO_KIND(kern_mtype->info));
808 return -ENOTSUP;
809 }
810
811 if (btf_is_ptr(mtype)) {
812 struct bpf_program *prog;
813
814 mtype = skip_mods_and_typedefs(btf, mtype->type, &mtype_id);
815 kern_mtype = skip_mods_and_typedefs(kern_btf,
816 kern_mtype->type,
817 &kern_mtype_id);
818 if (!btf_is_func_proto(mtype) ||
819 !btf_is_func_proto(kern_mtype)) {
820 pr_warn("struct_ops init_kern %s: non func ptr %s is not supported\n",
821 map->name, mname);
822 return -ENOTSUP;
823 }
824
825 prog = st_ops->progs[i];
826 if (!prog) {
827 pr_debug("struct_ops init_kern %s: func ptr %s is not set\n",
828 map->name, mname);
829 continue;
830 }
831
832 prog->attach_btf_id = kern_type_id;
833 prog->expected_attach_type = kern_member_idx;
834
835 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
836
837 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
838 map->name, mname, prog->name, moff,
839 kern_moff);
840
841 continue;
842 }
843
844 msize = btf__resolve_size(btf, mtype_id);
845 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
846 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
847 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
848 map->name, mname, (ssize_t)msize,
849 (ssize_t)kern_msize);
850 return -ENOTSUP;
851 }
852
853 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
854 map->name, mname, (unsigned int)msize,
855 moff, kern_moff);
856 memcpy(kern_mdata, mdata, msize);
857 }
858
859 return 0;
860}
861
862static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
863{
864 struct bpf_map *map;
865 size_t i;
866 int err;
867
868 for (i = 0; i < obj->nr_maps; i++) {
869 map = &obj->maps[i];
870
871 if (!bpf_map__is_struct_ops(map))
872 continue;
873
874 err = bpf_map__init_kern_struct_ops(map, obj->btf,
875 obj->btf_vmlinux);
876 if (err)
877 return err;
878 }
879
880 return 0;
881}
882
883static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
884{
885 const struct btf_type *type, *datasec;
886 const struct btf_var_secinfo *vsi;
887 struct bpf_struct_ops *st_ops;
888 const char *tname, *var_name;
889 __s32 type_id, datasec_id;
890 const struct btf *btf;
891 struct bpf_map *map;
892 __u32 i;
893
894 if (obj->efile.st_ops_shndx == -1)
895 return 0;
896
897 btf = obj->btf;
898 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
899 BTF_KIND_DATASEC);
900 if (datasec_id < 0) {
901 pr_warn("struct_ops init: DATASEC %s not found\n",
902 STRUCT_OPS_SEC);
903 return -EINVAL;
904 }
905
906 datasec = btf__type_by_id(btf, datasec_id);
907 vsi = btf_var_secinfos(datasec);
908 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
909 type = btf__type_by_id(obj->btf, vsi->type);
910 var_name = btf__name_by_offset(obj->btf, type->name_off);
911
912 type_id = btf__resolve_type(obj->btf, vsi->type);
913 if (type_id < 0) {
914 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
915 vsi->type, STRUCT_OPS_SEC);
916 return -EINVAL;
917 }
918
919 type = btf__type_by_id(obj->btf, type_id);
920 tname = btf__name_by_offset(obj->btf, type->name_off);
921 if (!tname[0]) {
922 pr_warn("struct_ops init: anonymous type is not supported\n");
923 return -ENOTSUP;
924 }
925 if (!btf_is_struct(type)) {
926 pr_warn("struct_ops init: %s is not a struct\n", tname);
927 return -EINVAL;
928 }
929
930 map = bpf_object__add_map(obj);
931 if (IS_ERR(map))
932 return PTR_ERR(map);
933
934 map->sec_idx = obj->efile.st_ops_shndx;
935 map->sec_offset = vsi->offset;
936 map->name = strdup(var_name);
937 if (!map->name)
938 return -ENOMEM;
939
940 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
941 map->def.key_size = sizeof(int);
942 map->def.value_size = type->size;
943 map->def.max_entries = 1;
944
945 map->st_ops = calloc(1, sizeof(*map->st_ops));
946 if (!map->st_ops)
947 return -ENOMEM;
948 st_ops = map->st_ops;
949 st_ops->data = malloc(type->size);
950 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
951 st_ops->kern_func_off = malloc(btf_vlen(type) *
952 sizeof(*st_ops->kern_func_off));
953 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
954 return -ENOMEM;
955
956 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
957 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
958 var_name, STRUCT_OPS_SEC);
959 return -EINVAL;
960 }
961
962 memcpy(st_ops->data,
963 obj->efile.st_ops_data->d_buf + vsi->offset,
964 type->size);
965 st_ops->tname = tname;
966 st_ops->type = type;
967 st_ops->type_id = type_id;
968
969 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
970 tname, type_id, var_name, vsi->offset);
971 }
972
973 return 0;
974}
975
976static struct bpf_object *bpf_object__new(const char *path,
977 const void *obj_buf,
978 size_t obj_buf_sz,
979 const char *obj_name)
980{
981 struct bpf_object *obj;
982 char *end;
983
984 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
985 if (!obj) {
986 pr_warn("alloc memory failed for %s\n", path);
987 return ERR_PTR(-ENOMEM);
988 }
989
990 strcpy(obj->path, path);
991 if (obj_name) {
992 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
993 obj->name[sizeof(obj->name) - 1] = 0;
994 } else {
995 /* Using basename() GNU version which doesn't modify arg. */
996 strncpy(obj->name, basename((void *)path),
997 sizeof(obj->name) - 1);
998 end = strchr(obj->name, '.');
999 if (end)
1000 *end = 0;
1001 }
1002
1003 obj->efile.fd = -1;
1004 /*
1005 * Caller of this function should also call
1006 * bpf_object__elf_finish() after data collection to return
1007 * obj_buf to user. If not, we should duplicate the buffer to
1008 * avoid user freeing them before elf finish.
1009 */
1010 obj->efile.obj_buf = obj_buf;
1011 obj->efile.obj_buf_sz = obj_buf_sz;
1012 obj->efile.maps_shndx = -1;
1013 obj->efile.btf_maps_shndx = -1;
1014 obj->efile.data_shndx = -1;
1015 obj->efile.rodata_shndx = -1;
1016 obj->efile.bss_shndx = -1;
1017 obj->efile.st_ops_shndx = -1;
1018 obj->kconfig_map_idx = -1;
1019
1020 obj->kern_version = get_kernel_version();
1021 obj->loaded = false;
1022
1023 INIT_LIST_HEAD(&obj->list);
1024 list_add(&obj->list, &bpf_objects_list);
1025 return obj;
1026}
1027
1028static void bpf_object__elf_finish(struct bpf_object *obj)
1029{
1030 if (!obj_elf_valid(obj))
1031 return;
1032
1033 if (obj->efile.elf) {
1034 elf_end(obj->efile.elf);
1035 obj->efile.elf = NULL;
1036 }
1037 obj->efile.symbols = NULL;
1038 obj->efile.data = NULL;
1039 obj->efile.rodata = NULL;
1040 obj->efile.bss = NULL;
1041 obj->efile.st_ops_data = NULL;
1042
1043 zfree(&obj->efile.reloc_sects);
1044 obj->efile.nr_reloc_sects = 0;
1045 zclose(obj->efile.fd);
1046 obj->efile.obj_buf = NULL;
1047 obj->efile.obj_buf_sz = 0;
1048}
1049
1050static int bpf_object__elf_init(struct bpf_object *obj)
1051{
1052 int err = 0;
1053 GElf_Ehdr *ep;
1054
1055 if (obj_elf_valid(obj)) {
1056 pr_warn("elf init: internal error\n");
1057 return -LIBBPF_ERRNO__LIBELF;
1058 }
1059
1060 if (obj->efile.obj_buf_sz > 0) {
1061 /*
1062 * obj_buf should have been validated by
1063 * bpf_object__open_buffer().
1064 */
1065 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
1066 obj->efile.obj_buf_sz);
1067 } else {
1068 obj->efile.fd = open(obj->path, O_RDONLY);
1069 if (obj->efile.fd < 0) {
1070 char errmsg[STRERR_BUFSIZE], *cp;
1071
1072 err = -errno;
1073 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1074 pr_warn("failed to open %s: %s\n", obj->path, cp);
1075 return err;
1076 }
1077
1078 obj->efile.elf = elf_begin(obj->efile.fd,
1079 LIBBPF_ELF_C_READ_MMAP, NULL);
1080 }
1081
1082 if (!obj->efile.elf) {
1083 pr_warn("failed to open %s as ELF file\n", obj->path);
1084 err = -LIBBPF_ERRNO__LIBELF;
1085 goto errout;
1086 }
1087
1088 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
1089 pr_warn("failed to get EHDR from %s\n", obj->path);
1090 err = -LIBBPF_ERRNO__FORMAT;
1091 goto errout;
1092 }
1093 ep = &obj->efile.ehdr;
1094
1095 /* Old LLVM set e_machine to EM_NONE */
1096 if (ep->e_type != ET_REL ||
1097 (ep->e_machine && ep->e_machine != EM_BPF)) {
1098 pr_warn("%s is not an eBPF object file\n", obj->path);
1099 err = -LIBBPF_ERRNO__FORMAT;
1100 goto errout;
1101 }
1102
1103 return 0;
1104errout:
1105 bpf_object__elf_finish(obj);
1106 return err;
1107}
1108
1109static int bpf_object__check_endianness(struct bpf_object *obj)
1110{
1111#if __BYTE_ORDER == __LITTLE_ENDIAN
1112 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1113 return 0;
1114#elif __BYTE_ORDER == __BIG_ENDIAN
1115 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1116 return 0;
1117#else
1118# error "Unrecognized __BYTE_ORDER__"
1119#endif
1120 pr_warn("endianness mismatch.\n");
1121 return -LIBBPF_ERRNO__ENDIAN;
1122}
1123
1124static int
1125bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1126{
1127 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
1128 pr_debug("license of %s is %s\n", obj->path, obj->license);
1129 return 0;
1130}
1131
1132static int
1133bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1134{
1135 __u32 kver;
1136
1137 if (size != sizeof(kver)) {
1138 pr_warn("invalid kver section in %s\n", obj->path);
1139 return -LIBBPF_ERRNO__FORMAT;
1140 }
1141 memcpy(&kver, data, sizeof(kver));
1142 obj->kern_version = kver;
1143 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1144 return 0;
1145}
1146
1147static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1148{
1149 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1150 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1151 return true;
1152 return false;
1153}
1154
1155static int bpf_object_search_section_size(const struct bpf_object *obj,
1156 const char *name, size_t *d_size)
1157{
1158 const GElf_Ehdr *ep = &obj->efile.ehdr;
1159 Elf *elf = obj->efile.elf;
1160 Elf_Scn *scn = NULL;
1161 int idx = 0;
1162
1163 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1164 const char *sec_name;
1165 Elf_Data *data;
1166 GElf_Shdr sh;
1167
1168 idx++;
1169 if (gelf_getshdr(scn, &sh) != &sh) {
1170 pr_warn("failed to get section(%d) header from %s\n",
1171 idx, obj->path);
1172 return -EIO;
1173 }
1174
1175 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1176 if (!sec_name) {
1177 pr_warn("failed to get section(%d) name from %s\n",
1178 idx, obj->path);
1179 return -EIO;
1180 }
1181
1182 if (strcmp(name, sec_name))
1183 continue;
1184
1185 data = elf_getdata(scn, 0);
1186 if (!data) {
1187 pr_warn("failed to get section(%d) data from %s(%s)\n",
1188 idx, name, obj->path);
1189 return -EIO;
1190 }
1191
1192 *d_size = data->d_size;
1193 return 0;
1194 }
1195
1196 return -ENOENT;
1197}
1198
1199int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1200 __u32 *size)
1201{
1202 int ret = -ENOENT;
1203 size_t d_size;
1204
1205 *size = 0;
1206 if (!name) {
1207 return -EINVAL;
1208 } else if (!strcmp(name, DATA_SEC)) {
1209 if (obj->efile.data)
1210 *size = obj->efile.data->d_size;
1211 } else if (!strcmp(name, BSS_SEC)) {
1212 if (obj->efile.bss)
1213 *size = obj->efile.bss->d_size;
1214 } else if (!strcmp(name, RODATA_SEC)) {
1215 if (obj->efile.rodata)
1216 *size = obj->efile.rodata->d_size;
1217 } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1218 if (obj->efile.st_ops_data)
1219 *size = obj->efile.st_ops_data->d_size;
1220 } else {
1221 ret = bpf_object_search_section_size(obj, name, &d_size);
1222 if (!ret)
1223 *size = d_size;
1224 }
1225
1226 return *size ? 0 : ret;
1227}
1228
1229int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1230 __u32 *off)
1231{
1232 Elf_Data *symbols = obj->efile.symbols;
1233 const char *sname;
1234 size_t si;
1235
1236 if (!name || !off)
1237 return -EINVAL;
1238
1239 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1240 GElf_Sym sym;
1241
1242 if (!gelf_getsym(symbols, si, &sym))
1243 continue;
1244 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1245 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1246 continue;
1247
1248 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1249 sym.st_name);
1250 if (!sname) {
1251 pr_warn("failed to get sym name string for var %s\n",
1252 name);
1253 return -EIO;
1254 }
1255 if (strcmp(name, sname) == 0) {
1256 *off = sym.st_value;
1257 return 0;
1258 }
1259 }
1260
1261 return -ENOENT;
1262}
1263
1264static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1265{
1266 struct bpf_map *new_maps;
1267 size_t new_cap;
1268 int i;
1269
1270 if (obj->nr_maps < obj->maps_cap)
1271 return &obj->maps[obj->nr_maps++];
1272
1273 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
1274 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
1275 if (!new_maps) {
1276 pr_warn("alloc maps for object failed\n");
1277 return ERR_PTR(-ENOMEM);
1278 }
1279
1280 obj->maps_cap = new_cap;
1281 obj->maps = new_maps;
1282
1283 /* zero out new maps */
1284 memset(obj->maps + obj->nr_maps, 0,
1285 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1286 /*
1287 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1288 * when failure (zclose won't close negative fd)).
1289 */
1290 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1291 obj->maps[i].fd = -1;
1292 obj->maps[i].inner_map_fd = -1;
1293 }
1294
1295 return &obj->maps[obj->nr_maps++];
1296}
1297
1298static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1299{
1300 long page_sz = sysconf(_SC_PAGE_SIZE);
1301 size_t map_sz;
1302
1303 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1304 map_sz = roundup(map_sz, page_sz);
1305 return map_sz;
1306}
1307
1308static char *internal_map_name(struct bpf_object *obj,
1309 enum libbpf_map_type type)
1310{
1311 char map_name[BPF_OBJ_NAME_LEN], *p;
1312 const char *sfx = libbpf_type_to_btf_name[type];
1313 int sfx_len = max((size_t)7, strlen(sfx));
1314 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1315 strlen(obj->name));
1316
1317 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1318 sfx_len, libbpf_type_to_btf_name[type]);
1319
1320 /* sanitise map name to characters allowed by kernel */
1321 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1322 if (!isalnum(*p) && *p != '_' && *p != '.')
1323 *p = '_';
1324
1325 return strdup(map_name);
1326}
1327
1328static int
1329bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1330 int sec_idx, void *data, size_t data_sz)
1331{
1332 struct bpf_map_def *def;
1333 struct bpf_map *map;
1334 int err;
1335
1336 map = bpf_object__add_map(obj);
1337 if (IS_ERR(map))
1338 return PTR_ERR(map);
1339
1340 map->libbpf_type = type;
1341 map->sec_idx = sec_idx;
1342 map->sec_offset = 0;
1343 map->name = internal_map_name(obj, type);
1344 if (!map->name) {
1345 pr_warn("failed to alloc map name\n");
1346 return -ENOMEM;
1347 }
1348
1349 def = &map->def;
1350 def->type = BPF_MAP_TYPE_ARRAY;
1351 def->key_size = sizeof(int);
1352 def->value_size = data_sz;
1353 def->max_entries = 1;
1354 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1355 ? BPF_F_RDONLY_PROG : 0;
1356 def->map_flags |= BPF_F_MMAPABLE;
1357
1358 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1359 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1360
1361 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1362 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1363 if (map->mmaped == MAP_FAILED) {
1364 err = -errno;
1365 map->mmaped = NULL;
1366 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1367 map->name, err);
1368 zfree(&map->name);
1369 return err;
1370 }
1371
1372 if (data)
1373 memcpy(map->mmaped, data, data_sz);
1374
1375 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1376 return 0;
1377}
1378
1379static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1380{
1381 int err;
1382
1383 /*
1384 * Populate obj->maps with libbpf internal maps.
1385 */
1386 if (obj->efile.data_shndx >= 0) {
1387 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1388 obj->efile.data_shndx,
1389 obj->efile.data->d_buf,
1390 obj->efile.data->d_size);
1391 if (err)
1392 return err;
1393 }
1394 if (obj->efile.rodata_shndx >= 0) {
1395 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1396 obj->efile.rodata_shndx,
1397 obj->efile.rodata->d_buf,
1398 obj->efile.rodata->d_size);
1399 if (err)
1400 return err;
1401 }
1402 if (obj->efile.bss_shndx >= 0) {
1403 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1404 obj->efile.bss_shndx,
1405 NULL,
1406 obj->efile.bss->d_size);
1407 if (err)
1408 return err;
1409 }
1410 return 0;
1411}
1412
1413
1414static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1415 const void *name)
1416{
1417 int i;
1418
1419 for (i = 0; i < obj->nr_extern; i++) {
1420 if (strcmp(obj->externs[i].name, name) == 0)
1421 return &obj->externs[i];
1422 }
1423 return NULL;
1424}
1425
1426static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1427 char value)
1428{
1429 switch (ext->type) {
1430 case EXT_BOOL:
1431 if (value == 'm') {
1432 pr_warn("extern %s=%c should be tristate or char\n",
1433 ext->name, value);
1434 return -EINVAL;
1435 }
1436 *(bool *)ext_val = value == 'y' ? true : false;
1437 break;
1438 case EXT_TRISTATE:
1439 if (value == 'y')
1440 *(enum libbpf_tristate *)ext_val = TRI_YES;
1441 else if (value == 'm')
1442 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1443 else /* value == 'n' */
1444 *(enum libbpf_tristate *)ext_val = TRI_NO;
1445 break;
1446 case EXT_CHAR:
1447 *(char *)ext_val = value;
1448 break;
1449 case EXT_UNKNOWN:
1450 case EXT_INT:
1451 case EXT_CHAR_ARR:
1452 default:
1453 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1454 ext->name, value);
1455 return -EINVAL;
1456 }
1457 ext->is_set = true;
1458 return 0;
1459}
1460
1461static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1462 const char *value)
1463{
1464 size_t len;
1465
1466 if (ext->type != EXT_CHAR_ARR) {
1467 pr_warn("extern %s=%s should char array\n", ext->name, value);
1468 return -EINVAL;
1469 }
1470
1471 len = strlen(value);
1472 if (value[len - 1] != '"') {
1473 pr_warn("extern '%s': invalid string config '%s'\n",
1474 ext->name, value);
1475 return -EINVAL;
1476 }
1477
1478 /* strip quotes */
1479 len -= 2;
1480 if (len >= ext->sz) {
1481 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1482 ext->name, value, len, ext->sz - 1);
1483 len = ext->sz - 1;
1484 }
1485 memcpy(ext_val, value + 1, len);
1486 ext_val[len] = '\0';
1487 ext->is_set = true;
1488 return 0;
1489}
1490
1491static int parse_u64(const char *value, __u64 *res)
1492{
1493 char *value_end;
1494 int err;
1495
1496 errno = 0;
1497 *res = strtoull(value, &value_end, 0);
1498 if (errno) {
1499 err = -errno;
1500 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1501 return err;
1502 }
1503 if (*value_end) {
1504 pr_warn("failed to parse '%s' as integer completely\n", value);
1505 return -EINVAL;
1506 }
1507 return 0;
1508}
1509
1510static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1511{
1512 int bit_sz = ext->sz * 8;
1513
1514 if (ext->sz == 8)
1515 return true;
1516
1517 /* Validate that value stored in u64 fits in integer of `ext->sz`
1518 * bytes size without any loss of information. If the target integer
1519 * is signed, we rely on the following limits of integer type of
1520 * Y bits and subsequent transformation:
1521 *
1522 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1523 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1524 * 0 <= X + 2^(Y-1) < 2^Y
1525 *
1526 * For unsigned target integer, check that all the (64 - Y) bits are
1527 * zero.
1528 */
1529 if (ext->is_signed)
1530 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1531 else
1532 return (v >> bit_sz) == 0;
1533}
1534
1535static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1536 __u64 value)
1537{
1538 if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1539 pr_warn("extern %s=%llu should be integer\n",
1540 ext->name, (unsigned long long)value);
1541 return -EINVAL;
1542 }
1543 if (!is_ext_value_in_range(ext, value)) {
1544 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1545 ext->name, (unsigned long long)value, ext->sz);
1546 return -ERANGE;
1547 }
1548 switch (ext->sz) {
1549 case 1: *(__u8 *)ext_val = value; break;
1550 case 2: *(__u16 *)ext_val = value; break;
1551 case 4: *(__u32 *)ext_val = value; break;
1552 case 8: *(__u64 *)ext_val = value; break;
1553 default:
1554 return -EINVAL;
1555 }
1556 ext->is_set = true;
1557 return 0;
1558}
1559
1560static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1561 char *buf, void *data)
1562{
1563 struct extern_desc *ext;
1564 char *sep, *value;
1565 int len, err = 0;
1566 void *ext_val;
1567 __u64 num;
1568
1569 if (strncmp(buf, "CONFIG_", 7))
1570 return 0;
1571
1572 sep = strchr(buf, '=');
1573 if (!sep) {
1574 pr_warn("failed to parse '%s': no separator\n", buf);
1575 return -EINVAL;
1576 }
1577
1578 /* Trim ending '\n' */
1579 len = strlen(buf);
1580 if (buf[len - 1] == '\n')
1581 buf[len - 1] = '\0';
1582 /* Split on '=' and ensure that a value is present. */
1583 *sep = '\0';
1584 if (!sep[1]) {
1585 *sep = '=';
1586 pr_warn("failed to parse '%s': no value\n", buf);
1587 return -EINVAL;
1588 }
1589
1590 ext = find_extern_by_name(obj, buf);
1591 if (!ext || ext->is_set)
1592 return 0;
1593
1594 ext_val = data + ext->data_off;
1595 value = sep + 1;
1596
1597 switch (*value) {
1598 case 'y': case 'n': case 'm':
1599 err = set_ext_value_tri(ext, ext_val, *value);
1600 break;
1601 case '"':
1602 err = set_ext_value_str(ext, ext_val, value);
1603 break;
1604 default:
1605 /* assume integer */
1606 err = parse_u64(value, &num);
1607 if (err) {
1608 pr_warn("extern %s=%s should be integer\n",
1609 ext->name, value);
1610 return err;
1611 }
1612 err = set_ext_value_num(ext, ext_val, num);
1613 break;
1614 }
1615 if (err)
1616 return err;
1617 pr_debug("extern %s=%s\n", ext->name, value);
1618 return 0;
1619}
1620
1621static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1622{
1623 char buf[PATH_MAX];
1624 struct utsname uts;
1625 int len, err = 0;
1626 gzFile file;
1627
1628 uname(&uts);
1629 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1630 if (len < 0)
1631 return -EINVAL;
1632 else if (len >= PATH_MAX)
1633 return -ENAMETOOLONG;
1634
1635 /* gzopen also accepts uncompressed files. */
1636 file = gzopen(buf, "r");
1637 if (!file)
1638 file = gzopen("/proc/config.gz", "r");
1639
1640 if (!file) {
1641 pr_warn("failed to open system Kconfig\n");
1642 return -ENOENT;
1643 }
1644
1645 while (gzgets(file, buf, sizeof(buf))) {
1646 err = bpf_object__process_kconfig_line(obj, buf, data);
1647 if (err) {
1648 pr_warn("error parsing system Kconfig line '%s': %d\n",
1649 buf, err);
1650 goto out;
1651 }
1652 }
1653
1654out:
1655 gzclose(file);
1656 return err;
1657}
1658
1659static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1660 const char *config, void *data)
1661{
1662 char buf[PATH_MAX];
1663 int err = 0;
1664 FILE *file;
1665
1666 file = fmemopen((void *)config, strlen(config), "r");
1667 if (!file) {
1668 err = -errno;
1669 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1670 return err;
1671 }
1672
1673 while (fgets(buf, sizeof(buf), file)) {
1674 err = bpf_object__process_kconfig_line(obj, buf, data);
1675 if (err) {
1676 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1677 buf, err);
1678 break;
1679 }
1680 }
1681
1682 fclose(file);
1683 return err;
1684}
1685
1686static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1687{
1688 struct extern_desc *last_ext;
1689 size_t map_sz;
1690 int err;
1691
1692 if (obj->nr_extern == 0)
1693 return 0;
1694
1695 last_ext = &obj->externs[obj->nr_extern - 1];
1696 map_sz = last_ext->data_off + last_ext->sz;
1697
1698 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1699 obj->efile.symbols_shndx,
1700 NULL, map_sz);
1701 if (err)
1702 return err;
1703
1704 obj->kconfig_map_idx = obj->nr_maps - 1;
1705
1706 return 0;
1707}
1708
1709static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1710{
1711 Elf_Data *symbols = obj->efile.symbols;
1712 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1713 Elf_Data *data = NULL;
1714 Elf_Scn *scn;
1715
1716 if (obj->efile.maps_shndx < 0)
1717 return 0;
1718
1719 if (!symbols)
1720 return -EINVAL;
1721
1722 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1723 if (scn)
1724 data = elf_getdata(scn, NULL);
1725 if (!scn || !data) {
1726 pr_warn("failed to get Elf_Data from map section %d\n",
1727 obj->efile.maps_shndx);
1728 return -EINVAL;
1729 }
1730
1731 /*
1732 * Count number of maps. Each map has a name.
1733 * Array of maps is not supported: only the first element is
1734 * considered.
1735 *
1736 * TODO: Detect array of map and report error.
1737 */
1738 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1739 for (i = 0; i < nr_syms; i++) {
1740 GElf_Sym sym;
1741
1742 if (!gelf_getsym(symbols, i, &sym))
1743 continue;
1744 if (sym.st_shndx != obj->efile.maps_shndx)
1745 continue;
1746 nr_maps++;
1747 }
1748 /* Assume equally sized map definitions */
1749 pr_debug("maps in %s: %d maps in %zd bytes\n",
1750 obj->path, nr_maps, data->d_size);
1751
1752 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1753 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
1754 obj->path, nr_maps, data->d_size);
1755 return -EINVAL;
1756 }
1757 map_def_sz = data->d_size / nr_maps;
1758
1759 /* Fill obj->maps using data in "maps" section. */
1760 for (i = 0; i < nr_syms; i++) {
1761 GElf_Sym sym;
1762 const char *map_name;
1763 struct bpf_map_def *def;
1764 struct bpf_map *map;
1765
1766 if (!gelf_getsym(symbols, i, &sym))
1767 continue;
1768 if (sym.st_shndx != obj->efile.maps_shndx)
1769 continue;
1770
1771 map = bpf_object__add_map(obj);
1772 if (IS_ERR(map))
1773 return PTR_ERR(map);
1774
1775 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
1776 sym.st_name);
1777 if (!map_name) {
1778 pr_warn("failed to get map #%d name sym string for obj %s\n",
1779 i, obj->path);
1780 return -LIBBPF_ERRNO__FORMAT;
1781 }
1782
1783 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1784 map->sec_idx = sym.st_shndx;
1785 map->sec_offset = sym.st_value;
1786 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1787 map_name, map->sec_idx, map->sec_offset);
1788 if (sym.st_value + map_def_sz > data->d_size) {
1789 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1790 obj->path, map_name);
1791 return -EINVAL;
1792 }
1793
1794 map->name = strdup(map_name);
1795 if (!map->name) {
1796 pr_warn("failed to alloc map name\n");
1797 return -ENOMEM;
1798 }
1799 pr_debug("map %d is \"%s\"\n", i, map->name);
1800 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1801 /*
1802 * If the definition of the map in the object file fits in
1803 * bpf_map_def, copy it. Any extra fields in our version
1804 * of bpf_map_def will default to zero as a result of the
1805 * calloc above.
1806 */
1807 if (map_def_sz <= sizeof(struct bpf_map_def)) {
1808 memcpy(&map->def, def, map_def_sz);
1809 } else {
1810 /*
1811 * Here the map structure being read is bigger than what
1812 * we expect, truncate if the excess bits are all zero.
1813 * If they are not zero, reject this map as
1814 * incompatible.
1815 */
1816 char *b;
1817
1818 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1819 b < ((char *)def) + map_def_sz; b++) {
1820 if (*b != 0) {
1821 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1822 obj->path, map_name);
1823 if (strict)
1824 return -EINVAL;
1825 }
1826 }
1827 memcpy(&map->def, def, sizeof(struct bpf_map_def));
1828 }
1829 }
1830 return 0;
1831}
1832
1833static const struct btf_type *
1834skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1835{
1836 const struct btf_type *t = btf__type_by_id(btf, id);
1837
1838 if (res_id)
1839 *res_id = id;
1840
1841 while (btf_is_mod(t) || btf_is_typedef(t)) {
1842 if (res_id)
1843 *res_id = t->type;
1844 t = btf__type_by_id(btf, t->type);
1845 }
1846
1847 return t;
1848}
1849
1850static const struct btf_type *
1851resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1852{
1853 const struct btf_type *t;
1854
1855 t = skip_mods_and_typedefs(btf, id, NULL);
1856 if (!btf_is_ptr(t))
1857 return NULL;
1858
1859 t = skip_mods_and_typedefs(btf, t->type, res_id);
1860
1861 return btf_is_func_proto(t) ? t : NULL;
1862}
1863
1864/*
1865 * Fetch integer attribute of BTF map definition. Such attributes are
1866 * represented using a pointer to an array, in which dimensionality of array
1867 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1868 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1869 * type definition, while using only sizeof(void *) space in ELF data section.
1870 */
1871static bool get_map_field_int(const char *map_name, const struct btf *btf,
1872 const struct btf_member *m, __u32 *res)
1873{
1874 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1875 const char *name = btf__name_by_offset(btf, m->name_off);
1876 const struct btf_array *arr_info;
1877 const struct btf_type *arr_t;
1878
1879 if (!btf_is_ptr(t)) {
1880 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1881 map_name, name, btf_kind(t));
1882 return false;
1883 }
1884
1885 arr_t = btf__type_by_id(btf, t->type);
1886 if (!arr_t) {
1887 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1888 map_name, name, t->type);
1889 return false;
1890 }
1891 if (!btf_is_array(arr_t)) {
1892 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1893 map_name, name, btf_kind(arr_t));
1894 return false;
1895 }
1896 arr_info = btf_array(arr_t);
1897 *res = arr_info->nelems;
1898 return true;
1899}
1900
1901static int build_map_pin_path(struct bpf_map *map, const char *path)
1902{
1903 char buf[PATH_MAX];
1904 int err, len;
1905
1906 if (!path)
1907 path = "/sys/fs/bpf";
1908
1909 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1910 if (len < 0)
1911 return -EINVAL;
1912 else if (len >= PATH_MAX)
1913 return -ENAMETOOLONG;
1914
1915 err = bpf_map__set_pin_path(map, buf);
1916 if (err)
1917 return err;
1918
1919 return 0;
1920}
1921
1922
1923static int parse_btf_map_def(struct bpf_object *obj,
1924 struct bpf_map *map,
1925 const struct btf_type *def,
1926 bool strict, bool is_inner,
1927 const char *pin_root_path)
1928{
1929 const struct btf_type *t;
1930 const struct btf_member *m;
1931 int vlen, i;
1932
1933 vlen = btf_vlen(def);
1934 m = btf_members(def);
1935 for (i = 0; i < vlen; i++, m++) {
1936 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1937
1938 if (!name) {
1939 pr_warn("map '%s': invalid field #%d.\n", map->name, i);
1940 return -EINVAL;
1941 }
1942 if (strcmp(name, "type") == 0) {
1943 if (!get_map_field_int(map->name, obj->btf, m,
1944 &map->def.type))
1945 return -EINVAL;
1946 pr_debug("map '%s': found type = %u.\n",
1947 map->name, map->def.type);
1948 } else if (strcmp(name, "max_entries") == 0) {
1949 if (!get_map_field_int(map->name, obj->btf, m,
1950 &map->def.max_entries))
1951 return -EINVAL;
1952 pr_debug("map '%s': found max_entries = %u.\n",
1953 map->name, map->def.max_entries);
1954 } else if (strcmp(name, "map_flags") == 0) {
1955 if (!get_map_field_int(map->name, obj->btf, m,
1956 &map->def.map_flags))
1957 return -EINVAL;
1958 pr_debug("map '%s': found map_flags = %u.\n",
1959 map->name, map->def.map_flags);
1960 } else if (strcmp(name, "key_size") == 0) {
1961 __u32 sz;
1962
1963 if (!get_map_field_int(map->name, obj->btf, m, &sz))
1964 return -EINVAL;
1965 pr_debug("map '%s': found key_size = %u.\n",
1966 map->name, sz);
1967 if (map->def.key_size && map->def.key_size != sz) {
1968 pr_warn("map '%s': conflicting key size %u != %u.\n",
1969 map->name, map->def.key_size, sz);
1970 return -EINVAL;
1971 }
1972 map->def.key_size = sz;
1973 } else if (strcmp(name, "key") == 0) {
1974 __s64 sz;
1975
1976 t = btf__type_by_id(obj->btf, m->type);
1977 if (!t) {
1978 pr_warn("map '%s': key type [%d] not found.\n",
1979 map->name, m->type);
1980 return -EINVAL;
1981 }
1982 if (!btf_is_ptr(t)) {
1983 pr_warn("map '%s': key spec is not PTR: %u.\n",
1984 map->name, btf_kind(t));
1985 return -EINVAL;
1986 }
1987 sz = btf__resolve_size(obj->btf, t->type);
1988 if (sz < 0) {
1989 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1990 map->name, t->type, (ssize_t)sz);
1991 return sz;
1992 }
1993 pr_debug("map '%s': found key [%u], sz = %zd.\n",
1994 map->name, t->type, (ssize_t)sz);
1995 if (map->def.key_size && map->def.key_size != sz) {
1996 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1997 map->name, map->def.key_size, (ssize_t)sz);
1998 return -EINVAL;
1999 }
2000 map->def.key_size = sz;
2001 map->btf_key_type_id = t->type;
2002 } else if (strcmp(name, "value_size") == 0) {
2003 __u32 sz;
2004
2005 if (!get_map_field_int(map->name, obj->btf, m, &sz))
2006 return -EINVAL;
2007 pr_debug("map '%s': found value_size = %u.\n",
2008 map->name, sz);
2009 if (map->def.value_size && map->def.value_size != sz) {
2010 pr_warn("map '%s': conflicting value size %u != %u.\n",
2011 map->name, map->def.value_size, sz);
2012 return -EINVAL;
2013 }
2014 map->def.value_size = sz;
2015 } else if (strcmp(name, "value") == 0) {
2016 __s64 sz;
2017
2018 t = btf__type_by_id(obj->btf, m->type);
2019 if (!t) {
2020 pr_warn("map '%s': value type [%d] not found.\n",
2021 map->name, m->type);
2022 return -EINVAL;
2023 }
2024 if (!btf_is_ptr(t)) {
2025 pr_warn("map '%s': value spec is not PTR: %u.\n",
2026 map->name, btf_kind(t));
2027 return -EINVAL;
2028 }
2029 sz = btf__resolve_size(obj->btf, t->type);
2030 if (sz < 0) {
2031 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2032 map->name, t->type, (ssize_t)sz);
2033 return sz;
2034 }
2035 pr_debug("map '%s': found value [%u], sz = %zd.\n",
2036 map->name, t->type, (ssize_t)sz);
2037 if (map->def.value_size && map->def.value_size != sz) {
2038 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2039 map->name, map->def.value_size, (ssize_t)sz);
2040 return -EINVAL;
2041 }
2042 map->def.value_size = sz;
2043 map->btf_value_type_id = t->type;
2044 }
2045 else if (strcmp(name, "values") == 0) {
2046 int err;
2047
2048 if (is_inner) {
2049 pr_warn("map '%s': multi-level inner maps not supported.\n",
2050 map->name);
2051 return -ENOTSUP;
2052 }
2053 if (i != vlen - 1) {
2054 pr_warn("map '%s': '%s' member should be last.\n",
2055 map->name, name);
2056 return -EINVAL;
2057 }
2058 if (!bpf_map_type__is_map_in_map(map->def.type)) {
2059 pr_warn("map '%s': should be map-in-map.\n",
2060 map->name);
2061 return -ENOTSUP;
2062 }
2063 if (map->def.value_size && map->def.value_size != 4) {
2064 pr_warn("map '%s': conflicting value size %u != 4.\n",
2065 map->name, map->def.value_size);
2066 return -EINVAL;
2067 }
2068 map->def.value_size = 4;
2069 t = btf__type_by_id(obj->btf, m->type);
2070 if (!t) {
2071 pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2072 map->name, m->type);
2073 return -EINVAL;
2074 }
2075 if (!btf_is_array(t) || btf_array(t)->nelems) {
2076 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2077 map->name);
2078 return -EINVAL;
2079 }
2080 t = skip_mods_and_typedefs(obj->btf, btf_array(t)->type,
2081 NULL);
2082 if (!btf_is_ptr(t)) {
2083 pr_warn("map '%s': map-in-map inner def is of unexpected kind %u.\n",
2084 map->name, btf_kind(t));
2085 return -EINVAL;
2086 }
2087 t = skip_mods_and_typedefs(obj->btf, t->type, NULL);
2088 if (!btf_is_struct(t)) {
2089 pr_warn("map '%s': map-in-map inner def is of unexpected kind %u.\n",
2090 map->name, btf_kind(t));
2091 return -EINVAL;
2092 }
2093
2094 map->inner_map = calloc(1, sizeof(*map->inner_map));
2095 if (!map->inner_map)
2096 return -ENOMEM;
2097 map->inner_map->sec_idx = obj->efile.btf_maps_shndx;
2098 map->inner_map->name = malloc(strlen(map->name) +
2099 sizeof(".inner") + 1);
2100 if (!map->inner_map->name)
2101 return -ENOMEM;
2102 sprintf(map->inner_map->name, "%s.inner", map->name);
2103
2104 err = parse_btf_map_def(obj, map->inner_map, t, strict,
2105 true /* is_inner */, NULL);
2106 if (err)
2107 return err;
2108 } else if (strcmp(name, "pinning") == 0) {
2109 __u32 val;
2110 int err;
2111
2112 if (is_inner) {
2113 pr_debug("map '%s': inner def can't be pinned.\n",
2114 map->name);
2115 return -EINVAL;
2116 }
2117 if (!get_map_field_int(map->name, obj->btf, m, &val))
2118 return -EINVAL;
2119 pr_debug("map '%s': found pinning = %u.\n",
2120 map->name, val);
2121
2122 if (val != LIBBPF_PIN_NONE &&
2123 val != LIBBPF_PIN_BY_NAME) {
2124 pr_warn("map '%s': invalid pinning value %u.\n",
2125 map->name, val);
2126 return -EINVAL;
2127 }
2128 if (val == LIBBPF_PIN_BY_NAME) {
2129 err = build_map_pin_path(map, pin_root_path);
2130 if (err) {
2131 pr_warn("map '%s': couldn't build pin path.\n",
2132 map->name);
2133 return err;
2134 }
2135 }
2136 } else {
2137 if (strict) {
2138 pr_warn("map '%s': unknown field '%s'.\n",
2139 map->name, name);
2140 return -ENOTSUP;
2141 }
2142 pr_debug("map '%s': ignoring unknown field '%s'.\n",
2143 map->name, name);
2144 }
2145 }
2146
2147 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
2148 pr_warn("map '%s': map type isn't specified.\n", map->name);
2149 return -EINVAL;
2150 }
2151
2152 return 0;
2153}
2154
2155static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2156 const struct btf_type *sec,
2157 int var_idx, int sec_idx,
2158 const Elf_Data *data, bool strict,
2159 const char *pin_root_path)
2160{
2161 const struct btf_type *var, *def;
2162 const struct btf_var_secinfo *vi;
2163 const struct btf_var *var_extra;
2164 const char *map_name;
2165 struct bpf_map *map;
2166
2167 vi = btf_var_secinfos(sec) + var_idx;
2168 var = btf__type_by_id(obj->btf, vi->type);
2169 var_extra = btf_var(var);
2170 map_name = btf__name_by_offset(obj->btf, var->name_off);
2171
2172 if (map_name == NULL || map_name[0] == '\0') {
2173 pr_warn("map #%d: empty name.\n", var_idx);
2174 return -EINVAL;
2175 }
2176 if ((__u64)vi->offset + vi->size > data->d_size) {
2177 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2178 return -EINVAL;
2179 }
2180 if (!btf_is_var(var)) {
2181 pr_warn("map '%s': unexpected var kind %u.\n",
2182 map_name, btf_kind(var));
2183 return -EINVAL;
2184 }
2185 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2186 var_extra->linkage != BTF_VAR_STATIC) {
2187 pr_warn("map '%s': unsupported var linkage %u.\n",
2188 map_name, var_extra->linkage);
2189 return -EOPNOTSUPP;
2190 }
2191
2192 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2193 if (!btf_is_struct(def)) {
2194 pr_warn("map '%s': unexpected def kind %u.\n",
2195 map_name, btf_kind(var));
2196 return -EINVAL;
2197 }
2198 if (def->size > vi->size) {
2199 pr_warn("map '%s': invalid def size.\n", map_name);
2200 return -EINVAL;
2201 }
2202
2203 map = bpf_object__add_map(obj);
2204 if (IS_ERR(map))
2205 return PTR_ERR(map);
2206 map->name = strdup(map_name);
2207 if (!map->name) {
2208 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2209 return -ENOMEM;
2210 }
2211 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2212 map->def.type = BPF_MAP_TYPE_UNSPEC;
2213 map->sec_idx = sec_idx;
2214 map->sec_offset = vi->offset;
2215 map->btf_var_idx = var_idx;
2216 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2217 map_name, map->sec_idx, map->sec_offset);
2218
2219 return parse_btf_map_def(obj, map, def, strict, false, pin_root_path);
2220}
2221
2222static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2223 const char *pin_root_path)
2224{
2225 const struct btf_type *sec = NULL;
2226 int nr_types, i, vlen, err;
2227 const struct btf_type *t;
2228 const char *name;
2229 Elf_Data *data;
2230 Elf_Scn *scn;
2231
2232 if (obj->efile.btf_maps_shndx < 0)
2233 return 0;
2234
2235 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
2236 if (scn)
2237 data = elf_getdata(scn, NULL);
2238 if (!scn || !data) {
2239 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
2240 obj->efile.maps_shndx, MAPS_ELF_SEC);
2241 return -EINVAL;
2242 }
2243
2244 nr_types = btf__get_nr_types(obj->btf);
2245 for (i = 1; i <= nr_types; i++) {
2246 t = btf__type_by_id(obj->btf, i);
2247 if (!btf_is_datasec(t))
2248 continue;
2249 name = btf__name_by_offset(obj->btf, t->name_off);
2250 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2251 sec = t;
2252 obj->efile.btf_maps_sec_btf_id = i;
2253 break;
2254 }
2255 }
2256
2257 if (!sec) {
2258 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2259 return -ENOENT;
2260 }
2261
2262 vlen = btf_vlen(sec);
2263 for (i = 0; i < vlen; i++) {
2264 err = bpf_object__init_user_btf_map(obj, sec, i,
2265 obj->efile.btf_maps_shndx,
2266 data, strict,
2267 pin_root_path);
2268 if (err)
2269 return err;
2270 }
2271
2272 return 0;
2273}
2274
2275static int bpf_object__init_maps(struct bpf_object *obj,
2276 const struct bpf_object_open_opts *opts)
2277{
2278 const char *pin_root_path;
2279 bool strict;
2280 int err;
2281
2282 strict = !OPTS_GET(opts, relaxed_maps, false);
2283 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2284
2285 err = bpf_object__init_user_maps(obj, strict);
2286 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2287 err = err ?: bpf_object__init_global_data_maps(obj);
2288 err = err ?: bpf_object__init_kconfig_map(obj);
2289 err = err ?: bpf_object__init_struct_ops_maps(obj);
2290 if (err)
2291 return err;
2292
2293 return 0;
2294}
2295
2296static bool section_have_execinstr(struct bpf_object *obj, int idx)
2297{
2298 Elf_Scn *scn;
2299 GElf_Shdr sh;
2300
2301 scn = elf_getscn(obj->efile.elf, idx);
2302 if (!scn)
2303 return false;
2304
2305 if (gelf_getshdr(scn, &sh) != &sh)
2306 return false;
2307
2308 if (sh.sh_flags & SHF_EXECINSTR)
2309 return true;
2310
2311 return false;
2312}
2313
2314static void bpf_object__sanitize_btf(struct bpf_object *obj)
2315{
2316 bool has_func_global = obj->caps.btf_func_global;
2317 bool has_datasec = obj->caps.btf_datasec;
2318 bool has_func = obj->caps.btf_func;
2319 struct btf *btf = obj->btf;
2320 struct btf_type *t;
2321 int i, j, vlen;
2322
2323 if (!obj->btf || (has_func && has_datasec && has_func_global))
2324 return;
2325
2326 for (i = 1; i <= btf__get_nr_types(btf); i++) {
2327 t = (struct btf_type *)btf__type_by_id(btf, i);
2328
2329 if (!has_datasec && btf_is_var(t)) {
2330 /* replace VAR with INT */
2331 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2332 /*
2333 * using size = 1 is the safest choice, 4 will be too
2334 * big and cause kernel BTF validation failure if
2335 * original variable took less than 4 bytes
2336 */
2337 t->size = 1;
2338 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2339 } else if (!has_datasec && btf_is_datasec(t)) {
2340 /* replace DATASEC with STRUCT */
2341 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2342 struct btf_member *m = btf_members(t);
2343 struct btf_type *vt;
2344 char *name;
2345
2346 name = (char *)btf__name_by_offset(btf, t->name_off);
2347 while (*name) {
2348 if (*name == '.')
2349 *name = '_';
2350 name++;
2351 }
2352
2353 vlen = btf_vlen(t);
2354 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2355 for (j = 0; j < vlen; j++, v++, m++) {
2356 /* order of field assignments is important */
2357 m->offset = v->offset * 8;
2358 m->type = v->type;
2359 /* preserve variable name as member name */
2360 vt = (void *)btf__type_by_id(btf, v->type);
2361 m->name_off = vt->name_off;
2362 }
2363 } else if (!has_func && btf_is_func_proto(t)) {
2364 /* replace FUNC_PROTO with ENUM */
2365 vlen = btf_vlen(t);
2366 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2367 t->size = sizeof(__u32); /* kernel enforced */
2368 } else if (!has_func && btf_is_func(t)) {
2369 /* replace FUNC with TYPEDEF */
2370 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2371 } else if (!has_func_global && btf_is_func(t)) {
2372 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2373 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2374 }
2375 }
2376}
2377
2378static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
2379{
2380 if (!obj->btf_ext)
2381 return;
2382
2383 if (!obj->caps.btf_func) {
2384 btf_ext__free(obj->btf_ext);
2385 obj->btf_ext = NULL;
2386 }
2387}
2388
2389static bool libbpf_needs_btf(const struct bpf_object *obj)
2390{
2391 return obj->efile.btf_maps_shndx >= 0 ||
2392 obj->efile.st_ops_shndx >= 0 ||
2393 obj->nr_extern > 0;
2394}
2395
2396static bool kernel_needs_btf(const struct bpf_object *obj)
2397{
2398 return obj->efile.st_ops_shndx >= 0;
2399}
2400
2401static int bpf_object__init_btf(struct bpf_object *obj,
2402 Elf_Data *btf_data,
2403 Elf_Data *btf_ext_data)
2404{
2405 int err = -ENOENT;
2406
2407 if (btf_data) {
2408 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2409 if (IS_ERR(obj->btf)) {
2410 err = PTR_ERR(obj->btf);
2411 obj->btf = NULL;
2412 pr_warn("Error loading ELF section %s: %d.\n",
2413 BTF_ELF_SEC, err);
2414 goto out;
2415 }
2416 err = 0;
2417 }
2418 if (btf_ext_data) {
2419 if (!obj->btf) {
2420 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2421 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2422 goto out;
2423 }
2424 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
2425 btf_ext_data->d_size);
2426 if (IS_ERR(obj->btf_ext)) {
2427 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2428 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
2429 obj->btf_ext = NULL;
2430 goto out;
2431 }
2432 }
2433out:
2434 if (err && libbpf_needs_btf(obj)) {
2435 pr_warn("BTF is required, but is missing or corrupted.\n");
2436 return err;
2437 }
2438 return 0;
2439}
2440
2441static int bpf_object__finalize_btf(struct bpf_object *obj)
2442{
2443 int err;
2444
2445 if (!obj->btf)
2446 return 0;
2447
2448 err = btf__finalize_data(obj, obj->btf);
2449 if (!err)
2450 return 0;
2451
2452 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2453 btf__free(obj->btf);
2454 obj->btf = NULL;
2455 btf_ext__free(obj->btf_ext);
2456 obj->btf_ext = NULL;
2457
2458 if (libbpf_needs_btf(obj)) {
2459 pr_warn("BTF is required, but is missing or corrupted.\n");
2460 return -ENOENT;
2461 }
2462 return 0;
2463}
2464
2465static inline bool libbpf_prog_needs_vmlinux_btf(struct bpf_program *prog)
2466{
2467 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2468 prog->type == BPF_PROG_TYPE_LSM)
2469 return true;
2470
2471 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2472 * also need vmlinux BTF
2473 */
2474 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2475 return true;
2476
2477 return false;
2478}
2479
2480static int bpf_object__load_vmlinux_btf(struct bpf_object *obj)
2481{
2482 struct bpf_program *prog;
2483 int err;
2484
2485 bpf_object__for_each_program(prog, obj) {
2486 if (libbpf_prog_needs_vmlinux_btf(prog)) {
2487 obj->btf_vmlinux = libbpf_find_kernel_btf();
2488 if (IS_ERR(obj->btf_vmlinux)) {
2489 err = PTR_ERR(obj->btf_vmlinux);
2490 pr_warn("Error loading vmlinux BTF: %d\n", err);
2491 obj->btf_vmlinux = NULL;
2492 return err;
2493 }
2494 return 0;
2495 }
2496 }
2497
2498 return 0;
2499}
2500
2501static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2502{
2503 int err = 0;
2504
2505 if (!obj->btf)
2506 return 0;
2507
2508 bpf_object__sanitize_btf(obj);
2509 bpf_object__sanitize_btf_ext(obj);
2510
2511 err = btf__load(obj->btf);
2512 if (err) {
2513 pr_warn("Error loading %s into kernel: %d.\n",
2514 BTF_ELF_SEC, err);
2515 btf__free(obj->btf);
2516 obj->btf = NULL;
2517 /* btf_ext can't exist without btf, so free it as well */
2518 if (obj->btf_ext) {
2519 btf_ext__free(obj->btf_ext);
2520 obj->btf_ext = NULL;
2521 }
2522
2523 if (kernel_needs_btf(obj))
2524 return err;
2525 }
2526 return 0;
2527}
2528
2529static int bpf_object__elf_collect(struct bpf_object *obj)
2530{
2531 Elf *elf = obj->efile.elf;
2532 GElf_Ehdr *ep = &obj->efile.ehdr;
2533 Elf_Data *btf_ext_data = NULL;
2534 Elf_Data *btf_data = NULL;
2535 Elf_Scn *scn = NULL;
2536 int idx = 0, err = 0;
2537
2538 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
2539 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
2540 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
2541 return -LIBBPF_ERRNO__FORMAT;
2542 }
2543
2544 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2545 char *name;
2546 GElf_Shdr sh;
2547 Elf_Data *data;
2548
2549 idx++;
2550 if (gelf_getshdr(scn, &sh) != &sh) {
2551 pr_warn("failed to get section(%d) header from %s\n",
2552 idx, obj->path);
2553 return -LIBBPF_ERRNO__FORMAT;
2554 }
2555
2556 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
2557 if (!name) {
2558 pr_warn("failed to get section(%d) name from %s\n",
2559 idx, obj->path);
2560 return -LIBBPF_ERRNO__FORMAT;
2561 }
2562
2563 data = elf_getdata(scn, 0);
2564 if (!data) {
2565 pr_warn("failed to get section(%d) data from %s(%s)\n",
2566 idx, name, obj->path);
2567 return -LIBBPF_ERRNO__FORMAT;
2568 }
2569 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
2570 idx, name, (unsigned long)data->d_size,
2571 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2572 (int)sh.sh_type);
2573
2574 if (strcmp(name, "license") == 0) {
2575 err = bpf_object__init_license(obj,
2576 data->d_buf,
2577 data->d_size);
2578 if (err)
2579 return err;
2580 } else if (strcmp(name, "version") == 0) {
2581 err = bpf_object__init_kversion(obj,
2582 data->d_buf,
2583 data->d_size);
2584 if (err)
2585 return err;
2586 } else if (strcmp(name, "maps") == 0) {
2587 obj->efile.maps_shndx = idx;
2588 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2589 obj->efile.btf_maps_shndx = idx;
2590 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2591 btf_data = data;
2592 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2593 btf_ext_data = data;
2594 } else if (sh.sh_type == SHT_SYMTAB) {
2595 if (obj->efile.symbols) {
2596 pr_warn("bpf: multiple SYMTAB in %s\n",
2597 obj->path);
2598 return -LIBBPF_ERRNO__FORMAT;
2599 }
2600 obj->efile.symbols = data;
2601 obj->efile.symbols_shndx = idx;
2602 obj->efile.strtabidx = sh.sh_link;
2603 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2604 if (sh.sh_flags & SHF_EXECINSTR) {
2605 if (strcmp(name, ".text") == 0)
2606 obj->efile.text_shndx = idx;
2607 err = bpf_object__add_program(obj, data->d_buf,
2608 data->d_size,
2609 name, idx);
2610 if (err) {
2611 char errmsg[STRERR_BUFSIZE];
2612 char *cp;
2613
2614 cp = libbpf_strerror_r(-err, errmsg,
2615 sizeof(errmsg));
2616 pr_warn("failed to alloc program %s (%s): %s",
2617 name, obj->path, cp);
2618 return err;
2619 }
2620 } else if (strcmp(name, DATA_SEC) == 0) {
2621 obj->efile.data = data;
2622 obj->efile.data_shndx = idx;
2623 } else if (strcmp(name, RODATA_SEC) == 0) {
2624 obj->efile.rodata = data;
2625 obj->efile.rodata_shndx = idx;
2626 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
2627 obj->efile.st_ops_data = data;
2628 obj->efile.st_ops_shndx = idx;
2629 } else {
2630 pr_debug("skip section(%d) %s\n", idx, name);
2631 }
2632 } else if (sh.sh_type == SHT_REL) {
2633 int nr_sects = obj->efile.nr_reloc_sects;
2634 void *sects = obj->efile.reloc_sects;
2635 int sec = sh.sh_info; /* points to other section */
2636
2637 /* Only do relo for section with exec instructions */
2638 if (!section_have_execinstr(obj, sec) &&
2639 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
2640 strcmp(name, ".rel" MAPS_ELF_SEC)) {
2641 pr_debug("skip relo %s(%d) for section(%d)\n",
2642 name, idx, sec);
2643 continue;
2644 }
2645
2646 sects = reallocarray(sects, nr_sects + 1,
2647 sizeof(*obj->efile.reloc_sects));
2648 if (!sects) {
2649 pr_warn("reloc_sects realloc failed\n");
2650 return -ENOMEM;
2651 }
2652
2653 obj->efile.reloc_sects = sects;
2654 obj->efile.nr_reloc_sects++;
2655
2656 obj->efile.reloc_sects[nr_sects].shdr = sh;
2657 obj->efile.reloc_sects[nr_sects].data = data;
2658 } else if (sh.sh_type == SHT_NOBITS &&
2659 strcmp(name, BSS_SEC) == 0) {
2660 obj->efile.bss = data;
2661 obj->efile.bss_shndx = idx;
2662 } else {
2663 pr_debug("skip section(%d) %s\n", idx, name);
2664 }
2665 }
2666
2667 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2668 pr_warn("Corrupted ELF file: index of strtab invalid\n");
2669 return -LIBBPF_ERRNO__FORMAT;
2670 }
2671 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
2672}
2673
2674static bool sym_is_extern(const GElf_Sym *sym)
2675{
2676 int bind = GELF_ST_BIND(sym->st_info);
2677 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2678 return sym->st_shndx == SHN_UNDEF &&
2679 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2680 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2681}
2682
2683static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2684{
2685 const struct btf_type *t;
2686 const char *var_name;
2687 int i, n;
2688
2689 if (!btf)
2690 return -ESRCH;
2691
2692 n = btf__get_nr_types(btf);
2693 for (i = 1; i <= n; i++) {
2694 t = btf__type_by_id(btf, i);
2695
2696 if (!btf_is_var(t))
2697 continue;
2698
2699 var_name = btf__name_by_offset(btf, t->name_off);
2700 if (strcmp(var_name, ext_name))
2701 continue;
2702
2703 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2704 return -EINVAL;
2705
2706 return i;
2707 }
2708
2709 return -ENOENT;
2710}
2711
2712static enum extern_type find_extern_type(const struct btf *btf, int id,
2713 bool *is_signed)
2714{
2715 const struct btf_type *t;
2716 const char *name;
2717
2718 t = skip_mods_and_typedefs(btf, id, NULL);
2719 name = btf__name_by_offset(btf, t->name_off);
2720
2721 if (is_signed)
2722 *is_signed = false;
2723 switch (btf_kind(t)) {
2724 case BTF_KIND_INT: {
2725 int enc = btf_int_encoding(t);
2726
2727 if (enc & BTF_INT_BOOL)
2728 return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2729 if (is_signed)
2730 *is_signed = enc & BTF_INT_SIGNED;
2731 if (t->size == 1)
2732 return EXT_CHAR;
2733 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2734 return EXT_UNKNOWN;
2735 return EXT_INT;
2736 }
2737 case BTF_KIND_ENUM:
2738 if (t->size != 4)
2739 return EXT_UNKNOWN;
2740 if (strcmp(name, "libbpf_tristate"))
2741 return EXT_UNKNOWN;
2742 return EXT_TRISTATE;
2743 case BTF_KIND_ARRAY:
2744 if (btf_array(t)->nelems == 0)
2745 return EXT_UNKNOWN;
2746 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2747 return EXT_UNKNOWN;
2748 return EXT_CHAR_ARR;
2749 default:
2750 return EXT_UNKNOWN;
2751 }
2752}
2753
2754static int cmp_externs(const void *_a, const void *_b)
2755{
2756 const struct extern_desc *a = _a;
2757 const struct extern_desc *b = _b;
2758
2759 /* descending order by alignment requirements */
2760 if (a->align != b->align)
2761 return a->align > b->align ? -1 : 1;
2762 /* ascending order by size, within same alignment class */
2763 if (a->sz != b->sz)
2764 return a->sz < b->sz ? -1 : 1;
2765 /* resolve ties by name */
2766 return strcmp(a->name, b->name);
2767}
2768
2769static int bpf_object__collect_externs(struct bpf_object *obj)
2770{
2771 const struct btf_type *t;
2772 struct extern_desc *ext;
2773 int i, n, off, btf_id;
2774 struct btf_type *sec;
2775 const char *ext_name;
2776 Elf_Scn *scn;
2777 GElf_Shdr sh;
2778
2779 if (!obj->efile.symbols)
2780 return 0;
2781
2782 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2783 if (!scn)
2784 return -LIBBPF_ERRNO__FORMAT;
2785 if (gelf_getshdr(scn, &sh) != &sh)
2786 return -LIBBPF_ERRNO__FORMAT;
2787 n = sh.sh_size / sh.sh_entsize;
2788
2789 pr_debug("looking for externs among %d symbols...\n", n);
2790 for (i = 0; i < n; i++) {
2791 GElf_Sym sym;
2792
2793 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2794 return -LIBBPF_ERRNO__FORMAT;
2795 if (!sym_is_extern(&sym))
2796 continue;
2797 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2798 sym.st_name);
2799 if (!ext_name || !ext_name[0])
2800 continue;
2801
2802 ext = obj->externs;
2803 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2804 if (!ext)
2805 return -ENOMEM;
2806 obj->externs = ext;
2807 ext = &ext[obj->nr_extern];
2808 memset(ext, 0, sizeof(*ext));
2809 obj->nr_extern++;
2810
2811 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2812 if (ext->btf_id <= 0) {
2813 pr_warn("failed to find BTF for extern '%s': %d\n",
2814 ext_name, ext->btf_id);
2815 return ext->btf_id;
2816 }
2817 t = btf__type_by_id(obj->btf, ext->btf_id);
2818 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2819 ext->sym_idx = i;
2820 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2821 ext->sz = btf__resolve_size(obj->btf, t->type);
2822 if (ext->sz <= 0) {
2823 pr_warn("failed to resolve size of extern '%s': %d\n",
2824 ext_name, ext->sz);
2825 return ext->sz;
2826 }
2827 ext->align = btf__align_of(obj->btf, t->type);
2828 if (ext->align <= 0) {
2829 pr_warn("failed to determine alignment of extern '%s': %d\n",
2830 ext_name, ext->align);
2831 return -EINVAL;
2832 }
2833 ext->type = find_extern_type(obj->btf, t->type,
2834 &ext->is_signed);
2835 if (ext->type == EXT_UNKNOWN) {
2836 pr_warn("extern '%s' type is unsupported\n", ext_name);
2837 return -ENOTSUP;
2838 }
2839 }
2840 pr_debug("collected %d externs total\n", obj->nr_extern);
2841
2842 if (!obj->nr_extern)
2843 return 0;
2844
2845 /* sort externs by (alignment, size, name) and calculate their offsets
2846 * within a map */
2847 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2848 off = 0;
2849 for (i = 0; i < obj->nr_extern; i++) {
2850 ext = &obj->externs[i];
2851 ext->data_off = roundup(off, ext->align);
2852 off = ext->data_off + ext->sz;
2853 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2854 i, ext->sym_idx, ext->data_off, ext->name);
2855 }
2856
2857 btf_id = btf__find_by_name(obj->btf, KCONFIG_SEC);
2858 if (btf_id <= 0) {
2859 pr_warn("no BTF info found for '%s' datasec\n", KCONFIG_SEC);
2860 return -ESRCH;
2861 }
2862
2863 sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2864 sec->size = off;
2865 n = btf_vlen(sec);
2866 for (i = 0; i < n; i++) {
2867 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2868
2869 t = btf__type_by_id(obj->btf, vs->type);
2870 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2871 ext = find_extern_by_name(obj, ext_name);
2872 if (!ext) {
2873 pr_warn("failed to find extern definition for BTF var '%s'\n",
2874 ext_name);
2875 return -ESRCH;
2876 }
2877 vs->offset = ext->data_off;
2878 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2879 }
2880
2881 return 0;
2882}
2883
2884static struct bpf_program *
2885bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2886{
2887 struct bpf_program *prog;
2888 size_t i;
2889
2890 for (i = 0; i < obj->nr_programs; i++) {
2891 prog = &obj->programs[i];
2892 if (prog->idx == idx)
2893 return prog;
2894 }
2895 return NULL;
2896}
2897
2898struct bpf_program *
2899bpf_object__find_program_by_title(const struct bpf_object *obj,
2900 const char *title)
2901{
2902 struct bpf_program *pos;
2903
2904 bpf_object__for_each_program(pos, obj) {
2905 if (pos->section_name && !strcmp(pos->section_name, title))
2906 return pos;
2907 }
2908 return NULL;
2909}
2910
2911struct bpf_program *
2912bpf_object__find_program_by_name(const struct bpf_object *obj,
2913 const char *name)
2914{
2915 struct bpf_program *prog;
2916
2917 bpf_object__for_each_program(prog, obj) {
2918 if (!strcmp(prog->name, name))
2919 return prog;
2920 }
2921 return NULL;
2922}
2923
2924static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2925 int shndx)
2926{
2927 return shndx == obj->efile.data_shndx ||
2928 shndx == obj->efile.bss_shndx ||
2929 shndx == obj->efile.rodata_shndx;
2930}
2931
2932static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2933 int shndx)
2934{
2935 return shndx == obj->efile.maps_shndx ||
2936 shndx == obj->efile.btf_maps_shndx;
2937}
2938
2939static enum libbpf_map_type
2940bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2941{
2942 if (shndx == obj->efile.data_shndx)
2943 return LIBBPF_MAP_DATA;
2944 else if (shndx == obj->efile.bss_shndx)
2945 return LIBBPF_MAP_BSS;
2946 else if (shndx == obj->efile.rodata_shndx)
2947 return LIBBPF_MAP_RODATA;
2948 else if (shndx == obj->efile.symbols_shndx)
2949 return LIBBPF_MAP_KCONFIG;
2950 else
2951 return LIBBPF_MAP_UNSPEC;
2952}
2953
2954static int bpf_program__record_reloc(struct bpf_program *prog,
2955 struct reloc_desc *reloc_desc,
2956 __u32 insn_idx, const char *name,
2957 const GElf_Sym *sym, const GElf_Rel *rel)
2958{
2959 struct bpf_insn *insn = &prog->insns[insn_idx];
2960 size_t map_idx, nr_maps = prog->obj->nr_maps;
2961 struct bpf_object *obj = prog->obj;
2962 __u32 shdr_idx = sym->st_shndx;
2963 enum libbpf_map_type type;
2964 struct bpf_map *map;
2965
2966 /* sub-program call relocation */
2967 if (insn->code == (BPF_JMP | BPF_CALL)) {
2968 if (insn->src_reg != BPF_PSEUDO_CALL) {
2969 pr_warn("incorrect bpf_call opcode\n");
2970 return -LIBBPF_ERRNO__RELOC;
2971 }
2972 /* text_shndx can be 0, if no default "main" program exists */
2973 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2974 pr_warn("bad call relo against section %u\n", shdr_idx);
2975 return -LIBBPF_ERRNO__RELOC;
2976 }
2977 if (sym->st_value % 8) {
2978 pr_warn("bad call relo offset: %zu\n",
2979 (size_t)sym->st_value);
2980 return -LIBBPF_ERRNO__RELOC;
2981 }
2982 reloc_desc->type = RELO_CALL;
2983 reloc_desc->insn_idx = insn_idx;
2984 reloc_desc->sym_off = sym->st_value;
2985 obj->has_pseudo_calls = true;
2986 return 0;
2987 }
2988
2989 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
2990 pr_warn("invalid relo for insns[%d].code 0x%x\n",
2991 insn_idx, insn->code);
2992 return -LIBBPF_ERRNO__RELOC;
2993 }
2994
2995 if (sym_is_extern(sym)) {
2996 int sym_idx = GELF_R_SYM(rel->r_info);
2997 int i, n = obj->nr_extern;
2998 struct extern_desc *ext;
2999
3000 for (i = 0; i < n; i++) {
3001 ext = &obj->externs[i];
3002 if (ext->sym_idx == sym_idx)
3003 break;
3004 }
3005 if (i >= n) {
3006 pr_warn("extern relo failed to find extern for sym %d\n",
3007 sym_idx);
3008 return -LIBBPF_ERRNO__RELOC;
3009 }
3010 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
3011 i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
3012 reloc_desc->type = RELO_EXTERN;
3013 reloc_desc->insn_idx = insn_idx;
3014 reloc_desc->sym_off = ext->data_off;
3015 return 0;
3016 }
3017
3018 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3019 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
3020 name, shdr_idx);
3021 return -LIBBPF_ERRNO__RELOC;
3022 }
3023
3024 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3025
3026 /* generic map reference relocation */
3027 if (type == LIBBPF_MAP_UNSPEC) {
3028 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3029 pr_warn("bad map relo against section %u\n",
3030 shdr_idx);
3031 return -LIBBPF_ERRNO__RELOC;
3032 }
3033 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3034 map = &obj->maps[map_idx];
3035 if (map->libbpf_type != type ||
3036 map->sec_idx != sym->st_shndx ||
3037 map->sec_offset != sym->st_value)
3038 continue;
3039 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
3040 map_idx, map->name, map->sec_idx,
3041 map->sec_offset, insn_idx);
3042 break;
3043 }
3044 if (map_idx >= nr_maps) {
3045 pr_warn("map relo failed to find map for sec %u, off %zu\n",
3046 shdr_idx, (size_t)sym->st_value);
3047 return -LIBBPF_ERRNO__RELOC;
3048 }
3049 reloc_desc->type = RELO_LD64;
3050 reloc_desc->insn_idx = insn_idx;
3051 reloc_desc->map_idx = map_idx;
3052 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3053 return 0;
3054 }
3055
3056 /* global data map relocation */
3057 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3058 pr_warn("bad data relo against section %u\n", shdr_idx);
3059 return -LIBBPF_ERRNO__RELOC;
3060 }
3061 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3062 map = &obj->maps[map_idx];
3063 if (map->libbpf_type != type)
3064 continue;
3065 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3066 map_idx, map->name, map->sec_idx, map->sec_offset,
3067 insn_idx);
3068 break;
3069 }
3070 if (map_idx >= nr_maps) {
3071 pr_warn("data relo failed to find map for sec %u\n",
3072 shdr_idx);
3073 return -LIBBPF_ERRNO__RELOC;
3074 }
3075
3076 reloc_desc->type = RELO_DATA;
3077 reloc_desc->insn_idx = insn_idx;
3078 reloc_desc->map_idx = map_idx;
3079 reloc_desc->sym_off = sym->st_value;
3080 return 0;
3081}
3082
3083static int
3084bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
3085 Elf_Data *data, struct bpf_object *obj)
3086{
3087 Elf_Data *symbols = obj->efile.symbols;
3088 int err, i, nrels;
3089
3090 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
3091 nrels = shdr->sh_size / shdr->sh_entsize;
3092
3093 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
3094 if (!prog->reloc_desc) {
3095 pr_warn("failed to alloc memory in relocation\n");
3096 return -ENOMEM;
3097 }
3098 prog->nr_reloc = nrels;
3099
3100 for (i = 0; i < nrels; i++) {
3101 const char *name;
3102 __u32 insn_idx;
3103 GElf_Sym sym;
3104 GElf_Rel rel;
3105
3106 if (!gelf_getrel(data, i, &rel)) {
3107 pr_warn("relocation: failed to get %d reloc\n", i);
3108 return -LIBBPF_ERRNO__FORMAT;
3109 }
3110 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
3111 pr_warn("relocation: symbol %"PRIx64" not found\n",
3112 GELF_R_SYM(rel.r_info));
3113 return -LIBBPF_ERRNO__FORMAT;
3114 }
3115 if (rel.r_offset % sizeof(struct bpf_insn))
3116 return -LIBBPF_ERRNO__FORMAT;
3117
3118 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
3119 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
3120 sym.st_name) ? : "<?>";
3121
3122 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
3123 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
3124 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
3125 GELF_ST_BIND(sym.st_info), sym.st_name, name,
3126 insn_idx);
3127
3128 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
3129 insn_idx, name, &sym, &rel);
3130 if (err)
3131 return err;
3132 }
3133 return 0;
3134}
3135
3136static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
3137{
3138 struct bpf_map_def *def = &map->def;
3139 __u32 key_type_id = 0, value_type_id = 0;
3140 int ret;
3141
3142 /* if it's BTF-defined map, we don't need to search for type IDs.
3143 * For struct_ops map, it does not need btf_key_type_id and
3144 * btf_value_type_id.
3145 */
3146 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3147 bpf_map__is_struct_ops(map))
3148 return 0;
3149
3150 if (!bpf_map__is_internal(map)) {
3151 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3152 def->value_size, &key_type_id,
3153 &value_type_id);
3154 } else {
3155 /*
3156 * LLVM annotates global data differently in BTF, that is,
3157 * only as '.data', '.bss' or '.rodata'.
3158 */
3159 ret = btf__find_by_name(obj->btf,
3160 libbpf_type_to_btf_name[map->libbpf_type]);
3161 }
3162 if (ret < 0)
3163 return ret;
3164
3165 map->btf_key_type_id = key_type_id;
3166 map->btf_value_type_id = bpf_map__is_internal(map) ?
3167 ret : value_type_id;
3168 return 0;
3169}
3170
3171int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3172{
3173 struct bpf_map_info info = {};
3174 __u32 len = sizeof(info);
3175 int new_fd, err;
3176 char *new_name;
3177
3178 err = bpf_obj_get_info_by_fd(fd, &info, &len);
3179 if (err)
3180 return err;
3181
3182 new_name = strdup(info.name);
3183 if (!new_name)
3184 return -errno;
3185
3186 new_fd = open("/", O_RDONLY | O_CLOEXEC);
3187 if (new_fd < 0) {
3188 err = -errno;
3189 goto err_free_new_name;
3190 }
3191
3192 new_fd = dup3(fd, new_fd, O_CLOEXEC);
3193 if (new_fd < 0) {
3194 err = -errno;
3195 goto err_close_new_fd;
3196 }
3197
3198 err = zclose(map->fd);
3199 if (err) {
3200 err = -errno;
3201 goto err_close_new_fd;
3202 }
3203 free(map->name);
3204
3205 map->fd = new_fd;
3206 map->name = new_name;
3207 map->def.type = info.type;
3208 map->def.key_size = info.key_size;
3209 map->def.value_size = info.value_size;
3210 map->def.max_entries = info.max_entries;
3211 map->def.map_flags = info.map_flags;
3212 map->btf_key_type_id = info.btf_key_type_id;
3213 map->btf_value_type_id = info.btf_value_type_id;
3214 map->reused = true;
3215
3216 return 0;
3217
3218err_close_new_fd:
3219 close(new_fd);
3220err_free_new_name:
3221 free(new_name);
3222 return err;
3223}
3224
3225int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
3226{
3227 if (!map || !max_entries)
3228 return -EINVAL;
3229
3230 /* If map already created, its attributes can't be changed. */
3231 if (map->fd >= 0)
3232 return -EBUSY;
3233
3234 map->def.max_entries = max_entries;
3235
3236 return 0;
3237}
3238
3239static int
3240bpf_object__probe_loading(struct bpf_object *obj)
3241{
3242 struct bpf_load_program_attr attr;
3243 char *cp, errmsg[STRERR_BUFSIZE];
3244 struct bpf_insn insns[] = {
3245 BPF_MOV64_IMM(BPF_REG_0, 0),
3246 BPF_EXIT_INSN(),
3247 };
3248 int ret;
3249
3250 /* make sure basic loading works */
3251
3252 memset(&attr, 0, sizeof(attr));
3253 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3254 attr.insns = insns;
3255 attr.insns_cnt = ARRAY_SIZE(insns);
3256 attr.license = "GPL";
3257
3258 ret = bpf_load_program_xattr(&attr, NULL, 0);
3259 if (ret < 0) {
3260 ret = errno;
3261 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
3262 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
3263 "program. Make sure your kernel supports BPF "
3264 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
3265 "set to big enough value.\n", __func__, cp, ret);
3266 return -ret;
3267 }
3268 close(ret);
3269
3270 return 0;
3271}
3272
3273static int
3274bpf_object__probe_name(struct bpf_object *obj)
3275{
3276 struct bpf_load_program_attr attr;
3277 struct bpf_insn insns[] = {
3278 BPF_MOV64_IMM(BPF_REG_0, 0),
3279 BPF_EXIT_INSN(),
3280 };
3281 int ret;
3282
3283 /* make sure loading with name works */
3284
3285 memset(&attr, 0, sizeof(attr));
3286 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3287 attr.insns = insns;
3288 attr.insns_cnt = ARRAY_SIZE(insns);
3289 attr.license = "GPL";
3290 attr.name = "test";
3291 ret = bpf_load_program_xattr(&attr, NULL, 0);
3292 if (ret >= 0) {
3293 obj->caps.name = 1;
3294 close(ret);
3295 }
3296
3297 return 0;
3298}
3299
3300static int
3301bpf_object__probe_global_data(struct bpf_object *obj)
3302{
3303 struct bpf_load_program_attr prg_attr;
3304 struct bpf_create_map_attr map_attr;
3305 char *cp, errmsg[STRERR_BUFSIZE];
3306 struct bpf_insn insns[] = {
3307 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
3308 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
3309 BPF_MOV64_IMM(BPF_REG_0, 0),
3310 BPF_EXIT_INSN(),
3311 };
3312 int ret, map;
3313
3314 memset(&map_attr, 0, sizeof(map_attr));
3315 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3316 map_attr.key_size = sizeof(int);
3317 map_attr.value_size = 32;
3318 map_attr.max_entries = 1;
3319
3320 map = bpf_create_map_xattr(&map_attr);
3321 if (map < 0) {
3322 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
3323 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3324 __func__, cp, errno);
3325 return -errno;
3326 }
3327
3328 insns[0].imm = map;
3329
3330 memset(&prg_attr, 0, sizeof(prg_attr));
3331 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3332 prg_attr.insns = insns;
3333 prg_attr.insns_cnt = ARRAY_SIZE(insns);
3334 prg_attr.license = "GPL";
3335
3336 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
3337 if (ret >= 0) {
3338 obj->caps.global_data = 1;
3339 close(ret);
3340 }
3341
3342 close(map);
3343 return 0;
3344}
3345
3346static int bpf_object__probe_btf_func(struct bpf_object *obj)
3347{
3348 static const char strs[] = "\0int\0x\0a";
3349 /* void x(int a) {} */
3350 __u32 types[] = {
3351 /* int */
3352 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3353 /* FUNC_PROTO */ /* [2] */
3354 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3355 BTF_PARAM_ENC(7, 1),
3356 /* FUNC x */ /* [3] */
3357 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
3358 };
3359 int btf_fd;
3360
3361 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3362 strs, sizeof(strs));
3363 if (btf_fd >= 0) {
3364 obj->caps.btf_func = 1;
3365 close(btf_fd);
3366 return 1;
3367 }
3368
3369 return 0;
3370}
3371
3372static int bpf_object__probe_btf_func_global(struct bpf_object *obj)
3373{
3374 static const char strs[] = "\0int\0x\0a";
3375 /* static void x(int a) {} */
3376 __u32 types[] = {
3377 /* int */
3378 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3379 /* FUNC_PROTO */ /* [2] */
3380 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3381 BTF_PARAM_ENC(7, 1),
3382 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
3383 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
3384 };
3385 int btf_fd;
3386
3387 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3388 strs, sizeof(strs));
3389 if (btf_fd >= 0) {
3390 obj->caps.btf_func_global = 1;
3391 close(btf_fd);
3392 return 1;
3393 }
3394
3395 return 0;
3396}
3397
3398static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
3399{
3400 static const char strs[] = "\0x\0.data";
3401 /* static int a; */
3402 __u32 types[] = {
3403 /* int */
3404 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3405 /* VAR x */ /* [2] */
3406 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
3407 BTF_VAR_STATIC,
3408 /* DATASEC val */ /* [3] */
3409 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
3410 BTF_VAR_SECINFO_ENC(2, 0, 4),
3411 };
3412 int btf_fd;
3413
3414 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
3415 strs, sizeof(strs));
3416 if (btf_fd >= 0) {
3417 obj->caps.btf_datasec = 1;
3418 close(btf_fd);
3419 return 1;
3420 }
3421
3422 return 0;
3423}
3424
3425static int bpf_object__probe_array_mmap(struct bpf_object *obj)
3426{
3427 struct bpf_create_map_attr attr = {
3428 .map_type = BPF_MAP_TYPE_ARRAY,
3429 .map_flags = BPF_F_MMAPABLE,
3430 .key_size = sizeof(int),
3431 .value_size = sizeof(int),
3432 .max_entries = 1,
3433 };
3434 int fd;
3435
3436 fd = bpf_create_map_xattr(&attr);
3437 if (fd >= 0) {
3438 obj->caps.array_mmap = 1;
3439 close(fd);
3440 return 1;
3441 }
3442
3443 return 0;
3444}
3445
3446static int
3447bpf_object__probe_exp_attach_type(struct bpf_object *obj)
3448{
3449 struct bpf_load_program_attr attr;
3450 struct bpf_insn insns[] = {
3451 BPF_MOV64_IMM(BPF_REG_0, 0),
3452 BPF_EXIT_INSN(),
3453 };
3454 int fd;
3455
3456 memset(&attr, 0, sizeof(attr));
3457 /* use any valid combination of program type and (optional)
3458 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
3459 * to see if kernel supports expected_attach_type field for
3460 * BPF_PROG_LOAD command
3461 */
3462 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
3463 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
3464 attr.insns = insns;
3465 attr.insns_cnt = ARRAY_SIZE(insns);
3466 attr.license = "GPL";
3467
3468 fd = bpf_load_program_xattr(&attr, NULL, 0);
3469 if (fd >= 0) {
3470 obj->caps.exp_attach_type = 1;
3471 close(fd);
3472 return 1;
3473 }
3474 return 0;
3475}
3476
3477static int
3478bpf_object__probe_caps(struct bpf_object *obj)
3479{
3480 int (*probe_fn[])(struct bpf_object *obj) = {
3481 bpf_object__probe_name,
3482 bpf_object__probe_global_data,
3483 bpf_object__probe_btf_func,
3484 bpf_object__probe_btf_func_global,
3485 bpf_object__probe_btf_datasec,
3486 bpf_object__probe_array_mmap,
3487 bpf_object__probe_exp_attach_type,
3488 };
3489 int i, ret;
3490
3491 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
3492 ret = probe_fn[i](obj);
3493 if (ret < 0)
3494 pr_debug("Probe #%d failed with %d.\n", i, ret);
3495 }
3496
3497 return 0;
3498}
3499
3500static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
3501{
3502 struct bpf_map_info map_info = {};
3503 char msg[STRERR_BUFSIZE];
3504 __u32 map_info_len;
3505
3506 map_info_len = sizeof(map_info);
3507
3508 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
3509 pr_warn("failed to get map info for map FD %d: %s\n",
3510 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
3511 return false;
3512 }
3513
3514 return (map_info.type == map->def.type &&
3515 map_info.key_size == map->def.key_size &&
3516 map_info.value_size == map->def.value_size &&
3517 map_info.max_entries == map->def.max_entries &&
3518 map_info.map_flags == map->def.map_flags);
3519}
3520
3521static int
3522bpf_object__reuse_map(struct bpf_map *map)
3523{
3524 char *cp, errmsg[STRERR_BUFSIZE];
3525 int err, pin_fd;
3526
3527 pin_fd = bpf_obj_get(map->pin_path);
3528 if (pin_fd < 0) {
3529 err = -errno;
3530 if (err == -ENOENT) {
3531 pr_debug("found no pinned map to reuse at '%s'\n",
3532 map->pin_path);
3533 return 0;
3534 }
3535
3536 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
3537 pr_warn("couldn't retrieve pinned map '%s': %s\n",
3538 map->pin_path, cp);
3539 return err;
3540 }
3541
3542 if (!map_is_reuse_compat(map, pin_fd)) {
3543 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
3544 map->pin_path);
3545 close(pin_fd);
3546 return -EINVAL;
3547 }
3548
3549 err = bpf_map__reuse_fd(map, pin_fd);
3550 if (err) {
3551 close(pin_fd);
3552 return err;
3553 }
3554 map->pinned = true;
3555 pr_debug("reused pinned map at '%s'\n", map->pin_path);
3556
3557 return 0;
3558}
3559
3560static int
3561bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
3562{
3563 enum libbpf_map_type map_type = map->libbpf_type;
3564 char *cp, errmsg[STRERR_BUFSIZE];
3565 int err, zero = 0;
3566
3567 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
3568 if (err) {
3569 err = -errno;
3570 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3571 pr_warn("Error setting initial map(%s) contents: %s\n",
3572 map->name, cp);
3573 return err;
3574 }
3575
3576 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
3577 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
3578 err = bpf_map_freeze(map->fd);
3579 if (err) {
3580 err = -errno;
3581 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3582 pr_warn("Error freezing map(%s) as read-only: %s\n",
3583 map->name, cp);
3584 return err;
3585 }
3586 }
3587 return 0;
3588}
3589
3590static void bpf_map__destroy(struct bpf_map *map);
3591
3592static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map)
3593{
3594 struct bpf_create_map_attr create_attr;
3595 struct bpf_map_def *def = &map->def;
3596
3597 memset(&create_attr, 0, sizeof(create_attr));
3598
3599 if (obj->caps.name)
3600 create_attr.name = map->name;
3601 create_attr.map_ifindex = map->map_ifindex;
3602 create_attr.map_type = def->type;
3603 create_attr.map_flags = def->map_flags;
3604 create_attr.key_size = def->key_size;
3605 create_attr.value_size = def->value_size;
3606
3607 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
3608 int nr_cpus;
3609
3610 nr_cpus = libbpf_num_possible_cpus();
3611 if (nr_cpus < 0) {
3612 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
3613 map->name, nr_cpus);
3614 return nr_cpus;
3615 }
3616 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
3617 create_attr.max_entries = nr_cpus;
3618 } else {
3619 create_attr.max_entries = def->max_entries;
3620 }
3621
3622 if (bpf_map__is_struct_ops(map))
3623 create_attr.btf_vmlinux_value_type_id =
3624 map->btf_vmlinux_value_type_id;
3625
3626 create_attr.btf_fd = 0;
3627 create_attr.btf_key_type_id = 0;
3628 create_attr.btf_value_type_id = 0;
3629 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
3630 create_attr.btf_fd = btf__fd(obj->btf);
3631 create_attr.btf_key_type_id = map->btf_key_type_id;
3632 create_attr.btf_value_type_id = map->btf_value_type_id;
3633 }
3634
3635 if (bpf_map_type__is_map_in_map(def->type)) {
3636 if (map->inner_map) {
3637 int err;
3638
3639 err = bpf_object__create_map(obj, map->inner_map);
3640 if (err) {
3641 pr_warn("map '%s': failed to create inner map: %d\n",
3642 map->name, err);
3643 return err;
3644 }
3645 map->inner_map_fd = bpf_map__fd(map->inner_map);
3646 }
3647 if (map->inner_map_fd >= 0)
3648 create_attr.inner_map_fd = map->inner_map_fd;
3649 }
3650
3651 map->fd = bpf_create_map_xattr(&create_attr);
3652 if (map->fd < 0 && (create_attr.btf_key_type_id ||
3653 create_attr.btf_value_type_id)) {
3654 char *cp, errmsg[STRERR_BUFSIZE];
3655 int err = -errno;
3656
3657 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3658 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
3659 map->name, cp, err);
3660 create_attr.btf_fd = 0;
3661 create_attr.btf_key_type_id = 0;
3662 create_attr.btf_value_type_id = 0;
3663 map->btf_key_type_id = 0;
3664 map->btf_value_type_id = 0;
3665 map->fd = bpf_create_map_xattr(&create_attr);
3666 }
3667
3668 if (map->fd < 0)
3669 return -errno;
3670
3671 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
3672 bpf_map__destroy(map->inner_map);
3673 zfree(&map->inner_map);
3674 }
3675
3676 return 0;
3677}
3678
3679static int
3680bpf_object__create_maps(struct bpf_object *obj)
3681{
3682 struct bpf_map *map;
3683 char *cp, errmsg[STRERR_BUFSIZE];
3684 unsigned int i, j;
3685 int err;
3686
3687 for (i = 0; i < obj->nr_maps; i++) {
3688 map = &obj->maps[i];
3689
3690 if (map->pin_path) {
3691 err = bpf_object__reuse_map(map);
3692 if (err) {
3693 pr_warn("map '%s': error reusing pinned map\n",
3694 map->name);
3695 goto err_out;
3696 }
3697 }
3698
3699 if (map->fd >= 0) {
3700 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
3701 map->name, map->fd);
3702 continue;
3703 }
3704
3705 err = bpf_object__create_map(obj, map);
3706 if (err)
3707 goto err_out;
3708
3709 pr_debug("map '%s': created successfully, fd=%d\n", map->name,
3710 map->fd);
3711
3712 if (bpf_map__is_internal(map)) {
3713 err = bpf_object__populate_internal_map(obj, map);
3714 if (err < 0) {
3715 zclose(map->fd);
3716 goto err_out;
3717 }
3718 }
3719
3720 if (map->init_slots_sz) {
3721 for (j = 0; j < map->init_slots_sz; j++) {
3722 const struct bpf_map *targ_map;
3723 int fd;
3724
3725 if (!map->init_slots[j])
3726 continue;
3727
3728 targ_map = map->init_slots[j];
3729 fd = bpf_map__fd(targ_map);
3730 err = bpf_map_update_elem(map->fd, &j, &fd, 0);
3731 if (err) {
3732 err = -errno;
3733 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
3734 map->name, j, targ_map->name,
3735 fd, err);
3736 goto err_out;
3737 }
3738 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
3739 map->name, j, targ_map->name, fd);
3740 }
3741 zfree(&map->init_slots);
3742 map->init_slots_sz = 0;
3743 }
3744
3745 if (map->pin_path && !map->pinned) {
3746 err = bpf_map__pin(map, NULL);
3747 if (err) {
3748 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
3749 map->name, map->pin_path, err);
3750 zclose(map->fd);
3751 goto err_out;
3752 }
3753 }
3754 }
3755
3756 return 0;
3757
3758err_out:
3759 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
3760 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
3761 pr_perm_msg(err);
3762 for (j = 0; j < i; j++)
3763 zclose(obj->maps[j].fd);
3764 return err;
3765}
3766
3767static int
3768check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3769 void *btf_prog_info, const char *info_name)
3770{
3771 if (err != -ENOENT) {
3772 pr_warn("Error in loading %s for sec %s.\n",
3773 info_name, prog->section_name);
3774 return err;
3775 }
3776
3777 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3778
3779 if (btf_prog_info) {
3780 /*
3781 * Some info has already been found but has problem
3782 * in the last btf_ext reloc. Must have to error out.
3783 */
3784 pr_warn("Error in relocating %s for sec %s.\n",
3785 info_name, prog->section_name);
3786 return err;
3787 }
3788
3789 /* Have problem loading the very first info. Ignore the rest. */
3790 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3791 info_name, prog->section_name, info_name);
3792 return 0;
3793}
3794
3795static int
3796bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3797 const char *section_name, __u32 insn_offset)
3798{
3799 int err;
3800
3801 if (!insn_offset || prog->func_info) {
3802 /*
3803 * !insn_offset => main program
3804 *
3805 * For sub prog, the main program's func_info has to
3806 * be loaded first (i.e. prog->func_info != NULL)
3807 */
3808 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3809 section_name, insn_offset,
3810 &prog->func_info,
3811 &prog->func_info_cnt);
3812 if (err)
3813 return check_btf_ext_reloc_err(prog, err,
3814 prog->func_info,
3815 "bpf_func_info");
3816
3817 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3818 }
3819
3820 if (!insn_offset || prog->line_info) {
3821 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3822 section_name, insn_offset,
3823 &prog->line_info,
3824 &prog->line_info_cnt);
3825 if (err)
3826 return check_btf_ext_reloc_err(prog, err,
3827 prog->line_info,
3828 "bpf_line_info");
3829
3830 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3831 }
3832
3833 return 0;
3834}
3835
3836#define BPF_CORE_SPEC_MAX_LEN 64
3837
3838/* represents BPF CO-RE field or array element accessor */
3839struct bpf_core_accessor {
3840 __u32 type_id; /* struct/union type or array element type */
3841 __u32 idx; /* field index or array index */
3842 const char *name; /* field name or NULL for array accessor */
3843};
3844
3845struct bpf_core_spec {
3846 const struct btf *btf;
3847 /* high-level spec: named fields and array indices only */
3848 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3849 /* high-level spec length */
3850 int len;
3851 /* raw, low-level spec: 1-to-1 with accessor spec string */
3852 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3853 /* raw spec length */
3854 int raw_len;
3855 /* field bit offset represented by spec */
3856 __u32 bit_offset;
3857};
3858
3859static bool str_is_empty(const char *s)
3860{
3861 return !s || !s[0];
3862}
3863
3864static bool is_flex_arr(const struct btf *btf,
3865 const struct bpf_core_accessor *acc,
3866 const struct btf_array *arr)
3867{
3868 const struct btf_type *t;
3869
3870 /* not a flexible array, if not inside a struct or has non-zero size */
3871 if (!acc->name || arr->nelems > 0)
3872 return false;
3873
3874 /* has to be the last member of enclosing struct */
3875 t = btf__type_by_id(btf, acc->type_id);
3876 return acc->idx == btf_vlen(t) - 1;
3877}
3878
3879/*
3880 * Turn bpf_field_reloc into a low- and high-level spec representation,
3881 * validating correctness along the way, as well as calculating resulting
3882 * field bit offset, specified by accessor string. Low-level spec captures
3883 * every single level of nestedness, including traversing anonymous
3884 * struct/union members. High-level one only captures semantically meaningful
3885 * "turning points": named fields and array indicies.
3886 * E.g., for this case:
3887 *
3888 * struct sample {
3889 * int __unimportant;
3890 * struct {
3891 * int __1;
3892 * int __2;
3893 * int a[7];
3894 * };
3895 * };
3896 *
3897 * struct sample *s = ...;
3898 *
3899 * int x = &s->a[3]; // access string = '0:1:2:3'
3900 *
3901 * Low-level spec has 1:1 mapping with each element of access string (it's
3902 * just a parsed access string representation): [0, 1, 2, 3].
3903 *
3904 * High-level spec will capture only 3 points:
3905 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3906 * - field 'a' access (corresponds to '2' in low-level spec);
3907 * - array element #3 access (corresponds to '3' in low-level spec).
3908 *
3909 */
3910static int bpf_core_spec_parse(const struct btf *btf,
3911 __u32 type_id,
3912 const char *spec_str,
3913 struct bpf_core_spec *spec)
3914{
3915 int access_idx, parsed_len, i;
3916 struct bpf_core_accessor *acc;
3917 const struct btf_type *t;
3918 const char *name;
3919 __u32 id;
3920 __s64 sz;
3921
3922 if (str_is_empty(spec_str) || *spec_str == ':')
3923 return -EINVAL;
3924
3925 memset(spec, 0, sizeof(*spec));
3926 spec->btf = btf;
3927
3928 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3929 while (*spec_str) {
3930 if (*spec_str == ':')
3931 ++spec_str;
3932 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3933 return -EINVAL;
3934 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3935 return -E2BIG;
3936 spec_str += parsed_len;
3937 spec->raw_spec[spec->raw_len++] = access_idx;
3938 }
3939
3940 if (spec->raw_len == 0)
3941 return -EINVAL;
3942
3943 /* first spec value is always reloc type array index */
3944 t = skip_mods_and_typedefs(btf, type_id, &id);
3945 if (!t)
3946 return -EINVAL;
3947
3948 access_idx = spec->raw_spec[0];
3949 spec->spec[0].type_id = id;
3950 spec->spec[0].idx = access_idx;
3951 spec->len++;
3952
3953 sz = btf__resolve_size(btf, id);
3954 if (sz < 0)
3955 return sz;
3956 spec->bit_offset = access_idx * sz * 8;
3957
3958 for (i = 1; i < spec->raw_len; i++) {
3959 t = skip_mods_and_typedefs(btf, id, &id);
3960 if (!t)
3961 return -EINVAL;
3962
3963 access_idx = spec->raw_spec[i];
3964 acc = &spec->spec[spec->len];
3965
3966 if (btf_is_composite(t)) {
3967 const struct btf_member *m;
3968 __u32 bit_offset;
3969
3970 if (access_idx >= btf_vlen(t))
3971 return -EINVAL;
3972
3973 bit_offset = btf_member_bit_offset(t, access_idx);
3974 spec->bit_offset += bit_offset;
3975
3976 m = btf_members(t) + access_idx;
3977 if (m->name_off) {
3978 name = btf__name_by_offset(btf, m->name_off);
3979 if (str_is_empty(name))
3980 return -EINVAL;
3981
3982 acc->type_id = id;
3983 acc->idx = access_idx;
3984 acc->name = name;
3985 spec->len++;
3986 }
3987
3988 id = m->type;
3989 } else if (btf_is_array(t)) {
3990 const struct btf_array *a = btf_array(t);
3991 bool flex;
3992
3993 t = skip_mods_and_typedefs(btf, a->type, &id);
3994 if (!t)
3995 return -EINVAL;
3996
3997 flex = is_flex_arr(btf, acc - 1, a);
3998 if (!flex && access_idx >= a->nelems)
3999 return -EINVAL;
4000
4001 spec->spec[spec->len].type_id = id;
4002 spec->spec[spec->len].idx = access_idx;
4003 spec->len++;
4004
4005 sz = btf__resolve_size(btf, id);
4006 if (sz < 0)
4007 return sz;
4008 spec->bit_offset += access_idx * sz * 8;
4009 } else {
4010 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
4011 type_id, spec_str, i, id, btf_kind(t));
4012 return -EINVAL;
4013 }
4014 }
4015
4016 return 0;
4017}
4018
4019static bool bpf_core_is_flavor_sep(const char *s)
4020{
4021 /* check X___Y name pattern, where X and Y are not underscores */
4022 return s[0] != '_' && /* X */
4023 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
4024 s[4] != '_'; /* Y */
4025}
4026
4027/* Given 'some_struct_name___with_flavor' return the length of a name prefix
4028 * before last triple underscore. Struct name part after last triple
4029 * underscore is ignored by BPF CO-RE relocation during relocation matching.
4030 */
4031static size_t bpf_core_essential_name_len(const char *name)
4032{
4033 size_t n = strlen(name);
4034 int i;
4035
4036 for (i = n - 5; i >= 0; i--) {
4037 if (bpf_core_is_flavor_sep(name + i))
4038 return i + 1;
4039 }
4040 return n;
4041}
4042
4043/* dynamically sized list of type IDs */
4044struct ids_vec {
4045 __u32 *data;
4046 int len;
4047};
4048
4049static void bpf_core_free_cands(struct ids_vec *cand_ids)
4050{
4051 free(cand_ids->data);
4052 free(cand_ids);
4053}
4054
4055static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
4056 __u32 local_type_id,
4057 const struct btf *targ_btf)
4058{
4059 size_t local_essent_len, targ_essent_len;
4060 const char *local_name, *targ_name;
4061 const struct btf_type *t;
4062 struct ids_vec *cand_ids;
4063 __u32 *new_ids;
4064 int i, err, n;
4065
4066 t = btf__type_by_id(local_btf, local_type_id);
4067 if (!t)
4068 return ERR_PTR(-EINVAL);
4069
4070 local_name = btf__name_by_offset(local_btf, t->name_off);
4071 if (str_is_empty(local_name))
4072 return ERR_PTR(-EINVAL);
4073 local_essent_len = bpf_core_essential_name_len(local_name);
4074
4075 cand_ids = calloc(1, sizeof(*cand_ids));
4076 if (!cand_ids)
4077 return ERR_PTR(-ENOMEM);
4078
4079 n = btf__get_nr_types(targ_btf);
4080 for (i = 1; i <= n; i++) {
4081 t = btf__type_by_id(targ_btf, i);
4082 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4083 if (str_is_empty(targ_name))
4084 continue;
4085
4086 t = skip_mods_and_typedefs(targ_btf, i, NULL);
4087 if (!btf_is_composite(t) && !btf_is_array(t))
4088 continue;
4089
4090 targ_essent_len = bpf_core_essential_name_len(targ_name);
4091 if (targ_essent_len != local_essent_len)
4092 continue;
4093
4094 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
4095 pr_debug("[%d] %s: found candidate [%d] %s\n",
4096 local_type_id, local_name, i, targ_name);
4097 new_ids = reallocarray(cand_ids->data,
4098 cand_ids->len + 1,
4099 sizeof(*cand_ids->data));
4100 if (!new_ids) {
4101 err = -ENOMEM;
4102 goto err_out;
4103 }
4104 cand_ids->data = new_ids;
4105 cand_ids->data[cand_ids->len++] = i;
4106 }
4107 }
4108 return cand_ids;
4109err_out:
4110 bpf_core_free_cands(cand_ids);
4111 return ERR_PTR(err);
4112}
4113
4114/* Check two types for compatibility, skipping const/volatile/restrict and
4115 * typedefs, to ensure we are relocating compatible entities:
4116 * - any two STRUCTs/UNIONs are compatible and can be mixed;
4117 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
4118 * - any two PTRs are always compatible;
4119 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
4120 * least one of enums should be anonymous;
4121 * - for ENUMs, check sizes, names are ignored;
4122 * - for INT, size and signedness are ignored;
4123 * - for ARRAY, dimensionality is ignored, element types are checked for
4124 * compatibility recursively;
4125 * - everything else shouldn't be ever a target of relocation.
4126 * These rules are not set in stone and probably will be adjusted as we get
4127 * more experience with using BPF CO-RE relocations.
4128 */
4129static int bpf_core_fields_are_compat(const struct btf *local_btf,
4130 __u32 local_id,
4131 const struct btf *targ_btf,
4132 __u32 targ_id)
4133{
4134 const struct btf_type *local_type, *targ_type;
4135
4136recur:
4137 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
4138 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4139 if (!local_type || !targ_type)
4140 return -EINVAL;
4141
4142 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
4143 return 1;
4144 if (btf_kind(local_type) != btf_kind(targ_type))
4145 return 0;
4146
4147 switch (btf_kind(local_type)) {
4148 case BTF_KIND_PTR:
4149 return 1;
4150 case BTF_KIND_FWD:
4151 case BTF_KIND_ENUM: {
4152 const char *local_name, *targ_name;
4153 size_t local_len, targ_len;
4154
4155 local_name = btf__name_by_offset(local_btf,
4156 local_type->name_off);
4157 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
4158 local_len = bpf_core_essential_name_len(local_name);
4159 targ_len = bpf_core_essential_name_len(targ_name);
4160 /* one of them is anonymous or both w/ same flavor-less names */
4161 return local_len == 0 || targ_len == 0 ||
4162 (local_len == targ_len &&
4163 strncmp(local_name, targ_name, local_len) == 0);
4164 }
4165 case BTF_KIND_INT:
4166 /* just reject deprecated bitfield-like integers; all other
4167 * integers are by default compatible between each other
4168 */
4169 return btf_int_offset(local_type) == 0 &&
4170 btf_int_offset(targ_type) == 0;
4171 case BTF_KIND_ARRAY:
4172 local_id = btf_array(local_type)->type;
4173 targ_id = btf_array(targ_type)->type;
4174 goto recur;
4175 default:
4176 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
4177 btf_kind(local_type), local_id, targ_id);
4178 return 0;
4179 }
4180}
4181
4182/*
4183 * Given single high-level named field accessor in local type, find
4184 * corresponding high-level accessor for a target type. Along the way,
4185 * maintain low-level spec for target as well. Also keep updating target
4186 * bit offset.
4187 *
4188 * Searching is performed through recursive exhaustive enumeration of all
4189 * fields of a struct/union. If there are any anonymous (embedded)
4190 * structs/unions, they are recursively searched as well. If field with
4191 * desired name is found, check compatibility between local and target types,
4192 * before returning result.
4193 *
4194 * 1 is returned, if field is found.
4195 * 0 is returned if no compatible field is found.
4196 * <0 is returned on error.
4197 */
4198static int bpf_core_match_member(const struct btf *local_btf,
4199 const struct bpf_core_accessor *local_acc,
4200 const struct btf *targ_btf,
4201 __u32 targ_id,
4202 struct bpf_core_spec *spec,
4203 __u32 *next_targ_id)
4204{
4205 const struct btf_type *local_type, *targ_type;
4206 const struct btf_member *local_member, *m;
4207 const char *local_name, *targ_name;
4208 __u32 local_id;
4209 int i, n, found;
4210
4211 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4212 if (!targ_type)
4213 return -EINVAL;
4214 if (!btf_is_composite(targ_type))
4215 return 0;
4216
4217 local_id = local_acc->type_id;
4218 local_type = btf__type_by_id(local_btf, local_id);
4219 local_member = btf_members(local_type) + local_acc->idx;
4220 local_name = btf__name_by_offset(local_btf, local_member->name_off);
4221
4222 n = btf_vlen(targ_type);
4223 m = btf_members(targ_type);
4224 for (i = 0; i < n; i++, m++) {
4225 __u32 bit_offset;
4226
4227 bit_offset = btf_member_bit_offset(targ_type, i);
4228
4229 /* too deep struct/union/array nesting */
4230 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4231 return -E2BIG;
4232
4233 /* speculate this member will be the good one */
4234 spec->bit_offset += bit_offset;
4235 spec->raw_spec[spec->raw_len++] = i;
4236
4237 targ_name = btf__name_by_offset(targ_btf, m->name_off);
4238 if (str_is_empty(targ_name)) {
4239 /* embedded struct/union, we need to go deeper */
4240 found = bpf_core_match_member(local_btf, local_acc,
4241 targ_btf, m->type,
4242 spec, next_targ_id);
4243 if (found) /* either found or error */
4244 return found;
4245 } else if (strcmp(local_name, targ_name) == 0) {
4246 /* matching named field */
4247 struct bpf_core_accessor *targ_acc;
4248
4249 targ_acc = &spec->spec[spec->len++];
4250 targ_acc->type_id = targ_id;
4251 targ_acc->idx = i;
4252 targ_acc->name = targ_name;
4253
4254 *next_targ_id = m->type;
4255 found = bpf_core_fields_are_compat(local_btf,
4256 local_member->type,
4257 targ_btf, m->type);
4258 if (!found)
4259 spec->len--; /* pop accessor */
4260 return found;
4261 }
4262 /* member turned out not to be what we looked for */
4263 spec->bit_offset -= bit_offset;
4264 spec->raw_len--;
4265 }
4266
4267 return 0;
4268}
4269
4270/*
4271 * Try to match local spec to a target type and, if successful, produce full
4272 * target spec (high-level, low-level + bit offset).
4273 */
4274static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
4275 const struct btf *targ_btf, __u32 targ_id,
4276 struct bpf_core_spec *targ_spec)
4277{
4278 const struct btf_type *targ_type;
4279 const struct bpf_core_accessor *local_acc;
4280 struct bpf_core_accessor *targ_acc;
4281 int i, sz, matched;
4282
4283 memset(targ_spec, 0, sizeof(*targ_spec));
4284 targ_spec->btf = targ_btf;
4285
4286 local_acc = &local_spec->spec[0];
4287 targ_acc = &targ_spec->spec[0];
4288
4289 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
4290 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
4291 &targ_id);
4292 if (!targ_type)
4293 return -EINVAL;
4294
4295 if (local_acc->name) {
4296 matched = bpf_core_match_member(local_spec->btf,
4297 local_acc,
4298 targ_btf, targ_id,
4299 targ_spec, &targ_id);
4300 if (matched <= 0)
4301 return matched;
4302 } else {
4303 /* for i=0, targ_id is already treated as array element
4304 * type (because it's the original struct), for others
4305 * we should find array element type first
4306 */
4307 if (i > 0) {
4308 const struct btf_array *a;
4309 bool flex;
4310
4311 if (!btf_is_array(targ_type))
4312 return 0;
4313
4314 a = btf_array(targ_type);
4315 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
4316 if (!flex && local_acc->idx >= a->nelems)
4317 return 0;
4318 if (!skip_mods_and_typedefs(targ_btf, a->type,
4319 &targ_id))
4320 return -EINVAL;
4321 }
4322
4323 /* too deep struct/union/array nesting */
4324 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4325 return -E2BIG;
4326
4327 targ_acc->type_id = targ_id;
4328 targ_acc->idx = local_acc->idx;
4329 targ_acc->name = NULL;
4330 targ_spec->len++;
4331 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
4332 targ_spec->raw_len++;
4333
4334 sz = btf__resolve_size(targ_btf, targ_id);
4335 if (sz < 0)
4336 return sz;
4337 targ_spec->bit_offset += local_acc->idx * sz * 8;
4338 }
4339 }
4340
4341 return 1;
4342}
4343
4344static int bpf_core_calc_field_relo(const struct bpf_program *prog,
4345 const struct bpf_field_reloc *relo,
4346 const struct bpf_core_spec *spec,
4347 __u32 *val, bool *validate)
4348{
4349 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
4350 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
4351 __u32 byte_off, byte_sz, bit_off, bit_sz;
4352 const struct btf_member *m;
4353 const struct btf_type *mt;
4354 bool bitfield;
4355 __s64 sz;
4356
4357 /* a[n] accessor needs special handling */
4358 if (!acc->name) {
4359 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
4360 *val = spec->bit_offset / 8;
4361 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
4362 sz = btf__resolve_size(spec->btf, acc->type_id);
4363 if (sz < 0)
4364 return -EINVAL;
4365 *val = sz;
4366 } else {
4367 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
4368 bpf_program__title(prog, false),
4369 relo->kind, relo->insn_off / 8);
4370 return -EINVAL;
4371 }
4372 if (validate)
4373 *validate = true;
4374 return 0;
4375 }
4376
4377 m = btf_members(t) + acc->idx;
4378 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
4379 bit_off = spec->bit_offset;
4380 bit_sz = btf_member_bitfield_size(t, acc->idx);
4381
4382 bitfield = bit_sz > 0;
4383 if (bitfield) {
4384 byte_sz = mt->size;
4385 byte_off = bit_off / 8 / byte_sz * byte_sz;
4386 /* figure out smallest int size necessary for bitfield load */
4387 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
4388 if (byte_sz >= 8) {
4389 /* bitfield can't be read with 64-bit read */
4390 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
4391 bpf_program__title(prog, false),
4392 relo->kind, relo->insn_off / 8);
4393 return -E2BIG;
4394 }
4395 byte_sz *= 2;
4396 byte_off = bit_off / 8 / byte_sz * byte_sz;
4397 }
4398 } else {
4399 sz = btf__resolve_size(spec->btf, m->type);
4400 if (sz < 0)
4401 return -EINVAL;
4402 byte_sz = sz;
4403 byte_off = spec->bit_offset / 8;
4404 bit_sz = byte_sz * 8;
4405 }
4406
4407 /* for bitfields, all the relocatable aspects are ambiguous and we
4408 * might disagree with compiler, so turn off validation of expected
4409 * value, except for signedness
4410 */
4411 if (validate)
4412 *validate = !bitfield;
4413
4414 switch (relo->kind) {
4415 case BPF_FIELD_BYTE_OFFSET:
4416 *val = byte_off;
4417 break;
4418 case BPF_FIELD_BYTE_SIZE:
4419 *val = byte_sz;
4420 break;
4421 case BPF_FIELD_SIGNED:
4422 /* enums will be assumed unsigned */
4423 *val = btf_is_enum(mt) ||
4424 (btf_int_encoding(mt) & BTF_INT_SIGNED);
4425 if (validate)
4426 *validate = true; /* signedness is never ambiguous */
4427 break;
4428 case BPF_FIELD_LSHIFT_U64:
4429#if __BYTE_ORDER == __LITTLE_ENDIAN
4430 *val = 64 - (bit_off + bit_sz - byte_off * 8);
4431#else
4432 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
4433#endif
4434 break;
4435 case BPF_FIELD_RSHIFT_U64:
4436 *val = 64 - bit_sz;
4437 if (validate)
4438 *validate = true; /* right shift is never ambiguous */
4439 break;
4440 case BPF_FIELD_EXISTS:
4441 default:
4442 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
4443 bpf_program__title(prog, false),
4444 relo->kind, relo->insn_off / 8);
4445 return -EINVAL;
4446 }
4447
4448 return 0;
4449}
4450
4451/*
4452 * Patch relocatable BPF instruction.
4453 *
4454 * Patched value is determined by relocation kind and target specification.
4455 * For field existence relocation target spec will be NULL if field is not
4456 * found.
4457 * Expected insn->imm value is determined using relocation kind and local
4458 * spec, and is checked before patching instruction. If actual insn->imm value
4459 * is wrong, bail out with error.
4460 *
4461 * Currently three kinds of BPF instructions are supported:
4462 * 1. rX = <imm> (assignment with immediate operand);
4463 * 2. rX += <imm> (arithmetic operations with immediate operand);
4464 */
4465static int bpf_core_reloc_insn(struct bpf_program *prog,
4466 const struct bpf_field_reloc *relo,
4467 int relo_idx,
4468 const struct bpf_core_spec *local_spec,
4469 const struct bpf_core_spec *targ_spec)
4470{
4471 __u32 orig_val, new_val;
4472 struct bpf_insn *insn;
4473 bool validate = true;
4474 int insn_idx, err;
4475 __u8 class;
4476
4477 if (relo->insn_off % sizeof(struct bpf_insn))
4478 return -EINVAL;
4479 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
4480 insn = &prog->insns[insn_idx];
4481 class = BPF_CLASS(insn->code);
4482
4483 if (relo->kind == BPF_FIELD_EXISTS) {
4484 orig_val = 1; /* can't generate EXISTS relo w/o local field */
4485 new_val = targ_spec ? 1 : 0;
4486 } else if (!targ_spec) {
4487 pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
4488 bpf_program__title(prog, false), relo_idx, insn_idx);
4489 insn->code = BPF_JMP | BPF_CALL;
4490 insn->dst_reg = 0;
4491 insn->src_reg = 0;
4492 insn->off = 0;
4493 /* if this instruction is reachable (not a dead code),
4494 * verifier will complain with the following message:
4495 * invalid func unknown#195896080
4496 */
4497 insn->imm = 195896080; /* => 0xbad2310 => "bad relo" */
4498 return 0;
4499 } else {
4500 err = bpf_core_calc_field_relo(prog, relo, local_spec,
4501 &orig_val, &validate);
4502 if (err)
4503 return err;
4504 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
4505 &new_val, NULL);
4506 if (err)
4507 return err;
4508 }
4509
4510 switch (class) {
4511 case BPF_ALU:
4512 case BPF_ALU64:
4513 if (BPF_SRC(insn->code) != BPF_K)
4514 return -EINVAL;
4515 if (validate && insn->imm != orig_val) {
4516 pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
4517 bpf_program__title(prog, false), relo_idx,
4518 insn_idx, insn->imm, orig_val, new_val);
4519 return -EINVAL;
4520 }
4521 orig_val = insn->imm;
4522 insn->imm = new_val;
4523 pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %u -> %u\n",
4524 bpf_program__title(prog, false), relo_idx, insn_idx,
4525 orig_val, new_val);
4526 break;
4527 case BPF_LDX:
4528 case BPF_ST:
4529 case BPF_STX:
4530 if (validate && insn->off != orig_val) {
4531 pr_warn("prog '%s': relo #%d: unexpected insn #%d (LD/LDX/ST/STX) value: got %u, exp %u -> %u\n",
4532 bpf_program__title(prog, false), relo_idx,
4533 insn_idx, insn->off, orig_val, new_val);
4534 return -EINVAL;
4535 }
4536 if (new_val > SHRT_MAX) {
4537 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %u\n",
4538 bpf_program__title(prog, false), relo_idx,
4539 insn_idx, new_val);
4540 return -ERANGE;
4541 }
4542 orig_val = insn->off;
4543 insn->off = new_val;
4544 pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %u -> %u\n",
4545 bpf_program__title(prog, false), relo_idx, insn_idx,
4546 orig_val, new_val);
4547 break;
4548 default:
4549 pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
4550 bpf_program__title(prog, false), relo_idx,
4551 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
4552 insn->off, insn->imm);
4553 return -EINVAL;
4554 }
4555
4556 return 0;
4557}
4558
4559/* Output spec definition in the format:
4560 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
4561 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
4562 */
4563static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
4564{
4565 const struct btf_type *t;
4566 const char *s;
4567 __u32 type_id;
4568 int i;
4569
4570 type_id = spec->spec[0].type_id;
4571 t = btf__type_by_id(spec->btf, type_id);
4572 s = btf__name_by_offset(spec->btf, t->name_off);
4573 libbpf_print(level, "[%u] %s + ", type_id, s);
4574
4575 for (i = 0; i < spec->raw_len; i++)
4576 libbpf_print(level, "%d%s", spec->raw_spec[i],
4577 i == spec->raw_len - 1 ? " => " : ":");
4578
4579 libbpf_print(level, "%u.%u @ &x",
4580 spec->bit_offset / 8, spec->bit_offset % 8);
4581
4582 for (i = 0; i < spec->len; i++) {
4583 if (spec->spec[i].name)
4584 libbpf_print(level, ".%s", spec->spec[i].name);
4585 else
4586 libbpf_print(level, "[%u]", spec->spec[i].idx);
4587 }
4588
4589}
4590
4591static size_t bpf_core_hash_fn(const void *key, void *ctx)
4592{
4593 return (size_t)key;
4594}
4595
4596static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
4597{
4598 return k1 == k2;
4599}
4600
4601static void *u32_as_hash_key(__u32 x)
4602{
4603 return (void *)(uintptr_t)x;
4604}
4605
4606/*
4607 * CO-RE relocate single instruction.
4608 *
4609 * The outline and important points of the algorithm:
4610 * 1. For given local type, find corresponding candidate target types.
4611 * Candidate type is a type with the same "essential" name, ignoring
4612 * everything after last triple underscore (___). E.g., `sample`,
4613 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
4614 * for each other. Names with triple underscore are referred to as
4615 * "flavors" and are useful, among other things, to allow to
4616 * specify/support incompatible variations of the same kernel struct, which
4617 * might differ between different kernel versions and/or build
4618 * configurations.
4619 *
4620 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
4621 * converter, when deduplicated BTF of a kernel still contains more than
4622 * one different types with the same name. In that case, ___2, ___3, etc
4623 * are appended starting from second name conflict. But start flavors are
4624 * also useful to be defined "locally", in BPF program, to extract same
4625 * data from incompatible changes between different kernel
4626 * versions/configurations. For instance, to handle field renames between
4627 * kernel versions, one can use two flavors of the struct name with the
4628 * same common name and use conditional relocations to extract that field,
4629 * depending on target kernel version.
4630 * 2. For each candidate type, try to match local specification to this
4631 * candidate target type. Matching involves finding corresponding
4632 * high-level spec accessors, meaning that all named fields should match,
4633 * as well as all array accesses should be within the actual bounds. Also,
4634 * types should be compatible (see bpf_core_fields_are_compat for details).
4635 * 3. It is supported and expected that there might be multiple flavors
4636 * matching the spec. As long as all the specs resolve to the same set of
4637 * offsets across all candidates, there is no error. If there is any
4638 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
4639 * imprefection of BTF deduplication, which can cause slight duplication of
4640 * the same BTF type, if some directly or indirectly referenced (by
4641 * pointer) type gets resolved to different actual types in different
4642 * object files. If such situation occurs, deduplicated BTF will end up
4643 * with two (or more) structurally identical types, which differ only in
4644 * types they refer to through pointer. This should be OK in most cases and
4645 * is not an error.
4646 * 4. Candidate types search is performed by linearly scanning through all
4647 * types in target BTF. It is anticipated that this is overall more
4648 * efficient memory-wise and not significantly worse (if not better)
4649 * CPU-wise compared to prebuilding a map from all local type names to
4650 * a list of candidate type names. It's also sped up by caching resolved
4651 * list of matching candidates per each local "root" type ID, that has at
4652 * least one bpf_field_reloc associated with it. This list is shared
4653 * between multiple relocations for the same type ID and is updated as some
4654 * of the candidates are pruned due to structural incompatibility.
4655 */
4656static int bpf_core_reloc_field(struct bpf_program *prog,
4657 const struct bpf_field_reloc *relo,
4658 int relo_idx,
4659 const struct btf *local_btf,
4660 const struct btf *targ_btf,
4661 struct hashmap *cand_cache)
4662{
4663 const char *prog_name = bpf_program__title(prog, false);
4664 struct bpf_core_spec local_spec, cand_spec, targ_spec;
4665 const void *type_key = u32_as_hash_key(relo->type_id);
4666 const struct btf_type *local_type, *cand_type;
4667 const char *local_name, *cand_name;
4668 struct ids_vec *cand_ids;
4669 __u32 local_id, cand_id;
4670 const char *spec_str;
4671 int i, j, err;
4672
4673 local_id = relo->type_id;
4674 local_type = btf__type_by_id(local_btf, local_id);
4675 if (!local_type)
4676 return -EINVAL;
4677
4678 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4679 if (str_is_empty(local_name))
4680 return -EINVAL;
4681
4682 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4683 if (str_is_empty(spec_str))
4684 return -EINVAL;
4685
4686 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4687 if (err) {
4688 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4689 prog_name, relo_idx, local_id, local_name, spec_str,
4690 err);
4691 return -EINVAL;
4692 }
4693
4694 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4695 relo->kind);
4696 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4697 libbpf_print(LIBBPF_DEBUG, "\n");
4698
4699 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4700 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4701 if (IS_ERR(cand_ids)) {
4702 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4703 prog_name, relo_idx, local_id, local_name,
4704 PTR_ERR(cand_ids));
4705 return PTR_ERR(cand_ids);
4706 }
4707 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4708 if (err) {
4709 bpf_core_free_cands(cand_ids);
4710 return err;
4711 }
4712 }
4713
4714 for (i = 0, j = 0; i < cand_ids->len; i++) {
4715 cand_id = cand_ids->data[i];
4716 cand_type = btf__type_by_id(targ_btf, cand_id);
4717 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4718
4719 err = bpf_core_spec_match(&local_spec, targ_btf,
4720 cand_id, &cand_spec);
4721 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4722 prog_name, relo_idx, i, cand_name);
4723 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4724 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4725 if (err < 0) {
4726 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4727 prog_name, relo_idx, err);
4728 return err;
4729 }
4730 if (err == 0)
4731 continue;
4732
4733 if (j == 0) {
4734 targ_spec = cand_spec;
4735 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
4736 /* if there are many candidates, they should all
4737 * resolve to the same bit offset
4738 */
4739 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
4740 prog_name, relo_idx, cand_spec.bit_offset,
4741 targ_spec.bit_offset);
4742 return -EINVAL;
4743 }
4744
4745 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4746 }
4747
4748 /*
4749 * For BPF_FIELD_EXISTS relo or when used BPF program has field
4750 * existence checks or kernel version/config checks, it's expected
4751 * that we might not find any candidates. In this case, if field
4752 * wasn't found in any candidate, the list of candidates shouldn't
4753 * change at all, we'll just handle relocating appropriately,
4754 * depending on relo's kind.
4755 */
4756 if (j > 0)
4757 cand_ids->len = j;
4758
4759 /*
4760 * If no candidates were found, it might be both a programmer error,
4761 * as well as expected case, depending whether instruction w/
4762 * relocation is guarded in some way that makes it unreachable (dead
4763 * code) if relocation can't be resolved. This is handled in
4764 * bpf_core_reloc_insn() uniformly by replacing that instruction with
4765 * BPF helper call insn (using invalid helper ID). If that instruction
4766 * is indeed unreachable, then it will be ignored and eliminated by
4767 * verifier. If it was an error, then verifier will complain and point
4768 * to a specific instruction number in its log.
4769 */
4770 if (j == 0)
4771 pr_debug("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4772 prog_name, relo_idx, local_id, local_name, spec_str);
4773
4774 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4775 err = bpf_core_reloc_insn(prog, relo, relo_idx, &local_spec,
4776 j ? &targ_spec : NULL);
4777 if (err) {
4778 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4779 prog_name, relo_idx, relo->insn_off, err);
4780 return -EINVAL;
4781 }
4782
4783 return 0;
4784}
4785
4786static int
4787bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
4788{
4789 const struct btf_ext_info_sec *sec;
4790 const struct bpf_field_reloc *rec;
4791 const struct btf_ext_info *seg;
4792 struct hashmap_entry *entry;
4793 struct hashmap *cand_cache = NULL;
4794 struct bpf_program *prog;
4795 struct btf *targ_btf;
4796 const char *sec_name;
4797 int i, err = 0;
4798
4799 if (targ_btf_path)
4800 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4801 else
4802 targ_btf = libbpf_find_kernel_btf();
4803 if (IS_ERR(targ_btf)) {
4804 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
4805 return PTR_ERR(targ_btf);
4806 }
4807
4808 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4809 if (IS_ERR(cand_cache)) {
4810 err = PTR_ERR(cand_cache);
4811 goto out;
4812 }
4813
4814 seg = &obj->btf_ext->field_reloc_info;
4815 for_each_btf_ext_sec(seg, sec) {
4816 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4817 if (str_is_empty(sec_name)) {
4818 err = -EINVAL;
4819 goto out;
4820 }
4821 prog = NULL;
4822 for (i = 0; i < obj->nr_programs; i++) {
4823 if (!strcmp(obj->programs[i].section_name, sec_name)) {
4824 prog = &obj->programs[i];
4825 break;
4826 }
4827 }
4828 if (!prog) {
4829 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4830 sec_name);
4831 err = -EINVAL;
4832 goto out;
4833 }
4834
4835 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4836 sec_name, sec->num_info);
4837
4838 for_each_btf_ext_rec(seg, sec, i, rec) {
4839 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4840 targ_btf, cand_cache);
4841 if (err) {
4842 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4843 sec_name, i, err);
4844 goto out;
4845 }
4846 }
4847 }
4848
4849out:
4850 btf__free(targ_btf);
4851 if (!IS_ERR_OR_NULL(cand_cache)) {
4852 hashmap__for_each_entry(cand_cache, entry, i) {
4853 bpf_core_free_cands(entry->value);
4854 }
4855 hashmap__free(cand_cache);
4856 }
4857 return err;
4858}
4859
4860static int
4861bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4862{
4863 int err = 0;
4864
4865 if (obj->btf_ext->field_reloc_info.len)
4866 err = bpf_core_reloc_fields(obj, targ_btf_path);
4867
4868 return err;
4869}
4870
4871static int
4872bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4873 struct reloc_desc *relo)
4874{
4875 struct bpf_insn *insn, *new_insn;
4876 struct bpf_program *text;
4877 size_t new_cnt;
4878 int err;
4879
4880 if (prog->idx != obj->efile.text_shndx && prog->main_prog_cnt == 0) {
4881 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4882 if (!text) {
4883 pr_warn("no .text section found yet relo into text exist\n");
4884 return -LIBBPF_ERRNO__RELOC;
4885 }
4886 new_cnt = prog->insns_cnt + text->insns_cnt;
4887 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
4888 if (!new_insn) {
4889 pr_warn("oom in prog realloc\n");
4890 return -ENOMEM;
4891 }
4892 prog->insns = new_insn;
4893
4894 if (obj->btf_ext) {
4895 err = bpf_program_reloc_btf_ext(prog, obj,
4896 text->section_name,
4897 prog->insns_cnt);
4898 if (err)
4899 return err;
4900 }
4901
4902 memcpy(new_insn + prog->insns_cnt, text->insns,
4903 text->insns_cnt * sizeof(*insn));
4904 prog->main_prog_cnt = prog->insns_cnt;
4905 prog->insns_cnt = new_cnt;
4906 pr_debug("added %zd insn from %s to prog %s\n",
4907 text->insns_cnt, text->section_name,
4908 prog->section_name);
4909 }
4910
4911 insn = &prog->insns[relo->insn_idx];
4912 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
4913 return 0;
4914}
4915
4916static int
4917bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
4918{
4919 int i, err;
4920
4921 if (!prog)
4922 return 0;
4923
4924 if (obj->btf_ext) {
4925 err = bpf_program_reloc_btf_ext(prog, obj,
4926 prog->section_name, 0);
4927 if (err)
4928 return err;
4929 }
4930
4931 if (!prog->reloc_desc)
4932 return 0;
4933
4934 for (i = 0; i < prog->nr_reloc; i++) {
4935 struct reloc_desc *relo = &prog->reloc_desc[i];
4936 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
4937
4938 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4939 pr_warn("relocation out of range: '%s'\n",
4940 prog->section_name);
4941 return -LIBBPF_ERRNO__RELOC;
4942 }
4943
4944 switch (relo->type) {
4945 case RELO_LD64:
4946 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
4947 insn[0].imm = obj->maps[relo->map_idx].fd;
4948 break;
4949 case RELO_DATA:
4950 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4951 insn[1].imm = insn[0].imm + relo->sym_off;
4952 insn[0].imm = obj->maps[relo->map_idx].fd;
4953 break;
4954 case RELO_EXTERN:
4955 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4956 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
4957 insn[1].imm = relo->sym_off;
4958 break;
4959 case RELO_CALL:
4960 err = bpf_program__reloc_text(prog, obj, relo);
4961 if (err)
4962 return err;
4963 break;
4964 default:
4965 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4966 return -EINVAL;
4967 }
4968 }
4969
4970 zfree(&prog->reloc_desc);
4971 prog->nr_reloc = 0;
4972 return 0;
4973}
4974
4975static int
4976bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
4977{
4978 struct bpf_program *prog;
4979 size_t i;
4980 int err;
4981
4982 if (obj->btf_ext) {
4983 err = bpf_object__relocate_core(obj, targ_btf_path);
4984 if (err) {
4985 pr_warn("failed to perform CO-RE relocations: %d\n",
4986 err);
4987 return err;
4988 }
4989 }
4990 /* ensure .text is relocated first, as it's going to be copied as-is
4991 * later for sub-program calls
4992 */
4993 for (i = 0; i < obj->nr_programs; i++) {
4994 prog = &obj->programs[i];
4995 if (prog->idx != obj->efile.text_shndx)
4996 continue;
4997
4998 err = bpf_program__relocate(prog, obj);
4999 if (err) {
5000 pr_warn("failed to relocate '%s'\n", prog->section_name);
5001 return err;
5002 }
5003 break;
5004 }
5005 /* now relocate everything but .text, which by now is relocated
5006 * properly, so we can copy raw sub-program instructions as is safely
5007 */
5008 for (i = 0; i < obj->nr_programs; i++) {
5009 prog = &obj->programs[i];
5010 if (prog->idx == obj->efile.text_shndx)
5011 continue;
5012
5013 err = bpf_program__relocate(prog, obj);
5014 if (err) {
5015 pr_warn("failed to relocate '%s'\n", prog->section_name);
5016 return err;
5017 }
5018 }
5019 return 0;
5020}
5021
5022static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
5023 GElf_Shdr *shdr, Elf_Data *data);
5024
5025static int bpf_object__collect_map_relos(struct bpf_object *obj,
5026 GElf_Shdr *shdr, Elf_Data *data)
5027{
5028 int i, j, nrels, new_sz, ptr_sz = sizeof(void *);
5029 const struct btf_var_secinfo *vi = NULL;
5030 const struct btf_type *sec, *var, *def;
5031 const struct btf_member *member;
5032 struct bpf_map *map, *targ_map;
5033 const char *name, *mname;
5034 Elf_Data *symbols;
5035 unsigned int moff;
5036 GElf_Sym sym;
5037 GElf_Rel rel;
5038 void *tmp;
5039
5040 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
5041 return -EINVAL;
5042 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
5043 if (!sec)
5044 return -EINVAL;
5045
5046 symbols = obj->efile.symbols;
5047 nrels = shdr->sh_size / shdr->sh_entsize;
5048 for (i = 0; i < nrels; i++) {
5049 if (!gelf_getrel(data, i, &rel)) {
5050 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
5051 return -LIBBPF_ERRNO__FORMAT;
5052 }
5053 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
5054 pr_warn(".maps relo #%d: symbol %zx not found\n",
5055 i, (size_t)GELF_R_SYM(rel.r_info));
5056 return -LIBBPF_ERRNO__FORMAT;
5057 }
5058 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
5059 sym.st_name) ? : "<?>";
5060 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
5061 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
5062 i, name);
5063 return -LIBBPF_ERRNO__RELOC;
5064 }
5065
5066 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
5067 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
5068 (size_t)rel.r_offset, sym.st_name, name);
5069
5070 for (j = 0; j < obj->nr_maps; j++) {
5071 map = &obj->maps[j];
5072 if (map->sec_idx != obj->efile.btf_maps_shndx)
5073 continue;
5074
5075 vi = btf_var_secinfos(sec) + map->btf_var_idx;
5076 if (vi->offset <= rel.r_offset &&
5077 rel.r_offset + sizeof(void *) <= vi->offset + vi->size)
5078 break;
5079 }
5080 if (j == obj->nr_maps) {
5081 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
5082 i, name, (size_t)rel.r_offset);
5083 return -EINVAL;
5084 }
5085
5086 if (!bpf_map_type__is_map_in_map(map->def.type))
5087 return -EINVAL;
5088 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
5089 map->def.key_size != sizeof(int)) {
5090 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
5091 i, map->name, sizeof(int));
5092 return -EINVAL;
5093 }
5094
5095 targ_map = bpf_object__find_map_by_name(obj, name);
5096 if (!targ_map)
5097 return -ESRCH;
5098
5099 var = btf__type_by_id(obj->btf, vi->type);
5100 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
5101 if (btf_vlen(def) == 0)
5102 return -EINVAL;
5103 member = btf_members(def) + btf_vlen(def) - 1;
5104 mname = btf__name_by_offset(obj->btf, member->name_off);
5105 if (strcmp(mname, "values"))
5106 return -EINVAL;
5107
5108 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
5109 if (rel.r_offset - vi->offset < moff)
5110 return -EINVAL;
5111
5112 moff = rel.r_offset - vi->offset - moff;
5113 if (moff % ptr_sz)
5114 return -EINVAL;
5115 moff /= ptr_sz;
5116 if (moff >= map->init_slots_sz) {
5117 new_sz = moff + 1;
5118 tmp = realloc(map->init_slots, new_sz * ptr_sz);
5119 if (!tmp)
5120 return -ENOMEM;
5121 map->init_slots = tmp;
5122 memset(map->init_slots + map->init_slots_sz, 0,
5123 (new_sz - map->init_slots_sz) * ptr_sz);
5124 map->init_slots_sz = new_sz;
5125 }
5126 map->init_slots[moff] = targ_map;
5127
5128 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
5129 i, map->name, moff, name);
5130 }
5131
5132 return 0;
5133}
5134
5135static int bpf_object__collect_reloc(struct bpf_object *obj)
5136{
5137 int i, err;
5138
5139 if (!obj_elf_valid(obj)) {
5140 pr_warn("Internal error: elf object is closed\n");
5141 return -LIBBPF_ERRNO__INTERNAL;
5142 }
5143
5144 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
5145 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
5146 Elf_Data *data = obj->efile.reloc_sects[i].data;
5147 int idx = shdr->sh_info;
5148 struct bpf_program *prog;
5149
5150 if (shdr->sh_type != SHT_REL) {
5151 pr_warn("internal error at %d\n", __LINE__);
5152 return -LIBBPF_ERRNO__INTERNAL;
5153 }
5154
5155 if (idx == obj->efile.st_ops_shndx) {
5156 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
5157 } else if (idx == obj->efile.btf_maps_shndx) {
5158 err = bpf_object__collect_map_relos(obj, shdr, data);
5159 } else {
5160 prog = bpf_object__find_prog_by_idx(obj, idx);
5161 if (!prog) {
5162 pr_warn("relocation failed: no prog in section(%d)\n", idx);
5163 return -LIBBPF_ERRNO__RELOC;
5164 }
5165 err = bpf_program__collect_reloc(prog, shdr, data, obj);
5166 }
5167 if (err)
5168 return err;
5169 }
5170 return 0;
5171}
5172
5173static int
5174load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
5175 char *license, __u32 kern_version, int *pfd)
5176{
5177 struct bpf_load_program_attr load_attr;
5178 char *cp, errmsg[STRERR_BUFSIZE];
5179 size_t log_buf_size = 0;
5180 char *log_buf = NULL;
5181 int btf_fd, ret;
5182
5183 if (!insns || !insns_cnt)
5184 return -EINVAL;
5185
5186 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
5187 load_attr.prog_type = prog->type;
5188 /* old kernels might not support specifying expected_attach_type */
5189 if (!prog->caps->exp_attach_type && prog->sec_def &&
5190 prog->sec_def->is_exp_attach_type_optional)
5191 load_attr.expected_attach_type = 0;
5192 else
5193 load_attr.expected_attach_type = prog->expected_attach_type;
5194 if (prog->caps->name)
5195 load_attr.name = prog->name;
5196 load_attr.insns = insns;
5197 load_attr.insns_cnt = insns_cnt;
5198 load_attr.license = license;
5199 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
5200 prog->type == BPF_PROG_TYPE_LSM) {
5201 load_attr.attach_btf_id = prog->attach_btf_id;
5202 } else if (prog->type == BPF_PROG_TYPE_TRACING ||
5203 prog->type == BPF_PROG_TYPE_EXT) {
5204 load_attr.attach_prog_fd = prog->attach_prog_fd;
5205 load_attr.attach_btf_id = prog->attach_btf_id;
5206 } else {
5207 load_attr.kern_version = kern_version;
5208 load_attr.prog_ifindex = prog->prog_ifindex;
5209 }
5210 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
5211 if (prog->obj->btf_ext)
5212 btf_fd = bpf_object__btf_fd(prog->obj);
5213 else
5214 btf_fd = -1;
5215 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
5216 load_attr.func_info = prog->func_info;
5217 load_attr.func_info_rec_size = prog->func_info_rec_size;
5218 load_attr.func_info_cnt = prog->func_info_cnt;
5219 load_attr.line_info = prog->line_info;
5220 load_attr.line_info_rec_size = prog->line_info_rec_size;
5221 load_attr.line_info_cnt = prog->line_info_cnt;
5222 load_attr.log_level = prog->log_level;
5223 load_attr.prog_flags = prog->prog_flags;
5224
5225retry_load:
5226 if (log_buf_size) {
5227 log_buf = malloc(log_buf_size);
5228 if (!log_buf)
5229 return -ENOMEM;
5230
5231 *log_buf = 0;
5232 }
5233
5234 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
5235
5236 if (ret >= 0) {
5237 if (log_buf && load_attr.log_level)
5238 pr_debug("verifier log:\n%s", log_buf);
5239 *pfd = ret;
5240 ret = 0;
5241 goto out;
5242 }
5243
5244 if (!log_buf || errno == ENOSPC) {
5245 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
5246 log_buf_size << 1);
5247
5248 free(log_buf);
5249 goto retry_load;
5250 }
5251 ret = -errno;
5252 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5253 pr_warn("load bpf program failed: %s\n", cp);
5254 pr_perm_msg(ret);
5255
5256 if (log_buf && log_buf[0] != '\0') {
5257 ret = -LIBBPF_ERRNO__VERIFY;
5258 pr_warn("-- BEGIN DUMP LOG ---\n");
5259 pr_warn("\n%s\n", log_buf);
5260 pr_warn("-- END LOG --\n");
5261 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
5262 pr_warn("Program too large (%zu insns), at most %d insns\n",
5263 load_attr.insns_cnt, BPF_MAXINSNS);
5264 ret = -LIBBPF_ERRNO__PROG2BIG;
5265 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
5266 /* Wrong program type? */
5267 int fd;
5268
5269 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
5270 load_attr.expected_attach_type = 0;
5271 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
5272 if (fd >= 0) {
5273 close(fd);
5274 ret = -LIBBPF_ERRNO__PROGTYPE;
5275 goto out;
5276 }
5277 }
5278
5279out:
5280 free(log_buf);
5281 return ret;
5282}
5283
5284static int libbpf_find_attach_btf_id(struct bpf_program *prog);
5285
5286int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
5287{
5288 int err = 0, fd, i, btf_id;
5289
5290 if ((prog->type == BPF_PROG_TYPE_TRACING ||
5291 prog->type == BPF_PROG_TYPE_LSM ||
5292 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
5293 btf_id = libbpf_find_attach_btf_id(prog);
5294 if (btf_id <= 0)
5295 return btf_id;
5296 prog->attach_btf_id = btf_id;
5297 }
5298
5299 if (prog->instances.nr < 0 || !prog->instances.fds) {
5300 if (prog->preprocessor) {
5301 pr_warn("Internal error: can't load program '%s'\n",
5302 prog->section_name);
5303 return -LIBBPF_ERRNO__INTERNAL;
5304 }
5305
5306 prog->instances.fds = malloc(sizeof(int));
5307 if (!prog->instances.fds) {
5308 pr_warn("Not enough memory for BPF fds\n");
5309 return -ENOMEM;
5310 }
5311 prog->instances.nr = 1;
5312 prog->instances.fds[0] = -1;
5313 }
5314
5315 if (!prog->preprocessor) {
5316 if (prog->instances.nr != 1) {
5317 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
5318 prog->section_name, prog->instances.nr);
5319 }
5320 err = load_program(prog, prog->insns, prog->insns_cnt,
5321 license, kern_ver, &fd);
5322 if (!err)
5323 prog->instances.fds[0] = fd;
5324 goto out;
5325 }
5326
5327 for (i = 0; i < prog->instances.nr; i++) {
5328 struct bpf_prog_prep_result result;
5329 bpf_program_prep_t preprocessor = prog->preprocessor;
5330
5331 memset(&result, 0, sizeof(result));
5332 err = preprocessor(prog, i, prog->insns,
5333 prog->insns_cnt, &result);
5334 if (err) {
5335 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
5336 i, prog->section_name);
5337 goto out;
5338 }
5339
5340 if (!result.new_insn_ptr || !result.new_insn_cnt) {
5341 pr_debug("Skip loading the %dth instance of program '%s'\n",
5342 i, prog->section_name);
5343 prog->instances.fds[i] = -1;
5344 if (result.pfd)
5345 *result.pfd = -1;
5346 continue;
5347 }
5348
5349 err = load_program(prog, result.new_insn_ptr,
5350 result.new_insn_cnt, license, kern_ver, &fd);
5351 if (err) {
5352 pr_warn("Loading the %dth instance of program '%s' failed\n",
5353 i, prog->section_name);
5354 goto out;
5355 }
5356
5357 if (result.pfd)
5358 *result.pfd = fd;
5359 prog->instances.fds[i] = fd;
5360 }
5361out:
5362 if (err)
5363 pr_warn("failed to load program '%s'\n", prog->section_name);
5364 zfree(&prog->insns);
5365 prog->insns_cnt = 0;
5366 return err;
5367}
5368
5369static bool bpf_program__is_function_storage(const struct bpf_program *prog,
5370 const struct bpf_object *obj)
5371{
5372 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
5373}
5374
5375static int
5376bpf_object__load_progs(struct bpf_object *obj, int log_level)
5377{
5378 size_t i;
5379 int err;
5380
5381 for (i = 0; i < obj->nr_programs; i++) {
5382 if (bpf_program__is_function_storage(&obj->programs[i], obj))
5383 continue;
5384 obj->programs[i].log_level |= log_level;
5385 err = bpf_program__load(&obj->programs[i],
5386 obj->license,
5387 obj->kern_version);
5388 if (err)
5389 return err;
5390 }
5391 return 0;
5392}
5393
5394static const struct bpf_sec_def *find_sec_def(const char *sec_name);
5395
5396static struct bpf_object *
5397__bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
5398 const struct bpf_object_open_opts *opts)
5399{
5400 const char *obj_name, *kconfig;
5401 struct bpf_program *prog;
5402 struct bpf_object *obj;
5403 char tmp_name[64];
5404 int err;
5405
5406 if (elf_version(EV_CURRENT) == EV_NONE) {
5407 pr_warn("failed to init libelf for %s\n",
5408 path ? : "(mem buf)");
5409 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
5410 }
5411
5412 if (!OPTS_VALID(opts, bpf_object_open_opts))
5413 return ERR_PTR(-EINVAL);
5414
5415 obj_name = OPTS_GET(opts, object_name, NULL);
5416 if (obj_buf) {
5417 if (!obj_name) {
5418 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
5419 (unsigned long)obj_buf,
5420 (unsigned long)obj_buf_sz);
5421 obj_name = tmp_name;
5422 }
5423 path = obj_name;
5424 pr_debug("loading object '%s' from buffer\n", obj_name);
5425 }
5426
5427 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
5428 if (IS_ERR(obj))
5429 return obj;
5430
5431 kconfig = OPTS_GET(opts, kconfig, NULL);
5432 if (kconfig) {
5433 obj->kconfig = strdup(kconfig);
5434 if (!obj->kconfig)
5435 return ERR_PTR(-ENOMEM);
5436 }
5437
5438 err = bpf_object__elf_init(obj);
5439 err = err ? : bpf_object__check_endianness(obj);
5440 err = err ? : bpf_object__elf_collect(obj);
5441 err = err ? : bpf_object__collect_externs(obj);
5442 err = err ? : bpf_object__finalize_btf(obj);
5443 err = err ? : bpf_object__init_maps(obj, opts);
5444 err = err ? : bpf_object__init_prog_names(obj);
5445 err = err ? : bpf_object__collect_reloc(obj);
5446 if (err)
5447 goto out;
5448 bpf_object__elf_finish(obj);
5449
5450 bpf_object__for_each_program(prog, obj) {
5451 prog->sec_def = find_sec_def(prog->section_name);
5452 if (!prog->sec_def)
5453 /* couldn't guess, but user might manually specify */
5454 continue;
5455
5456 bpf_program__set_type(prog, prog->sec_def->prog_type);
5457 bpf_program__set_expected_attach_type(prog,
5458 prog->sec_def->expected_attach_type);
5459
5460 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
5461 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
5462 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
5463 }
5464
5465 return obj;
5466out:
5467 bpf_object__close(obj);
5468 return ERR_PTR(err);
5469}
5470
5471static struct bpf_object *
5472__bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
5473{
5474 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5475 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
5476 );
5477
5478 /* param validation */
5479 if (!attr->file)
5480 return NULL;
5481
5482 pr_debug("loading %s\n", attr->file);
5483 return __bpf_object__open(attr->file, NULL, 0, &opts);
5484}
5485
5486struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
5487{
5488 return __bpf_object__open_xattr(attr, 0);
5489}
5490
5491struct bpf_object *bpf_object__open(const char *path)
5492{
5493 struct bpf_object_open_attr attr = {
5494 .file = path,
5495 .prog_type = BPF_PROG_TYPE_UNSPEC,
5496 };
5497
5498 return bpf_object__open_xattr(&attr);
5499}
5500
5501struct bpf_object *
5502bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
5503{
5504 if (!path)
5505 return ERR_PTR(-EINVAL);
5506
5507 pr_debug("loading %s\n", path);
5508
5509 return __bpf_object__open(path, NULL, 0, opts);
5510}
5511
5512struct bpf_object *
5513bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
5514 const struct bpf_object_open_opts *opts)
5515{
5516 if (!obj_buf || obj_buf_sz == 0)
5517 return ERR_PTR(-EINVAL);
5518
5519 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
5520}
5521
5522struct bpf_object *
5523bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
5524 const char *name)
5525{
5526 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
5527 .object_name = name,
5528 /* wrong default, but backwards-compatible */
5529 .relaxed_maps = true,
5530 );
5531
5532 /* returning NULL is wrong, but backwards-compatible */
5533 if (!obj_buf || obj_buf_sz == 0)
5534 return NULL;
5535
5536 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
5537}
5538
5539int bpf_object__unload(struct bpf_object *obj)
5540{
5541 size_t i;
5542
5543 if (!obj)
5544 return -EINVAL;
5545
5546 for (i = 0; i < obj->nr_maps; i++) {
5547 zclose(obj->maps[i].fd);
5548 if (obj->maps[i].st_ops)
5549 zfree(&obj->maps[i].st_ops->kern_vdata);
5550 }
5551
5552 for (i = 0; i < obj->nr_programs; i++)
5553 bpf_program__unload(&obj->programs[i]);
5554
5555 return 0;
5556}
5557
5558static int bpf_object__sanitize_maps(struct bpf_object *obj)
5559{
5560 struct bpf_map *m;
5561
5562 bpf_object__for_each_map(m, obj) {
5563 if (!bpf_map__is_internal(m))
5564 continue;
5565 if (!obj->caps.global_data) {
5566 pr_warn("kernel doesn't support global data\n");
5567 return -ENOTSUP;
5568 }
5569 if (!obj->caps.array_mmap)
5570 m->def.map_flags ^= BPF_F_MMAPABLE;
5571 }
5572
5573 return 0;
5574}
5575
5576static int bpf_object__resolve_externs(struct bpf_object *obj,
5577 const char *extra_kconfig)
5578{
5579 bool need_config = false;
5580 struct extern_desc *ext;
5581 int err, i;
5582 void *data;
5583
5584 if (obj->nr_extern == 0)
5585 return 0;
5586
5587 data = obj->maps[obj->kconfig_map_idx].mmaped;
5588
5589 for (i = 0; i < obj->nr_extern; i++) {
5590 ext = &obj->externs[i];
5591
5592 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
5593 void *ext_val = data + ext->data_off;
5594 __u32 kver = get_kernel_version();
5595
5596 if (!kver) {
5597 pr_warn("failed to get kernel version\n");
5598 return -EINVAL;
5599 }
5600 err = set_ext_value_num(ext, ext_val, kver);
5601 if (err)
5602 return err;
5603 pr_debug("extern %s=0x%x\n", ext->name, kver);
5604 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
5605 need_config = true;
5606 } else {
5607 pr_warn("unrecognized extern '%s'\n", ext->name);
5608 return -EINVAL;
5609 }
5610 }
5611 if (need_config && extra_kconfig) {
5612 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, data);
5613 if (err)
5614 return -EINVAL;
5615 need_config = false;
5616 for (i = 0; i < obj->nr_extern; i++) {
5617 ext = &obj->externs[i];
5618 if (!ext->is_set) {
5619 need_config = true;
5620 break;
5621 }
5622 }
5623 }
5624 if (need_config) {
5625 err = bpf_object__read_kconfig_file(obj, data);
5626 if (err)
5627 return -EINVAL;
5628 }
5629 for (i = 0; i < obj->nr_extern; i++) {
5630 ext = &obj->externs[i];
5631
5632 if (!ext->is_set && !ext->is_weak) {
5633 pr_warn("extern %s (strong) not resolved\n", ext->name);
5634 return -ESRCH;
5635 } else if (!ext->is_set) {
5636 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
5637 ext->name);
5638 }
5639 }
5640
5641 return 0;
5642}
5643
5644int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
5645{
5646 struct bpf_object *obj;
5647 int err, i;
5648
5649 if (!attr)
5650 return -EINVAL;
5651 obj = attr->obj;
5652 if (!obj)
5653 return -EINVAL;
5654
5655 if (obj->loaded) {
5656 pr_warn("object should not be loaded twice\n");
5657 return -EINVAL;
5658 }
5659
5660 obj->loaded = true;
5661
5662 err = bpf_object__probe_loading(obj);
5663 err = err ? : bpf_object__probe_caps(obj);
5664 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
5665 err = err ? : bpf_object__sanitize_and_load_btf(obj);
5666 err = err ? : bpf_object__sanitize_maps(obj);
5667 err = err ? : bpf_object__load_vmlinux_btf(obj);
5668 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
5669 err = err ? : bpf_object__create_maps(obj);
5670 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
5671 err = err ? : bpf_object__load_progs(obj, attr->log_level);
5672
5673 btf__free(obj->btf_vmlinux);
5674 obj->btf_vmlinux = NULL;
5675
5676 if (err)
5677 goto out;
5678
5679 return 0;
5680out:
5681 /* unpin any maps that were auto-pinned during load */
5682 for (i = 0; i < obj->nr_maps; i++)
5683 if (obj->maps[i].pinned && !obj->maps[i].reused)
5684 bpf_map__unpin(&obj->maps[i], NULL);
5685
5686 bpf_object__unload(obj);
5687 pr_warn("failed to load object '%s'\n", obj->path);
5688 return err;
5689}
5690
5691int bpf_object__load(struct bpf_object *obj)
5692{
5693 struct bpf_object_load_attr attr = {
5694 .obj = obj,
5695 };
5696
5697 return bpf_object__load_xattr(&attr);
5698}
5699
5700static int make_parent_dir(const char *path)
5701{
5702 char *cp, errmsg[STRERR_BUFSIZE];
5703 char *dname, *dir;
5704 int err = 0;
5705
5706 dname = strdup(path);
5707 if (dname == NULL)
5708 return -ENOMEM;
5709
5710 dir = dirname(dname);
5711 if (mkdir(dir, 0700) && errno != EEXIST)
5712 err = -errno;
5713
5714 free(dname);
5715 if (err) {
5716 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5717 pr_warn("failed to mkdir %s: %s\n", path, cp);
5718 }
5719 return err;
5720}
5721
5722static int check_path(const char *path)
5723{
5724 char *cp, errmsg[STRERR_BUFSIZE];
5725 struct statfs st_fs;
5726 char *dname, *dir;
5727 int err = 0;
5728
5729 if (path == NULL)
5730 return -EINVAL;
5731
5732 dname = strdup(path);
5733 if (dname == NULL)
5734 return -ENOMEM;
5735
5736 dir = dirname(dname);
5737 if (statfs(dir, &st_fs)) {
5738 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5739 pr_warn("failed to statfs %s: %s\n", dir, cp);
5740 err = -errno;
5741 }
5742 free(dname);
5743
5744 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
5745 pr_warn("specified path %s is not on BPF FS\n", path);
5746 err = -EINVAL;
5747 }
5748
5749 return err;
5750}
5751
5752int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
5753 int instance)
5754{
5755 char *cp, errmsg[STRERR_BUFSIZE];
5756 int err;
5757
5758 err = make_parent_dir(path);
5759 if (err)
5760 return err;
5761
5762 err = check_path(path);
5763 if (err)
5764 return err;
5765
5766 if (prog == NULL) {
5767 pr_warn("invalid program pointer\n");
5768 return -EINVAL;
5769 }
5770
5771 if (instance < 0 || instance >= prog->instances.nr) {
5772 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5773 instance, prog->section_name, prog->instances.nr);
5774 return -EINVAL;
5775 }
5776
5777 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
5778 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
5779 pr_warn("failed to pin program: %s\n", cp);
5780 return -errno;
5781 }
5782 pr_debug("pinned program '%s'\n", path);
5783
5784 return 0;
5785}
5786
5787int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
5788 int instance)
5789{
5790 int err;
5791
5792 err = check_path(path);
5793 if (err)
5794 return err;
5795
5796 if (prog == NULL) {
5797 pr_warn("invalid program pointer\n");
5798 return -EINVAL;
5799 }
5800
5801 if (instance < 0 || instance >= prog->instances.nr) {
5802 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
5803 instance, prog->section_name, prog->instances.nr);
5804 return -EINVAL;
5805 }
5806
5807 err = unlink(path);
5808 if (err != 0)
5809 return -errno;
5810 pr_debug("unpinned program '%s'\n", path);
5811
5812 return 0;
5813}
5814
5815int bpf_program__pin(struct bpf_program *prog, const char *path)
5816{
5817 int i, err;
5818
5819 err = make_parent_dir(path);
5820 if (err)
5821 return err;
5822
5823 err = check_path(path);
5824 if (err)
5825 return err;
5826
5827 if (prog == NULL) {
5828 pr_warn("invalid program pointer\n");
5829 return -EINVAL;
5830 }
5831
5832 if (prog->instances.nr <= 0) {
5833 pr_warn("no instances of prog %s to pin\n",
5834 prog->section_name);
5835 return -EINVAL;
5836 }
5837
5838 if (prog->instances.nr == 1) {
5839 /* don't create subdirs when pinning single instance */
5840 return bpf_program__pin_instance(prog, path, 0);
5841 }
5842
5843 for (i = 0; i < prog->instances.nr; i++) {
5844 char buf[PATH_MAX];
5845 int len;
5846
5847 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5848 if (len < 0) {
5849 err = -EINVAL;
5850 goto err_unpin;
5851 } else if (len >= PATH_MAX) {
5852 err = -ENAMETOOLONG;
5853 goto err_unpin;
5854 }
5855
5856 err = bpf_program__pin_instance(prog, buf, i);
5857 if (err)
5858 goto err_unpin;
5859 }
5860
5861 return 0;
5862
5863err_unpin:
5864 for (i = i - 1; i >= 0; i--) {
5865 char buf[PATH_MAX];
5866 int len;
5867
5868 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5869 if (len < 0)
5870 continue;
5871 else if (len >= PATH_MAX)
5872 continue;
5873
5874 bpf_program__unpin_instance(prog, buf, i);
5875 }
5876
5877 rmdir(path);
5878
5879 return err;
5880}
5881
5882int bpf_program__unpin(struct bpf_program *prog, const char *path)
5883{
5884 int i, err;
5885
5886 err = check_path(path);
5887 if (err)
5888 return err;
5889
5890 if (prog == NULL) {
5891 pr_warn("invalid program pointer\n");
5892 return -EINVAL;
5893 }
5894
5895 if (prog->instances.nr <= 0) {
5896 pr_warn("no instances of prog %s to pin\n",
5897 prog->section_name);
5898 return -EINVAL;
5899 }
5900
5901 if (prog->instances.nr == 1) {
5902 /* don't create subdirs when pinning single instance */
5903 return bpf_program__unpin_instance(prog, path, 0);
5904 }
5905
5906 for (i = 0; i < prog->instances.nr; i++) {
5907 char buf[PATH_MAX];
5908 int len;
5909
5910 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5911 if (len < 0)
5912 return -EINVAL;
5913 else if (len >= PATH_MAX)
5914 return -ENAMETOOLONG;
5915
5916 err = bpf_program__unpin_instance(prog, buf, i);
5917 if (err)
5918 return err;
5919 }
5920
5921 err = rmdir(path);
5922 if (err)
5923 return -errno;
5924
5925 return 0;
5926}
5927
5928int bpf_map__pin(struct bpf_map *map, const char *path)
5929{
5930 char *cp, errmsg[STRERR_BUFSIZE];
5931 int err;
5932
5933 if (map == NULL) {
5934 pr_warn("invalid map pointer\n");
5935 return -EINVAL;
5936 }
5937
5938 if (map->pin_path) {
5939 if (path && strcmp(path, map->pin_path)) {
5940 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5941 bpf_map__name(map), map->pin_path, path);
5942 return -EINVAL;
5943 } else if (map->pinned) {
5944 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5945 bpf_map__name(map), map->pin_path);
5946 return 0;
5947 }
5948 } else {
5949 if (!path) {
5950 pr_warn("missing a path to pin map '%s' at\n",
5951 bpf_map__name(map));
5952 return -EINVAL;
5953 } else if (map->pinned) {
5954 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5955 return -EEXIST;
5956 }
5957
5958 map->pin_path = strdup(path);
5959 if (!map->pin_path) {
5960 err = -errno;
5961 goto out_err;
5962 }
5963 }
5964
5965 err = make_parent_dir(map->pin_path);
5966 if (err)
5967 return err;
5968
5969 err = check_path(map->pin_path);
5970 if (err)
5971 return err;
5972
5973 if (bpf_obj_pin(map->fd, map->pin_path)) {
5974 err = -errno;
5975 goto out_err;
5976 }
5977
5978 map->pinned = true;
5979 pr_debug("pinned map '%s'\n", map->pin_path);
5980
5981 return 0;
5982
5983out_err:
5984 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5985 pr_warn("failed to pin map: %s\n", cp);
5986 return err;
5987}
5988
5989int bpf_map__unpin(struct bpf_map *map, const char *path)
5990{
5991 int err;
5992
5993 if (map == NULL) {
5994 pr_warn("invalid map pointer\n");
5995 return -EINVAL;
5996 }
5997
5998 if (map->pin_path) {
5999 if (path && strcmp(path, map->pin_path)) {
6000 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
6001 bpf_map__name(map), map->pin_path, path);
6002 return -EINVAL;
6003 }
6004 path = map->pin_path;
6005 } else if (!path) {
6006 pr_warn("no path to unpin map '%s' from\n",
6007 bpf_map__name(map));
6008 return -EINVAL;
6009 }
6010
6011 err = check_path(path);
6012 if (err)
6013 return err;
6014
6015 err = unlink(path);
6016 if (err != 0)
6017 return -errno;
6018
6019 map->pinned = false;
6020 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
6021
6022 return 0;
6023}
6024
6025int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
6026{
6027 char *new = NULL;
6028
6029 if (path) {
6030 new = strdup(path);
6031 if (!new)
6032 return -errno;
6033 }
6034
6035 free(map->pin_path);
6036 map->pin_path = new;
6037 return 0;
6038}
6039
6040const char *bpf_map__get_pin_path(const struct bpf_map *map)
6041{
6042 return map->pin_path;
6043}
6044
6045bool bpf_map__is_pinned(const struct bpf_map *map)
6046{
6047 return map->pinned;
6048}
6049
6050int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
6051{
6052 struct bpf_map *map;
6053 int err;
6054
6055 if (!obj)
6056 return -ENOENT;
6057
6058 if (!obj->loaded) {
6059 pr_warn("object not yet loaded; load it first\n");
6060 return -ENOENT;
6061 }
6062
6063 bpf_object__for_each_map(map, obj) {
6064 char *pin_path = NULL;
6065 char buf[PATH_MAX];
6066
6067 if (path) {
6068 int len;
6069
6070 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6071 bpf_map__name(map));
6072 if (len < 0) {
6073 err = -EINVAL;
6074 goto err_unpin_maps;
6075 } else if (len >= PATH_MAX) {
6076 err = -ENAMETOOLONG;
6077 goto err_unpin_maps;
6078 }
6079 pin_path = buf;
6080 } else if (!map->pin_path) {
6081 continue;
6082 }
6083
6084 err = bpf_map__pin(map, pin_path);
6085 if (err)
6086 goto err_unpin_maps;
6087 }
6088
6089 return 0;
6090
6091err_unpin_maps:
6092 while ((map = bpf_map__prev(map, obj))) {
6093 if (!map->pin_path)
6094 continue;
6095
6096 bpf_map__unpin(map, NULL);
6097 }
6098
6099 return err;
6100}
6101
6102int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
6103{
6104 struct bpf_map *map;
6105 int err;
6106
6107 if (!obj)
6108 return -ENOENT;
6109
6110 bpf_object__for_each_map(map, obj) {
6111 char *pin_path = NULL;
6112 char buf[PATH_MAX];
6113
6114 if (path) {
6115 int len;
6116
6117 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6118 bpf_map__name(map));
6119 if (len < 0)
6120 return -EINVAL;
6121 else if (len >= PATH_MAX)
6122 return -ENAMETOOLONG;
6123 pin_path = buf;
6124 } else if (!map->pin_path) {
6125 continue;
6126 }
6127
6128 err = bpf_map__unpin(map, pin_path);
6129 if (err)
6130 return err;
6131 }
6132
6133 return 0;
6134}
6135
6136int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
6137{
6138 struct bpf_program *prog;
6139 int err;
6140
6141 if (!obj)
6142 return -ENOENT;
6143
6144 if (!obj->loaded) {
6145 pr_warn("object not yet loaded; load it first\n");
6146 return -ENOENT;
6147 }
6148
6149 bpf_object__for_each_program(prog, obj) {
6150 char buf[PATH_MAX];
6151 int len;
6152
6153 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6154 prog->pin_name);
6155 if (len < 0) {
6156 err = -EINVAL;
6157 goto err_unpin_programs;
6158 } else if (len >= PATH_MAX) {
6159 err = -ENAMETOOLONG;
6160 goto err_unpin_programs;
6161 }
6162
6163 err = bpf_program__pin(prog, buf);
6164 if (err)
6165 goto err_unpin_programs;
6166 }
6167
6168 return 0;
6169
6170err_unpin_programs:
6171 while ((prog = bpf_program__prev(prog, obj))) {
6172 char buf[PATH_MAX];
6173 int len;
6174
6175 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6176 prog->pin_name);
6177 if (len < 0)
6178 continue;
6179 else if (len >= PATH_MAX)
6180 continue;
6181
6182 bpf_program__unpin(prog, buf);
6183 }
6184
6185 return err;
6186}
6187
6188int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
6189{
6190 struct bpf_program *prog;
6191 int err;
6192
6193 if (!obj)
6194 return -ENOENT;
6195
6196 bpf_object__for_each_program(prog, obj) {
6197 char buf[PATH_MAX];
6198 int len;
6199
6200 len = snprintf(buf, PATH_MAX, "%s/%s", path,
6201 prog->pin_name);
6202 if (len < 0)
6203 return -EINVAL;
6204 else if (len >= PATH_MAX)
6205 return -ENAMETOOLONG;
6206
6207 err = bpf_program__unpin(prog, buf);
6208 if (err)
6209 return err;
6210 }
6211
6212 return 0;
6213}
6214
6215int bpf_object__pin(struct bpf_object *obj, const char *path)
6216{
6217 int err;
6218
6219 err = bpf_object__pin_maps(obj, path);
6220 if (err)
6221 return err;
6222
6223 err = bpf_object__pin_programs(obj, path);
6224 if (err) {
6225 bpf_object__unpin_maps(obj, path);
6226 return err;
6227 }
6228
6229 return 0;
6230}
6231
6232static void bpf_map__destroy(struct bpf_map *map)
6233{
6234 if (map->clear_priv)
6235 map->clear_priv(map, map->priv);
6236 map->priv = NULL;
6237 map->clear_priv = NULL;
6238
6239 if (map->inner_map) {
6240 bpf_map__destroy(map->inner_map);
6241 zfree(&map->inner_map);
6242 }
6243
6244 zfree(&map->init_slots);
6245 map->init_slots_sz = 0;
6246
6247 if (map->mmaped) {
6248 munmap(map->mmaped, bpf_map_mmap_sz(map));
6249 map->mmaped = NULL;
6250 }
6251
6252 if (map->st_ops) {
6253 zfree(&map->st_ops->data);
6254 zfree(&map->st_ops->progs);
6255 zfree(&map->st_ops->kern_func_off);
6256 zfree(&map->st_ops);
6257 }
6258
6259 zfree(&map->name);
6260 zfree(&map->pin_path);
6261
6262 if (map->fd >= 0)
6263 zclose(map->fd);
6264}
6265
6266void bpf_object__close(struct bpf_object *obj)
6267{
6268 size_t i;
6269
6270 if (!obj)
6271 return;
6272
6273 if (obj->clear_priv)
6274 obj->clear_priv(obj, obj->priv);
6275
6276 bpf_object__elf_finish(obj);
6277 bpf_object__unload(obj);
6278 btf__free(obj->btf);
6279 btf_ext__free(obj->btf_ext);
6280
6281 for (i = 0; i < obj->nr_maps; i++)
6282 bpf_map__destroy(&obj->maps[i]);
6283
6284 zfree(&obj->kconfig);
6285 zfree(&obj->externs);
6286 obj->nr_extern = 0;
6287
6288 zfree(&obj->maps);
6289 obj->nr_maps = 0;
6290
6291 if (obj->programs && obj->nr_programs) {
6292 for (i = 0; i < obj->nr_programs; i++)
6293 bpf_program__exit(&obj->programs[i]);
6294 }
6295 zfree(&obj->programs);
6296
6297 list_del(&obj->list);
6298 free(obj);
6299}
6300
6301struct bpf_object *
6302bpf_object__next(struct bpf_object *prev)
6303{
6304 struct bpf_object *next;
6305
6306 if (!prev)
6307 next = list_first_entry(&bpf_objects_list,
6308 struct bpf_object,
6309 list);
6310 else
6311 next = list_next_entry(prev, list);
6312
6313 /* Empty list is noticed here so don't need checking on entry. */
6314 if (&next->list == &bpf_objects_list)
6315 return NULL;
6316
6317 return next;
6318}
6319
6320const char *bpf_object__name(const struct bpf_object *obj)
6321{
6322 return obj ? obj->name : ERR_PTR(-EINVAL);
6323}
6324
6325unsigned int bpf_object__kversion(const struct bpf_object *obj)
6326{
6327 return obj ? obj->kern_version : 0;
6328}
6329
6330struct btf *bpf_object__btf(const struct bpf_object *obj)
6331{
6332 return obj ? obj->btf : NULL;
6333}
6334
6335int bpf_object__btf_fd(const struct bpf_object *obj)
6336{
6337 return obj->btf ? btf__fd(obj->btf) : -1;
6338}
6339
6340int bpf_object__set_priv(struct bpf_object *obj, void *priv,
6341 bpf_object_clear_priv_t clear_priv)
6342{
6343 if (obj->priv && obj->clear_priv)
6344 obj->clear_priv(obj, obj->priv);
6345
6346 obj->priv = priv;
6347 obj->clear_priv = clear_priv;
6348 return 0;
6349}
6350
6351void *bpf_object__priv(const struct bpf_object *obj)
6352{
6353 return obj ? obj->priv : ERR_PTR(-EINVAL);
6354}
6355
6356static struct bpf_program *
6357__bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
6358 bool forward)
6359{
6360 size_t nr_programs = obj->nr_programs;
6361 ssize_t idx;
6362
6363 if (!nr_programs)
6364 return NULL;
6365
6366 if (!p)
6367 /* Iter from the beginning */
6368 return forward ? &obj->programs[0] :
6369 &obj->programs[nr_programs - 1];
6370
6371 if (p->obj != obj) {
6372 pr_warn("error: program handler doesn't match object\n");
6373 return NULL;
6374 }
6375
6376 idx = (p - obj->programs) + (forward ? 1 : -1);
6377 if (idx >= obj->nr_programs || idx < 0)
6378 return NULL;
6379 return &obj->programs[idx];
6380}
6381
6382struct bpf_program *
6383bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
6384{
6385 struct bpf_program *prog = prev;
6386
6387 do {
6388 prog = __bpf_program__iter(prog, obj, true);
6389 } while (prog && bpf_program__is_function_storage(prog, obj));
6390
6391 return prog;
6392}
6393
6394struct bpf_program *
6395bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
6396{
6397 struct bpf_program *prog = next;
6398
6399 do {
6400 prog = __bpf_program__iter(prog, obj, false);
6401 } while (prog && bpf_program__is_function_storage(prog, obj));
6402
6403 return prog;
6404}
6405
6406int bpf_program__set_priv(struct bpf_program *prog, void *priv,
6407 bpf_program_clear_priv_t clear_priv)
6408{
6409 if (prog->priv && prog->clear_priv)
6410 prog->clear_priv(prog, prog->priv);
6411
6412 prog->priv = priv;
6413 prog->clear_priv = clear_priv;
6414 return 0;
6415}
6416
6417void *bpf_program__priv(const struct bpf_program *prog)
6418{
6419 return prog ? prog->priv : ERR_PTR(-EINVAL);
6420}
6421
6422void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
6423{
6424 prog->prog_ifindex = ifindex;
6425}
6426
6427const char *bpf_program__name(const struct bpf_program *prog)
6428{
6429 return prog->name;
6430}
6431
6432const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
6433{
6434 const char *title;
6435
6436 title = prog->section_name;
6437 if (needs_copy) {
6438 title = strdup(title);
6439 if (!title) {
6440 pr_warn("failed to strdup program title\n");
6441 return ERR_PTR(-ENOMEM);
6442 }
6443 }
6444
6445 return title;
6446}
6447
6448int bpf_program__fd(const struct bpf_program *prog)
6449{
6450 return bpf_program__nth_fd(prog, 0);
6451}
6452
6453size_t bpf_program__size(const struct bpf_program *prog)
6454{
6455 return prog->insns_cnt * sizeof(struct bpf_insn);
6456}
6457
6458int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
6459 bpf_program_prep_t prep)
6460{
6461 int *instances_fds;
6462
6463 if (nr_instances <= 0 || !prep)
6464 return -EINVAL;
6465
6466 if (prog->instances.nr > 0 || prog->instances.fds) {
6467 pr_warn("Can't set pre-processor after loading\n");
6468 return -EINVAL;
6469 }
6470
6471 instances_fds = malloc(sizeof(int) * nr_instances);
6472 if (!instances_fds) {
6473 pr_warn("alloc memory failed for fds\n");
6474 return -ENOMEM;
6475 }
6476
6477 /* fill all fd with -1 */
6478 memset(instances_fds, -1, sizeof(int) * nr_instances);
6479
6480 prog->instances.nr = nr_instances;
6481 prog->instances.fds = instances_fds;
6482 prog->preprocessor = prep;
6483 return 0;
6484}
6485
6486int bpf_program__nth_fd(const struct bpf_program *prog, int n)
6487{
6488 int fd;
6489
6490 if (!prog)
6491 return -EINVAL;
6492
6493 if (n >= prog->instances.nr || n < 0) {
6494 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
6495 n, prog->section_name, prog->instances.nr);
6496 return -EINVAL;
6497 }
6498
6499 fd = prog->instances.fds[n];
6500 if (fd < 0) {
6501 pr_warn("%dth instance of program '%s' is invalid\n",
6502 n, prog->section_name);
6503 return -ENOENT;
6504 }
6505
6506 return fd;
6507}
6508
6509enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
6510{
6511 return prog->type;
6512}
6513
6514void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
6515{
6516 prog->type = type;
6517}
6518
6519static bool bpf_program__is_type(const struct bpf_program *prog,
6520 enum bpf_prog_type type)
6521{
6522 return prog ? (prog->type == type) : false;
6523}
6524
6525#define BPF_PROG_TYPE_FNS(NAME, TYPE) \
6526int bpf_program__set_##NAME(struct bpf_program *prog) \
6527{ \
6528 if (!prog) \
6529 return -EINVAL; \
6530 bpf_program__set_type(prog, TYPE); \
6531 return 0; \
6532} \
6533 \
6534bool bpf_program__is_##NAME(const struct bpf_program *prog) \
6535{ \
6536 return bpf_program__is_type(prog, TYPE); \
6537} \
6538
6539BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
6540BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
6541BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
6542BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
6543BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
6544BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
6545BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
6546BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
6547BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
6548BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
6549BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
6550BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
6551
6552enum bpf_attach_type
6553bpf_program__get_expected_attach_type(struct bpf_program *prog)
6554{
6555 return prog->expected_attach_type;
6556}
6557
6558void bpf_program__set_expected_attach_type(struct bpf_program *prog,
6559 enum bpf_attach_type type)
6560{
6561 prog->expected_attach_type = type;
6562}
6563
6564#define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional, \
6565 attachable, attach_btf) \
6566 { \
6567 .sec = string, \
6568 .len = sizeof(string) - 1, \
6569 .prog_type = ptype, \
6570 .expected_attach_type = eatype, \
6571 .is_exp_attach_type_optional = eatype_optional, \
6572 .is_attachable = attachable, \
6573 .is_attach_btf = attach_btf, \
6574 }
6575
6576/* Programs that can NOT be attached. */
6577#define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
6578
6579/* Programs that can be attached. */
6580#define BPF_APROG_SEC(string, ptype, atype) \
6581 BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
6582
6583/* Programs that must specify expected attach type at load time. */
6584#define BPF_EAPROG_SEC(string, ptype, eatype) \
6585 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
6586
6587/* Programs that use BTF to identify attach point */
6588#define BPF_PROG_BTF(string, ptype, eatype) \
6589 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
6590
6591/* Programs that can be attached but attach type can't be identified by section
6592 * name. Kept for backward compatibility.
6593 */
6594#define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
6595
6596#define SEC_DEF(sec_pfx, ptype, ...) { \
6597 .sec = sec_pfx, \
6598 .len = sizeof(sec_pfx) - 1, \
6599 .prog_type = BPF_PROG_TYPE_##ptype, \
6600 __VA_ARGS__ \
6601}
6602
6603static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6604 struct bpf_program *prog);
6605static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6606 struct bpf_program *prog);
6607static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6608 struct bpf_program *prog);
6609static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6610 struct bpf_program *prog);
6611static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
6612 struct bpf_program *prog);
6613static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
6614 struct bpf_program *prog);
6615
6616static const struct bpf_sec_def section_defs[] = {
6617 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
6618 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
6619 SEC_DEF("kprobe/", KPROBE,
6620 .attach_fn = attach_kprobe),
6621 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
6622 SEC_DEF("kretprobe/", KPROBE,
6623 .attach_fn = attach_kprobe),
6624 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
6625 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
6626 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
6627 SEC_DEF("tracepoint/", TRACEPOINT,
6628 .attach_fn = attach_tp),
6629 SEC_DEF("tp/", TRACEPOINT,
6630 .attach_fn = attach_tp),
6631 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
6632 .attach_fn = attach_raw_tp),
6633 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
6634 .attach_fn = attach_raw_tp),
6635 SEC_DEF("tp_btf/", TRACING,
6636 .expected_attach_type = BPF_TRACE_RAW_TP,
6637 .is_attach_btf = true,
6638 .attach_fn = attach_trace),
6639 SEC_DEF("fentry/", TRACING,
6640 .expected_attach_type = BPF_TRACE_FENTRY,
6641 .is_attach_btf = true,
6642 .attach_fn = attach_trace),
6643 SEC_DEF("fmod_ret/", TRACING,
6644 .expected_attach_type = BPF_MODIFY_RETURN,
6645 .is_attach_btf = true,
6646 .attach_fn = attach_trace),
6647 SEC_DEF("fexit/", TRACING,
6648 .expected_attach_type = BPF_TRACE_FEXIT,
6649 .is_attach_btf = true,
6650 .attach_fn = attach_trace),
6651 SEC_DEF("freplace/", EXT,
6652 .is_attach_btf = true,
6653 .attach_fn = attach_trace),
6654 SEC_DEF("lsm/", LSM,
6655 .is_attach_btf = true,
6656 .expected_attach_type = BPF_LSM_MAC,
6657 .attach_fn = attach_lsm),
6658 SEC_DEF("iter/", TRACING,
6659 .expected_attach_type = BPF_TRACE_ITER,
6660 .is_attach_btf = true,
6661 .attach_fn = attach_iter),
6662 BPF_EAPROG_SEC("xdp_devmap/", BPF_PROG_TYPE_XDP,
6663 BPF_XDP_DEVMAP),
6664 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
6665 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
6666 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
6667 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
6668 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
6669 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
6670 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
6671 BPF_CGROUP_INET_INGRESS),
6672 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
6673 BPF_CGROUP_INET_EGRESS),
6674 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
6675 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
6676 BPF_CGROUP_INET_SOCK_CREATE),
6677 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
6678 BPF_CGROUP_INET4_POST_BIND),
6679 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
6680 BPF_CGROUP_INET6_POST_BIND),
6681 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
6682 BPF_CGROUP_DEVICE),
6683 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
6684 BPF_CGROUP_SOCK_OPS),
6685 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
6686 BPF_SK_SKB_STREAM_PARSER),
6687 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
6688 BPF_SK_SKB_STREAM_VERDICT),
6689 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
6690 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
6691 BPF_SK_MSG_VERDICT),
6692 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
6693 BPF_LIRC_MODE2),
6694 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
6695 BPF_FLOW_DISSECTOR),
6696 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6697 BPF_CGROUP_INET4_BIND),
6698 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6699 BPF_CGROUP_INET6_BIND),
6700 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6701 BPF_CGROUP_INET4_CONNECT),
6702 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6703 BPF_CGROUP_INET6_CONNECT),
6704 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6705 BPF_CGROUP_UDP4_SENDMSG),
6706 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6707 BPF_CGROUP_UDP6_SENDMSG),
6708 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6709 BPF_CGROUP_UDP4_RECVMSG),
6710 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6711 BPF_CGROUP_UDP6_RECVMSG),
6712 BPF_EAPROG_SEC("cgroup/getpeername4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6713 BPF_CGROUP_INET4_GETPEERNAME),
6714 BPF_EAPROG_SEC("cgroup/getpeername6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6715 BPF_CGROUP_INET6_GETPEERNAME),
6716 BPF_EAPROG_SEC("cgroup/getsockname4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6717 BPF_CGROUP_INET4_GETSOCKNAME),
6718 BPF_EAPROG_SEC("cgroup/getsockname6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
6719 BPF_CGROUP_INET6_GETSOCKNAME),
6720 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
6721 BPF_CGROUP_SYSCTL),
6722 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6723 BPF_CGROUP_GETSOCKOPT),
6724 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
6725 BPF_CGROUP_SETSOCKOPT),
6726 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS),
6727};
6728
6729#undef BPF_PROG_SEC_IMPL
6730#undef BPF_PROG_SEC
6731#undef BPF_APROG_SEC
6732#undef BPF_EAPROG_SEC
6733#undef BPF_APROG_COMPAT
6734#undef SEC_DEF
6735
6736#define MAX_TYPE_NAME_SIZE 32
6737
6738static const struct bpf_sec_def *find_sec_def(const char *sec_name)
6739{
6740 int i, n = ARRAY_SIZE(section_defs);
6741
6742 for (i = 0; i < n; i++) {
6743 if (strncmp(sec_name,
6744 section_defs[i].sec, section_defs[i].len))
6745 continue;
6746 return §ion_defs[i];
6747 }
6748 return NULL;
6749}
6750
6751static char *libbpf_get_type_names(bool attach_type)
6752{
6753 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
6754 char *buf;
6755
6756 buf = malloc(len);
6757 if (!buf)
6758 return NULL;
6759
6760 buf[0] = '\0';
6761 /* Forge string buf with all available names */
6762 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
6763 if (attach_type && !section_defs[i].is_attachable)
6764 continue;
6765
6766 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
6767 free(buf);
6768 return NULL;
6769 }
6770 strcat(buf, " ");
6771 strcat(buf, section_defs[i].sec);
6772 }
6773
6774 return buf;
6775}
6776
6777int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
6778 enum bpf_attach_type *expected_attach_type)
6779{
6780 const struct bpf_sec_def *sec_def;
6781 char *type_names;
6782
6783 if (!name)
6784 return -EINVAL;
6785
6786 sec_def = find_sec_def(name);
6787 if (sec_def) {
6788 *prog_type = sec_def->prog_type;
6789 *expected_attach_type = sec_def->expected_attach_type;
6790 return 0;
6791 }
6792
6793 pr_debug("failed to guess program type from ELF section '%s'\n", name);
6794 type_names = libbpf_get_type_names(false);
6795 if (type_names != NULL) {
6796 pr_debug("supported section(type) names are:%s\n", type_names);
6797 free(type_names);
6798 }
6799
6800 return -ESRCH;
6801}
6802
6803static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
6804 size_t offset)
6805{
6806 struct bpf_map *map;
6807 size_t i;
6808
6809 for (i = 0; i < obj->nr_maps; i++) {
6810 map = &obj->maps[i];
6811 if (!bpf_map__is_struct_ops(map))
6812 continue;
6813 if (map->sec_offset <= offset &&
6814 offset - map->sec_offset < map->def.value_size)
6815 return map;
6816 }
6817
6818 return NULL;
6819}
6820
6821/* Collect the reloc from ELF and populate the st_ops->progs[] */
6822static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6823 GElf_Shdr *shdr, Elf_Data *data)
6824{
6825 const struct btf_member *member;
6826 struct bpf_struct_ops *st_ops;
6827 struct bpf_program *prog;
6828 unsigned int shdr_idx;
6829 const struct btf *btf;
6830 struct bpf_map *map;
6831 Elf_Data *symbols;
6832 unsigned int moff;
6833 const char *name;
6834 __u32 member_idx;
6835 GElf_Sym sym;
6836 GElf_Rel rel;
6837 int i, nrels;
6838
6839 symbols = obj->efile.symbols;
6840 btf = obj->btf;
6841 nrels = shdr->sh_size / shdr->sh_entsize;
6842 for (i = 0; i < nrels; i++) {
6843 if (!gelf_getrel(data, i, &rel)) {
6844 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
6845 return -LIBBPF_ERRNO__FORMAT;
6846 }
6847
6848 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
6849 pr_warn("struct_ops reloc: symbol %zx not found\n",
6850 (size_t)GELF_R_SYM(rel.r_info));
6851 return -LIBBPF_ERRNO__FORMAT;
6852 }
6853
6854 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
6855 sym.st_name) ? : "<?>";
6856 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
6857 if (!map) {
6858 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
6859 (size_t)rel.r_offset);
6860 return -EINVAL;
6861 }
6862
6863 moff = rel.r_offset - map->sec_offset;
6864 shdr_idx = sym.st_shndx;
6865 st_ops = map->st_ops;
6866 pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel.r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
6867 map->name,
6868 (long long)(rel.r_info >> 32),
6869 (long long)sym.st_value,
6870 shdr_idx, (size_t)rel.r_offset,
6871 map->sec_offset, sym.st_name, name);
6872
6873 if (shdr_idx >= SHN_LORESERVE) {
6874 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
6875 map->name, (size_t)rel.r_offset, shdr_idx);
6876 return -LIBBPF_ERRNO__RELOC;
6877 }
6878
6879 member = find_member_by_offset(st_ops->type, moff * 8);
6880 if (!member) {
6881 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
6882 map->name, moff);
6883 return -EINVAL;
6884 }
6885 member_idx = member - btf_members(st_ops->type);
6886 name = btf__name_by_offset(btf, member->name_off);
6887
6888 if (!resolve_func_ptr(btf, member->type, NULL)) {
6889 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
6890 map->name, name);
6891 return -EINVAL;
6892 }
6893
6894 prog = bpf_object__find_prog_by_idx(obj, shdr_idx);
6895 if (!prog) {
6896 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
6897 map->name, shdr_idx, name);
6898 return -EINVAL;
6899 }
6900
6901 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6902 const struct bpf_sec_def *sec_def;
6903
6904 sec_def = find_sec_def(prog->section_name);
6905 if (sec_def &&
6906 sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
6907 /* for pr_warn */
6908 prog->type = sec_def->prog_type;
6909 goto invalid_prog;
6910 }
6911
6912 prog->type = BPF_PROG_TYPE_STRUCT_OPS;
6913 prog->attach_btf_id = st_ops->type_id;
6914 prog->expected_attach_type = member_idx;
6915 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
6916 prog->attach_btf_id != st_ops->type_id ||
6917 prog->expected_attach_type != member_idx) {
6918 goto invalid_prog;
6919 }
6920 st_ops->progs[member_idx] = prog;
6921 }
6922
6923 return 0;
6924
6925invalid_prog:
6926 pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
6927 map->name, prog->name, prog->section_name, prog->type,
6928 prog->attach_btf_id, prog->expected_attach_type, name);
6929 return -EINVAL;
6930}
6931
6932#define BTF_TRACE_PREFIX "btf_trace_"
6933#define BTF_LSM_PREFIX "bpf_lsm_"
6934#define BTF_ITER_PREFIX "bpf_iter_"
6935#define BTF_MAX_NAME_SIZE 128
6936
6937static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
6938 const char *name, __u32 kind)
6939{
6940 char btf_type_name[BTF_MAX_NAME_SIZE];
6941 int ret;
6942
6943 ret = snprintf(btf_type_name, sizeof(btf_type_name),
6944 "%s%s", prefix, name);
6945 /* snprintf returns the number of characters written excluding the
6946 * the terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
6947 * indicates truncation.
6948 */
6949 if (ret < 0 || ret >= sizeof(btf_type_name))
6950 return -ENAMETOOLONG;
6951 return btf__find_by_name_kind(btf, btf_type_name, kind);
6952}
6953
6954static inline int __find_vmlinux_btf_id(struct btf *btf, const char *name,
6955 enum bpf_attach_type attach_type)
6956{
6957 int err;
6958
6959 if (attach_type == BPF_TRACE_RAW_TP)
6960 err = find_btf_by_prefix_kind(btf, BTF_TRACE_PREFIX, name,
6961 BTF_KIND_TYPEDEF);
6962 else if (attach_type == BPF_LSM_MAC)
6963 err = find_btf_by_prefix_kind(btf, BTF_LSM_PREFIX, name,
6964 BTF_KIND_FUNC);
6965 else if (attach_type == BPF_TRACE_ITER)
6966 err = find_btf_by_prefix_kind(btf, BTF_ITER_PREFIX, name,
6967 BTF_KIND_FUNC);
6968 else
6969 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
6970
6971 if (err <= 0)
6972 pr_warn("%s is not found in vmlinux BTF\n", name);
6973
6974 return err;
6975}
6976
6977int libbpf_find_vmlinux_btf_id(const char *name,
6978 enum bpf_attach_type attach_type)
6979{
6980 struct btf *btf;
6981 int err;
6982
6983 btf = libbpf_find_kernel_btf();
6984 if (IS_ERR(btf)) {
6985 pr_warn("vmlinux BTF is not found\n");
6986 return -EINVAL;
6987 }
6988
6989 err = __find_vmlinux_btf_id(btf, name, attach_type);
6990 btf__free(btf);
6991 return err;
6992}
6993
6994static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
6995{
6996 struct bpf_prog_info_linear *info_linear;
6997 struct bpf_prog_info *info;
6998 struct btf *btf = NULL;
6999 int err = -EINVAL;
7000
7001 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
7002 if (IS_ERR_OR_NULL(info_linear)) {
7003 pr_warn("failed get_prog_info_linear for FD %d\n",
7004 attach_prog_fd);
7005 return -EINVAL;
7006 }
7007 info = &info_linear->info;
7008 if (!info->btf_id) {
7009 pr_warn("The target program doesn't have BTF\n");
7010 goto out;
7011 }
7012 if (btf__get_from_id(info->btf_id, &btf)) {
7013 pr_warn("Failed to get BTF of the program\n");
7014 goto out;
7015 }
7016 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
7017 btf__free(btf);
7018 if (err <= 0) {
7019 pr_warn("%s is not found in prog's BTF\n", name);
7020 goto out;
7021 }
7022out:
7023 free(info_linear);
7024 return err;
7025}
7026
7027static int libbpf_find_attach_btf_id(struct bpf_program *prog)
7028{
7029 enum bpf_attach_type attach_type = prog->expected_attach_type;
7030 __u32 attach_prog_fd = prog->attach_prog_fd;
7031 const char *name = prog->section_name;
7032 int i, err;
7033
7034 if (!name)
7035 return -EINVAL;
7036
7037 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7038 if (!section_defs[i].is_attach_btf)
7039 continue;
7040 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
7041 continue;
7042 if (attach_prog_fd)
7043 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
7044 attach_prog_fd);
7045 else
7046 err = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
7047 name + section_defs[i].len,
7048 attach_type);
7049 return err;
7050 }
7051 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
7052 return -ESRCH;
7053}
7054
7055int libbpf_attach_type_by_name(const char *name,
7056 enum bpf_attach_type *attach_type)
7057{
7058 char *type_names;
7059 int i;
7060
7061 if (!name)
7062 return -EINVAL;
7063
7064 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
7065 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
7066 continue;
7067 if (!section_defs[i].is_attachable)
7068 return -EINVAL;
7069 *attach_type = section_defs[i].expected_attach_type;
7070 return 0;
7071 }
7072 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
7073 type_names = libbpf_get_type_names(true);
7074 if (type_names != NULL) {
7075 pr_debug("attachable section(type) names are:%s\n", type_names);
7076 free(type_names);
7077 }
7078
7079 return -EINVAL;
7080}
7081
7082int bpf_map__fd(const struct bpf_map *map)
7083{
7084 return map ? map->fd : -EINVAL;
7085}
7086
7087const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
7088{
7089 return map ? &map->def : ERR_PTR(-EINVAL);
7090}
7091
7092const char *bpf_map__name(const struct bpf_map *map)
7093{
7094 return map ? map->name : NULL;
7095}
7096
7097__u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
7098{
7099 return map ? map->btf_key_type_id : 0;
7100}
7101
7102__u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
7103{
7104 return map ? map->btf_value_type_id : 0;
7105}
7106
7107int bpf_map__set_priv(struct bpf_map *map, void *priv,
7108 bpf_map_clear_priv_t clear_priv)
7109{
7110 if (!map)
7111 return -EINVAL;
7112
7113 if (map->priv) {
7114 if (map->clear_priv)
7115 map->clear_priv(map, map->priv);
7116 }
7117
7118 map->priv = priv;
7119 map->clear_priv = clear_priv;
7120 return 0;
7121}
7122
7123void *bpf_map__priv(const struct bpf_map *map)
7124{
7125 return map ? map->priv : ERR_PTR(-EINVAL);
7126}
7127
7128int bpf_map__set_initial_value(struct bpf_map *map,
7129 const void *data, size_t size)
7130{
7131 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
7132 size != map->def.value_size || map->fd >= 0)
7133 return -EINVAL;
7134
7135 memcpy(map->mmaped, data, size);
7136 return 0;
7137}
7138
7139bool bpf_map__is_offload_neutral(const struct bpf_map *map)
7140{
7141 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
7142}
7143
7144bool bpf_map__is_internal(const struct bpf_map *map)
7145{
7146 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
7147}
7148
7149void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
7150{
7151 map->map_ifindex = ifindex;
7152}
7153
7154int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
7155{
7156 if (!bpf_map_type__is_map_in_map(map->def.type)) {
7157 pr_warn("error: unsupported map type\n");
7158 return -EINVAL;
7159 }
7160 if (map->inner_map_fd != -1) {
7161 pr_warn("error: inner_map_fd already specified\n");
7162 return -EINVAL;
7163 }
7164 map->inner_map_fd = fd;
7165 return 0;
7166}
7167
7168static struct bpf_map *
7169__bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
7170{
7171 ssize_t idx;
7172 struct bpf_map *s, *e;
7173
7174 if (!obj || !obj->maps)
7175 return NULL;
7176
7177 s = obj->maps;
7178 e = obj->maps + obj->nr_maps;
7179
7180 if ((m < s) || (m >= e)) {
7181 pr_warn("error in %s: map handler doesn't belong to object\n",
7182 __func__);
7183 return NULL;
7184 }
7185
7186 idx = (m - obj->maps) + i;
7187 if (idx >= obj->nr_maps || idx < 0)
7188 return NULL;
7189 return &obj->maps[idx];
7190}
7191
7192struct bpf_map *
7193bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
7194{
7195 if (prev == NULL)
7196 return obj->maps;
7197
7198 return __bpf_map__iter(prev, obj, 1);
7199}
7200
7201struct bpf_map *
7202bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
7203{
7204 if (next == NULL) {
7205 if (!obj->nr_maps)
7206 return NULL;
7207 return obj->maps + obj->nr_maps - 1;
7208 }
7209
7210 return __bpf_map__iter(next, obj, -1);
7211}
7212
7213struct bpf_map *
7214bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
7215{
7216 struct bpf_map *pos;
7217
7218 bpf_object__for_each_map(pos, obj) {
7219 if (pos->name && !strcmp(pos->name, name))
7220 return pos;
7221 }
7222 return NULL;
7223}
7224
7225int
7226bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
7227{
7228 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
7229}
7230
7231struct bpf_map *
7232bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
7233{
7234 return ERR_PTR(-ENOTSUP);
7235}
7236
7237long libbpf_get_error(const void *ptr)
7238{
7239 return PTR_ERR_OR_ZERO(ptr);
7240}
7241
7242int bpf_prog_load(const char *file, enum bpf_prog_type type,
7243 struct bpf_object **pobj, int *prog_fd)
7244{
7245 struct bpf_prog_load_attr attr;
7246
7247 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
7248 attr.file = file;
7249 attr.prog_type = type;
7250 attr.expected_attach_type = 0;
7251
7252 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
7253}
7254
7255int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
7256 struct bpf_object **pobj, int *prog_fd)
7257{
7258 struct bpf_object_open_attr open_attr = {};
7259 struct bpf_program *prog, *first_prog = NULL;
7260 struct bpf_object *obj;
7261 struct bpf_map *map;
7262 int err;
7263
7264 if (!attr)
7265 return -EINVAL;
7266 if (!attr->file)
7267 return -EINVAL;
7268
7269 open_attr.file = attr->file;
7270 open_attr.prog_type = attr->prog_type;
7271
7272 obj = bpf_object__open_xattr(&open_attr);
7273 if (IS_ERR_OR_NULL(obj))
7274 return -ENOENT;
7275
7276 bpf_object__for_each_program(prog, obj) {
7277 enum bpf_attach_type attach_type = attr->expected_attach_type;
7278 /*
7279 * to preserve backwards compatibility, bpf_prog_load treats
7280 * attr->prog_type, if specified, as an override to whatever
7281 * bpf_object__open guessed
7282 */
7283 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
7284 bpf_program__set_type(prog, attr->prog_type);
7285 bpf_program__set_expected_attach_type(prog,
7286 attach_type);
7287 }
7288 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
7289 /*
7290 * we haven't guessed from section name and user
7291 * didn't provide a fallback type, too bad...
7292 */
7293 bpf_object__close(obj);
7294 return -EINVAL;
7295 }
7296
7297 prog->prog_ifindex = attr->ifindex;
7298 prog->log_level = attr->log_level;
7299 prog->prog_flags = attr->prog_flags;
7300 if (!first_prog)
7301 first_prog = prog;
7302 }
7303
7304 bpf_object__for_each_map(map, obj) {
7305 if (!bpf_map__is_offload_neutral(map))
7306 map->map_ifindex = attr->ifindex;
7307 }
7308
7309 if (!first_prog) {
7310 pr_warn("object file doesn't contain bpf program\n");
7311 bpf_object__close(obj);
7312 return -ENOENT;
7313 }
7314
7315 err = bpf_object__load(obj);
7316 if (err) {
7317 bpf_object__close(obj);
7318 return err;
7319 }
7320
7321 *pobj = obj;
7322 *prog_fd = bpf_program__fd(first_prog);
7323 return 0;
7324}
7325
7326struct bpf_link {
7327 int (*detach)(struct bpf_link *link);
7328 int (*destroy)(struct bpf_link *link);
7329 char *pin_path; /* NULL, if not pinned */
7330 int fd; /* hook FD, -1 if not applicable */
7331 bool disconnected;
7332};
7333
7334/* Replace link's underlying BPF program with the new one */
7335int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
7336{
7337 return bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
7338}
7339
7340/* Release "ownership" of underlying BPF resource (typically, BPF program
7341 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
7342 * link, when destructed through bpf_link__destroy() call won't attempt to
7343 * detach/unregisted that BPF resource. This is useful in situations where,
7344 * say, attached BPF program has to outlive userspace program that attached it
7345 * in the system. Depending on type of BPF program, though, there might be
7346 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
7347 * exit of userspace program doesn't trigger automatic detachment and clean up
7348 * inside the kernel.
7349 */
7350void bpf_link__disconnect(struct bpf_link *link)
7351{
7352 link->disconnected = true;
7353}
7354
7355int bpf_link__destroy(struct bpf_link *link)
7356{
7357 int err = 0;
7358
7359 if (!link)
7360 return 0;
7361
7362 if (!link->disconnected && link->detach)
7363 err = link->detach(link);
7364 if (link->destroy)
7365 link->destroy(link);
7366 if (link->pin_path)
7367 free(link->pin_path);
7368 free(link);
7369
7370 return err;
7371}
7372
7373int bpf_link__fd(const struct bpf_link *link)
7374{
7375 return link->fd;
7376}
7377
7378const char *bpf_link__pin_path(const struct bpf_link *link)
7379{
7380 return link->pin_path;
7381}
7382
7383static int bpf_link__detach_fd(struct bpf_link *link)
7384{
7385 return close(link->fd);
7386}
7387
7388struct bpf_link *bpf_link__open(const char *path)
7389{
7390 struct bpf_link *link;
7391 int fd;
7392
7393 fd = bpf_obj_get(path);
7394 if (fd < 0) {
7395 fd = -errno;
7396 pr_warn("failed to open link at %s: %d\n", path, fd);
7397 return ERR_PTR(fd);
7398 }
7399
7400 link = calloc(1, sizeof(*link));
7401 if (!link) {
7402 close(fd);
7403 return ERR_PTR(-ENOMEM);
7404 }
7405 link->detach = &bpf_link__detach_fd;
7406 link->fd = fd;
7407
7408 link->pin_path = strdup(path);
7409 if (!link->pin_path) {
7410 bpf_link__destroy(link);
7411 return ERR_PTR(-ENOMEM);
7412 }
7413
7414 return link;
7415}
7416
7417int bpf_link__pin(struct bpf_link *link, const char *path)
7418{
7419 int err;
7420
7421 if (link->pin_path)
7422 return -EBUSY;
7423 err = make_parent_dir(path);
7424 if (err)
7425 return err;
7426 err = check_path(path);
7427 if (err)
7428 return err;
7429
7430 link->pin_path = strdup(path);
7431 if (!link->pin_path)
7432 return -ENOMEM;
7433
7434 if (bpf_obj_pin(link->fd, link->pin_path)) {
7435 err = -errno;
7436 zfree(&link->pin_path);
7437 return err;
7438 }
7439
7440 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
7441 return 0;
7442}
7443
7444int bpf_link__unpin(struct bpf_link *link)
7445{
7446 int err;
7447
7448 if (!link->pin_path)
7449 return -EINVAL;
7450
7451 err = unlink(link->pin_path);
7452 if (err != 0)
7453 return -errno;
7454
7455 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
7456 zfree(&link->pin_path);
7457 return 0;
7458}
7459
7460static int bpf_link__detach_perf_event(struct bpf_link *link)
7461{
7462 int err;
7463
7464 err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
7465 if (err)
7466 err = -errno;
7467
7468 close(link->fd);
7469 return err;
7470}
7471
7472struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
7473 int pfd)
7474{
7475 char errmsg[STRERR_BUFSIZE];
7476 struct bpf_link *link;
7477 int prog_fd, err;
7478
7479 if (pfd < 0) {
7480 pr_warn("program '%s': invalid perf event FD %d\n",
7481 bpf_program__title(prog, false), pfd);
7482 return ERR_PTR(-EINVAL);
7483 }
7484 prog_fd = bpf_program__fd(prog);
7485 if (prog_fd < 0) {
7486 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
7487 bpf_program__title(prog, false));
7488 return ERR_PTR(-EINVAL);
7489 }
7490
7491 link = calloc(1, sizeof(*link));
7492 if (!link)
7493 return ERR_PTR(-ENOMEM);
7494 link->detach = &bpf_link__detach_perf_event;
7495 link->fd = pfd;
7496
7497 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
7498 err = -errno;
7499 free(link);
7500 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
7501 bpf_program__title(prog, false), pfd,
7502 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7503 return ERR_PTR(err);
7504 }
7505 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
7506 err = -errno;
7507 free(link);
7508 pr_warn("program '%s': failed to enable pfd %d: %s\n",
7509 bpf_program__title(prog, false), pfd,
7510 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7511 return ERR_PTR(err);
7512 }
7513 return link;
7514}
7515
7516/*
7517 * this function is expected to parse integer in the range of [0, 2^31-1] from
7518 * given file using scanf format string fmt. If actual parsed value is
7519 * negative, the result might be indistinguishable from error
7520 */
7521static int parse_uint_from_file(const char *file, const char *fmt)
7522{
7523 char buf[STRERR_BUFSIZE];
7524 int err, ret;
7525 FILE *f;
7526
7527 f = fopen(file, "r");
7528 if (!f) {
7529 err = -errno;
7530 pr_debug("failed to open '%s': %s\n", file,
7531 libbpf_strerror_r(err, buf, sizeof(buf)));
7532 return err;
7533 }
7534 err = fscanf(f, fmt, &ret);
7535 if (err != 1) {
7536 err = err == EOF ? -EIO : -errno;
7537 pr_debug("failed to parse '%s': %s\n", file,
7538 libbpf_strerror_r(err, buf, sizeof(buf)));
7539 fclose(f);
7540 return err;
7541 }
7542 fclose(f);
7543 return ret;
7544}
7545
7546static int determine_kprobe_perf_type(void)
7547{
7548 const char *file = "/sys/bus/event_source/devices/kprobe/type";
7549
7550 return parse_uint_from_file(file, "%d\n");
7551}
7552
7553static int determine_uprobe_perf_type(void)
7554{
7555 const char *file = "/sys/bus/event_source/devices/uprobe/type";
7556
7557 return parse_uint_from_file(file, "%d\n");
7558}
7559
7560static int determine_kprobe_retprobe_bit(void)
7561{
7562 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
7563
7564 return parse_uint_from_file(file, "config:%d\n");
7565}
7566
7567static int determine_uprobe_retprobe_bit(void)
7568{
7569 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
7570
7571 return parse_uint_from_file(file, "config:%d\n");
7572}
7573
7574static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
7575 uint64_t offset, int pid)
7576{
7577 struct perf_event_attr attr = {};
7578 char errmsg[STRERR_BUFSIZE];
7579 int type, pfd, err;
7580
7581 type = uprobe ? determine_uprobe_perf_type()
7582 : determine_kprobe_perf_type();
7583 if (type < 0) {
7584 pr_warn("failed to determine %s perf type: %s\n",
7585 uprobe ? "uprobe" : "kprobe",
7586 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
7587 return type;
7588 }
7589 if (retprobe) {
7590 int bit = uprobe ? determine_uprobe_retprobe_bit()
7591 : determine_kprobe_retprobe_bit();
7592
7593 if (bit < 0) {
7594 pr_warn("failed to determine %s retprobe bit: %s\n",
7595 uprobe ? "uprobe" : "kprobe",
7596 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
7597 return bit;
7598 }
7599 attr.config |= 1 << bit;
7600 }
7601 attr.size = sizeof(attr);
7602 attr.type = type;
7603 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
7604 attr.config2 = offset; /* kprobe_addr or probe_offset */
7605
7606 /* pid filter is meaningful only for uprobes */
7607 pfd = syscall(__NR_perf_event_open, &attr,
7608 pid < 0 ? -1 : pid /* pid */,
7609 pid == -1 ? 0 : -1 /* cpu */,
7610 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7611 if (pfd < 0) {
7612 err = -errno;
7613 pr_warn("%s perf_event_open() failed: %s\n",
7614 uprobe ? "uprobe" : "kprobe",
7615 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7616 return err;
7617 }
7618 return pfd;
7619}
7620
7621struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
7622 bool retprobe,
7623 const char *func_name)
7624{
7625 char errmsg[STRERR_BUFSIZE];
7626 struct bpf_link *link;
7627 int pfd, err;
7628
7629 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
7630 0 /* offset */, -1 /* pid */);
7631 if (pfd < 0) {
7632 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
7633 bpf_program__title(prog, false),
7634 retprobe ? "kretprobe" : "kprobe", func_name,
7635 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7636 return ERR_PTR(pfd);
7637 }
7638 link = bpf_program__attach_perf_event(prog, pfd);
7639 if (IS_ERR(link)) {
7640 close(pfd);
7641 err = PTR_ERR(link);
7642 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
7643 bpf_program__title(prog, false),
7644 retprobe ? "kretprobe" : "kprobe", func_name,
7645 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7646 return link;
7647 }
7648 return link;
7649}
7650
7651static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
7652 struct bpf_program *prog)
7653{
7654 const char *func_name;
7655 bool retprobe;
7656
7657 func_name = bpf_program__title(prog, false) + sec->len;
7658 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
7659
7660 return bpf_program__attach_kprobe(prog, retprobe, func_name);
7661}
7662
7663struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
7664 bool retprobe, pid_t pid,
7665 const char *binary_path,
7666 size_t func_offset)
7667{
7668 char errmsg[STRERR_BUFSIZE];
7669 struct bpf_link *link;
7670 int pfd, err;
7671
7672 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
7673 binary_path, func_offset, pid);
7674 if (pfd < 0) {
7675 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
7676 bpf_program__title(prog, false),
7677 retprobe ? "uretprobe" : "uprobe",
7678 binary_path, func_offset,
7679 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7680 return ERR_PTR(pfd);
7681 }
7682 link = bpf_program__attach_perf_event(prog, pfd);
7683 if (IS_ERR(link)) {
7684 close(pfd);
7685 err = PTR_ERR(link);
7686 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
7687 bpf_program__title(prog, false),
7688 retprobe ? "uretprobe" : "uprobe",
7689 binary_path, func_offset,
7690 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7691 return link;
7692 }
7693 return link;
7694}
7695
7696static int determine_tracepoint_id(const char *tp_category,
7697 const char *tp_name)
7698{
7699 char file[PATH_MAX];
7700 int ret;
7701
7702 ret = snprintf(file, sizeof(file),
7703 "/sys/kernel/debug/tracing/events/%s/%s/id",
7704 tp_category, tp_name);
7705 if (ret < 0)
7706 return -errno;
7707 if (ret >= sizeof(file)) {
7708 pr_debug("tracepoint %s/%s path is too long\n",
7709 tp_category, tp_name);
7710 return -E2BIG;
7711 }
7712 return parse_uint_from_file(file, "%d\n");
7713}
7714
7715static int perf_event_open_tracepoint(const char *tp_category,
7716 const char *tp_name)
7717{
7718 struct perf_event_attr attr = {};
7719 char errmsg[STRERR_BUFSIZE];
7720 int tp_id, pfd, err;
7721
7722 tp_id = determine_tracepoint_id(tp_category, tp_name);
7723 if (tp_id < 0) {
7724 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
7725 tp_category, tp_name,
7726 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
7727 return tp_id;
7728 }
7729
7730 attr.type = PERF_TYPE_TRACEPOINT;
7731 attr.size = sizeof(attr);
7732 attr.config = tp_id;
7733
7734 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
7735 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
7736 if (pfd < 0) {
7737 err = -errno;
7738 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
7739 tp_category, tp_name,
7740 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7741 return err;
7742 }
7743 return pfd;
7744}
7745
7746struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
7747 const char *tp_category,
7748 const char *tp_name)
7749{
7750 char errmsg[STRERR_BUFSIZE];
7751 struct bpf_link *link;
7752 int pfd, err;
7753
7754 pfd = perf_event_open_tracepoint(tp_category, tp_name);
7755 if (pfd < 0) {
7756 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
7757 bpf_program__title(prog, false),
7758 tp_category, tp_name,
7759 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7760 return ERR_PTR(pfd);
7761 }
7762 link = bpf_program__attach_perf_event(prog, pfd);
7763 if (IS_ERR(link)) {
7764 close(pfd);
7765 err = PTR_ERR(link);
7766 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
7767 bpf_program__title(prog, false),
7768 tp_category, tp_name,
7769 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
7770 return link;
7771 }
7772 return link;
7773}
7774
7775static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
7776 struct bpf_program *prog)
7777{
7778 char *sec_name, *tp_cat, *tp_name;
7779 struct bpf_link *link;
7780
7781 sec_name = strdup(bpf_program__title(prog, false));
7782 if (!sec_name)
7783 return ERR_PTR(-ENOMEM);
7784
7785 /* extract "tp/<category>/<name>" */
7786 tp_cat = sec_name + sec->len;
7787 tp_name = strchr(tp_cat, '/');
7788 if (!tp_name) {
7789 link = ERR_PTR(-EINVAL);
7790 goto out;
7791 }
7792 *tp_name = '\0';
7793 tp_name++;
7794
7795 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
7796out:
7797 free(sec_name);
7798 return link;
7799}
7800
7801struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
7802 const char *tp_name)
7803{
7804 char errmsg[STRERR_BUFSIZE];
7805 struct bpf_link *link;
7806 int prog_fd, pfd;
7807
7808 prog_fd = bpf_program__fd(prog);
7809 if (prog_fd < 0) {
7810 pr_warn("program '%s': can't attach before loaded\n",
7811 bpf_program__title(prog, false));
7812 return ERR_PTR(-EINVAL);
7813 }
7814
7815 link = calloc(1, sizeof(*link));
7816 if (!link)
7817 return ERR_PTR(-ENOMEM);
7818 link->detach = &bpf_link__detach_fd;
7819
7820 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
7821 if (pfd < 0) {
7822 pfd = -errno;
7823 free(link);
7824 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
7825 bpf_program__title(prog, false), tp_name,
7826 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7827 return ERR_PTR(pfd);
7828 }
7829 link->fd = pfd;
7830 return link;
7831}
7832
7833static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
7834 struct bpf_program *prog)
7835{
7836 const char *tp_name = bpf_program__title(prog, false) + sec->len;
7837
7838 return bpf_program__attach_raw_tracepoint(prog, tp_name);
7839}
7840
7841/* Common logic for all BPF program types that attach to a btf_id */
7842static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
7843{
7844 char errmsg[STRERR_BUFSIZE];
7845 struct bpf_link *link;
7846 int prog_fd, pfd;
7847
7848 prog_fd = bpf_program__fd(prog);
7849 if (prog_fd < 0) {
7850 pr_warn("program '%s': can't attach before loaded\n",
7851 bpf_program__title(prog, false));
7852 return ERR_PTR(-EINVAL);
7853 }
7854
7855 link = calloc(1, sizeof(*link));
7856 if (!link)
7857 return ERR_PTR(-ENOMEM);
7858 link->detach = &bpf_link__detach_fd;
7859
7860 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
7861 if (pfd < 0) {
7862 pfd = -errno;
7863 free(link);
7864 pr_warn("program '%s': failed to attach: %s\n",
7865 bpf_program__title(prog, false),
7866 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
7867 return ERR_PTR(pfd);
7868 }
7869 link->fd = pfd;
7870 return (struct bpf_link *)link;
7871}
7872
7873struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
7874{
7875 return bpf_program__attach_btf_id(prog);
7876}
7877
7878struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
7879{
7880 return bpf_program__attach_btf_id(prog);
7881}
7882
7883static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
7884 struct bpf_program *prog)
7885{
7886 return bpf_program__attach_trace(prog);
7887}
7888
7889static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
7890 struct bpf_program *prog)
7891{
7892 return bpf_program__attach_lsm(prog);
7893}
7894
7895static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
7896 struct bpf_program *prog)
7897{
7898 return bpf_program__attach_iter(prog, NULL);
7899}
7900
7901static struct bpf_link *
7902bpf_program__attach_fd(struct bpf_program *prog, int target_fd,
7903 const char *target_name)
7904{
7905 enum bpf_attach_type attach_type;
7906 char errmsg[STRERR_BUFSIZE];
7907 struct bpf_link *link;
7908 int prog_fd, link_fd;
7909
7910 prog_fd = bpf_program__fd(prog);
7911 if (prog_fd < 0) {
7912 pr_warn("program '%s': can't attach before loaded\n",
7913 bpf_program__title(prog, false));
7914 return ERR_PTR(-EINVAL);
7915 }
7916
7917 link = calloc(1, sizeof(*link));
7918 if (!link)
7919 return ERR_PTR(-ENOMEM);
7920 link->detach = &bpf_link__detach_fd;
7921
7922 attach_type = bpf_program__get_expected_attach_type(prog);
7923 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, NULL);
7924 if (link_fd < 0) {
7925 link_fd = -errno;
7926 free(link);
7927 pr_warn("program '%s': failed to attach to %s: %s\n",
7928 bpf_program__title(prog, false), target_name,
7929 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
7930 return ERR_PTR(link_fd);
7931 }
7932 link->fd = link_fd;
7933 return link;
7934}
7935
7936struct bpf_link *
7937bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
7938{
7939 return bpf_program__attach_fd(prog, cgroup_fd, "cgroup");
7940}
7941
7942struct bpf_link *
7943bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
7944{
7945 return bpf_program__attach_fd(prog, netns_fd, "netns");
7946}
7947
7948struct bpf_link *
7949bpf_program__attach_iter(struct bpf_program *prog,
7950 const struct bpf_iter_attach_opts *opts)
7951{
7952 char errmsg[STRERR_BUFSIZE];
7953 struct bpf_link *link;
7954 int prog_fd, link_fd;
7955
7956 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
7957 return ERR_PTR(-EINVAL);
7958
7959 prog_fd = bpf_program__fd(prog);
7960 if (prog_fd < 0) {
7961 pr_warn("program '%s': can't attach before loaded\n",
7962 bpf_program__title(prog, false));
7963 return ERR_PTR(-EINVAL);
7964 }
7965
7966 link = calloc(1, sizeof(*link));
7967 if (!link)
7968 return ERR_PTR(-ENOMEM);
7969 link->detach = &bpf_link__detach_fd;
7970
7971 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_ITER, NULL);
7972 if (link_fd < 0) {
7973 link_fd = -errno;
7974 free(link);
7975 pr_warn("program '%s': failed to attach to iterator: %s\n",
7976 bpf_program__title(prog, false),
7977 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
7978 return ERR_PTR(link_fd);
7979 }
7980 link->fd = link_fd;
7981 return link;
7982}
7983
7984struct bpf_link *bpf_program__attach(struct bpf_program *prog)
7985{
7986 const struct bpf_sec_def *sec_def;
7987
7988 sec_def = find_sec_def(bpf_program__title(prog, false));
7989 if (!sec_def || !sec_def->attach_fn)
7990 return ERR_PTR(-ESRCH);
7991
7992 return sec_def->attach_fn(sec_def, prog);
7993}
7994
7995static int bpf_link__detach_struct_ops(struct bpf_link *link)
7996{
7997 __u32 zero = 0;
7998
7999 if (bpf_map_delete_elem(link->fd, &zero))
8000 return -errno;
8001
8002 return 0;
8003}
8004
8005struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
8006{
8007 struct bpf_struct_ops *st_ops;
8008 struct bpf_link *link;
8009 __u32 i, zero = 0;
8010 int err;
8011
8012 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
8013 return ERR_PTR(-EINVAL);
8014
8015 link = calloc(1, sizeof(*link));
8016 if (!link)
8017 return ERR_PTR(-EINVAL);
8018
8019 st_ops = map->st_ops;
8020 for (i = 0; i < btf_vlen(st_ops->type); i++) {
8021 struct bpf_program *prog = st_ops->progs[i];
8022 void *kern_data;
8023 int prog_fd;
8024
8025 if (!prog)
8026 continue;
8027
8028 prog_fd = bpf_program__fd(prog);
8029 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8030 *(unsigned long *)kern_data = prog_fd;
8031 }
8032
8033 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
8034 if (err) {
8035 err = -errno;
8036 free(link);
8037 return ERR_PTR(err);
8038 }
8039
8040 link->detach = bpf_link__detach_struct_ops;
8041 link->fd = map->fd;
8042
8043 return link;
8044}
8045
8046enum bpf_perf_event_ret
8047bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
8048 void **copy_mem, size_t *copy_size,
8049 bpf_perf_event_print_t fn, void *private_data)
8050{
8051 struct perf_event_mmap_page *header = mmap_mem;
8052 __u64 data_head = ring_buffer_read_head(header);
8053 __u64 data_tail = header->data_tail;
8054 void *base = ((__u8 *)header) + page_size;
8055 int ret = LIBBPF_PERF_EVENT_CONT;
8056 struct perf_event_header *ehdr;
8057 size_t ehdr_size;
8058
8059 while (data_head != data_tail) {
8060 ehdr = base + (data_tail & (mmap_size - 1));
8061 ehdr_size = ehdr->size;
8062
8063 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
8064 void *copy_start = ehdr;
8065 size_t len_first = base + mmap_size - copy_start;
8066 size_t len_secnd = ehdr_size - len_first;
8067
8068 if (*copy_size < ehdr_size) {
8069 free(*copy_mem);
8070 *copy_mem = malloc(ehdr_size);
8071 if (!*copy_mem) {
8072 *copy_size = 0;
8073 ret = LIBBPF_PERF_EVENT_ERROR;
8074 break;
8075 }
8076 *copy_size = ehdr_size;
8077 }
8078
8079 memcpy(*copy_mem, copy_start, len_first);
8080 memcpy(*copy_mem + len_first, base, len_secnd);
8081 ehdr = *copy_mem;
8082 }
8083
8084 ret = fn(ehdr, private_data);
8085 data_tail += ehdr_size;
8086 if (ret != LIBBPF_PERF_EVENT_CONT)
8087 break;
8088 }
8089
8090 ring_buffer_write_tail(header, data_tail);
8091 return ret;
8092}
8093
8094struct perf_buffer;
8095
8096struct perf_buffer_params {
8097 struct perf_event_attr *attr;
8098 /* if event_cb is specified, it takes precendence */
8099 perf_buffer_event_fn event_cb;
8100 /* sample_cb and lost_cb are higher-level common-case callbacks */
8101 perf_buffer_sample_fn sample_cb;
8102 perf_buffer_lost_fn lost_cb;
8103 void *ctx;
8104 int cpu_cnt;
8105 int *cpus;
8106 int *map_keys;
8107};
8108
8109struct perf_cpu_buf {
8110 struct perf_buffer *pb;
8111 void *base; /* mmap()'ed memory */
8112 void *buf; /* for reconstructing segmented data */
8113 size_t buf_size;
8114 int fd;
8115 int cpu;
8116 int map_key;
8117};
8118
8119struct perf_buffer {
8120 perf_buffer_event_fn event_cb;
8121 perf_buffer_sample_fn sample_cb;
8122 perf_buffer_lost_fn lost_cb;
8123 void *ctx; /* passed into callbacks */
8124
8125 size_t page_size;
8126 size_t mmap_size;
8127 struct perf_cpu_buf **cpu_bufs;
8128 struct epoll_event *events;
8129 int cpu_cnt; /* number of allocated CPU buffers */
8130 int epoll_fd; /* perf event FD */
8131 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
8132};
8133
8134static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
8135 struct perf_cpu_buf *cpu_buf)
8136{
8137 if (!cpu_buf)
8138 return;
8139 if (cpu_buf->base &&
8140 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
8141 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
8142 if (cpu_buf->fd >= 0) {
8143 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
8144 close(cpu_buf->fd);
8145 }
8146 free(cpu_buf->buf);
8147 free(cpu_buf);
8148}
8149
8150void perf_buffer__free(struct perf_buffer *pb)
8151{
8152 int i;
8153
8154 if (!pb)
8155 return;
8156 if (pb->cpu_bufs) {
8157 for (i = 0; i < pb->cpu_cnt; i++) {
8158 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
8159
8160 if (!cpu_buf)
8161 continue;
8162
8163 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
8164 perf_buffer__free_cpu_buf(pb, cpu_buf);
8165 }
8166 free(pb->cpu_bufs);
8167 }
8168 if (pb->epoll_fd >= 0)
8169 close(pb->epoll_fd);
8170 free(pb->events);
8171 free(pb);
8172}
8173
8174static struct perf_cpu_buf *
8175perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
8176 int cpu, int map_key)
8177{
8178 struct perf_cpu_buf *cpu_buf;
8179 char msg[STRERR_BUFSIZE];
8180 int err;
8181
8182 cpu_buf = calloc(1, sizeof(*cpu_buf));
8183 if (!cpu_buf)
8184 return ERR_PTR(-ENOMEM);
8185
8186 cpu_buf->pb = pb;
8187 cpu_buf->cpu = cpu;
8188 cpu_buf->map_key = map_key;
8189
8190 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
8191 -1, PERF_FLAG_FD_CLOEXEC);
8192 if (cpu_buf->fd < 0) {
8193 err = -errno;
8194 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
8195 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8196 goto error;
8197 }
8198
8199 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
8200 PROT_READ | PROT_WRITE, MAP_SHARED,
8201 cpu_buf->fd, 0);
8202 if (cpu_buf->base == MAP_FAILED) {
8203 cpu_buf->base = NULL;
8204 err = -errno;
8205 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
8206 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8207 goto error;
8208 }
8209
8210 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
8211 err = -errno;
8212 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
8213 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
8214 goto error;
8215 }
8216
8217 return cpu_buf;
8218
8219error:
8220 perf_buffer__free_cpu_buf(pb, cpu_buf);
8221 return (struct perf_cpu_buf *)ERR_PTR(err);
8222}
8223
8224static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8225 struct perf_buffer_params *p);
8226
8227struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
8228 const struct perf_buffer_opts *opts)
8229{
8230 struct perf_buffer_params p = {};
8231 struct perf_event_attr attr = { 0, };
8232
8233 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
8234 attr.type = PERF_TYPE_SOFTWARE;
8235 attr.sample_type = PERF_SAMPLE_RAW;
8236 attr.sample_period = 1;
8237 attr.wakeup_events = 1;
8238
8239 p.attr = &attr;
8240 p.sample_cb = opts ? opts->sample_cb : NULL;
8241 p.lost_cb = opts ? opts->lost_cb : NULL;
8242 p.ctx = opts ? opts->ctx : NULL;
8243
8244 return __perf_buffer__new(map_fd, page_cnt, &p);
8245}
8246
8247struct perf_buffer *
8248perf_buffer__new_raw(int map_fd, size_t page_cnt,
8249 const struct perf_buffer_raw_opts *opts)
8250{
8251 struct perf_buffer_params p = {};
8252
8253 p.attr = opts->attr;
8254 p.event_cb = opts->event_cb;
8255 p.ctx = opts->ctx;
8256 p.cpu_cnt = opts->cpu_cnt;
8257 p.cpus = opts->cpus;
8258 p.map_keys = opts->map_keys;
8259
8260 return __perf_buffer__new(map_fd, page_cnt, &p);
8261}
8262
8263static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
8264 struct perf_buffer_params *p)
8265{
8266 const char *online_cpus_file = "/sys/devices/system/cpu/online";
8267 struct bpf_map_info map = {};
8268 char msg[STRERR_BUFSIZE];
8269 struct perf_buffer *pb;
8270 bool *online = NULL;
8271 __u32 map_info_len;
8272 int err, i, j, n;
8273
8274 if (page_cnt & (page_cnt - 1)) {
8275 pr_warn("page count should be power of two, but is %zu\n",
8276 page_cnt);
8277 return ERR_PTR(-EINVAL);
8278 }
8279
8280 map_info_len = sizeof(map);
8281 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
8282 if (err) {
8283 err = -errno;
8284 pr_warn("failed to get map info for map FD %d: %s\n",
8285 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
8286 return ERR_PTR(err);
8287 }
8288
8289 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
8290 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
8291 map.name);
8292 return ERR_PTR(-EINVAL);
8293 }
8294
8295 pb = calloc(1, sizeof(*pb));
8296 if (!pb)
8297 return ERR_PTR(-ENOMEM);
8298
8299 pb->event_cb = p->event_cb;
8300 pb->sample_cb = p->sample_cb;
8301 pb->lost_cb = p->lost_cb;
8302 pb->ctx = p->ctx;
8303
8304 pb->page_size = getpagesize();
8305 pb->mmap_size = pb->page_size * page_cnt;
8306 pb->map_fd = map_fd;
8307
8308 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
8309 if (pb->epoll_fd < 0) {
8310 err = -errno;
8311 pr_warn("failed to create epoll instance: %s\n",
8312 libbpf_strerror_r(err, msg, sizeof(msg)));
8313 goto error;
8314 }
8315
8316 if (p->cpu_cnt > 0) {
8317 pb->cpu_cnt = p->cpu_cnt;
8318 } else {
8319 pb->cpu_cnt = libbpf_num_possible_cpus();
8320 if (pb->cpu_cnt < 0) {
8321 err = pb->cpu_cnt;
8322 goto error;
8323 }
8324 if (map.max_entries < pb->cpu_cnt)
8325 pb->cpu_cnt = map.max_entries;
8326 }
8327
8328 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
8329 if (!pb->events) {
8330 err = -ENOMEM;
8331 pr_warn("failed to allocate events: out of memory\n");
8332 goto error;
8333 }
8334 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
8335 if (!pb->cpu_bufs) {
8336 err = -ENOMEM;
8337 pr_warn("failed to allocate buffers: out of memory\n");
8338 goto error;
8339 }
8340
8341 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
8342 if (err) {
8343 pr_warn("failed to get online CPU mask: %d\n", err);
8344 goto error;
8345 }
8346
8347 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
8348 struct perf_cpu_buf *cpu_buf;
8349 int cpu, map_key;
8350
8351 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
8352 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
8353
8354 /* in case user didn't explicitly requested particular CPUs to
8355 * be attached to, skip offline/not present CPUs
8356 */
8357 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
8358 continue;
8359
8360 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
8361 if (IS_ERR(cpu_buf)) {
8362 err = PTR_ERR(cpu_buf);
8363 goto error;
8364 }
8365
8366 pb->cpu_bufs[j] = cpu_buf;
8367
8368 err = bpf_map_update_elem(pb->map_fd, &map_key,
8369 &cpu_buf->fd, 0);
8370 if (err) {
8371 err = -errno;
8372 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
8373 cpu, map_key, cpu_buf->fd,
8374 libbpf_strerror_r(err, msg, sizeof(msg)));
8375 goto error;
8376 }
8377
8378 pb->events[j].events = EPOLLIN;
8379 pb->events[j].data.ptr = cpu_buf;
8380 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
8381 &pb->events[j]) < 0) {
8382 err = -errno;
8383 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
8384 cpu, cpu_buf->fd,
8385 libbpf_strerror_r(err, msg, sizeof(msg)));
8386 goto error;
8387 }
8388 j++;
8389 }
8390 pb->cpu_cnt = j;
8391 free(online);
8392
8393 return pb;
8394
8395error:
8396 free(online);
8397 if (pb)
8398 perf_buffer__free(pb);
8399 return ERR_PTR(err);
8400}
8401
8402struct perf_sample_raw {
8403 struct perf_event_header header;
8404 uint32_t size;
8405 char data[];
8406};
8407
8408struct perf_sample_lost {
8409 struct perf_event_header header;
8410 uint64_t id;
8411 uint64_t lost;
8412 uint64_t sample_id;
8413};
8414
8415static enum bpf_perf_event_ret
8416perf_buffer__process_record(struct perf_event_header *e, void *ctx)
8417{
8418 struct perf_cpu_buf *cpu_buf = ctx;
8419 struct perf_buffer *pb = cpu_buf->pb;
8420 void *data = e;
8421
8422 /* user wants full control over parsing perf event */
8423 if (pb->event_cb)
8424 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
8425
8426 switch (e->type) {
8427 case PERF_RECORD_SAMPLE: {
8428 struct perf_sample_raw *s = data;
8429
8430 if (pb->sample_cb)
8431 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
8432 break;
8433 }
8434 case PERF_RECORD_LOST: {
8435 struct perf_sample_lost *s = data;
8436
8437 if (pb->lost_cb)
8438 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
8439 break;
8440 }
8441 default:
8442 pr_warn("unknown perf sample type %d\n", e->type);
8443 return LIBBPF_PERF_EVENT_ERROR;
8444 }
8445 return LIBBPF_PERF_EVENT_CONT;
8446}
8447
8448static int perf_buffer__process_records(struct perf_buffer *pb,
8449 struct perf_cpu_buf *cpu_buf)
8450{
8451 enum bpf_perf_event_ret ret;
8452
8453 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
8454 pb->page_size, &cpu_buf->buf,
8455 &cpu_buf->buf_size,
8456 perf_buffer__process_record, cpu_buf);
8457 if (ret != LIBBPF_PERF_EVENT_CONT)
8458 return ret;
8459 return 0;
8460}
8461
8462int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
8463{
8464 int i, cnt, err;
8465
8466 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
8467 for (i = 0; i < cnt; i++) {
8468 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
8469
8470 err = perf_buffer__process_records(pb, cpu_buf);
8471 if (err) {
8472 pr_warn("error while processing records: %d\n", err);
8473 return err;
8474 }
8475 }
8476 return cnt < 0 ? -errno : cnt;
8477}
8478
8479int perf_buffer__consume(struct perf_buffer *pb)
8480{
8481 int i, err;
8482
8483 for (i = 0; i < pb->cpu_cnt; i++) {
8484 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
8485
8486 if (!cpu_buf)
8487 continue;
8488
8489 err = perf_buffer__process_records(pb, cpu_buf);
8490 if (err) {
8491 pr_warn("error while processing records: %d\n", err);
8492 return err;
8493 }
8494 }
8495 return 0;
8496}
8497
8498struct bpf_prog_info_array_desc {
8499 int array_offset; /* e.g. offset of jited_prog_insns */
8500 int count_offset; /* e.g. offset of jited_prog_len */
8501 int size_offset; /* > 0: offset of rec size,
8502 * < 0: fix size of -size_offset
8503 */
8504};
8505
8506static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
8507 [BPF_PROG_INFO_JITED_INSNS] = {
8508 offsetof(struct bpf_prog_info, jited_prog_insns),
8509 offsetof(struct bpf_prog_info, jited_prog_len),
8510 -1,
8511 },
8512 [BPF_PROG_INFO_XLATED_INSNS] = {
8513 offsetof(struct bpf_prog_info, xlated_prog_insns),
8514 offsetof(struct bpf_prog_info, xlated_prog_len),
8515 -1,
8516 },
8517 [BPF_PROG_INFO_MAP_IDS] = {
8518 offsetof(struct bpf_prog_info, map_ids),
8519 offsetof(struct bpf_prog_info, nr_map_ids),
8520 -(int)sizeof(__u32),
8521 },
8522 [BPF_PROG_INFO_JITED_KSYMS] = {
8523 offsetof(struct bpf_prog_info, jited_ksyms),
8524 offsetof(struct bpf_prog_info, nr_jited_ksyms),
8525 -(int)sizeof(__u64),
8526 },
8527 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
8528 offsetof(struct bpf_prog_info, jited_func_lens),
8529 offsetof(struct bpf_prog_info, nr_jited_func_lens),
8530 -(int)sizeof(__u32),
8531 },
8532 [BPF_PROG_INFO_FUNC_INFO] = {
8533 offsetof(struct bpf_prog_info, func_info),
8534 offsetof(struct bpf_prog_info, nr_func_info),
8535 offsetof(struct bpf_prog_info, func_info_rec_size),
8536 },
8537 [BPF_PROG_INFO_LINE_INFO] = {
8538 offsetof(struct bpf_prog_info, line_info),
8539 offsetof(struct bpf_prog_info, nr_line_info),
8540 offsetof(struct bpf_prog_info, line_info_rec_size),
8541 },
8542 [BPF_PROG_INFO_JITED_LINE_INFO] = {
8543 offsetof(struct bpf_prog_info, jited_line_info),
8544 offsetof(struct bpf_prog_info, nr_jited_line_info),
8545 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
8546 },
8547 [BPF_PROG_INFO_PROG_TAGS] = {
8548 offsetof(struct bpf_prog_info, prog_tags),
8549 offsetof(struct bpf_prog_info, nr_prog_tags),
8550 -(int)sizeof(__u8) * BPF_TAG_SIZE,
8551 },
8552
8553};
8554
8555static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
8556 int offset)
8557{
8558 __u32 *array = (__u32 *)info;
8559
8560 if (offset >= 0)
8561 return array[offset / sizeof(__u32)];
8562 return -(int)offset;
8563}
8564
8565static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
8566 int offset)
8567{
8568 __u64 *array = (__u64 *)info;
8569
8570 if (offset >= 0)
8571 return array[offset / sizeof(__u64)];
8572 return -(int)offset;
8573}
8574
8575static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
8576 __u32 val)
8577{
8578 __u32 *array = (__u32 *)info;
8579
8580 if (offset >= 0)
8581 array[offset / sizeof(__u32)] = val;
8582}
8583
8584static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
8585 __u64 val)
8586{
8587 __u64 *array = (__u64 *)info;
8588
8589 if (offset >= 0)
8590 array[offset / sizeof(__u64)] = val;
8591}
8592
8593struct bpf_prog_info_linear *
8594bpf_program__get_prog_info_linear(int fd, __u64 arrays)
8595{
8596 struct bpf_prog_info_linear *info_linear;
8597 struct bpf_prog_info info = {};
8598 __u32 info_len = sizeof(info);
8599 __u32 data_len = 0;
8600 int i, err;
8601 void *ptr;
8602
8603 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
8604 return ERR_PTR(-EINVAL);
8605
8606 /* step 1: get array dimensions */
8607 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
8608 if (err) {
8609 pr_debug("can't get prog info: %s", strerror(errno));
8610 return ERR_PTR(-EFAULT);
8611 }
8612
8613 /* step 2: calculate total size of all arrays */
8614 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8615 bool include_array = (arrays & (1UL << i)) > 0;
8616 struct bpf_prog_info_array_desc *desc;
8617 __u32 count, size;
8618
8619 desc = bpf_prog_info_array_desc + i;
8620
8621 /* kernel is too old to support this field */
8622 if (info_len < desc->array_offset + sizeof(__u32) ||
8623 info_len < desc->count_offset + sizeof(__u32) ||
8624 (desc->size_offset > 0 && info_len < desc->size_offset))
8625 include_array = false;
8626
8627 if (!include_array) {
8628 arrays &= ~(1UL << i); /* clear the bit */
8629 continue;
8630 }
8631
8632 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8633 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8634
8635 data_len += count * size;
8636 }
8637
8638 /* step 3: allocate continuous memory */
8639 data_len = roundup(data_len, sizeof(__u64));
8640 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
8641 if (!info_linear)
8642 return ERR_PTR(-ENOMEM);
8643
8644 /* step 4: fill data to info_linear->info */
8645 info_linear->arrays = arrays;
8646 memset(&info_linear->info, 0, sizeof(info));
8647 ptr = info_linear->data;
8648
8649 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8650 struct bpf_prog_info_array_desc *desc;
8651 __u32 count, size;
8652
8653 if ((arrays & (1UL << i)) == 0)
8654 continue;
8655
8656 desc = bpf_prog_info_array_desc + i;
8657 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8658 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8659 bpf_prog_info_set_offset_u32(&info_linear->info,
8660 desc->count_offset, count);
8661 bpf_prog_info_set_offset_u32(&info_linear->info,
8662 desc->size_offset, size);
8663 bpf_prog_info_set_offset_u64(&info_linear->info,
8664 desc->array_offset,
8665 ptr_to_u64(ptr));
8666 ptr += count * size;
8667 }
8668
8669 /* step 5: call syscall again to get required arrays */
8670 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
8671 if (err) {
8672 pr_debug("can't get prog info: %s", strerror(errno));
8673 free(info_linear);
8674 return ERR_PTR(-EFAULT);
8675 }
8676
8677 /* step 6: verify the data */
8678 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8679 struct bpf_prog_info_array_desc *desc;
8680 __u32 v1, v2;
8681
8682 if ((arrays & (1UL << i)) == 0)
8683 continue;
8684
8685 desc = bpf_prog_info_array_desc + i;
8686 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
8687 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8688 desc->count_offset);
8689 if (v1 != v2)
8690 pr_warn("%s: mismatch in element count\n", __func__);
8691
8692 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
8693 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
8694 desc->size_offset);
8695 if (v1 != v2)
8696 pr_warn("%s: mismatch in rec size\n", __func__);
8697 }
8698
8699 /* step 7: update info_len and data_len */
8700 info_linear->info_len = sizeof(struct bpf_prog_info);
8701 info_linear->data_len = data_len;
8702
8703 return info_linear;
8704}
8705
8706void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
8707{
8708 int i;
8709
8710 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8711 struct bpf_prog_info_array_desc *desc;
8712 __u64 addr, offs;
8713
8714 if ((info_linear->arrays & (1UL << i)) == 0)
8715 continue;
8716
8717 desc = bpf_prog_info_array_desc + i;
8718 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
8719 desc->array_offset);
8720 offs = addr - ptr_to_u64(info_linear->data);
8721 bpf_prog_info_set_offset_u64(&info_linear->info,
8722 desc->array_offset, offs);
8723 }
8724}
8725
8726void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
8727{
8728 int i;
8729
8730 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
8731 struct bpf_prog_info_array_desc *desc;
8732 __u64 addr, offs;
8733
8734 if ((info_linear->arrays & (1UL << i)) == 0)
8735 continue;
8736
8737 desc = bpf_prog_info_array_desc + i;
8738 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
8739 desc->array_offset);
8740 addr = offs + ptr_to_u64(info_linear->data);
8741 bpf_prog_info_set_offset_u64(&info_linear->info,
8742 desc->array_offset, addr);
8743 }
8744}
8745
8746int bpf_program__set_attach_target(struct bpf_program *prog,
8747 int attach_prog_fd,
8748 const char *attach_func_name)
8749{
8750 int btf_id;
8751
8752 if (!prog || attach_prog_fd < 0 || !attach_func_name)
8753 return -EINVAL;
8754
8755 if (attach_prog_fd)
8756 btf_id = libbpf_find_prog_btf_id(attach_func_name,
8757 attach_prog_fd);
8758 else
8759 btf_id = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
8760 attach_func_name,
8761 prog->expected_attach_type);
8762
8763 if (btf_id < 0)
8764 return btf_id;
8765
8766 prog->attach_btf_id = btf_id;
8767 prog->attach_prog_fd = attach_prog_fd;
8768 return 0;
8769}
8770
8771int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
8772{
8773 int err = 0, n, len, start, end = -1;
8774 bool *tmp;
8775
8776 *mask = NULL;
8777 *mask_sz = 0;
8778
8779 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
8780 while (*s) {
8781 if (*s == ',' || *s == '\n') {
8782 s++;
8783 continue;
8784 }
8785 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
8786 if (n <= 0 || n > 2) {
8787 pr_warn("Failed to get CPU range %s: %d\n", s, n);
8788 err = -EINVAL;
8789 goto cleanup;
8790 } else if (n == 1) {
8791 end = start;
8792 }
8793 if (start < 0 || start > end) {
8794 pr_warn("Invalid CPU range [%d,%d] in %s\n",
8795 start, end, s);
8796 err = -EINVAL;
8797 goto cleanup;
8798 }
8799 tmp = realloc(*mask, end + 1);
8800 if (!tmp) {
8801 err = -ENOMEM;
8802 goto cleanup;
8803 }
8804 *mask = tmp;
8805 memset(tmp + *mask_sz, 0, start - *mask_sz);
8806 memset(tmp + start, 1, end - start + 1);
8807 *mask_sz = end + 1;
8808 s += len;
8809 }
8810 if (!*mask_sz) {
8811 pr_warn("Empty CPU range\n");
8812 return -EINVAL;
8813 }
8814 return 0;
8815cleanup:
8816 free(*mask);
8817 *mask = NULL;
8818 return err;
8819}
8820
8821int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
8822{
8823 int fd, err = 0, len;
8824 char buf[128];
8825
8826 fd = open(fcpu, O_RDONLY);
8827 if (fd < 0) {
8828 err = -errno;
8829 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
8830 return err;
8831 }
8832 len = read(fd, buf, sizeof(buf));
8833 close(fd);
8834 if (len <= 0) {
8835 err = len ? -errno : -EINVAL;
8836 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
8837 return err;
8838 }
8839 if (len >= sizeof(buf)) {
8840 pr_warn("CPU mask is too big in file %s\n", fcpu);
8841 return -E2BIG;
8842 }
8843 buf[len] = '\0';
8844
8845 return parse_cpu_mask_str(buf, mask, mask_sz);
8846}
8847
8848int libbpf_num_possible_cpus(void)
8849{
8850 static const char *fcpu = "/sys/devices/system/cpu/possible";
8851 static int cpus;
8852 int err, n, i, tmp_cpus;
8853 bool *mask;
8854
8855 tmp_cpus = READ_ONCE(cpus);
8856 if (tmp_cpus > 0)
8857 return tmp_cpus;
8858
8859 err = parse_cpu_mask_file(fcpu, &mask, &n);
8860 if (err)
8861 return err;
8862
8863 tmp_cpus = 0;
8864 for (i = 0; i < n; i++) {
8865 if (mask[i])
8866 tmp_cpus++;
8867 }
8868 free(mask);
8869
8870 WRITE_ONCE(cpus, tmp_cpus);
8871 return tmp_cpus;
8872}
8873
8874int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
8875 const struct bpf_object_open_opts *opts)
8876{
8877 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
8878 .object_name = s->name,
8879 );
8880 struct bpf_object *obj;
8881 int i;
8882
8883 /* Attempt to preserve opts->object_name, unless overriden by user
8884 * explicitly. Overwriting object name for skeletons is discouraged,
8885 * as it breaks global data maps, because they contain object name
8886 * prefix as their own map name prefix. When skeleton is generated,
8887 * bpftool is making an assumption that this name will stay the same.
8888 */
8889 if (opts) {
8890 memcpy(&skel_opts, opts, sizeof(*opts));
8891 if (!opts->object_name)
8892 skel_opts.object_name = s->name;
8893 }
8894
8895 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
8896 if (IS_ERR(obj)) {
8897 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
8898 s->name, PTR_ERR(obj));
8899 return PTR_ERR(obj);
8900 }
8901
8902 *s->obj = obj;
8903
8904 for (i = 0; i < s->map_cnt; i++) {
8905 struct bpf_map **map = s->maps[i].map;
8906 const char *name = s->maps[i].name;
8907 void **mmaped = s->maps[i].mmaped;
8908
8909 *map = bpf_object__find_map_by_name(obj, name);
8910 if (!*map) {
8911 pr_warn("failed to find skeleton map '%s'\n", name);
8912 return -ESRCH;
8913 }
8914
8915 /* externs shouldn't be pre-setup from user code */
8916 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
8917 *mmaped = (*map)->mmaped;
8918 }
8919
8920 for (i = 0; i < s->prog_cnt; i++) {
8921 struct bpf_program **prog = s->progs[i].prog;
8922 const char *name = s->progs[i].name;
8923
8924 *prog = bpf_object__find_program_by_name(obj, name);
8925 if (!*prog) {
8926 pr_warn("failed to find skeleton program '%s'\n", name);
8927 return -ESRCH;
8928 }
8929 }
8930
8931 return 0;
8932}
8933
8934int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
8935{
8936 int i, err;
8937
8938 err = bpf_object__load(*s->obj);
8939 if (err) {
8940 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
8941 return err;
8942 }
8943
8944 for (i = 0; i < s->map_cnt; i++) {
8945 struct bpf_map *map = *s->maps[i].map;
8946 size_t mmap_sz = bpf_map_mmap_sz(map);
8947 int prot, map_fd = bpf_map__fd(map);
8948 void **mmaped = s->maps[i].mmaped;
8949
8950 if (!mmaped)
8951 continue;
8952
8953 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
8954 *mmaped = NULL;
8955 continue;
8956 }
8957
8958 if (map->def.map_flags & BPF_F_RDONLY_PROG)
8959 prot = PROT_READ;
8960 else
8961 prot = PROT_READ | PROT_WRITE;
8962
8963 /* Remap anonymous mmap()-ed "map initialization image" as
8964 * a BPF map-backed mmap()-ed memory, but preserving the same
8965 * memory address. This will cause kernel to change process'
8966 * page table to point to a different piece of kernel memory,
8967 * but from userspace point of view memory address (and its
8968 * contents, being identical at this point) will stay the
8969 * same. This mapping will be released by bpf_object__close()
8970 * as per normal clean up procedure, so we don't need to worry
8971 * about it from skeleton's clean up perspective.
8972 */
8973 *mmaped = mmap(map->mmaped, mmap_sz, prot,
8974 MAP_SHARED | MAP_FIXED, map_fd, 0);
8975 if (*mmaped == MAP_FAILED) {
8976 err = -errno;
8977 *mmaped = NULL;
8978 pr_warn("failed to re-mmap() map '%s': %d\n",
8979 bpf_map__name(map), err);
8980 return err;
8981 }
8982 }
8983
8984 return 0;
8985}
8986
8987int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
8988{
8989 int i;
8990
8991 for (i = 0; i < s->prog_cnt; i++) {
8992 struct bpf_program *prog = *s->progs[i].prog;
8993 struct bpf_link **link = s->progs[i].link;
8994 const struct bpf_sec_def *sec_def;
8995 const char *sec_name = bpf_program__title(prog, false);
8996
8997 sec_def = find_sec_def(sec_name);
8998 if (!sec_def || !sec_def->attach_fn)
8999 continue;
9000
9001 *link = sec_def->attach_fn(sec_def, prog);
9002 if (IS_ERR(*link)) {
9003 pr_warn("failed to auto-attach program '%s': %ld\n",
9004 bpf_program__name(prog), PTR_ERR(*link));
9005 return PTR_ERR(*link);
9006 }
9007 }
9008
9009 return 0;
9010}
9011
9012void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
9013{
9014 int i;
9015
9016 for (i = 0; i < s->prog_cnt; i++) {
9017 struct bpf_link **link = s->progs[i].link;
9018
9019 if (!IS_ERR_OR_NULL(*link))
9020 bpf_link__destroy(*link);
9021 *link = NULL;
9022 }
9023}
9024
9025void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
9026{
9027 if (s->progs)
9028 bpf_object__detach_skeleton(s);
9029 if (s->obj)
9030 bpf_object__close(*s->obj);
9031 free(s->maps);
9032 free(s->progs);
9033 free(s);
9034}