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