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