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 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
205 enum sec_def_flags {
206 	SEC_NONE = 0,
207 	/* expected_attach_type is optional, if kernel doesn't support that */
208 	SEC_EXP_ATTACH_OPT = 1,
209 	/* legacy, only used by libbpf_get_type_names() and
210 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
211 	 * This used to be associated with cgroup (and few other) BPF programs
212 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
213 	 * meaningless nowadays, though.
214 	 */
215 	SEC_ATTACHABLE = 2,
216 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
217 	/* attachment target is specified through BTF ID in either kernel or
218 	 * other BPF program's BTF object */
219 	SEC_ATTACH_BTF = 4,
220 	/* BPF program type allows sleeping/blocking in kernel */
221 	SEC_SLEEPABLE = 8,
222 	/* allow non-strict prefix matching */
223 	SEC_SLOPPY_PFX = 16,
224 	/* BPF program support non-linear XDP buffer */
225 	SEC_XDP_FRAGS = 32,
226 	/* deprecated sec definitions not supposed to be used */
227 	SEC_DEPRECATED = 64,
228 };
229 
230 struct bpf_sec_def {
231 	char *sec;
232 	enum bpf_prog_type prog_type;
233 	enum bpf_attach_type expected_attach_type;
234 	long cookie;
235 	int handler_id;
236 
237 	libbpf_prog_setup_fn_t prog_setup_fn;
238 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
239 	libbpf_prog_attach_fn_t prog_attach_fn;
240 };
241 
242 /*
243  * bpf_prog should be a better name but it has been used in
244  * linux/filter.h.
245  */
246 struct bpf_program {
247 	const struct bpf_sec_def *sec_def;
248 	char *sec_name;
249 	size_t sec_idx;
250 	/* this program's instruction offset (in number of instructions)
251 	 * within its containing ELF section
252 	 */
253 	size_t sec_insn_off;
254 	/* number of original instructions in ELF section belonging to this
255 	 * program, not taking into account subprogram instructions possible
256 	 * appended later during relocation
257 	 */
258 	size_t sec_insn_cnt;
259 	/* Offset (in number of instructions) of the start of instruction
260 	 * belonging to this BPF program  within its containing main BPF
261 	 * program. For the entry-point (main) BPF program, this is always
262 	 * zero. For a sub-program, this gets reset before each of main BPF
263 	 * programs are processed and relocated and is used to determined
264 	 * whether sub-program was already appended to the main program, and
265 	 * if yes, at which instruction offset.
266 	 */
267 	size_t sub_insn_off;
268 
269 	char *name;
270 	/* name with / replaced by _; makes recursive pinning
271 	 * in bpf_object__pin_programs easier
272 	 */
273 	char *pin_name;
274 
275 	/* instructions that belong to BPF program; insns[0] is located at
276 	 * sec_insn_off instruction within its ELF section in ELF file, so
277 	 * when mapping ELF file instruction index to the local instruction,
278 	 * one needs to subtract sec_insn_off; and vice versa.
279 	 */
280 	struct bpf_insn *insns;
281 	/* actual number of instruction in this BPF program's image; for
282 	 * entry-point BPF programs this includes the size of main program
283 	 * itself plus all the used sub-programs, appended at the end
284 	 */
285 	size_t insns_cnt;
286 
287 	struct reloc_desc *reloc_desc;
288 	int nr_reloc;
289 
290 	/* BPF verifier log settings */
291 	char *log_buf;
292 	size_t log_size;
293 	__u32 log_level;
294 
295 	struct {
296 		int nr;
297 		int *fds;
298 	} instances;
299 	bpf_program_prep_t preprocessor;
300 
301 	struct bpf_object *obj;
302 	void *priv;
303 	bpf_program_clear_priv_t clear_priv;
304 
305 	bool autoload;
306 	bool mark_btf_static;
307 	enum bpf_prog_type type;
308 	enum bpf_attach_type expected_attach_type;
309 	int prog_ifindex;
310 	__u32 attach_btf_obj_fd;
311 	__u32 attach_btf_id;
312 	__u32 attach_prog_fd;
313 	void *func_info;
314 	__u32 func_info_rec_size;
315 	__u32 func_info_cnt;
316 
317 	void *line_info;
318 	__u32 line_info_rec_size;
319 	__u32 line_info_cnt;
320 	__u32 prog_flags;
321 };
322 
323 struct bpf_struct_ops {
324 	const char *tname;
325 	const struct btf_type *type;
326 	struct bpf_program **progs;
327 	__u32 *kern_func_off;
328 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
329 	void *data;
330 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
331 	 *      btf_vmlinux's format.
332 	 * struct bpf_struct_ops_tcp_congestion_ops {
333 	 *	[... some other kernel fields ...]
334 	 *	struct tcp_congestion_ops data;
335 	 * }
336 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
337 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
338 	 * from "data".
339 	 */
340 	void *kern_vdata;
341 	__u32 type_id;
342 };
343 
344 #define DATA_SEC ".data"
345 #define BSS_SEC ".bss"
346 #define RODATA_SEC ".rodata"
347 #define KCONFIG_SEC ".kconfig"
348 #define KSYMS_SEC ".ksyms"
349 #define STRUCT_OPS_SEC ".struct_ops"
350 
351 enum libbpf_map_type {
352 	LIBBPF_MAP_UNSPEC,
353 	LIBBPF_MAP_DATA,
354 	LIBBPF_MAP_BSS,
355 	LIBBPF_MAP_RODATA,
356 	LIBBPF_MAP_KCONFIG,
357 };
358 
359 struct bpf_map {
360 	struct bpf_object *obj;
361 	char *name;
362 	/* real_name is defined for special internal maps (.rodata*,
363 	 * .data*, .bss, .kconfig) and preserves their original ELF section
364 	 * name. This is important to be be able to find corresponding BTF
365 	 * DATASEC information.
366 	 */
367 	char *real_name;
368 	int fd;
369 	int sec_idx;
370 	size_t sec_offset;
371 	int map_ifindex;
372 	int inner_map_fd;
373 	struct bpf_map_def def;
374 	__u32 numa_node;
375 	__u32 btf_var_idx;
376 	__u32 btf_key_type_id;
377 	__u32 btf_value_type_id;
378 	__u32 btf_vmlinux_value_type_id;
379 	void *priv;
380 	bpf_map_clear_priv_t clear_priv;
381 	enum libbpf_map_type libbpf_type;
382 	void *mmaped;
383 	struct bpf_struct_ops *st_ops;
384 	struct bpf_map *inner_map;
385 	void **init_slots;
386 	int init_slots_sz;
387 	char *pin_path;
388 	bool pinned;
389 	bool reused;
390 	bool autocreate;
391 	__u64 map_extra;
392 };
393 
394 enum extern_type {
395 	EXT_UNKNOWN,
396 	EXT_KCFG,
397 	EXT_KSYM,
398 };
399 
400 enum kcfg_type {
401 	KCFG_UNKNOWN,
402 	KCFG_CHAR,
403 	KCFG_BOOL,
404 	KCFG_INT,
405 	KCFG_TRISTATE,
406 	KCFG_CHAR_ARR,
407 };
408 
409 struct extern_desc {
410 	enum extern_type type;
411 	int sym_idx;
412 	int btf_id;
413 	int sec_btf_id;
414 	const char *name;
415 	bool is_set;
416 	bool is_weak;
417 	union {
418 		struct {
419 			enum kcfg_type type;
420 			int sz;
421 			int align;
422 			int data_off;
423 			bool is_signed;
424 		} kcfg;
425 		struct {
426 			unsigned long long addr;
427 
428 			/* target btf_id of the corresponding kernel var. */
429 			int kernel_btf_obj_fd;
430 			int kernel_btf_id;
431 
432 			/* local btf_id of the ksym extern's type. */
433 			__u32 type_id;
434 			/* BTF fd index to be patched in for insn->off, this is
435 			 * 0 for vmlinux BTF, index in obj->fd_array for module
436 			 * BTF
437 			 */
438 			__s16 btf_fd_idx;
439 		} ksym;
440 	};
441 };
442 
443 static LIST_HEAD(bpf_objects_list);
444 
445 struct module_btf {
446 	struct btf *btf;
447 	char *name;
448 	__u32 id;
449 	int fd;
450 	int fd_array_idx;
451 };
452 
453 enum sec_type {
454 	SEC_UNUSED = 0,
455 	SEC_RELO,
456 	SEC_BSS,
457 	SEC_DATA,
458 	SEC_RODATA,
459 };
460 
461 struct elf_sec_desc {
462 	enum sec_type sec_type;
463 	Elf64_Shdr *shdr;
464 	Elf_Data *data;
465 };
466 
467 struct elf_state {
468 	int fd;
469 	const void *obj_buf;
470 	size_t obj_buf_sz;
471 	Elf *elf;
472 	Elf64_Ehdr *ehdr;
473 	Elf_Data *symbols;
474 	Elf_Data *st_ops_data;
475 	size_t shstrndx; /* section index for section name strings */
476 	size_t strtabidx;
477 	struct elf_sec_desc *secs;
478 	int sec_cnt;
479 	int maps_shndx;
480 	int btf_maps_shndx;
481 	__u32 btf_maps_sec_btf_id;
482 	int text_shndx;
483 	int symbols_shndx;
484 	int st_ops_shndx;
485 };
486 
487 struct usdt_manager;
488 
489 struct bpf_object {
490 	char name[BPF_OBJ_NAME_LEN];
491 	char license[64];
492 	__u32 kern_version;
493 
494 	struct bpf_program *programs;
495 	size_t nr_programs;
496 	struct bpf_map *maps;
497 	size_t nr_maps;
498 	size_t maps_cap;
499 
500 	char *kconfig;
501 	struct extern_desc *externs;
502 	int nr_extern;
503 	int kconfig_map_idx;
504 
505 	bool loaded;
506 	bool has_subcalls;
507 	bool has_rodata;
508 
509 	struct bpf_gen *gen_loader;
510 
511 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
512 	struct elf_state efile;
513 	/*
514 	 * All loaded bpf_object are linked in a list, which is
515 	 * hidden to caller. bpf_objects__<func> handlers deal with
516 	 * all objects.
517 	 */
518 	struct list_head list;
519 
520 	struct btf *btf;
521 	struct btf_ext *btf_ext;
522 
523 	/* Parse and load BTF vmlinux if any of the programs in the object need
524 	 * it at load time.
525 	 */
526 	struct btf *btf_vmlinux;
527 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
528 	 * override for vmlinux BTF.
529 	 */
530 	char *btf_custom_path;
531 	/* vmlinux BTF override for CO-RE relocations */
532 	struct btf *btf_vmlinux_override;
533 	/* Lazily initialized kernel module BTFs */
534 	struct module_btf *btf_modules;
535 	bool btf_modules_loaded;
536 	size_t btf_module_cnt;
537 	size_t btf_module_cap;
538 
539 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
540 	char *log_buf;
541 	size_t log_size;
542 	__u32 log_level;
543 
544 	void *priv;
545 	bpf_object_clear_priv_t clear_priv;
546 
547 	int *fd_array;
548 	size_t fd_array_cap;
549 	size_t fd_array_cnt;
550 
551 	struct usdt_manager *usdt_man;
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 
677 	/* libbpf's convention for SEC("?abc...") is that it's just like
678 	 * SEC("abc...") but the corresponding bpf_program starts out with
679 	 * autoload set to false.
680 	 */
681 	if (sec_name[0] == '?') {
682 		prog->autoload = false;
683 		/* from now on forget there was ? in section name */
684 		sec_name++;
685 	} else {
686 		prog->autoload = true;
687 	}
688 
689 	prog->instances.fds = NULL;
690 	prog->instances.nr = -1;
691 
692 	/* inherit object's log_level */
693 	prog->log_level = obj->log_level;
694 
695 	prog->sec_name = strdup(sec_name);
696 	if (!prog->sec_name)
697 		goto errout;
698 
699 	prog->name = strdup(name);
700 	if (!prog->name)
701 		goto errout;
702 
703 	prog->pin_name = __bpf_program__pin_name(prog);
704 	if (!prog->pin_name)
705 		goto errout;
706 
707 	prog->insns = malloc(insn_data_sz);
708 	if (!prog->insns)
709 		goto errout;
710 	memcpy(prog->insns, insn_data, insn_data_sz);
711 
712 	return 0;
713 errout:
714 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
715 	bpf_program__exit(prog);
716 	return -ENOMEM;
717 }
718 
719 static int
bpf_object__add_programs(struct bpf_object * obj,Elf_Data * sec_data,const char * sec_name,int sec_idx)720 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
721 			 const char *sec_name, int sec_idx)
722 {
723 	Elf_Data *symbols = obj->efile.symbols;
724 	struct bpf_program *prog, *progs;
725 	void *data = sec_data->d_buf;
726 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
727 	int nr_progs, err, i;
728 	const char *name;
729 	Elf64_Sym *sym;
730 
731 	progs = obj->programs;
732 	nr_progs = obj->nr_programs;
733 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
734 	sec_off = 0;
735 
736 	for (i = 0; i < nr_syms; i++) {
737 		sym = elf_sym_by_idx(obj, i);
738 
739 		if (sym->st_shndx != sec_idx)
740 			continue;
741 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
742 			continue;
743 
744 		prog_sz = sym->st_size;
745 		sec_off = sym->st_value;
746 
747 		name = elf_sym_str(obj, sym->st_name);
748 		if (!name) {
749 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
750 				sec_name, sec_off);
751 			return -LIBBPF_ERRNO__FORMAT;
752 		}
753 
754 		if (sec_off + prog_sz > sec_sz) {
755 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
756 				sec_name, sec_off);
757 			return -LIBBPF_ERRNO__FORMAT;
758 		}
759 
760 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
761 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
762 			return -ENOTSUP;
763 		}
764 
765 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
766 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
767 
768 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
769 		if (!progs) {
770 			/*
771 			 * In this case the original obj->programs
772 			 * is still valid, so don't need special treat for
773 			 * bpf_close_object().
774 			 */
775 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
776 				sec_name, name);
777 			return -ENOMEM;
778 		}
779 		obj->programs = progs;
780 
781 		prog = &progs[nr_progs];
782 
783 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
784 					    sec_off, data + sec_off, prog_sz);
785 		if (err)
786 			return err;
787 
788 		/* if function is a global/weak symbol, but has restricted
789 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
790 		 * as static to enable more permissive BPF verification mode
791 		 * with more outside context available to BPF verifier
792 		 */
793 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
794 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
795 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
796 			prog->mark_btf_static = true;
797 
798 		nr_progs++;
799 		obj->nr_programs = nr_progs;
800 	}
801 
802 	return 0;
803 }
804 
get_kernel_version(void)805 __u32 get_kernel_version(void)
806 {
807 	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
808 	 * but Ubuntu provides /proc/version_signature file, as described at
809 	 * https://ubuntu.com/kernel, with an example contents below, which we
810 	 * can use to get a proper LINUX_VERSION_CODE.
811 	 *
812 	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
813 	 *
814 	 * In the above, 5.4.8 is what kernel is actually expecting, while
815 	 * uname() call will return 5.4.0 in info.release.
816 	 */
817 	const char *ubuntu_kver_file = "/proc/version_signature";
818 	__u32 major, minor, patch;
819 	struct utsname info;
820 
821 	if (access(ubuntu_kver_file, R_OK) == 0) {
822 		FILE *f;
823 
824 		f = fopen(ubuntu_kver_file, "r");
825 		if (f) {
826 			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
827 				fclose(f);
828 				return KERNEL_VERSION(major, minor, patch);
829 			}
830 			fclose(f);
831 		}
832 		/* something went wrong, fall back to uname() approach */
833 	}
834 
835 	uname(&info);
836 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
837 		return 0;
838 	return KERNEL_VERSION(major, minor, patch);
839 }
840 
841 static const struct btf_member *
find_member_by_offset(const struct btf_type * t,__u32 bit_offset)842 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
843 {
844 	struct btf_member *m;
845 	int i;
846 
847 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
848 		if (btf_member_bit_offset(t, i) == bit_offset)
849 			return m;
850 	}
851 
852 	return NULL;
853 }
854 
855 static const struct btf_member *
find_member_by_name(const struct btf * btf,const struct btf_type * t,const char * name)856 find_member_by_name(const struct btf *btf, const struct btf_type *t,
857 		    const char *name)
858 {
859 	struct btf_member *m;
860 	int i;
861 
862 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
863 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
864 			return m;
865 	}
866 
867 	return NULL;
868 }
869 
870 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
871 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
872 				   const char *name, __u32 kind);
873 
874 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)875 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
876 			   const struct btf_type **type, __u32 *type_id,
877 			   const struct btf_type **vtype, __u32 *vtype_id,
878 			   const struct btf_member **data_member)
879 {
880 	const struct btf_type *kern_type, *kern_vtype;
881 	const struct btf_member *kern_data_member;
882 	__s32 kern_vtype_id, kern_type_id;
883 	__u32 i;
884 
885 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
886 	if (kern_type_id < 0) {
887 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
888 			tname);
889 		return kern_type_id;
890 	}
891 	kern_type = btf__type_by_id(btf, kern_type_id);
892 
893 	/* Find the corresponding "map_value" type that will be used
894 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
895 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
896 	 * btf_vmlinux.
897 	 */
898 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
899 						tname, BTF_KIND_STRUCT);
900 	if (kern_vtype_id < 0) {
901 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
902 			STRUCT_OPS_VALUE_PREFIX, tname);
903 		return kern_vtype_id;
904 	}
905 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
906 
907 	/* Find "struct tcp_congestion_ops" from
908 	 * struct bpf_struct_ops_tcp_congestion_ops {
909 	 *	[ ... ]
910 	 *	struct tcp_congestion_ops data;
911 	 * }
912 	 */
913 	kern_data_member = btf_members(kern_vtype);
914 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
915 		if (kern_data_member->type == kern_type_id)
916 			break;
917 	}
918 	if (i == btf_vlen(kern_vtype)) {
919 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
920 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
921 		return -EINVAL;
922 	}
923 
924 	*type = kern_type;
925 	*type_id = kern_type_id;
926 	*vtype = kern_vtype;
927 	*vtype_id = kern_vtype_id;
928 	*data_member = kern_data_member;
929 
930 	return 0;
931 }
932 
bpf_map__is_struct_ops(const struct bpf_map * map)933 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
934 {
935 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
936 }
937 
938 /* 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)939 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
940 					 const struct btf *btf,
941 					 const struct btf *kern_btf)
942 {
943 	const struct btf_member *member, *kern_member, *kern_data_member;
944 	const struct btf_type *type, *kern_type, *kern_vtype;
945 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
946 	struct bpf_struct_ops *st_ops;
947 	void *data, *kern_data;
948 	const char *tname;
949 	int err;
950 
951 	st_ops = map->st_ops;
952 	type = st_ops->type;
953 	tname = st_ops->tname;
954 	err = find_struct_ops_kern_types(kern_btf, tname,
955 					 &kern_type, &kern_type_id,
956 					 &kern_vtype, &kern_vtype_id,
957 					 &kern_data_member);
958 	if (err)
959 		return err;
960 
961 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
962 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
963 
964 	map->def.value_size = kern_vtype->size;
965 	map->btf_vmlinux_value_type_id = kern_vtype_id;
966 
967 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
968 	if (!st_ops->kern_vdata)
969 		return -ENOMEM;
970 
971 	data = st_ops->data;
972 	kern_data_off = kern_data_member->offset / 8;
973 	kern_data = st_ops->kern_vdata + kern_data_off;
974 
975 	member = btf_members(type);
976 	for (i = 0; i < btf_vlen(type); i++, member++) {
977 		const struct btf_type *mtype, *kern_mtype;
978 		__u32 mtype_id, kern_mtype_id;
979 		void *mdata, *kern_mdata;
980 		__s64 msize, kern_msize;
981 		__u32 moff, kern_moff;
982 		__u32 kern_member_idx;
983 		const char *mname;
984 
985 		mname = btf__name_by_offset(btf, member->name_off);
986 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
987 		if (!kern_member) {
988 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
989 				map->name, mname);
990 			return -ENOTSUP;
991 		}
992 
993 		kern_member_idx = kern_member - btf_members(kern_type);
994 		if (btf_member_bitfield_size(type, i) ||
995 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
996 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
997 				map->name, mname);
998 			return -ENOTSUP;
999 		}
1000 
1001 		moff = member->offset / 8;
1002 		kern_moff = kern_member->offset / 8;
1003 
1004 		mdata = data + moff;
1005 		kern_mdata = kern_data + kern_moff;
1006 
1007 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1008 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1009 						    &kern_mtype_id);
1010 		if (BTF_INFO_KIND(mtype->info) !=
1011 		    BTF_INFO_KIND(kern_mtype->info)) {
1012 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1013 				map->name, mname, BTF_INFO_KIND(mtype->info),
1014 				BTF_INFO_KIND(kern_mtype->info));
1015 			return -ENOTSUP;
1016 		}
1017 
1018 		if (btf_is_ptr(mtype)) {
1019 			struct bpf_program *prog;
1020 
1021 			prog = st_ops->progs[i];
1022 			if (!prog)
1023 				continue;
1024 
1025 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1026 							    kern_mtype->type,
1027 							    &kern_mtype_id);
1028 
1029 			/* mtype->type must be a func_proto which was
1030 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1031 			 * so only check kern_mtype for func_proto here.
1032 			 */
1033 			if (!btf_is_func_proto(kern_mtype)) {
1034 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1035 					map->name, mname);
1036 				return -ENOTSUP;
1037 			}
1038 
1039 			prog->attach_btf_id = kern_type_id;
1040 			prog->expected_attach_type = kern_member_idx;
1041 
1042 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1043 
1044 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1045 				 map->name, mname, prog->name, moff,
1046 				 kern_moff);
1047 
1048 			continue;
1049 		}
1050 
1051 		msize = btf__resolve_size(btf, mtype_id);
1052 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1053 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1054 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1055 				map->name, mname, (ssize_t)msize,
1056 				(ssize_t)kern_msize);
1057 			return -ENOTSUP;
1058 		}
1059 
1060 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1061 			 map->name, mname, (unsigned int)msize,
1062 			 moff, kern_moff);
1063 		memcpy(kern_mdata, mdata, msize);
1064 	}
1065 
1066 	return 0;
1067 }
1068 
bpf_object__init_kern_struct_ops_maps(struct bpf_object * obj)1069 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1070 {
1071 	struct bpf_map *map;
1072 	size_t i;
1073 	int err;
1074 
1075 	for (i = 0; i < obj->nr_maps; i++) {
1076 		map = &obj->maps[i];
1077 
1078 		if (!bpf_map__is_struct_ops(map))
1079 			continue;
1080 
1081 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1082 						    obj->btf_vmlinux);
1083 		if (err)
1084 			return err;
1085 	}
1086 
1087 	return 0;
1088 }
1089 
bpf_object__init_struct_ops_maps(struct bpf_object * obj)1090 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1091 {
1092 	const struct btf_type *type, *datasec;
1093 	const struct btf_var_secinfo *vsi;
1094 	struct bpf_struct_ops *st_ops;
1095 	const char *tname, *var_name;
1096 	__s32 type_id, datasec_id;
1097 	const struct btf *btf;
1098 	struct bpf_map *map;
1099 	__u32 i;
1100 
1101 	if (obj->efile.st_ops_shndx == -1)
1102 		return 0;
1103 
1104 	btf = obj->btf;
1105 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1106 					    BTF_KIND_DATASEC);
1107 	if (datasec_id < 0) {
1108 		pr_warn("struct_ops init: DATASEC %s not found\n",
1109 			STRUCT_OPS_SEC);
1110 		return -EINVAL;
1111 	}
1112 
1113 	datasec = btf__type_by_id(btf, datasec_id);
1114 	vsi = btf_var_secinfos(datasec);
1115 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1116 		type = btf__type_by_id(obj->btf, vsi->type);
1117 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1118 
1119 		type_id = btf__resolve_type(obj->btf, vsi->type);
1120 		if (type_id < 0) {
1121 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1122 				vsi->type, STRUCT_OPS_SEC);
1123 			return -EINVAL;
1124 		}
1125 
1126 		type = btf__type_by_id(obj->btf, type_id);
1127 		tname = btf__name_by_offset(obj->btf, type->name_off);
1128 		if (!tname[0]) {
1129 			pr_warn("struct_ops init: anonymous type is not supported\n");
1130 			return -ENOTSUP;
1131 		}
1132 		if (!btf_is_struct(type)) {
1133 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1134 			return -EINVAL;
1135 		}
1136 
1137 		map = bpf_object__add_map(obj);
1138 		if (IS_ERR(map))
1139 			return PTR_ERR(map);
1140 
1141 		map->sec_idx = obj->efile.st_ops_shndx;
1142 		map->sec_offset = vsi->offset;
1143 		map->name = strdup(var_name);
1144 		if (!map->name)
1145 			return -ENOMEM;
1146 
1147 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1148 		map->def.key_size = sizeof(int);
1149 		map->def.value_size = type->size;
1150 		map->def.max_entries = 1;
1151 
1152 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1153 		if (!map->st_ops)
1154 			return -ENOMEM;
1155 		st_ops = map->st_ops;
1156 		st_ops->data = malloc(type->size);
1157 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1158 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1159 					       sizeof(*st_ops->kern_func_off));
1160 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1161 			return -ENOMEM;
1162 
1163 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1164 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1165 				var_name, STRUCT_OPS_SEC);
1166 			return -EINVAL;
1167 		}
1168 
1169 		memcpy(st_ops->data,
1170 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1171 		       type->size);
1172 		st_ops->tname = tname;
1173 		st_ops->type = type;
1174 		st_ops->type_id = type_id;
1175 
1176 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1177 			 tname, type_id, var_name, vsi->offset);
1178 	}
1179 
1180 	return 0;
1181 }
1182 
bpf_object__new(const char * path,const void * obj_buf,size_t obj_buf_sz,const char * obj_name)1183 static struct bpf_object *bpf_object__new(const char *path,
1184 					  const void *obj_buf,
1185 					  size_t obj_buf_sz,
1186 					  const char *obj_name)
1187 {
1188 	bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1189 	struct bpf_object *obj;
1190 	char *end;
1191 
1192 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1193 	if (!obj) {
1194 		pr_warn("alloc memory failed for %s\n", path);
1195 		return ERR_PTR(-ENOMEM);
1196 	}
1197 
1198 	strcpy(obj->path, path);
1199 	if (obj_name) {
1200 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1201 	} else {
1202 		/* Using basename() GNU version which doesn't modify arg. */
1203 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1204 		end = strchr(obj->name, '.');
1205 		if (end)
1206 			*end = 0;
1207 	}
1208 
1209 	obj->efile.fd = -1;
1210 	/*
1211 	 * Caller of this function should also call
1212 	 * bpf_object__elf_finish() after data collection to return
1213 	 * obj_buf to user. If not, we should duplicate the buffer to
1214 	 * avoid user freeing them before elf finish.
1215 	 */
1216 	obj->efile.obj_buf = obj_buf;
1217 	obj->efile.obj_buf_sz = obj_buf_sz;
1218 	obj->efile.maps_shndx = -1;
1219 	obj->efile.btf_maps_shndx = -1;
1220 	obj->efile.st_ops_shndx = -1;
1221 	obj->kconfig_map_idx = -1;
1222 
1223 	obj->kern_version = get_kernel_version();
1224 	obj->loaded = false;
1225 
1226 	INIT_LIST_HEAD(&obj->list);
1227 	if (!strict)
1228 		list_add(&obj->list, &bpf_objects_list);
1229 	return obj;
1230 }
1231 
bpf_object__elf_finish(struct bpf_object * obj)1232 static void bpf_object__elf_finish(struct bpf_object *obj)
1233 {
1234 	if (!obj->efile.elf)
1235 		return;
1236 
1237 	elf_end(obj->efile.elf);
1238 	obj->efile.elf = NULL;
1239 	obj->efile.symbols = NULL;
1240 	obj->efile.st_ops_data = NULL;
1241 
1242 	zfree(&obj->efile.secs);
1243 	obj->efile.sec_cnt = 0;
1244 	zclose(obj->efile.fd);
1245 	obj->efile.obj_buf = NULL;
1246 	obj->efile.obj_buf_sz = 0;
1247 }
1248 
bpf_object__elf_init(struct bpf_object * obj)1249 static int bpf_object__elf_init(struct bpf_object *obj)
1250 {
1251 	Elf64_Ehdr *ehdr;
1252 	int err = 0;
1253 	Elf *elf;
1254 
1255 	if (obj->efile.elf) {
1256 		pr_warn("elf: init internal error\n");
1257 		return -LIBBPF_ERRNO__LIBELF;
1258 	}
1259 
1260 	if (obj->efile.obj_buf_sz > 0) {
1261 		/*
1262 		 * obj_buf should have been validated by
1263 		 * bpf_object__open_buffer().
1264 		 */
1265 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1266 	} else {
1267 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1268 		if (obj->efile.fd < 0) {
1269 			char errmsg[STRERR_BUFSIZE], *cp;
1270 
1271 			err = -errno;
1272 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1273 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1274 			return err;
1275 		}
1276 
1277 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1278 	}
1279 
1280 	if (!elf) {
1281 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1282 		err = -LIBBPF_ERRNO__LIBELF;
1283 		goto errout;
1284 	}
1285 
1286 	obj->efile.elf = elf;
1287 
1288 	if (elf_kind(elf) != ELF_K_ELF) {
1289 		err = -LIBBPF_ERRNO__FORMAT;
1290 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1291 		goto errout;
1292 	}
1293 
1294 	if (gelf_getclass(elf) != ELFCLASS64) {
1295 		err = -LIBBPF_ERRNO__FORMAT;
1296 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1297 		goto errout;
1298 	}
1299 
1300 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1301 	if (!obj->efile.ehdr) {
1302 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1303 		err = -LIBBPF_ERRNO__FORMAT;
1304 		goto errout;
1305 	}
1306 
1307 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1308 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1309 			obj->path, elf_errmsg(-1));
1310 		err = -LIBBPF_ERRNO__FORMAT;
1311 		goto errout;
1312 	}
1313 
1314 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1315 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1316 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1317 			obj->path, elf_errmsg(-1));
1318 		err = -LIBBPF_ERRNO__FORMAT;
1319 		goto errout;
1320 	}
1321 
1322 	/* Old LLVM set e_machine to EM_NONE */
1323 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1324 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1325 		err = -LIBBPF_ERRNO__FORMAT;
1326 		goto errout;
1327 	}
1328 
1329 	return 0;
1330 errout:
1331 	bpf_object__elf_finish(obj);
1332 	return err;
1333 }
1334 
bpf_object__check_endianness(struct bpf_object * obj)1335 static int bpf_object__check_endianness(struct bpf_object *obj)
1336 {
1337 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1338 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1339 		return 0;
1340 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1341 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1342 		return 0;
1343 #else
1344 # error "Unrecognized __BYTE_ORDER__"
1345 #endif
1346 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1347 	return -LIBBPF_ERRNO__ENDIAN;
1348 }
1349 
1350 static int
bpf_object__init_license(struct bpf_object * obj,void * data,size_t size)1351 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1352 {
1353 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1354 	 * go over allowed ELF data section buffer
1355 	 */
1356 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1357 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1358 	return 0;
1359 }
1360 
1361 static int
bpf_object__init_kversion(struct bpf_object * obj,void * data,size_t size)1362 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1363 {
1364 	__u32 kver;
1365 
1366 	if (size != sizeof(kver)) {
1367 		pr_warn("invalid kver section in %s\n", obj->path);
1368 		return -LIBBPF_ERRNO__FORMAT;
1369 	}
1370 	memcpy(&kver, data, sizeof(kver));
1371 	obj->kern_version = kver;
1372 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1373 	return 0;
1374 }
1375 
bpf_map_type__is_map_in_map(enum bpf_map_type type)1376 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1377 {
1378 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1379 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1380 		return true;
1381 	return false;
1382 }
1383 
find_elf_sec_sz(const struct bpf_object * obj,const char * name,__u32 * size)1384 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1385 {
1386 	Elf_Data *data;
1387 	Elf_Scn *scn;
1388 
1389 	if (!name)
1390 		return -EINVAL;
1391 
1392 	scn = elf_sec_by_name(obj, name);
1393 	data = elf_sec_data(obj, scn);
1394 	if (data) {
1395 		*size = data->d_size;
1396 		return 0; /* found it */
1397 	}
1398 
1399 	return -ENOENT;
1400 }
1401 
find_elf_var_offset(const struct bpf_object * obj,const char * name,__u32 * off)1402 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1403 {
1404 	Elf_Data *symbols = obj->efile.symbols;
1405 	const char *sname;
1406 	size_t si;
1407 
1408 	if (!name || !off)
1409 		return -EINVAL;
1410 
1411 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1412 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1413 
1414 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1415 			continue;
1416 
1417 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1418 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1419 			continue;
1420 
1421 		sname = elf_sym_str(obj, sym->st_name);
1422 		if (!sname) {
1423 			pr_warn("failed to get sym name string for var %s\n", name);
1424 			return -EIO;
1425 		}
1426 		if (strcmp(name, sname) == 0) {
1427 			*off = sym->st_value;
1428 			return 0;
1429 		}
1430 	}
1431 
1432 	return -ENOENT;
1433 }
1434 
bpf_object__add_map(struct bpf_object * obj)1435 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1436 {
1437 	struct bpf_map *map;
1438 	int err;
1439 
1440 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1441 				sizeof(*obj->maps), obj->nr_maps + 1);
1442 	if (err)
1443 		return ERR_PTR(err);
1444 
1445 	map = &obj->maps[obj->nr_maps++];
1446 	map->obj = obj;
1447 	map->fd = -1;
1448 	map->inner_map_fd = -1;
1449 	map->autocreate = true;
1450 
1451 	return map;
1452 }
1453 
bpf_map_mmap_sz(const struct bpf_map * map)1454 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1455 {
1456 	long page_sz = sysconf(_SC_PAGE_SIZE);
1457 	size_t map_sz;
1458 
1459 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1460 	map_sz = roundup(map_sz, page_sz);
1461 	return map_sz;
1462 }
1463 
internal_map_name(struct bpf_object * obj,const char * real_name)1464 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1465 {
1466 	char map_name[BPF_OBJ_NAME_LEN], *p;
1467 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1468 
1469 	/* This is one of the more confusing parts of libbpf for various
1470 	 * reasons, some of which are historical. The original idea for naming
1471 	 * internal names was to include as much of BPF object name prefix as
1472 	 * possible, so that it can be distinguished from similar internal
1473 	 * maps of a different BPF object.
1474 	 * As an example, let's say we have bpf_object named 'my_object_name'
1475 	 * and internal map corresponding to '.rodata' ELF section. The final
1476 	 * map name advertised to user and to the kernel will be
1477 	 * 'my_objec.rodata', taking first 8 characters of object name and
1478 	 * entire 7 characters of '.rodata'.
1479 	 * Somewhat confusingly, if internal map ELF section name is shorter
1480 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1481 	 * for the suffix, even though we only have 4 actual characters, and
1482 	 * resulting map will be called 'my_objec.bss', not even using all 15
1483 	 * characters allowed by the kernel. Oh well, at least the truncated
1484 	 * object name is somewhat consistent in this case. But if the map
1485 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1486 	 * (8 chars) and thus will be left with only first 7 characters of the
1487 	 * object name ('my_obje'). Happy guessing, user, that the final map
1488 	 * name will be "my_obje.kconfig".
1489 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1490 	 * and .data.* data sections, it's possible that ELF section name is
1491 	 * longer than allowed 15 chars, so we now need to be careful to take
1492 	 * only up to 15 first characters of ELF name, taking no BPF object
1493 	 * name characters at all. So '.rodata.abracadabra' will result in
1494 	 * '.rodata.abracad' kernel and user-visible name.
1495 	 * We need to keep this convoluted logic intact for .data, .bss and
1496 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1497 	 * maps we use their ELF names as is, not prepending bpf_object name
1498 	 * in front. We still need to truncate them to 15 characters for the
1499 	 * kernel. Full name can be recovered for such maps by using DATASEC
1500 	 * BTF type associated with such map's value type, though.
1501 	 */
1502 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1503 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1504 
1505 	/* if there are two or more dots in map name, it's a custom dot map */
1506 	if (strchr(real_name + 1, '.') != NULL)
1507 		pfx_len = 0;
1508 	else
1509 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1510 
1511 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1512 		 sfx_len, real_name);
1513 
1514 	/* sanitise map name to characters allowed by kernel */
1515 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1516 		if (!isalnum(*p) && *p != '_' && *p != '.')
1517 			*p = '_';
1518 
1519 	return strdup(map_name);
1520 }
1521 
1522 static int
1523 bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1524 
1525 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)1526 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1527 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1528 {
1529 	struct bpf_map_def *def;
1530 	struct bpf_map *map;
1531 	int err;
1532 
1533 	map = bpf_object__add_map(obj);
1534 	if (IS_ERR(map))
1535 		return PTR_ERR(map);
1536 
1537 	map->libbpf_type = type;
1538 	map->sec_idx = sec_idx;
1539 	map->sec_offset = 0;
1540 	map->real_name = strdup(real_name);
1541 	map->name = internal_map_name(obj, real_name);
1542 	if (!map->real_name || !map->name) {
1543 		zfree(&map->real_name);
1544 		zfree(&map->name);
1545 		return -ENOMEM;
1546 	}
1547 
1548 	def = &map->def;
1549 	def->type = BPF_MAP_TYPE_ARRAY;
1550 	def->key_size = sizeof(int);
1551 	def->value_size = data_sz;
1552 	def->max_entries = 1;
1553 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1554 			 ? BPF_F_RDONLY_PROG : 0;
1555 	def->map_flags |= BPF_F_MMAPABLE;
1556 
1557 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1558 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1559 
1560 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1561 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1562 	if (map->mmaped == MAP_FAILED) {
1563 		err = -errno;
1564 		map->mmaped = NULL;
1565 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1566 			map->name, err);
1567 		zfree(&map->real_name);
1568 		zfree(&map->name);
1569 		return err;
1570 	}
1571 
1572 	/* failures are fine because of maps like .rodata.str1.1 */
1573 	(void) bpf_map_find_btf_info(obj, map);
1574 
1575 	if (data)
1576 		memcpy(map->mmaped, data, data_sz);
1577 
1578 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1579 	return 0;
1580 }
1581 
bpf_object__init_global_data_maps(struct bpf_object * obj)1582 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1583 {
1584 	struct elf_sec_desc *sec_desc;
1585 	const char *sec_name;
1586 	int err = 0, sec_idx;
1587 
1588 	/*
1589 	 * Populate obj->maps with libbpf internal maps.
1590 	 */
1591 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1592 		sec_desc = &obj->efile.secs[sec_idx];
1593 
1594 		switch (sec_desc->sec_type) {
1595 		case SEC_DATA:
1596 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1597 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1598 							    sec_name, sec_idx,
1599 							    sec_desc->data->d_buf,
1600 							    sec_desc->data->d_size);
1601 			break;
1602 		case SEC_RODATA:
1603 			obj->has_rodata = true;
1604 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1605 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1606 							    sec_name, sec_idx,
1607 							    sec_desc->data->d_buf,
1608 							    sec_desc->data->d_size);
1609 			break;
1610 		case SEC_BSS:
1611 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1612 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1613 							    sec_name, sec_idx,
1614 							    NULL,
1615 							    sec_desc->data->d_size);
1616 			break;
1617 		default:
1618 			/* skip */
1619 			break;
1620 		}
1621 		if (err)
1622 			return err;
1623 	}
1624 	return 0;
1625 }
1626 
1627 
find_extern_by_name(const struct bpf_object * obj,const void * name)1628 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1629 					       const void *name)
1630 {
1631 	int i;
1632 
1633 	for (i = 0; i < obj->nr_extern; i++) {
1634 		if (strcmp(obj->externs[i].name, name) == 0)
1635 			return &obj->externs[i];
1636 	}
1637 	return NULL;
1638 }
1639 
set_kcfg_value_tri(struct extern_desc * ext,void * ext_val,char value)1640 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1641 			      char value)
1642 {
1643 	switch (ext->kcfg.type) {
1644 	case KCFG_BOOL:
1645 		if (value == 'm') {
1646 			pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1647 				ext->name, value);
1648 			return -EINVAL;
1649 		}
1650 		*(bool *)ext_val = value == 'y' ? true : false;
1651 		break;
1652 	case KCFG_TRISTATE:
1653 		if (value == 'y')
1654 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1655 		else if (value == 'm')
1656 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1657 		else /* value == 'n' */
1658 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1659 		break;
1660 	case KCFG_CHAR:
1661 		*(char *)ext_val = value;
1662 		break;
1663 	case KCFG_UNKNOWN:
1664 	case KCFG_INT:
1665 	case KCFG_CHAR_ARR:
1666 	default:
1667 		pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1668 			ext->name, value);
1669 		return -EINVAL;
1670 	}
1671 	ext->is_set = true;
1672 	return 0;
1673 }
1674 
set_kcfg_value_str(struct extern_desc * ext,char * ext_val,const char * value)1675 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1676 			      const char *value)
1677 {
1678 	size_t len;
1679 
1680 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1681 		pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1682 		return -EINVAL;
1683 	}
1684 
1685 	len = strlen(value);
1686 	if (value[len - 1] != '"') {
1687 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1688 			ext->name, value);
1689 		return -EINVAL;
1690 	}
1691 
1692 	/* strip quotes */
1693 	len -= 2;
1694 	if (len >= ext->kcfg.sz) {
1695 		pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1696 			ext->name, value, len, ext->kcfg.sz - 1);
1697 		len = ext->kcfg.sz - 1;
1698 	}
1699 	memcpy(ext_val, value + 1, len);
1700 	ext_val[len] = '\0';
1701 	ext->is_set = true;
1702 	return 0;
1703 }
1704 
parse_u64(const char * value,__u64 * res)1705 static int parse_u64(const char *value, __u64 *res)
1706 {
1707 	char *value_end;
1708 	int err;
1709 
1710 	errno = 0;
1711 	*res = strtoull(value, &value_end, 0);
1712 	if (errno) {
1713 		err = -errno;
1714 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1715 		return err;
1716 	}
1717 	if (*value_end) {
1718 		pr_warn("failed to parse '%s' as integer completely\n", value);
1719 		return -EINVAL;
1720 	}
1721 	return 0;
1722 }
1723 
is_kcfg_value_in_range(const struct extern_desc * ext,__u64 v)1724 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1725 {
1726 	int bit_sz = ext->kcfg.sz * 8;
1727 
1728 	if (ext->kcfg.sz == 8)
1729 		return true;
1730 
1731 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1732 	 * bytes size without any loss of information. If the target integer
1733 	 * is signed, we rely on the following limits of integer type of
1734 	 * Y bits and subsequent transformation:
1735 	 *
1736 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1737 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1738 	 *            0 <= X + 2^(Y-1) <  2^Y
1739 	 *
1740 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1741 	 *  zero.
1742 	 */
1743 	if (ext->kcfg.is_signed)
1744 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1745 	else
1746 		return (v >> bit_sz) == 0;
1747 }
1748 
set_kcfg_value_num(struct extern_desc * ext,void * ext_val,__u64 value)1749 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1750 			      __u64 value)
1751 {
1752 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1753 		pr_warn("extern (kcfg) %s=%llu should be integer\n",
1754 			ext->name, (unsigned long long)value);
1755 		return -EINVAL;
1756 	}
1757 	if (!is_kcfg_value_in_range(ext, value)) {
1758 		pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1759 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1760 		return -ERANGE;
1761 	}
1762 	switch (ext->kcfg.sz) {
1763 		case 1: *(__u8 *)ext_val = value; break;
1764 		case 2: *(__u16 *)ext_val = value; break;
1765 		case 4: *(__u32 *)ext_val = value; break;
1766 		case 8: *(__u64 *)ext_val = value; break;
1767 		default:
1768 			return -EINVAL;
1769 	}
1770 	ext->is_set = true;
1771 	return 0;
1772 }
1773 
bpf_object__process_kconfig_line(struct bpf_object * obj,char * buf,void * data)1774 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1775 					    char *buf, void *data)
1776 {
1777 	struct extern_desc *ext;
1778 	char *sep, *value;
1779 	int len, err = 0;
1780 	void *ext_val;
1781 	__u64 num;
1782 
1783 	if (!str_has_pfx(buf, "CONFIG_"))
1784 		return 0;
1785 
1786 	sep = strchr(buf, '=');
1787 	if (!sep) {
1788 		pr_warn("failed to parse '%s': no separator\n", buf);
1789 		return -EINVAL;
1790 	}
1791 
1792 	/* Trim ending '\n' */
1793 	len = strlen(buf);
1794 	if (buf[len - 1] == '\n')
1795 		buf[len - 1] = '\0';
1796 	/* Split on '=' and ensure that a value is present. */
1797 	*sep = '\0';
1798 	if (!sep[1]) {
1799 		*sep = '=';
1800 		pr_warn("failed to parse '%s': no value\n", buf);
1801 		return -EINVAL;
1802 	}
1803 
1804 	ext = find_extern_by_name(obj, buf);
1805 	if (!ext || ext->is_set)
1806 		return 0;
1807 
1808 	ext_val = data + ext->kcfg.data_off;
1809 	value = sep + 1;
1810 
1811 	switch (*value) {
1812 	case 'y': case 'n': case 'm':
1813 		err = set_kcfg_value_tri(ext, ext_val, *value);
1814 		break;
1815 	case '"':
1816 		err = set_kcfg_value_str(ext, ext_val, value);
1817 		break;
1818 	default:
1819 		/* assume integer */
1820 		err = parse_u64(value, &num);
1821 		if (err) {
1822 			pr_warn("extern (kcfg) %s=%s should be integer\n",
1823 				ext->name, value);
1824 			return err;
1825 		}
1826 		err = set_kcfg_value_num(ext, ext_val, num);
1827 		break;
1828 	}
1829 	if (err)
1830 		return err;
1831 	pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1832 	return 0;
1833 }
1834 
bpf_object__read_kconfig_file(struct bpf_object * obj,void * data)1835 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1836 {
1837 	char buf[PATH_MAX];
1838 	struct utsname uts;
1839 	int len, err = 0;
1840 	gzFile file;
1841 
1842 	uname(&uts);
1843 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1844 	if (len < 0)
1845 		return -EINVAL;
1846 	else if (len >= PATH_MAX)
1847 		return -ENAMETOOLONG;
1848 
1849 	/* gzopen also accepts uncompressed files. */
1850 	file = gzopen(buf, "r");
1851 	if (!file)
1852 		file = gzopen("/proc/config.gz", "r");
1853 
1854 	if (!file) {
1855 		pr_warn("failed to open system Kconfig\n");
1856 		return -ENOENT;
1857 	}
1858 
1859 	while (gzgets(file, buf, sizeof(buf))) {
1860 		err = bpf_object__process_kconfig_line(obj, buf, data);
1861 		if (err) {
1862 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1863 				buf, err);
1864 			goto out;
1865 		}
1866 	}
1867 
1868 out:
1869 	gzclose(file);
1870 	return err;
1871 }
1872 
bpf_object__read_kconfig_mem(struct bpf_object * obj,const char * config,void * data)1873 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1874 					const char *config, void *data)
1875 {
1876 	char buf[PATH_MAX];
1877 	int err = 0;
1878 	FILE *file;
1879 
1880 	file = fmemopen((void *)config, strlen(config), "r");
1881 	if (!file) {
1882 		err = -errno;
1883 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1884 		return err;
1885 	}
1886 
1887 	while (fgets(buf, sizeof(buf), file)) {
1888 		err = bpf_object__process_kconfig_line(obj, buf, data);
1889 		if (err) {
1890 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1891 				buf, err);
1892 			break;
1893 		}
1894 	}
1895 
1896 	fclose(file);
1897 	return err;
1898 }
1899 
bpf_object__init_kconfig_map(struct bpf_object * obj)1900 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1901 {
1902 	struct extern_desc *last_ext = NULL, *ext;
1903 	size_t map_sz;
1904 	int i, err;
1905 
1906 	for (i = 0; i < obj->nr_extern; i++) {
1907 		ext = &obj->externs[i];
1908 		if (ext->type == EXT_KCFG)
1909 			last_ext = ext;
1910 	}
1911 
1912 	if (!last_ext)
1913 		return 0;
1914 
1915 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1916 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1917 					    ".kconfig", obj->efile.symbols_shndx,
1918 					    NULL, map_sz);
1919 	if (err)
1920 		return err;
1921 
1922 	obj->kconfig_map_idx = obj->nr_maps - 1;
1923 
1924 	return 0;
1925 }
1926 
bpf_object__init_user_maps(struct bpf_object * obj,bool strict)1927 static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1928 {
1929 	Elf_Data *symbols = obj->efile.symbols;
1930 	int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1931 	Elf_Data *data = NULL;
1932 	Elf_Scn *scn;
1933 
1934 	if (obj->efile.maps_shndx < 0)
1935 		return 0;
1936 
1937 	if (libbpf_mode & LIBBPF_STRICT_MAP_DEFINITIONS) {
1938 		pr_warn("legacy map definitions in SEC(\"maps\") are not supported\n");
1939 		return -EOPNOTSUPP;
1940 	}
1941 
1942 	if (!symbols)
1943 		return -EINVAL;
1944 
1945 	scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1946 	data = elf_sec_data(obj, scn);
1947 	if (!scn || !data) {
1948 		pr_warn("elf: failed to get legacy map definitions for %s\n",
1949 			obj->path);
1950 		return -EINVAL;
1951 	}
1952 
1953 	/*
1954 	 * Count number of maps. Each map has a name.
1955 	 * Array of maps is not supported: only the first element is
1956 	 * considered.
1957 	 *
1958 	 * TODO: Detect array of map and report error.
1959 	 */
1960 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
1961 	for (i = 0; i < nr_syms; i++) {
1962 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
1963 
1964 		if (sym->st_shndx != obj->efile.maps_shndx)
1965 			continue;
1966 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
1967 			continue;
1968 		nr_maps++;
1969 	}
1970 	/* Assume equally sized map definitions */
1971 	pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1972 		 nr_maps, data->d_size, obj->path);
1973 
1974 	if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1975 		pr_warn("elf: unable to determine legacy map definition size in %s\n",
1976 			obj->path);
1977 		return -EINVAL;
1978 	}
1979 	map_def_sz = data->d_size / nr_maps;
1980 
1981 	/* Fill obj->maps using data in "maps" section.  */
1982 	for (i = 0; i < nr_syms; i++) {
1983 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
1984 		const char *map_name;
1985 		struct bpf_map_def *def;
1986 		struct bpf_map *map;
1987 
1988 		if (sym->st_shndx != obj->efile.maps_shndx)
1989 			continue;
1990 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
1991 			continue;
1992 
1993 		map = bpf_object__add_map(obj);
1994 		if (IS_ERR(map))
1995 			return PTR_ERR(map);
1996 
1997 		map_name = elf_sym_str(obj, sym->st_name);
1998 		if (!map_name) {
1999 			pr_warn("failed to get map #%d name sym string for obj %s\n",
2000 				i, obj->path);
2001 			return -LIBBPF_ERRNO__FORMAT;
2002 		}
2003 
2004 		pr_warn("map '%s' (legacy): legacy map definitions are deprecated, use BTF-defined maps instead\n", map_name);
2005 
2006 		if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
2007 			pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2008 			return -ENOTSUP;
2009 		}
2010 
2011 		map->libbpf_type = LIBBPF_MAP_UNSPEC;
2012 		map->sec_idx = sym->st_shndx;
2013 		map->sec_offset = sym->st_value;
2014 		pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2015 			 map_name, map->sec_idx, map->sec_offset);
2016 		if (sym->st_value + map_def_sz > data->d_size) {
2017 			pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2018 				obj->path, map_name);
2019 			return -EINVAL;
2020 		}
2021 
2022 		map->name = strdup(map_name);
2023 		if (!map->name) {
2024 			pr_warn("map '%s': failed to alloc map name\n", map_name);
2025 			return -ENOMEM;
2026 		}
2027 		pr_debug("map %d is \"%s\"\n", i, map->name);
2028 		def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
2029 		/*
2030 		 * If the definition of the map in the object file fits in
2031 		 * bpf_map_def, copy it.  Any extra fields in our version
2032 		 * of bpf_map_def will default to zero as a result of the
2033 		 * calloc above.
2034 		 */
2035 		if (map_def_sz <= sizeof(struct bpf_map_def)) {
2036 			memcpy(&map->def, def, map_def_sz);
2037 		} else {
2038 			/*
2039 			 * Here the map structure being read is bigger than what
2040 			 * we expect, truncate if the excess bits are all zero.
2041 			 * If they are not zero, reject this map as
2042 			 * incompatible.
2043 			 */
2044 			char *b;
2045 
2046 			for (b = ((char *)def) + sizeof(struct bpf_map_def);
2047 			     b < ((char *)def) + map_def_sz; b++) {
2048 				if (*b != 0) {
2049 					pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
2050 						obj->path, map_name);
2051 					if (strict)
2052 						return -EINVAL;
2053 				}
2054 			}
2055 			memcpy(&map->def, def, sizeof(struct bpf_map_def));
2056 		}
2057 
2058 		/* btf info may not exist but fill it in if it does exist */
2059 		(void) bpf_map_find_btf_info(obj, map);
2060 	}
2061 	return 0;
2062 }
2063 
2064 const struct btf_type *
skip_mods_and_typedefs(const struct btf * btf,__u32 id,__u32 * res_id)2065 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2066 {
2067 	const struct btf_type *t = btf__type_by_id(btf, id);
2068 
2069 	if (res_id)
2070 		*res_id = id;
2071 
2072 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2073 		if (res_id)
2074 			*res_id = t->type;
2075 		t = btf__type_by_id(btf, t->type);
2076 	}
2077 
2078 	return t;
2079 }
2080 
2081 static const struct btf_type *
resolve_func_ptr(const struct btf * btf,__u32 id,__u32 * res_id)2082 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2083 {
2084 	const struct btf_type *t;
2085 
2086 	t = skip_mods_and_typedefs(btf, id, NULL);
2087 	if (!btf_is_ptr(t))
2088 		return NULL;
2089 
2090 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2091 
2092 	return btf_is_func_proto(t) ? t : NULL;
2093 }
2094 
__btf_kind_str(__u16 kind)2095 static const char *__btf_kind_str(__u16 kind)
2096 {
2097 	switch (kind) {
2098 	case BTF_KIND_UNKN: return "void";
2099 	case BTF_KIND_INT: return "int";
2100 	case BTF_KIND_PTR: return "ptr";
2101 	case BTF_KIND_ARRAY: return "array";
2102 	case BTF_KIND_STRUCT: return "struct";
2103 	case BTF_KIND_UNION: return "union";
2104 	case BTF_KIND_ENUM: return "enum";
2105 	case BTF_KIND_FWD: return "fwd";
2106 	case BTF_KIND_TYPEDEF: return "typedef";
2107 	case BTF_KIND_VOLATILE: return "volatile";
2108 	case BTF_KIND_CONST: return "const";
2109 	case BTF_KIND_RESTRICT: return "restrict";
2110 	case BTF_KIND_FUNC: return "func";
2111 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2112 	case BTF_KIND_VAR: return "var";
2113 	case BTF_KIND_DATASEC: return "datasec";
2114 	case BTF_KIND_FLOAT: return "float";
2115 	case BTF_KIND_DECL_TAG: return "decl_tag";
2116 	case BTF_KIND_TYPE_TAG: return "type_tag";
2117 	default: return "unknown";
2118 	}
2119 }
2120 
btf_kind_str(const struct btf_type * t)2121 const char *btf_kind_str(const struct btf_type *t)
2122 {
2123 	return __btf_kind_str(btf_kind(t));
2124 }
2125 
2126 /*
2127  * Fetch integer attribute of BTF map definition. Such attributes are
2128  * represented using a pointer to an array, in which dimensionality of array
2129  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2130  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2131  * type definition, while using only sizeof(void *) space in ELF data section.
2132  */
get_map_field_int(const char * map_name,const struct btf * btf,const struct btf_member * m,__u32 * res)2133 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2134 			      const struct btf_member *m, __u32 *res)
2135 {
2136 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2137 	const char *name = btf__name_by_offset(btf, m->name_off);
2138 	const struct btf_array *arr_info;
2139 	const struct btf_type *arr_t;
2140 
2141 	if (!btf_is_ptr(t)) {
2142 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2143 			map_name, name, btf_kind_str(t));
2144 		return false;
2145 	}
2146 
2147 	arr_t = btf__type_by_id(btf, t->type);
2148 	if (!arr_t) {
2149 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2150 			map_name, name, t->type);
2151 		return false;
2152 	}
2153 	if (!btf_is_array(arr_t)) {
2154 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2155 			map_name, name, btf_kind_str(arr_t));
2156 		return false;
2157 	}
2158 	arr_info = btf_array(arr_t);
2159 	*res = arr_info->nelems;
2160 	return true;
2161 }
2162 
build_map_pin_path(struct bpf_map * map,const char * path)2163 static int build_map_pin_path(struct bpf_map *map, const char *path)
2164 {
2165 	char buf[PATH_MAX];
2166 	int len;
2167 
2168 	if (!path)
2169 		path = "/sys/fs/bpf";
2170 
2171 	len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2172 	if (len < 0)
2173 		return -EINVAL;
2174 	else if (len >= PATH_MAX)
2175 		return -ENAMETOOLONG;
2176 
2177 	return bpf_map__set_pin_path(map, buf);
2178 }
2179 
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)2180 int parse_btf_map_def(const char *map_name, struct btf *btf,
2181 		      const struct btf_type *def_t, bool strict,
2182 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2183 {
2184 	const struct btf_type *t;
2185 	const struct btf_member *m;
2186 	bool is_inner = inner_def == NULL;
2187 	int vlen, i;
2188 
2189 	vlen = btf_vlen(def_t);
2190 	m = btf_members(def_t);
2191 	for (i = 0; i < vlen; i++, m++) {
2192 		const char *name = btf__name_by_offset(btf, m->name_off);
2193 
2194 		if (!name) {
2195 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2196 			return -EINVAL;
2197 		}
2198 		if (strcmp(name, "type") == 0) {
2199 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2200 				return -EINVAL;
2201 			map_def->parts |= MAP_DEF_MAP_TYPE;
2202 		} else if (strcmp(name, "max_entries") == 0) {
2203 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2204 				return -EINVAL;
2205 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2206 		} else if (strcmp(name, "map_flags") == 0) {
2207 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2208 				return -EINVAL;
2209 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2210 		} else if (strcmp(name, "numa_node") == 0) {
2211 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2212 				return -EINVAL;
2213 			map_def->parts |= MAP_DEF_NUMA_NODE;
2214 		} else if (strcmp(name, "key_size") == 0) {
2215 			__u32 sz;
2216 
2217 			if (!get_map_field_int(map_name, btf, m, &sz))
2218 				return -EINVAL;
2219 			if (map_def->key_size && map_def->key_size != sz) {
2220 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2221 					map_name, map_def->key_size, sz);
2222 				return -EINVAL;
2223 			}
2224 			map_def->key_size = sz;
2225 			map_def->parts |= MAP_DEF_KEY_SIZE;
2226 		} else if (strcmp(name, "key") == 0) {
2227 			__s64 sz;
2228 
2229 			t = btf__type_by_id(btf, m->type);
2230 			if (!t) {
2231 				pr_warn("map '%s': key type [%d] not found.\n",
2232 					map_name, m->type);
2233 				return -EINVAL;
2234 			}
2235 			if (!btf_is_ptr(t)) {
2236 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2237 					map_name, btf_kind_str(t));
2238 				return -EINVAL;
2239 			}
2240 			sz = btf__resolve_size(btf, t->type);
2241 			if (sz < 0) {
2242 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2243 					map_name, t->type, (ssize_t)sz);
2244 				return sz;
2245 			}
2246 			if (map_def->key_size && map_def->key_size != sz) {
2247 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2248 					map_name, map_def->key_size, (ssize_t)sz);
2249 				return -EINVAL;
2250 			}
2251 			map_def->key_size = sz;
2252 			map_def->key_type_id = t->type;
2253 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2254 		} else if (strcmp(name, "value_size") == 0) {
2255 			__u32 sz;
2256 
2257 			if (!get_map_field_int(map_name, btf, m, &sz))
2258 				return -EINVAL;
2259 			if (map_def->value_size && map_def->value_size != sz) {
2260 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2261 					map_name, map_def->value_size, sz);
2262 				return -EINVAL;
2263 			}
2264 			map_def->value_size = sz;
2265 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2266 		} else if (strcmp(name, "value") == 0) {
2267 			__s64 sz;
2268 
2269 			t = btf__type_by_id(btf, m->type);
2270 			if (!t) {
2271 				pr_warn("map '%s': value type [%d] not found.\n",
2272 					map_name, m->type);
2273 				return -EINVAL;
2274 			}
2275 			if (!btf_is_ptr(t)) {
2276 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2277 					map_name, btf_kind_str(t));
2278 				return -EINVAL;
2279 			}
2280 			sz = btf__resolve_size(btf, t->type);
2281 			if (sz < 0) {
2282 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2283 					map_name, t->type, (ssize_t)sz);
2284 				return sz;
2285 			}
2286 			if (map_def->value_size && map_def->value_size != sz) {
2287 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2288 					map_name, map_def->value_size, (ssize_t)sz);
2289 				return -EINVAL;
2290 			}
2291 			map_def->value_size = sz;
2292 			map_def->value_type_id = t->type;
2293 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2294 		}
2295 		else if (strcmp(name, "values") == 0) {
2296 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2297 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2298 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2299 			char inner_map_name[128];
2300 			int err;
2301 
2302 			if (is_inner) {
2303 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2304 					map_name);
2305 				return -ENOTSUP;
2306 			}
2307 			if (i != vlen - 1) {
2308 				pr_warn("map '%s': '%s' member should be last.\n",
2309 					map_name, name);
2310 				return -EINVAL;
2311 			}
2312 			if (!is_map_in_map && !is_prog_array) {
2313 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2314 					map_name);
2315 				return -ENOTSUP;
2316 			}
2317 			if (map_def->value_size && map_def->value_size != 4) {
2318 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2319 					map_name, map_def->value_size);
2320 				return -EINVAL;
2321 			}
2322 			map_def->value_size = 4;
2323 			t = btf__type_by_id(btf, m->type);
2324 			if (!t) {
2325 				pr_warn("map '%s': %s type [%d] not found.\n",
2326 					map_name, desc, m->type);
2327 				return -EINVAL;
2328 			}
2329 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2330 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2331 					map_name, desc);
2332 				return -EINVAL;
2333 			}
2334 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2335 			if (!btf_is_ptr(t)) {
2336 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2337 					map_name, desc, btf_kind_str(t));
2338 				return -EINVAL;
2339 			}
2340 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2341 			if (is_prog_array) {
2342 				if (!btf_is_func_proto(t)) {
2343 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2344 						map_name, btf_kind_str(t));
2345 					return -EINVAL;
2346 				}
2347 				continue;
2348 			}
2349 			if (!btf_is_struct(t)) {
2350 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2351 					map_name, btf_kind_str(t));
2352 				return -EINVAL;
2353 			}
2354 
2355 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2356 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2357 			if (err)
2358 				return err;
2359 
2360 			map_def->parts |= MAP_DEF_INNER_MAP;
2361 		} else if (strcmp(name, "pinning") == 0) {
2362 			__u32 val;
2363 
2364 			if (is_inner) {
2365 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2366 				return -EINVAL;
2367 			}
2368 			if (!get_map_field_int(map_name, btf, m, &val))
2369 				return -EINVAL;
2370 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2371 				pr_warn("map '%s': invalid pinning value %u.\n",
2372 					map_name, val);
2373 				return -EINVAL;
2374 			}
2375 			map_def->pinning = val;
2376 			map_def->parts |= MAP_DEF_PINNING;
2377 		} else if (strcmp(name, "map_extra") == 0) {
2378 			__u32 map_extra;
2379 
2380 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2381 				return -EINVAL;
2382 			map_def->map_extra = map_extra;
2383 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2384 		} else {
2385 			if (strict) {
2386 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2387 				return -ENOTSUP;
2388 			}
2389 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2390 		}
2391 	}
2392 
2393 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2394 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2395 		return -EINVAL;
2396 	}
2397 
2398 	return 0;
2399 }
2400 
adjust_ringbuf_sz(size_t sz)2401 static size_t adjust_ringbuf_sz(size_t sz)
2402 {
2403 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2404 	__u32 mul;
2405 
2406 	/* if user forgot to set any size, make sure they see error */
2407 	if (sz == 0)
2408 		return 0;
2409 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2410 	 * a power-of-2 multiple of kernel's page size. If user diligently
2411 	 * satisified these conditions, pass the size through.
2412 	 */
2413 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2414 		return sz;
2415 
2416 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2417 	 * user-set size to satisfy both user size request and kernel
2418 	 * requirements and substitute correct max_entries for map creation.
2419 	 */
2420 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2421 		if (mul * page_sz > sz)
2422 			return mul * page_sz;
2423 	}
2424 
2425 	/* if it's impossible to satisfy the conditions (i.e., user size is
2426 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2427 	 * page_size) then just return original size and let kernel reject it
2428 	 */
2429 	return sz;
2430 }
2431 
fill_map_from_def(struct bpf_map * map,const struct btf_map_def * def)2432 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2433 {
2434 	map->def.type = def->map_type;
2435 	map->def.key_size = def->key_size;
2436 	map->def.value_size = def->value_size;
2437 	map->def.max_entries = def->max_entries;
2438 	map->def.map_flags = def->map_flags;
2439 	map->map_extra = def->map_extra;
2440 
2441 	map->numa_node = def->numa_node;
2442 	map->btf_key_type_id = def->key_type_id;
2443 	map->btf_value_type_id = def->value_type_id;
2444 
2445 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2446 	if (map->def.type == BPF_MAP_TYPE_RINGBUF)
2447 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2448 
2449 	if (def->parts & MAP_DEF_MAP_TYPE)
2450 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2451 
2452 	if (def->parts & MAP_DEF_KEY_TYPE)
2453 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2454 			 map->name, def->key_type_id, def->key_size);
2455 	else if (def->parts & MAP_DEF_KEY_SIZE)
2456 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2457 
2458 	if (def->parts & MAP_DEF_VALUE_TYPE)
2459 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2460 			 map->name, def->value_type_id, def->value_size);
2461 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2462 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2463 
2464 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2465 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2466 	if (def->parts & MAP_DEF_MAP_FLAGS)
2467 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2468 	if (def->parts & MAP_DEF_MAP_EXTRA)
2469 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2470 			 (unsigned long long)def->map_extra);
2471 	if (def->parts & MAP_DEF_PINNING)
2472 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2473 	if (def->parts & MAP_DEF_NUMA_NODE)
2474 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2475 
2476 	if (def->parts & MAP_DEF_INNER_MAP)
2477 		pr_debug("map '%s': found inner map definition.\n", map->name);
2478 }
2479 
btf_var_linkage_str(__u32 linkage)2480 static const char *btf_var_linkage_str(__u32 linkage)
2481 {
2482 	switch (linkage) {
2483 	case BTF_VAR_STATIC: return "static";
2484 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2485 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2486 	default: return "unknown";
2487 	}
2488 }
2489 
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)2490 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2491 					 const struct btf_type *sec,
2492 					 int var_idx, int sec_idx,
2493 					 const Elf_Data *data, bool strict,
2494 					 const char *pin_root_path)
2495 {
2496 	struct btf_map_def map_def = {}, inner_def = {};
2497 	const struct btf_type *var, *def;
2498 	const struct btf_var_secinfo *vi;
2499 	const struct btf_var *var_extra;
2500 	const char *map_name;
2501 	struct bpf_map *map;
2502 	int err;
2503 
2504 	vi = btf_var_secinfos(sec) + var_idx;
2505 	var = btf__type_by_id(obj->btf, vi->type);
2506 	var_extra = btf_var(var);
2507 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2508 
2509 	if (map_name == NULL || map_name[0] == '\0') {
2510 		pr_warn("map #%d: empty name.\n", var_idx);
2511 		return -EINVAL;
2512 	}
2513 	if ((__u64)vi->offset + vi->size > data->d_size) {
2514 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2515 		return -EINVAL;
2516 	}
2517 	if (!btf_is_var(var)) {
2518 		pr_warn("map '%s': unexpected var kind %s.\n",
2519 			map_name, btf_kind_str(var));
2520 		return -EINVAL;
2521 	}
2522 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2523 		pr_warn("map '%s': unsupported map linkage %s.\n",
2524 			map_name, btf_var_linkage_str(var_extra->linkage));
2525 		return -EOPNOTSUPP;
2526 	}
2527 
2528 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2529 	if (!btf_is_struct(def)) {
2530 		pr_warn("map '%s': unexpected def kind %s.\n",
2531 			map_name, btf_kind_str(var));
2532 		return -EINVAL;
2533 	}
2534 	if (def->size > vi->size) {
2535 		pr_warn("map '%s': invalid def size.\n", map_name);
2536 		return -EINVAL;
2537 	}
2538 
2539 	map = bpf_object__add_map(obj);
2540 	if (IS_ERR(map))
2541 		return PTR_ERR(map);
2542 	map->name = strdup(map_name);
2543 	if (!map->name) {
2544 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2545 		return -ENOMEM;
2546 	}
2547 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2548 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2549 	map->sec_idx = sec_idx;
2550 	map->sec_offset = vi->offset;
2551 	map->btf_var_idx = var_idx;
2552 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2553 		 map_name, map->sec_idx, map->sec_offset);
2554 
2555 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2556 	if (err)
2557 		return err;
2558 
2559 	fill_map_from_def(map, &map_def);
2560 
2561 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2562 		err = build_map_pin_path(map, pin_root_path);
2563 		if (err) {
2564 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2565 			return err;
2566 		}
2567 	}
2568 
2569 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2570 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2571 		if (!map->inner_map)
2572 			return -ENOMEM;
2573 		map->inner_map->fd = -1;
2574 		map->inner_map->sec_idx = sec_idx;
2575 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2576 		if (!map->inner_map->name)
2577 			return -ENOMEM;
2578 		sprintf(map->inner_map->name, "%s.inner", map_name);
2579 
2580 		fill_map_from_def(map->inner_map, &inner_def);
2581 	}
2582 
2583 	err = bpf_map_find_btf_info(obj, map);
2584 	if (err)
2585 		return err;
2586 
2587 	return 0;
2588 }
2589 
bpf_object__init_user_btf_maps(struct bpf_object * obj,bool strict,const char * pin_root_path)2590 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2591 					  const char *pin_root_path)
2592 {
2593 	const struct btf_type *sec = NULL;
2594 	int nr_types, i, vlen, err;
2595 	const struct btf_type *t;
2596 	const char *name;
2597 	Elf_Data *data;
2598 	Elf_Scn *scn;
2599 
2600 	if (obj->efile.btf_maps_shndx < 0)
2601 		return 0;
2602 
2603 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2604 	data = elf_sec_data(obj, scn);
2605 	if (!scn || !data) {
2606 		pr_warn("elf: failed to get %s map definitions for %s\n",
2607 			MAPS_ELF_SEC, obj->path);
2608 		return -EINVAL;
2609 	}
2610 
2611 	nr_types = btf__type_cnt(obj->btf);
2612 	for (i = 1; i < nr_types; i++) {
2613 		t = btf__type_by_id(obj->btf, i);
2614 		if (!btf_is_datasec(t))
2615 			continue;
2616 		name = btf__name_by_offset(obj->btf, t->name_off);
2617 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2618 			sec = t;
2619 			obj->efile.btf_maps_sec_btf_id = i;
2620 			break;
2621 		}
2622 	}
2623 
2624 	if (!sec) {
2625 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2626 		return -ENOENT;
2627 	}
2628 
2629 	vlen = btf_vlen(sec);
2630 	for (i = 0; i < vlen; i++) {
2631 		err = bpf_object__init_user_btf_map(obj, sec, i,
2632 						    obj->efile.btf_maps_shndx,
2633 						    data, strict,
2634 						    pin_root_path);
2635 		if (err)
2636 			return err;
2637 	}
2638 
2639 	return 0;
2640 }
2641 
bpf_object__init_maps(struct bpf_object * obj,const struct bpf_object_open_opts * opts)2642 static int bpf_object__init_maps(struct bpf_object *obj,
2643 				 const struct bpf_object_open_opts *opts)
2644 {
2645 	const char *pin_root_path;
2646 	bool strict;
2647 	int err;
2648 
2649 	strict = !OPTS_GET(opts, relaxed_maps, false);
2650 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2651 
2652 	err = bpf_object__init_user_maps(obj, strict);
2653 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2654 	err = err ?: bpf_object__init_global_data_maps(obj);
2655 	err = err ?: bpf_object__init_kconfig_map(obj);
2656 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2657 
2658 	return err;
2659 }
2660 
section_have_execinstr(struct bpf_object * obj,int idx)2661 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2662 {
2663 	Elf64_Shdr *sh;
2664 
2665 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2666 	if (!sh)
2667 		return false;
2668 
2669 	return sh->sh_flags & SHF_EXECINSTR;
2670 }
2671 
btf_needs_sanitization(struct bpf_object * obj)2672 static bool btf_needs_sanitization(struct bpf_object *obj)
2673 {
2674 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2675 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2676 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2677 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2678 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2679 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2680 
2681 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2682 	       !has_decl_tag || !has_type_tag;
2683 }
2684 
bpf_object__sanitize_btf(struct bpf_object * obj,struct btf * btf)2685 static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2686 {
2687 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2688 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2689 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2690 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2691 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2692 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2693 	struct btf_type *t;
2694 	int i, j, vlen;
2695 
2696 	for (i = 1; i < btf__type_cnt(btf); i++) {
2697 		t = (struct btf_type *)btf__type_by_id(btf, i);
2698 
2699 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2700 			/* replace VAR/DECL_TAG with INT */
2701 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2702 			/*
2703 			 * using size = 1 is the safest choice, 4 will be too
2704 			 * big and cause kernel BTF validation failure if
2705 			 * original variable took less than 4 bytes
2706 			 */
2707 			t->size = 1;
2708 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2709 		} else if (!has_datasec && btf_is_datasec(t)) {
2710 			/* replace DATASEC with STRUCT */
2711 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2712 			struct btf_member *m = btf_members(t);
2713 			struct btf_type *vt;
2714 			char *name;
2715 
2716 			name = (char *)btf__name_by_offset(btf, t->name_off);
2717 			while (*name) {
2718 				if (*name == '.')
2719 					*name = '_';
2720 				name++;
2721 			}
2722 
2723 			vlen = btf_vlen(t);
2724 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2725 			for (j = 0; j < vlen; j++, v++, m++) {
2726 				/* order of field assignments is important */
2727 				m->offset = v->offset * 8;
2728 				m->type = v->type;
2729 				/* preserve variable name as member name */
2730 				vt = (void *)btf__type_by_id(btf, v->type);
2731 				m->name_off = vt->name_off;
2732 			}
2733 		} else if (!has_func && btf_is_func_proto(t)) {
2734 			/* replace FUNC_PROTO with ENUM */
2735 			vlen = btf_vlen(t);
2736 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2737 			t->size = sizeof(__u32); /* kernel enforced */
2738 		} else if (!has_func && btf_is_func(t)) {
2739 			/* replace FUNC with TYPEDEF */
2740 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2741 		} else if (!has_func_global && btf_is_func(t)) {
2742 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2743 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2744 		} else if (!has_float && btf_is_float(t)) {
2745 			/* replace FLOAT with an equally-sized empty STRUCT;
2746 			 * since C compilers do not accept e.g. "float" as a
2747 			 * valid struct name, make it anonymous
2748 			 */
2749 			t->name_off = 0;
2750 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2751 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2752 			/* replace TYPE_TAG with a CONST */
2753 			t->name_off = 0;
2754 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2755 		}
2756 	}
2757 }
2758 
libbpf_needs_btf(const struct bpf_object * obj)2759 static bool libbpf_needs_btf(const struct bpf_object *obj)
2760 {
2761 	return obj->efile.btf_maps_shndx >= 0 ||
2762 	       obj->efile.st_ops_shndx >= 0 ||
2763 	       obj->nr_extern > 0;
2764 }
2765 
kernel_needs_btf(const struct bpf_object * obj)2766 static bool kernel_needs_btf(const struct bpf_object *obj)
2767 {
2768 	return obj->efile.st_ops_shndx >= 0;
2769 }
2770 
bpf_object__init_btf(struct bpf_object * obj,Elf_Data * btf_data,Elf_Data * btf_ext_data)2771 static int bpf_object__init_btf(struct bpf_object *obj,
2772 				Elf_Data *btf_data,
2773 				Elf_Data *btf_ext_data)
2774 {
2775 	int err = -ENOENT;
2776 
2777 	if (btf_data) {
2778 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2779 		err = libbpf_get_error(obj->btf);
2780 		if (err) {
2781 			obj->btf = NULL;
2782 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2783 			goto out;
2784 		}
2785 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2786 		btf__set_pointer_size(obj->btf, 8);
2787 	}
2788 	if (btf_ext_data) {
2789 		struct btf_ext_info *ext_segs[3];
2790 		int seg_num, sec_num;
2791 
2792 		if (!obj->btf) {
2793 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2794 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2795 			goto out;
2796 		}
2797 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2798 		err = libbpf_get_error(obj->btf_ext);
2799 		if (err) {
2800 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2801 				BTF_EXT_ELF_SEC, err);
2802 			obj->btf_ext = NULL;
2803 			goto out;
2804 		}
2805 
2806 		/* setup .BTF.ext to ELF section mapping */
2807 		ext_segs[0] = &obj->btf_ext->func_info;
2808 		ext_segs[1] = &obj->btf_ext->line_info;
2809 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2810 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2811 			struct btf_ext_info *seg = ext_segs[seg_num];
2812 			const struct btf_ext_info_sec *sec;
2813 			const char *sec_name;
2814 			Elf_Scn *scn;
2815 
2816 			if (seg->sec_cnt == 0)
2817 				continue;
2818 
2819 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2820 			if (!seg->sec_idxs) {
2821 				err = -ENOMEM;
2822 				goto out;
2823 			}
2824 
2825 			sec_num = 0;
2826 			for_each_btf_ext_sec(seg, sec) {
2827 				/* preventively increment index to avoid doing
2828 				 * this before every continue below
2829 				 */
2830 				sec_num++;
2831 
2832 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2833 				if (str_is_empty(sec_name))
2834 					continue;
2835 				scn = elf_sec_by_name(obj, sec_name);
2836 				if (!scn)
2837 					continue;
2838 
2839 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2840 			}
2841 		}
2842 	}
2843 out:
2844 	if (err && libbpf_needs_btf(obj)) {
2845 		pr_warn("BTF is required, but is missing or corrupted.\n");
2846 		return err;
2847 	}
2848 	return 0;
2849 }
2850 
compare_vsi_off(const void * _a,const void * _b)2851 static int compare_vsi_off(const void *_a, const void *_b)
2852 {
2853 	const struct btf_var_secinfo *a = _a;
2854 	const struct btf_var_secinfo *b = _b;
2855 
2856 	return a->offset - b->offset;
2857 }
2858 
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)2859 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2860 			     struct btf_type *t)
2861 {
2862 	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
2863 	const char *name = btf__name_by_offset(btf, t->name_off);
2864 	const struct btf_type *t_var;
2865 	struct btf_var_secinfo *vsi;
2866 	const struct btf_var *var;
2867 	int ret;
2868 
2869 	if (!name) {
2870 		pr_debug("No name found in string section for DATASEC kind.\n");
2871 		return -ENOENT;
2872 	}
2873 
2874 	/* .extern datasec size and var offsets were set correctly during
2875 	 * extern collection step, so just skip straight to sorting variables
2876 	 */
2877 	if (t->size)
2878 		goto sort_vars;
2879 
2880 	ret = find_elf_sec_sz(obj, name, &size);
2881 	if (ret || !size) {
2882 		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2883 		return -ENOENT;
2884 	}
2885 
2886 	t->size = size;
2887 
2888 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2889 		t_var = btf__type_by_id(btf, vsi->type);
2890 		if (!t_var || !btf_is_var(t_var)) {
2891 			pr_debug("Non-VAR type seen in section %s\n", name);
2892 			return -EINVAL;
2893 		}
2894 
2895 		var = btf_var(t_var);
2896 		if (var->linkage == BTF_VAR_STATIC)
2897 			continue;
2898 
2899 		name = btf__name_by_offset(btf, t_var->name_off);
2900 		if (!name) {
2901 			pr_debug("No name found in string section for VAR kind\n");
2902 			return -ENOENT;
2903 		}
2904 
2905 		ret = find_elf_var_offset(obj, name, &off);
2906 		if (ret) {
2907 			pr_debug("No offset found in symbol table for VAR %s\n",
2908 				 name);
2909 			return -ENOENT;
2910 		}
2911 
2912 		vsi->offset = off;
2913 	}
2914 
2915 sort_vars:
2916 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2917 	return 0;
2918 }
2919 
btf_finalize_data(struct bpf_object * obj,struct btf * btf)2920 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2921 {
2922 	int err = 0;
2923 	__u32 i, n = btf__type_cnt(btf);
2924 
2925 	for (i = 1; i < n; i++) {
2926 		struct btf_type *t = btf_type_by_id(btf, i);
2927 
2928 		/* Loader needs to fix up some of the things compiler
2929 		 * couldn't get its hands on while emitting BTF. This
2930 		 * is section size and global variable offset. We use
2931 		 * the info from the ELF itself for this purpose.
2932 		 */
2933 		if (btf_is_datasec(t)) {
2934 			err = btf_fixup_datasec(obj, btf, t);
2935 			if (err)
2936 				break;
2937 		}
2938 	}
2939 
2940 	return libbpf_err(err);
2941 }
2942 
btf__finalize_data(struct bpf_object * obj,struct btf * btf)2943 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
2944 {
2945 	return btf_finalize_data(obj, btf);
2946 }
2947 
bpf_object__finalize_btf(struct bpf_object * obj)2948 static int bpf_object__finalize_btf(struct bpf_object *obj)
2949 {
2950 	int err;
2951 
2952 	if (!obj->btf)
2953 		return 0;
2954 
2955 	err = btf_finalize_data(obj, obj->btf);
2956 	if (err) {
2957 		pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2958 		return err;
2959 	}
2960 
2961 	return 0;
2962 }
2963 
prog_needs_vmlinux_btf(struct bpf_program * prog)2964 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2965 {
2966 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2967 	    prog->type == BPF_PROG_TYPE_LSM)
2968 		return true;
2969 
2970 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2971 	 * also need vmlinux BTF
2972 	 */
2973 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2974 		return true;
2975 
2976 	return false;
2977 }
2978 
obj_needs_vmlinux_btf(const struct bpf_object * obj)2979 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2980 {
2981 	struct bpf_program *prog;
2982 	int i;
2983 
2984 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
2985 	 * is not specified
2986 	 */
2987 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2988 		return true;
2989 
2990 	/* Support for typed ksyms needs kernel BTF */
2991 	for (i = 0; i < obj->nr_extern; i++) {
2992 		const struct extern_desc *ext;
2993 
2994 		ext = &obj->externs[i];
2995 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
2996 			return true;
2997 	}
2998 
2999 	bpf_object__for_each_program(prog, obj) {
3000 		if (!prog->autoload)
3001 			continue;
3002 		if (prog_needs_vmlinux_btf(prog))
3003 			return true;
3004 	}
3005 
3006 	return false;
3007 }
3008 
bpf_object__load_vmlinux_btf(struct bpf_object * obj,bool force)3009 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3010 {
3011 	int err;
3012 
3013 	/* btf_vmlinux could be loaded earlier */
3014 	if (obj->btf_vmlinux || obj->gen_loader)
3015 		return 0;
3016 
3017 	if (!force && !obj_needs_vmlinux_btf(obj))
3018 		return 0;
3019 
3020 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3021 	err = libbpf_get_error(obj->btf_vmlinux);
3022 	if (err) {
3023 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3024 		obj->btf_vmlinux = NULL;
3025 		return err;
3026 	}
3027 	return 0;
3028 }
3029 
bpf_object__sanitize_and_load_btf(struct bpf_object * obj)3030 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3031 {
3032 	struct btf *kern_btf = obj->btf;
3033 	bool btf_mandatory, sanitize;
3034 	int i, err = 0;
3035 
3036 	if (!obj->btf)
3037 		return 0;
3038 
3039 	if (!kernel_supports(obj, FEAT_BTF)) {
3040 		if (kernel_needs_btf(obj)) {
3041 			err = -EOPNOTSUPP;
3042 			goto report;
3043 		}
3044 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3045 		return 0;
3046 	}
3047 
3048 	/* Even though some subprogs are global/weak, user might prefer more
3049 	 * permissive BPF verification process that BPF verifier performs for
3050 	 * static functions, taking into account more context from the caller
3051 	 * functions. In such case, they need to mark such subprogs with
3052 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3053 	 * corresponding FUNC BTF type to be marked as static and trigger more
3054 	 * involved BPF verification process.
3055 	 */
3056 	for (i = 0; i < obj->nr_programs; i++) {
3057 		struct bpf_program *prog = &obj->programs[i];
3058 		struct btf_type *t;
3059 		const char *name;
3060 		int j, n;
3061 
3062 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3063 			continue;
3064 
3065 		n = btf__type_cnt(obj->btf);
3066 		for (j = 1; j < n; j++) {
3067 			t = btf_type_by_id(obj->btf, j);
3068 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3069 				continue;
3070 
3071 			name = btf__str_by_offset(obj->btf, t->name_off);
3072 			if (strcmp(name, prog->name) != 0)
3073 				continue;
3074 
3075 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3076 			break;
3077 		}
3078 	}
3079 
3080 	sanitize = btf_needs_sanitization(obj);
3081 	if (sanitize) {
3082 		const void *raw_data;
3083 		__u32 sz;
3084 
3085 		/* clone BTF to sanitize a copy and leave the original intact */
3086 		raw_data = btf__raw_data(obj->btf, &sz);
3087 		kern_btf = btf__new(raw_data, sz);
3088 		err = libbpf_get_error(kern_btf);
3089 		if (err)
3090 			return err;
3091 
3092 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3093 		btf__set_pointer_size(obj->btf, 8);
3094 		bpf_object__sanitize_btf(obj, kern_btf);
3095 	}
3096 
3097 	if (obj->gen_loader) {
3098 		__u32 raw_size = 0;
3099 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3100 
3101 		if (!raw_data)
3102 			return -ENOMEM;
3103 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3104 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3105 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3106 		 */
3107 		btf__set_fd(kern_btf, 0);
3108 	} else {
3109 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3110 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3111 					   obj->log_level ? 1 : 0);
3112 	}
3113 	if (sanitize) {
3114 		if (!err) {
3115 			/* move fd to libbpf's BTF */
3116 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3117 			btf__set_fd(kern_btf, -1);
3118 		}
3119 		btf__free(kern_btf);
3120 	}
3121 report:
3122 	if (err) {
3123 		btf_mandatory = kernel_needs_btf(obj);
3124 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3125 			btf_mandatory ? "BTF is mandatory, can't proceed."
3126 				      : "BTF is optional, ignoring.");
3127 		if (!btf_mandatory)
3128 			err = 0;
3129 	}
3130 	return err;
3131 }
3132 
elf_sym_str(const struct bpf_object * obj,size_t off)3133 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3134 {
3135 	const char *name;
3136 
3137 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3138 	if (!name) {
3139 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3140 			off, obj->path, elf_errmsg(-1));
3141 		return NULL;
3142 	}
3143 
3144 	return name;
3145 }
3146 
elf_sec_str(const struct bpf_object * obj,size_t off)3147 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3148 {
3149 	const char *name;
3150 
3151 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3152 	if (!name) {
3153 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3154 			off, obj->path, elf_errmsg(-1));
3155 		return NULL;
3156 	}
3157 
3158 	return name;
3159 }
3160 
elf_sec_by_idx(const struct bpf_object * obj,size_t idx)3161 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3162 {
3163 	Elf_Scn *scn;
3164 
3165 	scn = elf_getscn(obj->efile.elf, idx);
3166 	if (!scn) {
3167 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3168 			idx, obj->path, elf_errmsg(-1));
3169 		return NULL;
3170 	}
3171 	return scn;
3172 }
3173 
elf_sec_by_name(const struct bpf_object * obj,const char * name)3174 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3175 {
3176 	Elf_Scn *scn = NULL;
3177 	Elf *elf = obj->efile.elf;
3178 	const char *sec_name;
3179 
3180 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3181 		sec_name = elf_sec_name(obj, scn);
3182 		if (!sec_name)
3183 			return NULL;
3184 
3185 		if (strcmp(sec_name, name) != 0)
3186 			continue;
3187 
3188 		return scn;
3189 	}
3190 	return NULL;
3191 }
3192 
elf_sec_hdr(const struct bpf_object * obj,Elf_Scn * scn)3193 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3194 {
3195 	Elf64_Shdr *shdr;
3196 
3197 	if (!scn)
3198 		return NULL;
3199 
3200 	shdr = elf64_getshdr(scn);
3201 	if (!shdr) {
3202 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3203 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3204 		return NULL;
3205 	}
3206 
3207 	return shdr;
3208 }
3209 
elf_sec_name(const struct bpf_object * obj,Elf_Scn * scn)3210 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3211 {
3212 	const char *name;
3213 	Elf64_Shdr *sh;
3214 
3215 	if (!scn)
3216 		return NULL;
3217 
3218 	sh = elf_sec_hdr(obj, scn);
3219 	if (!sh)
3220 		return NULL;
3221 
3222 	name = elf_sec_str(obj, sh->sh_name);
3223 	if (!name) {
3224 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3225 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3226 		return NULL;
3227 	}
3228 
3229 	return name;
3230 }
3231 
elf_sec_data(const struct bpf_object * obj,Elf_Scn * scn)3232 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3233 {
3234 	Elf_Data *data;
3235 
3236 	if (!scn)
3237 		return NULL;
3238 
3239 	data = elf_getdata(scn, 0);
3240 	if (!data) {
3241 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3242 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3243 			obj->path, elf_errmsg(-1));
3244 		return NULL;
3245 	}
3246 
3247 	return data;
3248 }
3249 
elf_sym_by_idx(const struct bpf_object * obj,size_t idx)3250 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3251 {
3252 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3253 		return NULL;
3254 
3255 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3256 }
3257 
elf_rel_by_idx(Elf_Data * data,size_t idx)3258 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3259 {
3260 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3261 		return NULL;
3262 
3263 	return (Elf64_Rel *)data->d_buf + idx;
3264 }
3265 
is_sec_name_dwarf(const char * name)3266 static bool is_sec_name_dwarf(const char *name)
3267 {
3268 	/* approximation, but the actual list is too long */
3269 	return str_has_pfx(name, ".debug_");
3270 }
3271 
ignore_elf_section(Elf64_Shdr * hdr,const char * name)3272 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3273 {
3274 	/* no special handling of .strtab */
3275 	if (hdr->sh_type == SHT_STRTAB)
3276 		return true;
3277 
3278 	/* ignore .llvm_addrsig section as well */
3279 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3280 		return true;
3281 
3282 	/* no subprograms will lead to an empty .text section, ignore it */
3283 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3284 	    strcmp(name, ".text") == 0)
3285 		return true;
3286 
3287 	/* DWARF sections */
3288 	if (is_sec_name_dwarf(name))
3289 		return true;
3290 
3291 	if (str_has_pfx(name, ".rel")) {
3292 		name += sizeof(".rel") - 1;
3293 		/* DWARF section relocations */
3294 		if (is_sec_name_dwarf(name))
3295 			return true;
3296 
3297 		/* .BTF and .BTF.ext don't need relocations */
3298 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3299 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3300 			return true;
3301 	}
3302 
3303 	return false;
3304 }
3305 
cmp_progs(const void * _a,const void * _b)3306 static int cmp_progs(const void *_a, const void *_b)
3307 {
3308 	const struct bpf_program *a = _a;
3309 	const struct bpf_program *b = _b;
3310 
3311 	if (a->sec_idx != b->sec_idx)
3312 		return a->sec_idx < b->sec_idx ? -1 : 1;
3313 
3314 	/* sec_insn_off can't be the same within the section */
3315 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3316 }
3317 
bpf_object__elf_collect(struct bpf_object * obj)3318 static int bpf_object__elf_collect(struct bpf_object *obj)
3319 {
3320 	struct elf_sec_desc *sec_desc;
3321 	Elf *elf = obj->efile.elf;
3322 	Elf_Data *btf_ext_data = NULL;
3323 	Elf_Data *btf_data = NULL;
3324 	int idx = 0, err = 0;
3325 	const char *name;
3326 	Elf_Data *data;
3327 	Elf_Scn *scn;
3328 	Elf64_Shdr *sh;
3329 
3330 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3331 	 * section. e_shnum does include sec #0, so e_shnum is the necessary
3332 	 * size of an array to keep all the sections.
3333 	 */
3334 	obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3335 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3336 	if (!obj->efile.secs)
3337 		return -ENOMEM;
3338 
3339 	/* a bunch of ELF parsing functionality depends on processing symbols,
3340 	 * so do the first pass and find the symbol table
3341 	 */
3342 	scn = NULL;
3343 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3344 		sh = elf_sec_hdr(obj, scn);
3345 		if (!sh)
3346 			return -LIBBPF_ERRNO__FORMAT;
3347 
3348 		if (sh->sh_type == SHT_SYMTAB) {
3349 			if (obj->efile.symbols) {
3350 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3351 				return -LIBBPF_ERRNO__FORMAT;
3352 			}
3353 
3354 			data = elf_sec_data(obj, scn);
3355 			if (!data)
3356 				return -LIBBPF_ERRNO__FORMAT;
3357 
3358 			idx = elf_ndxscn(scn);
3359 
3360 			obj->efile.symbols = data;
3361 			obj->efile.symbols_shndx = idx;
3362 			obj->efile.strtabidx = sh->sh_link;
3363 		}
3364 	}
3365 
3366 	if (!obj->efile.symbols) {
3367 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3368 			obj->path);
3369 		return -ENOENT;
3370 	}
3371 
3372 	scn = NULL;
3373 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3374 		idx = elf_ndxscn(scn);
3375 		sec_desc = &obj->efile.secs[idx];
3376 
3377 		sh = elf_sec_hdr(obj, scn);
3378 		if (!sh)
3379 			return -LIBBPF_ERRNO__FORMAT;
3380 
3381 		name = elf_sec_str(obj, sh->sh_name);
3382 		if (!name)
3383 			return -LIBBPF_ERRNO__FORMAT;
3384 
3385 		if (ignore_elf_section(sh, name))
3386 			continue;
3387 
3388 		data = elf_sec_data(obj, scn);
3389 		if (!data)
3390 			return -LIBBPF_ERRNO__FORMAT;
3391 
3392 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3393 			 idx, name, (unsigned long)data->d_size,
3394 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3395 			 (int)sh->sh_type);
3396 
3397 		if (strcmp(name, "license") == 0) {
3398 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3399 			if (err)
3400 				return err;
3401 		} else if (strcmp(name, "version") == 0) {
3402 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3403 			if (err)
3404 				return err;
3405 		} else if (strcmp(name, "maps") == 0) {
3406 			obj->efile.maps_shndx = idx;
3407 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3408 			obj->efile.btf_maps_shndx = idx;
3409 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3410 			if (sh->sh_type != SHT_PROGBITS)
3411 				return -LIBBPF_ERRNO__FORMAT;
3412 			btf_data = data;
3413 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3414 			if (sh->sh_type != SHT_PROGBITS)
3415 				return -LIBBPF_ERRNO__FORMAT;
3416 			btf_ext_data = data;
3417 		} else if (sh->sh_type == SHT_SYMTAB) {
3418 			/* already processed during the first pass above */
3419 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3420 			if (sh->sh_flags & SHF_EXECINSTR) {
3421 				if (strcmp(name, ".text") == 0)
3422 					obj->efile.text_shndx = idx;
3423 				err = bpf_object__add_programs(obj, data, name, idx);
3424 				if (err)
3425 					return err;
3426 			} else if (strcmp(name, DATA_SEC) == 0 ||
3427 				   str_has_pfx(name, DATA_SEC ".")) {
3428 				sec_desc->sec_type = SEC_DATA;
3429 				sec_desc->shdr = sh;
3430 				sec_desc->data = data;
3431 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3432 				   str_has_pfx(name, RODATA_SEC ".")) {
3433 				sec_desc->sec_type = SEC_RODATA;
3434 				sec_desc->shdr = sh;
3435 				sec_desc->data = data;
3436 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3437 				obj->efile.st_ops_data = data;
3438 				obj->efile.st_ops_shndx = idx;
3439 			} else {
3440 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3441 					idx, name);
3442 			}
3443 		} else if (sh->sh_type == SHT_REL) {
3444 			int targ_sec_idx = sh->sh_info; /* points to other section */
3445 
3446 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3447 			    targ_sec_idx >= obj->efile.sec_cnt)
3448 				return -LIBBPF_ERRNO__FORMAT;
3449 
3450 			/* Only do relo for section with exec instructions */
3451 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3452 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3453 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3454 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3455 					idx, name, targ_sec_idx,
3456 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3457 				continue;
3458 			}
3459 
3460 			sec_desc->sec_type = SEC_RELO;
3461 			sec_desc->shdr = sh;
3462 			sec_desc->data = data;
3463 		} else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3464 			sec_desc->sec_type = SEC_BSS;
3465 			sec_desc->shdr = sh;
3466 			sec_desc->data = data;
3467 		} else {
3468 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3469 				(size_t)sh->sh_size);
3470 		}
3471 	}
3472 
3473 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3474 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3475 		return -LIBBPF_ERRNO__FORMAT;
3476 	}
3477 
3478 	/* sort BPF programs by section name and in-section instruction offset
3479 	 * for faster search */
3480 	if (obj->nr_programs)
3481 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3482 
3483 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3484 }
3485 
sym_is_extern(const Elf64_Sym * sym)3486 static bool sym_is_extern(const Elf64_Sym *sym)
3487 {
3488 	int bind = ELF64_ST_BIND(sym->st_info);
3489 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3490 	return sym->st_shndx == SHN_UNDEF &&
3491 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3492 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3493 }
3494 
sym_is_subprog(const Elf64_Sym * sym,int text_shndx)3495 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3496 {
3497 	int bind = ELF64_ST_BIND(sym->st_info);
3498 	int type = ELF64_ST_TYPE(sym->st_info);
3499 
3500 	/* in .text section */
3501 	if (sym->st_shndx != text_shndx)
3502 		return false;
3503 
3504 	/* local function */
3505 	if (bind == STB_LOCAL && type == STT_SECTION)
3506 		return true;
3507 
3508 	/* global function */
3509 	return bind == STB_GLOBAL && type == STT_FUNC;
3510 }
3511 
find_extern_btf_id(const struct btf * btf,const char * ext_name)3512 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3513 {
3514 	const struct btf_type *t;
3515 	const char *tname;
3516 	int i, n;
3517 
3518 	if (!btf)
3519 		return -ESRCH;
3520 
3521 	n = btf__type_cnt(btf);
3522 	for (i = 1; i < n; i++) {
3523 		t = btf__type_by_id(btf, i);
3524 
3525 		if (!btf_is_var(t) && !btf_is_func(t))
3526 			continue;
3527 
3528 		tname = btf__name_by_offset(btf, t->name_off);
3529 		if (strcmp(tname, ext_name))
3530 			continue;
3531 
3532 		if (btf_is_var(t) &&
3533 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3534 			return -EINVAL;
3535 
3536 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3537 			return -EINVAL;
3538 
3539 		return i;
3540 	}
3541 
3542 	return -ENOENT;
3543 }
3544 
find_extern_sec_btf_id(struct btf * btf,int ext_btf_id)3545 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3546 	const struct btf_var_secinfo *vs;
3547 	const struct btf_type *t;
3548 	int i, j, n;
3549 
3550 	if (!btf)
3551 		return -ESRCH;
3552 
3553 	n = btf__type_cnt(btf);
3554 	for (i = 1; i < n; i++) {
3555 		t = btf__type_by_id(btf, i);
3556 
3557 		if (!btf_is_datasec(t))
3558 			continue;
3559 
3560 		vs = btf_var_secinfos(t);
3561 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3562 			if (vs->type == ext_btf_id)
3563 				return i;
3564 		}
3565 	}
3566 
3567 	return -ENOENT;
3568 }
3569 
find_kcfg_type(const struct btf * btf,int id,bool * is_signed)3570 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3571 				     bool *is_signed)
3572 {
3573 	const struct btf_type *t;
3574 	const char *name;
3575 
3576 	t = skip_mods_and_typedefs(btf, id, NULL);
3577 	name = btf__name_by_offset(btf, t->name_off);
3578 
3579 	if (is_signed)
3580 		*is_signed = false;
3581 	switch (btf_kind(t)) {
3582 	case BTF_KIND_INT: {
3583 		int enc = btf_int_encoding(t);
3584 
3585 		if (enc & BTF_INT_BOOL)
3586 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3587 		if (is_signed)
3588 			*is_signed = enc & BTF_INT_SIGNED;
3589 		if (t->size == 1)
3590 			return KCFG_CHAR;
3591 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3592 			return KCFG_UNKNOWN;
3593 		return KCFG_INT;
3594 	}
3595 	case BTF_KIND_ENUM:
3596 		if (t->size != 4)
3597 			return KCFG_UNKNOWN;
3598 		if (strcmp(name, "libbpf_tristate"))
3599 			return KCFG_UNKNOWN;
3600 		return KCFG_TRISTATE;
3601 	case BTF_KIND_ARRAY:
3602 		if (btf_array(t)->nelems == 0)
3603 			return KCFG_UNKNOWN;
3604 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3605 			return KCFG_UNKNOWN;
3606 		return KCFG_CHAR_ARR;
3607 	default:
3608 		return KCFG_UNKNOWN;
3609 	}
3610 }
3611 
cmp_externs(const void * _a,const void * _b)3612 static int cmp_externs(const void *_a, const void *_b)
3613 {
3614 	const struct extern_desc *a = _a;
3615 	const struct extern_desc *b = _b;
3616 
3617 	if (a->type != b->type)
3618 		return a->type < b->type ? -1 : 1;
3619 
3620 	if (a->type == EXT_KCFG) {
3621 		/* descending order by alignment requirements */
3622 		if (a->kcfg.align != b->kcfg.align)
3623 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3624 		/* ascending order by size, within same alignment class */
3625 		if (a->kcfg.sz != b->kcfg.sz)
3626 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3627 	}
3628 
3629 	/* resolve ties by name */
3630 	return strcmp(a->name, b->name);
3631 }
3632 
find_int_btf_id(const struct btf * btf)3633 static int find_int_btf_id(const struct btf *btf)
3634 {
3635 	const struct btf_type *t;
3636 	int i, n;
3637 
3638 	n = btf__type_cnt(btf);
3639 	for (i = 1; i < n; i++) {
3640 		t = btf__type_by_id(btf, i);
3641 
3642 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3643 			return i;
3644 	}
3645 
3646 	return 0;
3647 }
3648 
add_dummy_ksym_var(struct btf * btf)3649 static int add_dummy_ksym_var(struct btf *btf)
3650 {
3651 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3652 	const struct btf_var_secinfo *vs;
3653 	const struct btf_type *sec;
3654 
3655 	if (!btf)
3656 		return 0;
3657 
3658 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3659 					    BTF_KIND_DATASEC);
3660 	if (sec_btf_id < 0)
3661 		return 0;
3662 
3663 	sec = btf__type_by_id(btf, sec_btf_id);
3664 	vs = btf_var_secinfos(sec);
3665 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3666 		const struct btf_type *vt;
3667 
3668 		vt = btf__type_by_id(btf, vs->type);
3669 		if (btf_is_func(vt))
3670 			break;
3671 	}
3672 
3673 	/* No func in ksyms sec.  No need to add dummy var. */
3674 	if (i == btf_vlen(sec))
3675 		return 0;
3676 
3677 	int_btf_id = find_int_btf_id(btf);
3678 	dummy_var_btf_id = btf__add_var(btf,
3679 					"dummy_ksym",
3680 					BTF_VAR_GLOBAL_ALLOCATED,
3681 					int_btf_id);
3682 	if (dummy_var_btf_id < 0)
3683 		pr_warn("cannot create a dummy_ksym var\n");
3684 
3685 	return dummy_var_btf_id;
3686 }
3687 
bpf_object__collect_externs(struct bpf_object * obj)3688 static int bpf_object__collect_externs(struct bpf_object *obj)
3689 {
3690 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3691 	const struct btf_type *t;
3692 	struct extern_desc *ext;
3693 	int i, n, off, dummy_var_btf_id;
3694 	const char *ext_name, *sec_name;
3695 	Elf_Scn *scn;
3696 	Elf64_Shdr *sh;
3697 
3698 	if (!obj->efile.symbols)
3699 		return 0;
3700 
3701 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3702 	sh = elf_sec_hdr(obj, scn);
3703 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3704 		return -LIBBPF_ERRNO__FORMAT;
3705 
3706 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3707 	if (dummy_var_btf_id < 0)
3708 		return dummy_var_btf_id;
3709 
3710 	n = sh->sh_size / sh->sh_entsize;
3711 	pr_debug("looking for externs among %d symbols...\n", n);
3712 
3713 	for (i = 0; i < n; i++) {
3714 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3715 
3716 		if (!sym)
3717 			return -LIBBPF_ERRNO__FORMAT;
3718 		if (!sym_is_extern(sym))
3719 			continue;
3720 		ext_name = elf_sym_str(obj, sym->st_name);
3721 		if (!ext_name || !ext_name[0])
3722 			continue;
3723 
3724 		ext = obj->externs;
3725 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3726 		if (!ext)
3727 			return -ENOMEM;
3728 		obj->externs = ext;
3729 		ext = &ext[obj->nr_extern];
3730 		memset(ext, 0, sizeof(*ext));
3731 		obj->nr_extern++;
3732 
3733 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3734 		if (ext->btf_id <= 0) {
3735 			pr_warn("failed to find BTF for extern '%s': %d\n",
3736 				ext_name, ext->btf_id);
3737 			return ext->btf_id;
3738 		}
3739 		t = btf__type_by_id(obj->btf, ext->btf_id);
3740 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3741 		ext->sym_idx = i;
3742 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3743 
3744 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3745 		if (ext->sec_btf_id <= 0) {
3746 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3747 				ext_name, ext->btf_id, ext->sec_btf_id);
3748 			return ext->sec_btf_id;
3749 		}
3750 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3751 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3752 
3753 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3754 			if (btf_is_func(t)) {
3755 				pr_warn("extern function %s is unsupported under %s section\n",
3756 					ext->name, KCONFIG_SEC);
3757 				return -ENOTSUP;
3758 			}
3759 			kcfg_sec = sec;
3760 			ext->type = EXT_KCFG;
3761 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3762 			if (ext->kcfg.sz <= 0) {
3763 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3764 					ext_name, ext->kcfg.sz);
3765 				return ext->kcfg.sz;
3766 			}
3767 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3768 			if (ext->kcfg.align <= 0) {
3769 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3770 					ext_name, ext->kcfg.align);
3771 				return -EINVAL;
3772 			}
3773 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3774 						        &ext->kcfg.is_signed);
3775 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3776 				pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3777 				return -ENOTSUP;
3778 			}
3779 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3780 			ksym_sec = sec;
3781 			ext->type = EXT_KSYM;
3782 			skip_mods_and_typedefs(obj->btf, t->type,
3783 					       &ext->ksym.type_id);
3784 		} else {
3785 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3786 			return -ENOTSUP;
3787 		}
3788 	}
3789 	pr_debug("collected %d externs total\n", obj->nr_extern);
3790 
3791 	if (!obj->nr_extern)
3792 		return 0;
3793 
3794 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3795 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3796 
3797 	/* for .ksyms section, we need to turn all externs into allocated
3798 	 * variables in BTF to pass kernel verification; we do this by
3799 	 * pretending that each extern is a 8-byte variable
3800 	 */
3801 	if (ksym_sec) {
3802 		/* find existing 4-byte integer type in BTF to use for fake
3803 		 * extern variables in DATASEC
3804 		 */
3805 		int int_btf_id = find_int_btf_id(obj->btf);
3806 		/* For extern function, a dummy_var added earlier
3807 		 * will be used to replace the vs->type and
3808 		 * its name string will be used to refill
3809 		 * the missing param's name.
3810 		 */
3811 		const struct btf_type *dummy_var;
3812 
3813 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3814 		for (i = 0; i < obj->nr_extern; i++) {
3815 			ext = &obj->externs[i];
3816 			if (ext->type != EXT_KSYM)
3817 				continue;
3818 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3819 				 i, ext->sym_idx, ext->name);
3820 		}
3821 
3822 		sec = ksym_sec;
3823 		n = btf_vlen(sec);
3824 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3825 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3826 			struct btf_type *vt;
3827 
3828 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3829 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3830 			ext = find_extern_by_name(obj, ext_name);
3831 			if (!ext) {
3832 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3833 					btf_kind_str(vt), ext_name);
3834 				return -ESRCH;
3835 			}
3836 			if (btf_is_func(vt)) {
3837 				const struct btf_type *func_proto;
3838 				struct btf_param *param;
3839 				int j;
3840 
3841 				func_proto = btf__type_by_id(obj->btf,
3842 							     vt->type);
3843 				param = btf_params(func_proto);
3844 				/* Reuse the dummy_var string if the
3845 				 * func proto does not have param name.
3846 				 */
3847 				for (j = 0; j < btf_vlen(func_proto); j++)
3848 					if (param[j].type && !param[j].name_off)
3849 						param[j].name_off =
3850 							dummy_var->name_off;
3851 				vs->type = dummy_var_btf_id;
3852 				vt->info &= ~0xffff;
3853 				vt->info |= BTF_FUNC_GLOBAL;
3854 			} else {
3855 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3856 				vt->type = int_btf_id;
3857 			}
3858 			vs->offset = off;
3859 			vs->size = sizeof(int);
3860 		}
3861 		sec->size = off;
3862 	}
3863 
3864 	if (kcfg_sec) {
3865 		sec = kcfg_sec;
3866 		/* for kcfg externs calculate their offsets within a .kconfig map */
3867 		off = 0;
3868 		for (i = 0; i < obj->nr_extern; i++) {
3869 			ext = &obj->externs[i];
3870 			if (ext->type != EXT_KCFG)
3871 				continue;
3872 
3873 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3874 			off = ext->kcfg.data_off + ext->kcfg.sz;
3875 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3876 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3877 		}
3878 		sec->size = off;
3879 		n = btf_vlen(sec);
3880 		for (i = 0; i < n; i++) {
3881 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3882 
3883 			t = btf__type_by_id(obj->btf, vs->type);
3884 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3885 			ext = find_extern_by_name(obj, ext_name);
3886 			if (!ext) {
3887 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3888 					ext_name);
3889 				return -ESRCH;
3890 			}
3891 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3892 			vs->offset = ext->kcfg.data_off;
3893 		}
3894 	}
3895 	return 0;
3896 }
3897 
3898 struct bpf_program *
bpf_object__find_program_by_title(const struct bpf_object * obj,const char * title)3899 bpf_object__find_program_by_title(const struct bpf_object *obj,
3900 				  const char *title)
3901 {
3902 	struct bpf_program *pos;
3903 
3904 	bpf_object__for_each_program(pos, obj) {
3905 		if (pos->sec_name && !strcmp(pos->sec_name, title))
3906 			return pos;
3907 	}
3908 	return errno = ENOENT, NULL;
3909 }
3910 
prog_is_subprog(const struct bpf_object * obj,const struct bpf_program * prog)3911 static bool prog_is_subprog(const struct bpf_object *obj,
3912 			    const struct bpf_program *prog)
3913 {
3914 	/* For legacy reasons, libbpf supports an entry-point BPF programs
3915 	 * without SEC() attribute, i.e., those in the .text section. But if
3916 	 * there are 2 or more such programs in the .text section, they all
3917 	 * must be subprograms called from entry-point BPF programs in
3918 	 * designated SEC()'tions, otherwise there is no way to distinguish
3919 	 * which of those programs should be loaded vs which are a subprogram.
3920 	 * Similarly, if there is a function/program in .text and at least one
3921 	 * other BPF program with custom SEC() attribute, then we just assume
3922 	 * .text programs are subprograms (even if they are not called from
3923 	 * other programs), because libbpf never explicitly supported mixing
3924 	 * SEC()-designated BPF programs and .text entry-point BPF programs.
3925 	 *
3926 	 * In libbpf 1.0 strict mode, we always consider .text
3927 	 * programs to be subprograms.
3928 	 */
3929 
3930 	if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
3931 		return prog->sec_idx == obj->efile.text_shndx;
3932 
3933 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3934 }
3935 
3936 struct bpf_program *
bpf_object__find_program_by_name(const struct bpf_object * obj,const char * name)3937 bpf_object__find_program_by_name(const struct bpf_object *obj,
3938 				 const char *name)
3939 {
3940 	struct bpf_program *prog;
3941 
3942 	bpf_object__for_each_program(prog, obj) {
3943 		if (prog_is_subprog(obj, prog))
3944 			continue;
3945 		if (!strcmp(prog->name, name))
3946 			return prog;
3947 	}
3948 	return errno = ENOENT, NULL;
3949 }
3950 
bpf_object__shndx_is_data(const struct bpf_object * obj,int shndx)3951 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3952 				      int shndx)
3953 {
3954 	switch (obj->efile.secs[shndx].sec_type) {
3955 	case SEC_BSS:
3956 	case SEC_DATA:
3957 	case SEC_RODATA:
3958 		return true;
3959 	default:
3960 		return false;
3961 	}
3962 }
3963 
bpf_object__shndx_is_maps(const struct bpf_object * obj,int shndx)3964 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3965 				      int shndx)
3966 {
3967 	return shndx == obj->efile.maps_shndx ||
3968 	       shndx == obj->efile.btf_maps_shndx;
3969 }
3970 
3971 static enum libbpf_map_type
bpf_object__section_to_libbpf_map_type(const struct bpf_object * obj,int shndx)3972 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3973 {
3974 	if (shndx == obj->efile.symbols_shndx)
3975 		return LIBBPF_MAP_KCONFIG;
3976 
3977 	switch (obj->efile.secs[shndx].sec_type) {
3978 	case SEC_BSS:
3979 		return LIBBPF_MAP_BSS;
3980 	case SEC_DATA:
3981 		return LIBBPF_MAP_DATA;
3982 	case SEC_RODATA:
3983 		return LIBBPF_MAP_RODATA;
3984 	default:
3985 		return LIBBPF_MAP_UNSPEC;
3986 	}
3987 }
3988 
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)3989 static int bpf_program__record_reloc(struct bpf_program *prog,
3990 				     struct reloc_desc *reloc_desc,
3991 				     __u32 insn_idx, const char *sym_name,
3992 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
3993 {
3994 	struct bpf_insn *insn = &prog->insns[insn_idx];
3995 	size_t map_idx, nr_maps = prog->obj->nr_maps;
3996 	struct bpf_object *obj = prog->obj;
3997 	__u32 shdr_idx = sym->st_shndx;
3998 	enum libbpf_map_type type;
3999 	const char *sym_sec_name;
4000 	struct bpf_map *map;
4001 
4002 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4003 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4004 			prog->name, sym_name, insn_idx, insn->code);
4005 		return -LIBBPF_ERRNO__RELOC;
4006 	}
4007 
4008 	if (sym_is_extern(sym)) {
4009 		int sym_idx = ELF64_R_SYM(rel->r_info);
4010 		int i, n = obj->nr_extern;
4011 		struct extern_desc *ext;
4012 
4013 		for (i = 0; i < n; i++) {
4014 			ext = &obj->externs[i];
4015 			if (ext->sym_idx == sym_idx)
4016 				break;
4017 		}
4018 		if (i >= n) {
4019 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4020 				prog->name, sym_name, sym_idx);
4021 			return -LIBBPF_ERRNO__RELOC;
4022 		}
4023 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4024 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4025 		if (insn->code == (BPF_JMP | BPF_CALL))
4026 			reloc_desc->type = RELO_EXTERN_FUNC;
4027 		else
4028 			reloc_desc->type = RELO_EXTERN_VAR;
4029 		reloc_desc->insn_idx = insn_idx;
4030 		reloc_desc->sym_off = i; /* sym_off stores extern index */
4031 		return 0;
4032 	}
4033 
4034 	/* sub-program call relocation */
4035 	if (is_call_insn(insn)) {
4036 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4037 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4038 			return -LIBBPF_ERRNO__RELOC;
4039 		}
4040 		/* text_shndx can be 0, if no default "main" program exists */
4041 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4042 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4043 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4044 				prog->name, sym_name, sym_sec_name);
4045 			return -LIBBPF_ERRNO__RELOC;
4046 		}
4047 		if (sym->st_value % BPF_INSN_SZ) {
4048 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4049 				prog->name, sym_name, (size_t)sym->st_value);
4050 			return -LIBBPF_ERRNO__RELOC;
4051 		}
4052 		reloc_desc->type = RELO_CALL;
4053 		reloc_desc->insn_idx = insn_idx;
4054 		reloc_desc->sym_off = sym->st_value;
4055 		return 0;
4056 	}
4057 
4058 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4059 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4060 			prog->name, sym_name, shdr_idx);
4061 		return -LIBBPF_ERRNO__RELOC;
4062 	}
4063 
4064 	/* loading subprog addresses */
4065 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4066 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4067 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4068 		 */
4069 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4070 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4071 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4072 			return -LIBBPF_ERRNO__RELOC;
4073 		}
4074 
4075 		reloc_desc->type = RELO_SUBPROG_ADDR;
4076 		reloc_desc->insn_idx = insn_idx;
4077 		reloc_desc->sym_off = sym->st_value;
4078 		return 0;
4079 	}
4080 
4081 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4082 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4083 
4084 	/* generic map reference relocation */
4085 	if (type == LIBBPF_MAP_UNSPEC) {
4086 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4087 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4088 				prog->name, sym_name, sym_sec_name);
4089 			return -LIBBPF_ERRNO__RELOC;
4090 		}
4091 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4092 			map = &obj->maps[map_idx];
4093 			if (map->libbpf_type != type ||
4094 			    map->sec_idx != sym->st_shndx ||
4095 			    map->sec_offset != sym->st_value)
4096 				continue;
4097 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4098 				 prog->name, map_idx, map->name, map->sec_idx,
4099 				 map->sec_offset, insn_idx);
4100 			break;
4101 		}
4102 		if (map_idx >= nr_maps) {
4103 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4104 				prog->name, sym_sec_name, (size_t)sym->st_value);
4105 			return -LIBBPF_ERRNO__RELOC;
4106 		}
4107 		reloc_desc->type = RELO_LD64;
4108 		reloc_desc->insn_idx = insn_idx;
4109 		reloc_desc->map_idx = map_idx;
4110 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4111 		return 0;
4112 	}
4113 
4114 	/* global data map relocation */
4115 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4116 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4117 			prog->name, sym_sec_name);
4118 		return -LIBBPF_ERRNO__RELOC;
4119 	}
4120 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4121 		map = &obj->maps[map_idx];
4122 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4123 			continue;
4124 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4125 			 prog->name, map_idx, map->name, map->sec_idx,
4126 			 map->sec_offset, insn_idx);
4127 		break;
4128 	}
4129 	if (map_idx >= nr_maps) {
4130 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4131 			prog->name, sym_sec_name);
4132 		return -LIBBPF_ERRNO__RELOC;
4133 	}
4134 
4135 	reloc_desc->type = RELO_DATA;
4136 	reloc_desc->insn_idx = insn_idx;
4137 	reloc_desc->map_idx = map_idx;
4138 	reloc_desc->sym_off = sym->st_value;
4139 	return 0;
4140 }
4141 
prog_contains_insn(const struct bpf_program * prog,size_t insn_idx)4142 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4143 {
4144 	return insn_idx >= prog->sec_insn_off &&
4145 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4146 }
4147 
find_prog_by_sec_insn(const struct bpf_object * obj,size_t sec_idx,size_t insn_idx)4148 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4149 						 size_t sec_idx, size_t insn_idx)
4150 {
4151 	int l = 0, r = obj->nr_programs - 1, m;
4152 	struct bpf_program *prog;
4153 
4154 	while (l < r) {
4155 		m = l + (r - l + 1) / 2;
4156 		prog = &obj->programs[m];
4157 
4158 		if (prog->sec_idx < sec_idx ||
4159 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4160 			l = m;
4161 		else
4162 			r = m - 1;
4163 	}
4164 	/* matching program could be at index l, but it still might be the
4165 	 * wrong one, so we need to double check conditions for the last time
4166 	 */
4167 	prog = &obj->programs[l];
4168 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4169 		return prog;
4170 	return NULL;
4171 }
4172 
4173 static int
bpf_object__collect_prog_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)4174 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4175 {
4176 	const char *relo_sec_name, *sec_name;
4177 	size_t sec_idx = shdr->sh_info, sym_idx;
4178 	struct bpf_program *prog;
4179 	struct reloc_desc *relos;
4180 	int err, i, nrels;
4181 	const char *sym_name;
4182 	__u32 insn_idx;
4183 	Elf_Scn *scn;
4184 	Elf_Data *scn_data;
4185 	Elf64_Sym *sym;
4186 	Elf64_Rel *rel;
4187 
4188 	if (sec_idx >= obj->efile.sec_cnt)
4189 		return -EINVAL;
4190 
4191 	scn = elf_sec_by_idx(obj, sec_idx);
4192 	scn_data = elf_sec_data(obj, scn);
4193 
4194 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4195 	sec_name = elf_sec_name(obj, scn);
4196 	if (!relo_sec_name || !sec_name)
4197 		return -EINVAL;
4198 
4199 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4200 		 relo_sec_name, sec_idx, sec_name);
4201 	nrels = shdr->sh_size / shdr->sh_entsize;
4202 
4203 	for (i = 0; i < nrels; i++) {
4204 		rel = elf_rel_by_idx(data, i);
4205 		if (!rel) {
4206 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4207 			return -LIBBPF_ERRNO__FORMAT;
4208 		}
4209 
4210 		sym_idx = ELF64_R_SYM(rel->r_info);
4211 		sym = elf_sym_by_idx(obj, sym_idx);
4212 		if (!sym) {
4213 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4214 				relo_sec_name, sym_idx, i);
4215 			return -LIBBPF_ERRNO__FORMAT;
4216 		}
4217 
4218 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4219 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4220 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4221 			return -LIBBPF_ERRNO__FORMAT;
4222 		}
4223 
4224 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4225 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4226 				relo_sec_name, (size_t)rel->r_offset, i);
4227 			return -LIBBPF_ERRNO__FORMAT;
4228 		}
4229 
4230 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4231 		/* relocations against static functions are recorded as
4232 		 * relocations against the section that contains a function;
4233 		 * in such case, symbol will be STT_SECTION and sym.st_name
4234 		 * will point to empty string (0), so fetch section name
4235 		 * instead
4236 		 */
4237 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4238 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4239 		else
4240 			sym_name = elf_sym_str(obj, sym->st_name);
4241 		sym_name = sym_name ?: "<?";
4242 
4243 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4244 			 relo_sec_name, i, insn_idx, sym_name);
4245 
4246 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4247 		if (!prog) {
4248 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4249 				relo_sec_name, i, sec_name, insn_idx);
4250 			continue;
4251 		}
4252 
4253 		relos = libbpf_reallocarray(prog->reloc_desc,
4254 					    prog->nr_reloc + 1, sizeof(*relos));
4255 		if (!relos)
4256 			return -ENOMEM;
4257 		prog->reloc_desc = relos;
4258 
4259 		/* adjust insn_idx to local BPF program frame of reference */
4260 		insn_idx -= prog->sec_insn_off;
4261 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4262 						insn_idx, sym_name, sym, rel);
4263 		if (err)
4264 			return err;
4265 
4266 		prog->nr_reloc++;
4267 	}
4268 	return 0;
4269 }
4270 
bpf_map_find_btf_info(struct bpf_object * obj,struct bpf_map * map)4271 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4272 {
4273 	struct bpf_map_def *def = &map->def;
4274 	__u32 key_type_id = 0, value_type_id = 0;
4275 	int ret;
4276 
4277 	if (!obj->btf)
4278 		return -ENOENT;
4279 
4280 	/* if it's BTF-defined map, we don't need to search for type IDs.
4281 	 * For struct_ops map, it does not need btf_key_type_id and
4282 	 * btf_value_type_id.
4283 	 */
4284 	if (map->sec_idx == obj->efile.btf_maps_shndx ||
4285 	    bpf_map__is_struct_ops(map))
4286 		return 0;
4287 
4288 	if (!bpf_map__is_internal(map)) {
4289 		pr_warn("Use of BPF_ANNOTATE_KV_PAIR is deprecated, use BTF-defined maps in .maps section instead\n");
4290 #pragma GCC diagnostic push
4291 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4292 		ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
4293 					   def->value_size, &key_type_id,
4294 					   &value_type_id);
4295 #pragma GCC diagnostic pop
4296 	} else {
4297 		/*
4298 		 * LLVM annotates global data differently in BTF, that is,
4299 		 * only as '.data', '.bss' or '.rodata'.
4300 		 */
4301 		ret = btf__find_by_name(obj->btf, map->real_name);
4302 	}
4303 	if (ret < 0)
4304 		return ret;
4305 
4306 	map->btf_key_type_id = key_type_id;
4307 	map->btf_value_type_id = bpf_map__is_internal(map) ?
4308 				 ret : value_type_id;
4309 	return 0;
4310 }
4311 
bpf_get_map_info_from_fdinfo(int fd,struct bpf_map_info * info)4312 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4313 {
4314 	char file[PATH_MAX], buff[4096];
4315 	FILE *fp;
4316 	__u32 val;
4317 	int err;
4318 
4319 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4320 	memset(info, 0, sizeof(*info));
4321 
4322 	fp = fopen(file, "r");
4323 	if (!fp) {
4324 		err = -errno;
4325 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4326 			err);
4327 		return err;
4328 	}
4329 
4330 	while (fgets(buff, sizeof(buff), fp)) {
4331 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4332 			info->type = val;
4333 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4334 			info->key_size = val;
4335 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4336 			info->value_size = val;
4337 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4338 			info->max_entries = val;
4339 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4340 			info->map_flags = val;
4341 	}
4342 
4343 	fclose(fp);
4344 
4345 	return 0;
4346 }
4347 
bpf_map__autocreate(const struct bpf_map * map)4348 bool bpf_map__autocreate(const struct bpf_map *map)
4349 {
4350 	return map->autocreate;
4351 }
4352 
bpf_map__set_autocreate(struct bpf_map * map,bool autocreate)4353 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4354 {
4355 	if (map->obj->loaded)
4356 		return libbpf_err(-EBUSY);
4357 
4358 	map->autocreate = autocreate;
4359 	return 0;
4360 }
4361 
bpf_map__reuse_fd(struct bpf_map * map,int fd)4362 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4363 {
4364 	struct bpf_map_info info = {};
4365 	__u32 len = sizeof(info), name_len;
4366 	int new_fd, err;
4367 	char *new_name;
4368 
4369 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4370 	if (err && errno == EINVAL)
4371 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4372 	if (err)
4373 		return libbpf_err(err);
4374 
4375 	name_len = strlen(info.name);
4376 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4377 		new_name = strdup(map->name);
4378 	else
4379 		new_name = strdup(info.name);
4380 
4381 	if (!new_name)
4382 		return libbpf_err(-errno);
4383 
4384 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4385 	if (new_fd < 0) {
4386 		err = -errno;
4387 		goto err_free_new_name;
4388 	}
4389 
4390 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4391 	if (new_fd < 0) {
4392 		err = -errno;
4393 		goto err_close_new_fd;
4394 	}
4395 
4396 	err = zclose(map->fd);
4397 	if (err) {
4398 		err = -errno;
4399 		goto err_close_new_fd;
4400 	}
4401 	free(map->name);
4402 
4403 	map->fd = new_fd;
4404 	map->name = new_name;
4405 	map->def.type = info.type;
4406 	map->def.key_size = info.key_size;
4407 	map->def.value_size = info.value_size;
4408 	map->def.max_entries = info.max_entries;
4409 	map->def.map_flags = info.map_flags;
4410 	map->btf_key_type_id = info.btf_key_type_id;
4411 	map->btf_value_type_id = info.btf_value_type_id;
4412 	map->reused = true;
4413 	map->map_extra = info.map_extra;
4414 
4415 	return 0;
4416 
4417 err_close_new_fd:
4418 	close(new_fd);
4419 err_free_new_name:
4420 	free(new_name);
4421 	return libbpf_err(err);
4422 }
4423 
bpf_map__max_entries(const struct bpf_map * map)4424 __u32 bpf_map__max_entries(const struct bpf_map *map)
4425 {
4426 	return map->def.max_entries;
4427 }
4428 
bpf_map__inner_map(struct bpf_map * map)4429 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4430 {
4431 	if (!bpf_map_type__is_map_in_map(map->def.type))
4432 		return errno = EINVAL, NULL;
4433 
4434 	return map->inner_map;
4435 }
4436 
bpf_map__set_max_entries(struct bpf_map * map,__u32 max_entries)4437 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4438 {
4439 	if (map->obj->loaded)
4440 		return libbpf_err(-EBUSY);
4441 
4442 	map->def.max_entries = max_entries;
4443 
4444 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4445 	if (map->def.type == BPF_MAP_TYPE_RINGBUF)
4446 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4447 
4448 	return 0;
4449 }
4450 
bpf_map__resize(struct bpf_map * map,__u32 max_entries)4451 int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4452 {
4453 	if (!map || !max_entries)
4454 		return libbpf_err(-EINVAL);
4455 
4456 	return bpf_map__set_max_entries(map, max_entries);
4457 }
4458 
4459 static int
bpf_object__probe_loading(struct bpf_object * obj)4460 bpf_object__probe_loading(struct bpf_object *obj)
4461 {
4462 	char *cp, errmsg[STRERR_BUFSIZE];
4463 	struct bpf_insn insns[] = {
4464 		BPF_MOV64_IMM(BPF_REG_0, 0),
4465 		BPF_EXIT_INSN(),
4466 	};
4467 	int ret, insn_cnt = ARRAY_SIZE(insns);
4468 
4469 	if (obj->gen_loader)
4470 		return 0;
4471 
4472 	ret = bump_rlimit_memlock();
4473 	if (ret)
4474 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4475 
4476 	/* make sure basic loading works */
4477 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4478 	if (ret < 0)
4479 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4480 	if (ret < 0) {
4481 		ret = errno;
4482 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4483 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4484 			"program. Make sure your kernel supports BPF "
4485 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4486 			"set to big enough value.\n", __func__, cp, ret);
4487 		return -ret;
4488 	}
4489 	close(ret);
4490 
4491 	return 0;
4492 }
4493 
probe_fd(int fd)4494 static int probe_fd(int fd)
4495 {
4496 	if (fd >= 0)
4497 		close(fd);
4498 	return fd >= 0;
4499 }
4500 
probe_kern_prog_name(void)4501 static int probe_kern_prog_name(void)
4502 {
4503 	struct bpf_insn insns[] = {
4504 		BPF_MOV64_IMM(BPF_REG_0, 0),
4505 		BPF_EXIT_INSN(),
4506 	};
4507 	int ret, insn_cnt = ARRAY_SIZE(insns);
4508 
4509 	/* make sure loading with name works */
4510 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
4511 	return probe_fd(ret);
4512 }
4513 
probe_kern_global_data(void)4514 static int probe_kern_global_data(void)
4515 {
4516 	char *cp, errmsg[STRERR_BUFSIZE];
4517 	struct bpf_insn insns[] = {
4518 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4519 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4520 		BPF_MOV64_IMM(BPF_REG_0, 0),
4521 		BPF_EXIT_INSN(),
4522 	};
4523 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4524 
4525 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4526 	if (map < 0) {
4527 		ret = -errno;
4528 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4529 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4530 			__func__, cp, -ret);
4531 		return ret;
4532 	}
4533 
4534 	insns[0].imm = map;
4535 
4536 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4537 	close(map);
4538 	return probe_fd(ret);
4539 }
4540 
probe_kern_btf(void)4541 static int probe_kern_btf(void)
4542 {
4543 	static const char strs[] = "\0int";
4544 	__u32 types[] = {
4545 		/* int */
4546 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4547 	};
4548 
4549 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4550 					     strs, sizeof(strs)));
4551 }
4552 
probe_kern_btf_func(void)4553 static int probe_kern_btf_func(void)
4554 {
4555 	static const char strs[] = "\0int\0x\0a";
4556 	/* void x(int a) {} */
4557 	__u32 types[] = {
4558 		/* int */
4559 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4560 		/* FUNC_PROTO */                                /* [2] */
4561 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4562 		BTF_PARAM_ENC(7, 1),
4563 		/* FUNC x */                                    /* [3] */
4564 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4565 	};
4566 
4567 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4568 					     strs, sizeof(strs)));
4569 }
4570 
probe_kern_btf_func_global(void)4571 static int probe_kern_btf_func_global(void)
4572 {
4573 	static const char strs[] = "\0int\0x\0a";
4574 	/* static void x(int a) {} */
4575 	__u32 types[] = {
4576 		/* int */
4577 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4578 		/* FUNC_PROTO */                                /* [2] */
4579 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4580 		BTF_PARAM_ENC(7, 1),
4581 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4582 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4583 	};
4584 
4585 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4586 					     strs, sizeof(strs)));
4587 }
4588 
probe_kern_btf_datasec(void)4589 static int probe_kern_btf_datasec(void)
4590 {
4591 	static const char strs[] = "\0x\0.data";
4592 	/* static int a; */
4593 	__u32 types[] = {
4594 		/* int */
4595 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4596 		/* VAR x */                                     /* [2] */
4597 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4598 		BTF_VAR_STATIC,
4599 		/* DATASEC val */                               /* [3] */
4600 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4601 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4602 	};
4603 
4604 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4605 					     strs, sizeof(strs)));
4606 }
4607 
probe_kern_btf_float(void)4608 static int probe_kern_btf_float(void)
4609 {
4610 	static const char strs[] = "\0float";
4611 	__u32 types[] = {
4612 		/* float */
4613 		BTF_TYPE_FLOAT_ENC(1, 4),
4614 	};
4615 
4616 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4617 					     strs, sizeof(strs)));
4618 }
4619 
probe_kern_btf_decl_tag(void)4620 static int probe_kern_btf_decl_tag(void)
4621 {
4622 	static const char strs[] = "\0tag";
4623 	__u32 types[] = {
4624 		/* int */
4625 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4626 		/* VAR x */                                     /* [2] */
4627 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4628 		BTF_VAR_STATIC,
4629 		/* attr */
4630 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4631 	};
4632 
4633 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4634 					     strs, sizeof(strs)));
4635 }
4636 
probe_kern_btf_type_tag(void)4637 static int probe_kern_btf_type_tag(void)
4638 {
4639 	static const char strs[] = "\0tag";
4640 	__u32 types[] = {
4641 		/* int */
4642 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4643 		/* attr */
4644 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4645 		/* ptr */
4646 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4647 	};
4648 
4649 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4650 					     strs, sizeof(strs)));
4651 }
4652 
probe_kern_array_mmap(void)4653 static int probe_kern_array_mmap(void)
4654 {
4655 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4656 	int fd;
4657 
4658 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4659 	return probe_fd(fd);
4660 }
4661 
probe_kern_exp_attach_type(void)4662 static int probe_kern_exp_attach_type(void)
4663 {
4664 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4665 	struct bpf_insn insns[] = {
4666 		BPF_MOV64_IMM(BPF_REG_0, 0),
4667 		BPF_EXIT_INSN(),
4668 	};
4669 	int fd, insn_cnt = ARRAY_SIZE(insns);
4670 
4671 	/* use any valid combination of program type and (optional)
4672 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4673 	 * to see if kernel supports expected_attach_type field for
4674 	 * BPF_PROG_LOAD command
4675 	 */
4676 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4677 	return probe_fd(fd);
4678 }
4679 
probe_kern_probe_read_kernel(void)4680 static int probe_kern_probe_read_kernel(void)
4681 {
4682 	struct bpf_insn insns[] = {
4683 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4684 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4685 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4686 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4687 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4688 		BPF_EXIT_INSN(),
4689 	};
4690 	int fd, insn_cnt = ARRAY_SIZE(insns);
4691 
4692 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4693 	return probe_fd(fd);
4694 }
4695 
probe_prog_bind_map(void)4696 static int probe_prog_bind_map(void)
4697 {
4698 	char *cp, errmsg[STRERR_BUFSIZE];
4699 	struct bpf_insn insns[] = {
4700 		BPF_MOV64_IMM(BPF_REG_0, 0),
4701 		BPF_EXIT_INSN(),
4702 	};
4703 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4704 
4705 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
4706 	if (map < 0) {
4707 		ret = -errno;
4708 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4709 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4710 			__func__, cp, -ret);
4711 		return ret;
4712 	}
4713 
4714 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4715 	if (prog < 0) {
4716 		close(map);
4717 		return 0;
4718 	}
4719 
4720 	ret = bpf_prog_bind_map(prog, map, NULL);
4721 
4722 	close(map);
4723 	close(prog);
4724 
4725 	return ret >= 0;
4726 }
4727 
probe_module_btf(void)4728 static int probe_module_btf(void)
4729 {
4730 	static const char strs[] = "\0int";
4731 	__u32 types[] = {
4732 		/* int */
4733 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4734 	};
4735 	struct bpf_btf_info info;
4736 	__u32 len = sizeof(info);
4737 	char name[16];
4738 	int fd, err;
4739 
4740 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4741 	if (fd < 0)
4742 		return 0; /* BTF not supported at all */
4743 
4744 	memset(&info, 0, sizeof(info));
4745 	info.name = ptr_to_u64(name);
4746 	info.name_len = sizeof(name);
4747 
4748 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4749 	 * kernel's module BTF support coincides with support for
4750 	 * name/name_len fields in struct bpf_btf_info.
4751 	 */
4752 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4753 	close(fd);
4754 	return !err;
4755 }
4756 
probe_perf_link(void)4757 static int probe_perf_link(void)
4758 {
4759 	struct bpf_insn insns[] = {
4760 		BPF_MOV64_IMM(BPF_REG_0, 0),
4761 		BPF_EXIT_INSN(),
4762 	};
4763 	int prog_fd, link_fd, err;
4764 
4765 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4766 				insns, ARRAY_SIZE(insns), NULL);
4767 	if (prog_fd < 0)
4768 		return -errno;
4769 
4770 	/* use invalid perf_event FD to get EBADF, if link is supported;
4771 	 * otherwise EINVAL should be returned
4772 	 */
4773 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4774 	err = -errno; /* close() can clobber errno */
4775 
4776 	if (link_fd >= 0)
4777 		close(link_fd);
4778 	close(prog_fd);
4779 
4780 	return link_fd < 0 && err == -EBADF;
4781 }
4782 
probe_kern_bpf_cookie(void)4783 static int probe_kern_bpf_cookie(void)
4784 {
4785 	struct bpf_insn insns[] = {
4786 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4787 		BPF_EXIT_INSN(),
4788 	};
4789 	int ret, insn_cnt = ARRAY_SIZE(insns);
4790 
4791 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4792 	return probe_fd(ret);
4793 }
4794 
4795 enum kern_feature_result {
4796 	FEAT_UNKNOWN = 0,
4797 	FEAT_SUPPORTED = 1,
4798 	FEAT_MISSING = 2,
4799 };
4800 
4801 typedef int (*feature_probe_fn)(void);
4802 
4803 static struct kern_feature_desc {
4804 	const char *desc;
4805 	feature_probe_fn probe;
4806 	enum kern_feature_result res;
4807 } feature_probes[__FEAT_CNT] = {
4808 	[FEAT_PROG_NAME] = {
4809 		"BPF program name", probe_kern_prog_name,
4810 	},
4811 	[FEAT_GLOBAL_DATA] = {
4812 		"global variables", probe_kern_global_data,
4813 	},
4814 	[FEAT_BTF] = {
4815 		"minimal BTF", probe_kern_btf,
4816 	},
4817 	[FEAT_BTF_FUNC] = {
4818 		"BTF functions", probe_kern_btf_func,
4819 	},
4820 	[FEAT_BTF_GLOBAL_FUNC] = {
4821 		"BTF global function", probe_kern_btf_func_global,
4822 	},
4823 	[FEAT_BTF_DATASEC] = {
4824 		"BTF data section and variable", probe_kern_btf_datasec,
4825 	},
4826 	[FEAT_ARRAY_MMAP] = {
4827 		"ARRAY map mmap()", probe_kern_array_mmap,
4828 	},
4829 	[FEAT_EXP_ATTACH_TYPE] = {
4830 		"BPF_PROG_LOAD expected_attach_type attribute",
4831 		probe_kern_exp_attach_type,
4832 	},
4833 	[FEAT_PROBE_READ_KERN] = {
4834 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4835 	},
4836 	[FEAT_PROG_BIND_MAP] = {
4837 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4838 	},
4839 	[FEAT_MODULE_BTF] = {
4840 		"module BTF support", probe_module_btf,
4841 	},
4842 	[FEAT_BTF_FLOAT] = {
4843 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4844 	},
4845 	[FEAT_PERF_LINK] = {
4846 		"BPF perf link support", probe_perf_link,
4847 	},
4848 	[FEAT_BTF_DECL_TAG] = {
4849 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4850 	},
4851 	[FEAT_BTF_TYPE_TAG] = {
4852 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4853 	},
4854 	[FEAT_MEMCG_ACCOUNT] = {
4855 		"memcg-based memory accounting", probe_memcg_account,
4856 	},
4857 	[FEAT_BPF_COOKIE] = {
4858 		"BPF cookie support", probe_kern_bpf_cookie,
4859 	},
4860 };
4861 
kernel_supports(const struct bpf_object * obj,enum kern_feature_id feat_id)4862 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4863 {
4864 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4865 	int ret;
4866 
4867 	if (obj && obj->gen_loader)
4868 		/* To generate loader program assume the latest kernel
4869 		 * to avoid doing extra prog_load, map_create syscalls.
4870 		 */
4871 		return true;
4872 
4873 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4874 		ret = feat->probe();
4875 		if (ret > 0) {
4876 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4877 		} else if (ret == 0) {
4878 			WRITE_ONCE(feat->res, FEAT_MISSING);
4879 		} else {
4880 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4881 			WRITE_ONCE(feat->res, FEAT_MISSING);
4882 		}
4883 	}
4884 
4885 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4886 }
4887 
map_is_reuse_compat(const struct bpf_map * map,int map_fd)4888 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4889 {
4890 	struct bpf_map_info map_info = {};
4891 	char msg[STRERR_BUFSIZE];
4892 	__u32 map_info_len;
4893 	int err;
4894 
4895 	map_info_len = sizeof(map_info);
4896 
4897 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4898 	if (err && errno == EINVAL)
4899 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4900 	if (err) {
4901 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4902 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4903 		return false;
4904 	}
4905 
4906 	return (map_info.type == map->def.type &&
4907 		map_info.key_size == map->def.key_size &&
4908 		map_info.value_size == map->def.value_size &&
4909 		map_info.max_entries == map->def.max_entries &&
4910 		map_info.map_flags == map->def.map_flags &&
4911 		map_info.map_extra == map->map_extra);
4912 }
4913 
4914 static int
bpf_object__reuse_map(struct bpf_map * map)4915 bpf_object__reuse_map(struct bpf_map *map)
4916 {
4917 	char *cp, errmsg[STRERR_BUFSIZE];
4918 	int err, pin_fd;
4919 
4920 	pin_fd = bpf_obj_get(map->pin_path);
4921 	if (pin_fd < 0) {
4922 		err = -errno;
4923 		if (err == -ENOENT) {
4924 			pr_debug("found no pinned map to reuse at '%s'\n",
4925 				 map->pin_path);
4926 			return 0;
4927 		}
4928 
4929 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4930 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4931 			map->pin_path, cp);
4932 		return err;
4933 	}
4934 
4935 	if (!map_is_reuse_compat(map, pin_fd)) {
4936 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4937 			map->pin_path);
4938 		close(pin_fd);
4939 		return -EINVAL;
4940 	}
4941 
4942 	err = bpf_map__reuse_fd(map, pin_fd);
4943 	close(pin_fd);
4944 	if (err) {
4945 		return err;
4946 	}
4947 	map->pinned = true;
4948 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
4949 
4950 	return 0;
4951 }
4952 
4953 static int
bpf_object__populate_internal_map(struct bpf_object * obj,struct bpf_map * map)4954 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4955 {
4956 	enum libbpf_map_type map_type = map->libbpf_type;
4957 	char *cp, errmsg[STRERR_BUFSIZE];
4958 	int err, zero = 0;
4959 
4960 	if (obj->gen_loader) {
4961 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4962 					 map->mmaped, map->def.value_size);
4963 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4964 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4965 		return 0;
4966 	}
4967 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4968 	if (err) {
4969 		err = -errno;
4970 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4971 		pr_warn("Error setting initial map(%s) contents: %s\n",
4972 			map->name, cp);
4973 		return err;
4974 	}
4975 
4976 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
4977 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4978 		err = bpf_map_freeze(map->fd);
4979 		if (err) {
4980 			err = -errno;
4981 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4982 			pr_warn("Error freezing map(%s) as read-only: %s\n",
4983 				map->name, cp);
4984 			return err;
4985 		}
4986 	}
4987 	return 0;
4988 }
4989 
4990 static void bpf_map__destroy(struct bpf_map *map);
4991 
bpf_object__create_map(struct bpf_object * obj,struct bpf_map * map,bool is_inner)4992 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4993 {
4994 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
4995 	struct bpf_map_def *def = &map->def;
4996 	const char *map_name = NULL;
4997 	int err = 0;
4998 
4999 	if (kernel_supports(obj, FEAT_PROG_NAME))
5000 		map_name = map->name;
5001 	create_attr.map_ifindex = map->map_ifindex;
5002 	create_attr.map_flags = def->map_flags;
5003 	create_attr.numa_node = map->numa_node;
5004 	create_attr.map_extra = map->map_extra;
5005 
5006 	if (bpf_map__is_struct_ops(map))
5007 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5008 
5009 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5010 		create_attr.btf_fd = btf__fd(obj->btf);
5011 		create_attr.btf_key_type_id = map->btf_key_type_id;
5012 		create_attr.btf_value_type_id = map->btf_value_type_id;
5013 	}
5014 
5015 	if (bpf_map_type__is_map_in_map(def->type)) {
5016 		if (map->inner_map) {
5017 			err = bpf_object__create_map(obj, map->inner_map, true);
5018 			if (err) {
5019 				pr_warn("map '%s': failed to create inner map: %d\n",
5020 					map->name, err);
5021 				return err;
5022 			}
5023 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5024 		}
5025 		if (map->inner_map_fd >= 0)
5026 			create_attr.inner_map_fd = map->inner_map_fd;
5027 	}
5028 
5029 	switch (def->type) {
5030 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5031 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5032 	case BPF_MAP_TYPE_STACK_TRACE:
5033 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5034 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5035 	case BPF_MAP_TYPE_DEVMAP:
5036 	case BPF_MAP_TYPE_DEVMAP_HASH:
5037 	case BPF_MAP_TYPE_CPUMAP:
5038 	case BPF_MAP_TYPE_XSKMAP:
5039 	case BPF_MAP_TYPE_SOCKMAP:
5040 	case BPF_MAP_TYPE_SOCKHASH:
5041 	case BPF_MAP_TYPE_QUEUE:
5042 	case BPF_MAP_TYPE_STACK:
5043 		create_attr.btf_fd = 0;
5044 		create_attr.btf_key_type_id = 0;
5045 		create_attr.btf_value_type_id = 0;
5046 		map->btf_key_type_id = 0;
5047 		map->btf_value_type_id = 0;
5048 	default:
5049 		break;
5050 	}
5051 
5052 	if (obj->gen_loader) {
5053 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5054 				    def->key_size, def->value_size, def->max_entries,
5055 				    &create_attr, is_inner ? -1 : map - obj->maps);
5056 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5057 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5058 		 */
5059 		map->fd = 0;
5060 	} else {
5061 		map->fd = bpf_map_create(def->type, map_name,
5062 					 def->key_size, def->value_size,
5063 					 def->max_entries, &create_attr);
5064 	}
5065 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5066 			    create_attr.btf_value_type_id)) {
5067 		char *cp, errmsg[STRERR_BUFSIZE];
5068 
5069 		err = -errno;
5070 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5071 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5072 			map->name, cp, err);
5073 		create_attr.btf_fd = 0;
5074 		create_attr.btf_key_type_id = 0;
5075 		create_attr.btf_value_type_id = 0;
5076 		map->btf_key_type_id = 0;
5077 		map->btf_value_type_id = 0;
5078 		map->fd = bpf_map_create(def->type, map_name,
5079 					 def->key_size, def->value_size,
5080 					 def->max_entries, &create_attr);
5081 	}
5082 
5083 	err = map->fd < 0 ? -errno : 0;
5084 
5085 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5086 		if (obj->gen_loader)
5087 			map->inner_map->fd = -1;
5088 		bpf_map__destroy(map->inner_map);
5089 		zfree(&map->inner_map);
5090 	}
5091 
5092 	return err;
5093 }
5094 
init_map_in_map_slots(struct bpf_object * obj,struct bpf_map * map)5095 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5096 {
5097 	const struct bpf_map *targ_map;
5098 	unsigned int i;
5099 	int fd, err = 0;
5100 
5101 	for (i = 0; i < map->init_slots_sz; i++) {
5102 		if (!map->init_slots[i])
5103 			continue;
5104 
5105 		targ_map = map->init_slots[i];
5106 		fd = bpf_map__fd(targ_map);
5107 
5108 		if (obj->gen_loader) {
5109 			bpf_gen__populate_outer_map(obj->gen_loader,
5110 						    map - obj->maps, i,
5111 						    targ_map - obj->maps);
5112 		} else {
5113 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5114 		}
5115 		if (err) {
5116 			err = -errno;
5117 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5118 				map->name, i, targ_map->name, fd, err);
5119 			return err;
5120 		}
5121 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5122 			 map->name, i, targ_map->name, fd);
5123 	}
5124 
5125 	zfree(&map->init_slots);
5126 	map->init_slots_sz = 0;
5127 
5128 	return 0;
5129 }
5130 
init_prog_array_slots(struct bpf_object * obj,struct bpf_map * map)5131 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5132 {
5133 	const struct bpf_program *targ_prog;
5134 	unsigned int i;
5135 	int fd, err;
5136 
5137 	if (obj->gen_loader)
5138 		return -ENOTSUP;
5139 
5140 	for (i = 0; i < map->init_slots_sz; i++) {
5141 		if (!map->init_slots[i])
5142 			continue;
5143 
5144 		targ_prog = map->init_slots[i];
5145 		fd = bpf_program__fd(targ_prog);
5146 
5147 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5148 		if (err) {
5149 			err = -errno;
5150 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5151 				map->name, i, targ_prog->name, fd, err);
5152 			return err;
5153 		}
5154 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5155 			 map->name, i, targ_prog->name, fd);
5156 	}
5157 
5158 	zfree(&map->init_slots);
5159 	map->init_slots_sz = 0;
5160 
5161 	return 0;
5162 }
5163 
bpf_object_init_prog_arrays(struct bpf_object * obj)5164 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5165 {
5166 	struct bpf_map *map;
5167 	int i, err;
5168 
5169 	for (i = 0; i < obj->nr_maps; i++) {
5170 		map = &obj->maps[i];
5171 
5172 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5173 			continue;
5174 
5175 		err = init_prog_array_slots(obj, map);
5176 		if (err < 0) {
5177 			zclose(map->fd);
5178 			return err;
5179 		}
5180 	}
5181 	return 0;
5182 }
5183 
map_set_def_max_entries(struct bpf_map * map)5184 static int map_set_def_max_entries(struct bpf_map *map)
5185 {
5186 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5187 		int nr_cpus;
5188 
5189 		nr_cpus = libbpf_num_possible_cpus();
5190 		if (nr_cpus < 0) {
5191 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5192 				map->name, nr_cpus);
5193 			return nr_cpus;
5194 		}
5195 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5196 		map->def.max_entries = nr_cpus;
5197 	}
5198 
5199 	return 0;
5200 }
5201 
5202 static int
bpf_object__create_maps(struct bpf_object * obj)5203 bpf_object__create_maps(struct bpf_object *obj)
5204 {
5205 	struct bpf_map *map;
5206 	char *cp, errmsg[STRERR_BUFSIZE];
5207 	unsigned int i, j;
5208 	int err;
5209 	bool retried;
5210 
5211 	for (i = 0; i < obj->nr_maps; i++) {
5212 		map = &obj->maps[i];
5213 
5214 		/* To support old kernels, we skip creating global data maps
5215 		 * (.rodata, .data, .kconfig, etc); later on, during program
5216 		 * loading, if we detect that at least one of the to-be-loaded
5217 		 * programs is referencing any global data map, we'll error
5218 		 * out with program name and relocation index logged.
5219 		 * This approach allows to accommodate Clang emitting
5220 		 * unnecessary .rodata.str1.1 sections for string literals,
5221 		 * but also it allows to have CO-RE applications that use
5222 		 * global variables in some of BPF programs, but not others.
5223 		 * If those global variable-using programs are not loaded at
5224 		 * runtime due to bpf_program__set_autoload(prog, false),
5225 		 * bpf_object loading will succeed just fine even on old
5226 		 * kernels.
5227 		 */
5228 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5229 			map->autocreate = false;
5230 
5231 		if (!map->autocreate) {
5232 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5233 			continue;
5234 		}
5235 
5236 		err = map_set_def_max_entries(map);
5237 		if (err)
5238 			goto err_out;
5239 
5240 		retried = false;
5241 retry:
5242 		if (map->pin_path) {
5243 			err = bpf_object__reuse_map(map);
5244 			if (err) {
5245 				pr_warn("map '%s': error reusing pinned map\n",
5246 					map->name);
5247 				goto err_out;
5248 			}
5249 			if (retried && map->fd < 0) {
5250 				pr_warn("map '%s': cannot find pinned map\n",
5251 					map->name);
5252 				err = -ENOENT;
5253 				goto err_out;
5254 			}
5255 		}
5256 
5257 		if (map->fd >= 0) {
5258 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5259 				 map->name, map->fd);
5260 		} else {
5261 			err = bpf_object__create_map(obj, map, false);
5262 			if (err)
5263 				goto err_out;
5264 
5265 			pr_debug("map '%s': created successfully, fd=%d\n",
5266 				 map->name, map->fd);
5267 
5268 			if (bpf_map__is_internal(map)) {
5269 				err = bpf_object__populate_internal_map(obj, map);
5270 				if (err < 0) {
5271 					zclose(map->fd);
5272 					goto err_out;
5273 				}
5274 			}
5275 
5276 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5277 				err = init_map_in_map_slots(obj, map);
5278 				if (err < 0) {
5279 					zclose(map->fd);
5280 					goto err_out;
5281 				}
5282 			}
5283 		}
5284 
5285 		if (map->pin_path && !map->pinned) {
5286 			err = bpf_map__pin(map, NULL);
5287 			if (err) {
5288 				zclose(map->fd);
5289 				if (!retried && err == -EEXIST) {
5290 					retried = true;
5291 					goto retry;
5292 				}
5293 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5294 					map->name, map->pin_path, err);
5295 				goto err_out;
5296 			}
5297 		}
5298 	}
5299 
5300 	return 0;
5301 
5302 err_out:
5303 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5304 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5305 	pr_perm_msg(err);
5306 	for (j = 0; j < i; j++)
5307 		zclose(obj->maps[j].fd);
5308 	return err;
5309 }
5310 
bpf_core_is_flavor_sep(const char * s)5311 static bool bpf_core_is_flavor_sep(const char *s)
5312 {
5313 	/* check X___Y name pattern, where X and Y are not underscores */
5314 	return s[0] != '_' &&				      /* X */
5315 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5316 	       s[4] != '_';				      /* Y */
5317 }
5318 
5319 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5320  * before last triple underscore. Struct name part after last triple
5321  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5322  */
bpf_core_essential_name_len(const char * name)5323 size_t bpf_core_essential_name_len(const char *name)
5324 {
5325 	size_t n = strlen(name);
5326 	int i;
5327 
5328 	for (i = n - 5; i >= 0; i--) {
5329 		if (bpf_core_is_flavor_sep(name + i))
5330 			return i + 1;
5331 	}
5332 	return n;
5333 }
5334 
bpf_core_free_cands(struct bpf_core_cand_list * cands)5335 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5336 {
5337 	if (!cands)
5338 		return;
5339 
5340 	free(cands->cands);
5341 	free(cands);
5342 }
5343 
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)5344 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5345 		       size_t local_essent_len,
5346 		       const struct btf *targ_btf,
5347 		       const char *targ_btf_name,
5348 		       int targ_start_id,
5349 		       struct bpf_core_cand_list *cands)
5350 {
5351 	struct bpf_core_cand *new_cands, *cand;
5352 	const struct btf_type *t, *local_t;
5353 	const char *targ_name, *local_name;
5354 	size_t targ_essent_len;
5355 	int n, i;
5356 
5357 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5358 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5359 
5360 	n = btf__type_cnt(targ_btf);
5361 	for (i = targ_start_id; i < n; i++) {
5362 		t = btf__type_by_id(targ_btf, i);
5363 		if (btf_kind(t) != btf_kind(local_t))
5364 			continue;
5365 
5366 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5367 		if (str_is_empty(targ_name))
5368 			continue;
5369 
5370 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5371 		if (targ_essent_len != local_essent_len)
5372 			continue;
5373 
5374 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5375 			continue;
5376 
5377 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5378 			 local_cand->id, btf_kind_str(local_t),
5379 			 local_name, i, btf_kind_str(t), targ_name,
5380 			 targ_btf_name);
5381 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5382 					      sizeof(*cands->cands));
5383 		if (!new_cands)
5384 			return -ENOMEM;
5385 
5386 		cand = &new_cands[cands->len];
5387 		cand->btf = targ_btf;
5388 		cand->id = i;
5389 
5390 		cands->cands = new_cands;
5391 		cands->len++;
5392 	}
5393 	return 0;
5394 }
5395 
load_module_btfs(struct bpf_object * obj)5396 static int load_module_btfs(struct bpf_object *obj)
5397 {
5398 	struct bpf_btf_info info;
5399 	struct module_btf *mod_btf;
5400 	struct btf *btf;
5401 	char name[64];
5402 	__u32 id = 0, len;
5403 	int err, fd;
5404 
5405 	if (obj->btf_modules_loaded)
5406 		return 0;
5407 
5408 	if (obj->gen_loader)
5409 		return 0;
5410 
5411 	/* don't do this again, even if we find no module BTFs */
5412 	obj->btf_modules_loaded = true;
5413 
5414 	/* kernel too old to support module BTFs */
5415 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5416 		return 0;
5417 
5418 	while (true) {
5419 		err = bpf_btf_get_next_id(id, &id);
5420 		if (err && errno == ENOENT)
5421 			return 0;
5422 		if (err) {
5423 			err = -errno;
5424 			pr_warn("failed to iterate BTF objects: %d\n", err);
5425 			return err;
5426 		}
5427 
5428 		fd = bpf_btf_get_fd_by_id(id);
5429 		if (fd < 0) {
5430 			if (errno == ENOENT)
5431 				continue; /* expected race: BTF was unloaded */
5432 			err = -errno;
5433 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5434 			return err;
5435 		}
5436 
5437 		len = sizeof(info);
5438 		memset(&info, 0, sizeof(info));
5439 		info.name = ptr_to_u64(name);
5440 		info.name_len = sizeof(name);
5441 
5442 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5443 		if (err) {
5444 			err = -errno;
5445 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5446 			goto err_out;
5447 		}
5448 
5449 		/* ignore non-module BTFs */
5450 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5451 			close(fd);
5452 			continue;
5453 		}
5454 
5455 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5456 		err = libbpf_get_error(btf);
5457 		if (err) {
5458 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5459 				name, id, err);
5460 			goto err_out;
5461 		}
5462 
5463 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5464 				        sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5465 		if (err)
5466 			goto err_out;
5467 
5468 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5469 
5470 		mod_btf->btf = btf;
5471 		mod_btf->id = id;
5472 		mod_btf->fd = fd;
5473 		mod_btf->name = strdup(name);
5474 		if (!mod_btf->name) {
5475 			err = -ENOMEM;
5476 			goto err_out;
5477 		}
5478 		continue;
5479 
5480 err_out:
5481 		close(fd);
5482 		return err;
5483 	}
5484 
5485 	return 0;
5486 }
5487 
5488 static struct bpf_core_cand_list *
bpf_core_find_cands(struct bpf_object * obj,const struct btf * local_btf,__u32 local_type_id)5489 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5490 {
5491 	struct bpf_core_cand local_cand = {};
5492 	struct bpf_core_cand_list *cands;
5493 	const struct btf *main_btf;
5494 	const struct btf_type *local_t;
5495 	const char *local_name;
5496 	size_t local_essent_len;
5497 	int err, i;
5498 
5499 	local_cand.btf = local_btf;
5500 	local_cand.id = local_type_id;
5501 	local_t = btf__type_by_id(local_btf, local_type_id);
5502 	if (!local_t)
5503 		return ERR_PTR(-EINVAL);
5504 
5505 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5506 	if (str_is_empty(local_name))
5507 		return ERR_PTR(-EINVAL);
5508 	local_essent_len = bpf_core_essential_name_len(local_name);
5509 
5510 	cands = calloc(1, sizeof(*cands));
5511 	if (!cands)
5512 		return ERR_PTR(-ENOMEM);
5513 
5514 	/* Attempt to find target candidates in vmlinux BTF first */
5515 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5516 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5517 	if (err)
5518 		goto err_out;
5519 
5520 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5521 	if (cands->len)
5522 		return cands;
5523 
5524 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5525 	if (obj->btf_vmlinux_override)
5526 		return cands;
5527 
5528 	/* now look through module BTFs, trying to still find candidates */
5529 	err = load_module_btfs(obj);
5530 	if (err)
5531 		goto err_out;
5532 
5533 	for (i = 0; i < obj->btf_module_cnt; i++) {
5534 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5535 					 obj->btf_modules[i].btf,
5536 					 obj->btf_modules[i].name,
5537 					 btf__type_cnt(obj->btf_vmlinux),
5538 					 cands);
5539 		if (err)
5540 			goto err_out;
5541 	}
5542 
5543 	return cands;
5544 err_out:
5545 	bpf_core_free_cands(cands);
5546 	return ERR_PTR(err);
5547 }
5548 
5549 /* Check local and target types for compatibility. This check is used for
5550  * type-based CO-RE relocations and follow slightly different rules than
5551  * field-based relocations. This function assumes that root types were already
5552  * checked for name match. Beyond that initial root-level name check, names
5553  * are completely ignored. Compatibility rules are as follows:
5554  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5555  *     kind should match for local and target types (i.e., STRUCT is not
5556  *     compatible with UNION);
5557  *   - for ENUMs, the size is ignored;
5558  *   - for INT, size and signedness are ignored;
5559  *   - for ARRAY, dimensionality is ignored, element types are checked for
5560  *     compatibility recursively;
5561  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5562  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5563  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5564  *     number of input args and compatible return and argument types.
5565  * These rules are not set in stone and probably will be adjusted as we get
5566  * more experience with using BPF CO-RE relocations.
5567  */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)5568 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5569 			      const struct btf *targ_btf, __u32 targ_id)
5570 {
5571 	const struct btf_type *local_type, *targ_type;
5572 	int depth = 32; /* max recursion depth */
5573 
5574 	/* caller made sure that names match (ignoring flavor suffix) */
5575 	local_type = btf__type_by_id(local_btf, local_id);
5576 	targ_type = btf__type_by_id(targ_btf, targ_id);
5577 	if (btf_kind(local_type) != btf_kind(targ_type))
5578 		return 0;
5579 
5580 recur:
5581 	depth--;
5582 	if (depth < 0)
5583 		return -EINVAL;
5584 
5585 	local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5586 	targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5587 	if (!local_type || !targ_type)
5588 		return -EINVAL;
5589 
5590 	if (btf_kind(local_type) != btf_kind(targ_type))
5591 		return 0;
5592 
5593 	switch (btf_kind(local_type)) {
5594 	case BTF_KIND_UNKN:
5595 	case BTF_KIND_STRUCT:
5596 	case BTF_KIND_UNION:
5597 	case BTF_KIND_ENUM:
5598 	case BTF_KIND_FWD:
5599 		return 1;
5600 	case BTF_KIND_INT:
5601 		/* just reject deprecated bitfield-like integers; all other
5602 		 * integers are by default compatible between each other
5603 		 */
5604 		return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5605 	case BTF_KIND_PTR:
5606 		local_id = local_type->type;
5607 		targ_id = targ_type->type;
5608 		goto recur;
5609 	case BTF_KIND_ARRAY:
5610 		local_id = btf_array(local_type)->type;
5611 		targ_id = btf_array(targ_type)->type;
5612 		goto recur;
5613 	case BTF_KIND_FUNC_PROTO: {
5614 		struct btf_param *local_p = btf_params(local_type);
5615 		struct btf_param *targ_p = btf_params(targ_type);
5616 		__u16 local_vlen = btf_vlen(local_type);
5617 		__u16 targ_vlen = btf_vlen(targ_type);
5618 		int i, err;
5619 
5620 		if (local_vlen != targ_vlen)
5621 			return 0;
5622 
5623 		for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5624 			skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5625 			skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5626 			err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5627 			if (err <= 0)
5628 				return err;
5629 		}
5630 
5631 		/* tail recurse for return type check */
5632 		skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5633 		skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5634 		goto recur;
5635 	}
5636 	default:
5637 		pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5638 			btf_kind_str(local_type), local_id, targ_id);
5639 		return 0;
5640 	}
5641 }
5642 
bpf_core_hash_fn(const void * key,void * ctx)5643 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5644 {
5645 	return (size_t)key;
5646 }
5647 
bpf_core_equal_fn(const void * k1,const void * k2,void * ctx)5648 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5649 {
5650 	return k1 == k2;
5651 }
5652 
u32_as_hash_key(__u32 x)5653 static void *u32_as_hash_key(__u32 x)
5654 {
5655 	return (void *)(uintptr_t)x;
5656 }
5657 
record_relo_core(struct bpf_program * prog,const struct bpf_core_relo * core_relo,int insn_idx)5658 static int record_relo_core(struct bpf_program *prog,
5659 			    const struct bpf_core_relo *core_relo, int insn_idx)
5660 {
5661 	struct reloc_desc *relos, *relo;
5662 
5663 	relos = libbpf_reallocarray(prog->reloc_desc,
5664 				    prog->nr_reloc + 1, sizeof(*relos));
5665 	if (!relos)
5666 		return -ENOMEM;
5667 	relo = &relos[prog->nr_reloc];
5668 	relo->type = RELO_CORE;
5669 	relo->insn_idx = insn_idx;
5670 	relo->core_relo = core_relo;
5671 	prog->reloc_desc = relos;
5672 	prog->nr_reloc++;
5673 	return 0;
5674 }
5675 
find_relo_core(struct bpf_program * prog,int insn_idx)5676 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5677 {
5678 	struct reloc_desc *relo;
5679 	int i;
5680 
5681 	for (i = 0; i < prog->nr_reloc; i++) {
5682 		relo = &prog->reloc_desc[i];
5683 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5684 			continue;
5685 
5686 		return relo->core_relo;
5687 	}
5688 
5689 	return NULL;
5690 }
5691 
bpf_core_resolve_relo(struct bpf_program * prog,const struct bpf_core_relo * relo,int relo_idx,const struct btf * local_btf,struct hashmap * cand_cache,struct bpf_core_relo_res * targ_res)5692 static int bpf_core_resolve_relo(struct bpf_program *prog,
5693 				 const struct bpf_core_relo *relo,
5694 				 int relo_idx,
5695 				 const struct btf *local_btf,
5696 				 struct hashmap *cand_cache,
5697 				 struct bpf_core_relo_res *targ_res)
5698 {
5699 	struct bpf_core_spec specs_scratch[3] = {};
5700 	const void *type_key = u32_as_hash_key(relo->type_id);
5701 	struct bpf_core_cand_list *cands = NULL;
5702 	const char *prog_name = prog->name;
5703 	const struct btf_type *local_type;
5704 	const char *local_name;
5705 	__u32 local_id = relo->type_id;
5706 	int err;
5707 
5708 	local_type = btf__type_by_id(local_btf, local_id);
5709 	if (!local_type)
5710 		return -EINVAL;
5711 
5712 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5713 	if (!local_name)
5714 		return -EINVAL;
5715 
5716 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5717 	    !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5718 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5719 		if (IS_ERR(cands)) {
5720 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5721 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5722 				local_name, PTR_ERR(cands));
5723 			return PTR_ERR(cands);
5724 		}
5725 		err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5726 		if (err) {
5727 			bpf_core_free_cands(cands);
5728 			return err;
5729 		}
5730 	}
5731 
5732 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5733 				       targ_res);
5734 }
5735 
5736 static int
bpf_object__relocate_core(struct bpf_object * obj,const char * targ_btf_path)5737 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5738 {
5739 	const struct btf_ext_info_sec *sec;
5740 	struct bpf_core_relo_res targ_res;
5741 	const struct bpf_core_relo *rec;
5742 	const struct btf_ext_info *seg;
5743 	struct hashmap_entry *entry;
5744 	struct hashmap *cand_cache = NULL;
5745 	struct bpf_program *prog;
5746 	struct bpf_insn *insn;
5747 	const char *sec_name;
5748 	int i, err = 0, insn_idx, sec_idx, sec_num;
5749 
5750 	if (obj->btf_ext->core_relo_info.len == 0)
5751 		return 0;
5752 
5753 	if (targ_btf_path) {
5754 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5755 		err = libbpf_get_error(obj->btf_vmlinux_override);
5756 		if (err) {
5757 			pr_warn("failed to parse target BTF: %d\n", err);
5758 			return err;
5759 		}
5760 	}
5761 
5762 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5763 	if (IS_ERR(cand_cache)) {
5764 		err = PTR_ERR(cand_cache);
5765 		goto out;
5766 	}
5767 
5768 	seg = &obj->btf_ext->core_relo_info;
5769 	sec_num = 0;
5770 	for_each_btf_ext_sec(seg, sec) {
5771 		sec_idx = seg->sec_idxs[sec_num];
5772 		sec_num++;
5773 
5774 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5775 		if (str_is_empty(sec_name)) {
5776 			err = -EINVAL;
5777 			goto out;
5778 		}
5779 
5780 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5781 
5782 		for_each_btf_ext_rec(seg, sec, i, rec) {
5783 			if (rec->insn_off % BPF_INSN_SZ)
5784 				return -EINVAL;
5785 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5786 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5787 			if (!prog) {
5788 				/* When __weak subprog is "overridden" by another instance
5789 				 * of the subprog from a different object file, linker still
5790 				 * appends all the .BTF.ext info that used to belong to that
5791 				 * eliminated subprogram.
5792 				 * This is similar to what x86-64 linker does for relocations.
5793 				 * So just ignore such relocations just like we ignore
5794 				 * subprog instructions when discovering subprograms.
5795 				 */
5796 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5797 					 sec_name, i, insn_idx);
5798 				continue;
5799 			}
5800 			/* no need to apply CO-RE relocation if the program is
5801 			 * not going to be loaded
5802 			 */
5803 			if (!prog->autoload)
5804 				continue;
5805 
5806 			/* adjust insn_idx from section frame of reference to the local
5807 			 * program's frame of reference; (sub-)program code is not yet
5808 			 * relocated, so it's enough to just subtract in-section offset
5809 			 */
5810 			insn_idx = insn_idx - prog->sec_insn_off;
5811 			if (insn_idx >= prog->insns_cnt)
5812 				return -EINVAL;
5813 			insn = &prog->insns[insn_idx];
5814 
5815 			err = record_relo_core(prog, rec, insn_idx);
5816 			if (err) {
5817 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5818 					prog->name, i, err);
5819 				goto out;
5820 			}
5821 
5822 			if (prog->obj->gen_loader)
5823 				continue;
5824 
5825 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5826 			if (err) {
5827 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5828 					prog->name, i, err);
5829 				goto out;
5830 			}
5831 
5832 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5833 			if (err) {
5834 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5835 					prog->name, i, insn_idx, err);
5836 				goto out;
5837 			}
5838 		}
5839 	}
5840 
5841 out:
5842 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5843 	btf__free(obj->btf_vmlinux_override);
5844 	obj->btf_vmlinux_override = NULL;
5845 
5846 	if (!IS_ERR_OR_NULL(cand_cache)) {
5847 		hashmap__for_each_entry(cand_cache, entry, i) {
5848 			bpf_core_free_cands(entry->value);
5849 		}
5850 		hashmap__free(cand_cache);
5851 	}
5852 	return err;
5853 }
5854 
5855 /* base map load ldimm64 special constant, used also for log fixup logic */
5856 #define MAP_LDIMM64_POISON_BASE 2001000000
5857 #define MAP_LDIMM64_POISON_PFX "200100"
5858 
poison_map_ldimm64(struct bpf_program * prog,int relo_idx,int insn_idx,struct bpf_insn * insn,int map_idx,const struct bpf_map * map)5859 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5860 			       int insn_idx, struct bpf_insn *insn,
5861 			       int map_idx, const struct bpf_map *map)
5862 {
5863 	int i;
5864 
5865 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5866 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5867 
5868 	/* we turn single ldimm64 into two identical invalid calls */
5869 	for (i = 0; i < 2; i++) {
5870 		insn->code = BPF_JMP | BPF_CALL;
5871 		insn->dst_reg = 0;
5872 		insn->src_reg = 0;
5873 		insn->off = 0;
5874 		/* if this instruction is reachable (not a dead code),
5875 		 * verifier will complain with something like:
5876 		 * invalid func unknown#2001000123
5877 		 * where lower 123 is map index into obj->maps[] array
5878 		 */
5879 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5880 
5881 		insn++;
5882 	}
5883 }
5884 
5885 /* Relocate data references within program code:
5886  *  - map references;
5887  *  - global variable references;
5888  *  - extern references.
5889  */
5890 static int
bpf_object__relocate_data(struct bpf_object * obj,struct bpf_program * prog)5891 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5892 {
5893 	int i;
5894 
5895 	for (i = 0; i < prog->nr_reloc; i++) {
5896 		struct reloc_desc *relo = &prog->reloc_desc[i];
5897 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5898 		const struct bpf_map *map;
5899 		struct extern_desc *ext;
5900 
5901 		switch (relo->type) {
5902 		case RELO_LD64:
5903 			map = &obj->maps[relo->map_idx];
5904 			if (obj->gen_loader) {
5905 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5906 				insn[0].imm = relo->map_idx;
5907 			} else if (map->autocreate) {
5908 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5909 				insn[0].imm = map->fd;
5910 			} else {
5911 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5912 						   relo->map_idx, map);
5913 			}
5914 			break;
5915 		case RELO_DATA:
5916 			map = &obj->maps[relo->map_idx];
5917 			insn[1].imm = insn[0].imm + relo->sym_off;
5918 			if (obj->gen_loader) {
5919 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5920 				insn[0].imm = relo->map_idx;
5921 			} else if (map->autocreate) {
5922 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5923 				insn[0].imm = map->fd;
5924 			} else {
5925 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5926 						   relo->map_idx, map);
5927 			}
5928 			break;
5929 		case RELO_EXTERN_VAR:
5930 			ext = &obj->externs[relo->sym_off];
5931 			if (ext->type == EXT_KCFG) {
5932 				if (obj->gen_loader) {
5933 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5934 					insn[0].imm = obj->kconfig_map_idx;
5935 				} else {
5936 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5937 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5938 				}
5939 				insn[1].imm = ext->kcfg.data_off;
5940 			} else /* EXT_KSYM */ {
5941 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5942 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5943 					insn[0].imm = ext->ksym.kernel_btf_id;
5944 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5945 				} else { /* typeless ksyms or unresolved typed ksyms */
5946 					insn[0].imm = (__u32)ext->ksym.addr;
5947 					insn[1].imm = ext->ksym.addr >> 32;
5948 				}
5949 			}
5950 			break;
5951 		case RELO_EXTERN_FUNC:
5952 			ext = &obj->externs[relo->sym_off];
5953 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5954 			if (ext->is_set) {
5955 				insn[0].imm = ext->ksym.kernel_btf_id;
5956 				insn[0].off = ext->ksym.btf_fd_idx;
5957 			} else { /* unresolved weak kfunc */
5958 				insn[0].imm = 0;
5959 				insn[0].off = 0;
5960 			}
5961 			break;
5962 		case RELO_SUBPROG_ADDR:
5963 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5964 				pr_warn("prog '%s': relo #%d: bad insn\n",
5965 					prog->name, i);
5966 				return -EINVAL;
5967 			}
5968 			/* handled already */
5969 			break;
5970 		case RELO_CALL:
5971 			/* handled already */
5972 			break;
5973 		case RELO_CORE:
5974 			/* will be handled by bpf_program_record_relos() */
5975 			break;
5976 		default:
5977 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5978 				prog->name, i, relo->type);
5979 			return -EINVAL;
5980 		}
5981 	}
5982 
5983 	return 0;
5984 }
5985 
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)5986 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5987 				    const struct bpf_program *prog,
5988 				    const struct btf_ext_info *ext_info,
5989 				    void **prog_info, __u32 *prog_rec_cnt,
5990 				    __u32 *prog_rec_sz)
5991 {
5992 	void *copy_start = NULL, *copy_end = NULL;
5993 	void *rec, *rec_end, *new_prog_info;
5994 	const struct btf_ext_info_sec *sec;
5995 	size_t old_sz, new_sz;
5996 	int i, sec_num, sec_idx, off_adj;
5997 
5998 	sec_num = 0;
5999 	for_each_btf_ext_sec(ext_info, sec) {
6000 		sec_idx = ext_info->sec_idxs[sec_num];
6001 		sec_num++;
6002 		if (prog->sec_idx != sec_idx)
6003 			continue;
6004 
6005 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6006 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6007 
6008 			if (insn_off < prog->sec_insn_off)
6009 				continue;
6010 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6011 				break;
6012 
6013 			if (!copy_start)
6014 				copy_start = rec;
6015 			copy_end = rec + ext_info->rec_size;
6016 		}
6017 
6018 		if (!copy_start)
6019 			return -ENOENT;
6020 
6021 		/* append func/line info of a given (sub-)program to the main
6022 		 * program func/line info
6023 		 */
6024 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6025 		new_sz = old_sz + (copy_end - copy_start);
6026 		new_prog_info = realloc(*prog_info, new_sz);
6027 		if (!new_prog_info)
6028 			return -ENOMEM;
6029 		*prog_info = new_prog_info;
6030 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6031 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6032 
6033 		/* Kernel instruction offsets are in units of 8-byte
6034 		 * instructions, while .BTF.ext instruction offsets generated
6035 		 * by Clang are in units of bytes. So convert Clang offsets
6036 		 * into kernel offsets and adjust offset according to program
6037 		 * relocated position.
6038 		 */
6039 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6040 		rec = new_prog_info + old_sz;
6041 		rec_end = new_prog_info + new_sz;
6042 		for (; rec < rec_end; rec += ext_info->rec_size) {
6043 			__u32 *insn_off = rec;
6044 
6045 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6046 		}
6047 		*prog_rec_sz = ext_info->rec_size;
6048 		return 0;
6049 	}
6050 
6051 	return -ENOENT;
6052 }
6053 
6054 static int
reloc_prog_func_and_line_info(const struct bpf_object * obj,struct bpf_program * main_prog,const struct bpf_program * prog)6055 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6056 			      struct bpf_program *main_prog,
6057 			      const struct bpf_program *prog)
6058 {
6059 	int err;
6060 
6061 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6062 	 * supprot func/line info
6063 	 */
6064 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6065 		return 0;
6066 
6067 	/* only attempt func info relocation if main program's func_info
6068 	 * relocation was successful
6069 	 */
6070 	if (main_prog != prog && !main_prog->func_info)
6071 		goto line_info;
6072 
6073 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6074 				       &main_prog->func_info,
6075 				       &main_prog->func_info_cnt,
6076 				       &main_prog->func_info_rec_size);
6077 	if (err) {
6078 		if (err != -ENOENT) {
6079 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6080 				prog->name, err);
6081 			return err;
6082 		}
6083 		if (main_prog->func_info) {
6084 			/*
6085 			 * Some info has already been found but has problem
6086 			 * in the last btf_ext reloc. Must have to error out.
6087 			 */
6088 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6089 			return err;
6090 		}
6091 		/* Have problem loading the very first info. Ignore the rest. */
6092 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6093 			prog->name);
6094 	}
6095 
6096 line_info:
6097 	/* don't relocate line info if main program's relocation failed */
6098 	if (main_prog != prog && !main_prog->line_info)
6099 		return 0;
6100 
6101 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6102 				       &main_prog->line_info,
6103 				       &main_prog->line_info_cnt,
6104 				       &main_prog->line_info_rec_size);
6105 	if (err) {
6106 		if (err != -ENOENT) {
6107 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6108 				prog->name, err);
6109 			return err;
6110 		}
6111 		if (main_prog->line_info) {
6112 			/*
6113 			 * Some info has already been found but has problem
6114 			 * in the last btf_ext reloc. Must have to error out.
6115 			 */
6116 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6117 			return err;
6118 		}
6119 		/* Have problem loading the very first info. Ignore the rest. */
6120 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6121 			prog->name);
6122 	}
6123 	return 0;
6124 }
6125 
cmp_relo_by_insn_idx(const void * key,const void * elem)6126 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6127 {
6128 	size_t insn_idx = *(const size_t *)key;
6129 	const struct reloc_desc *relo = elem;
6130 
6131 	if (insn_idx == relo->insn_idx)
6132 		return 0;
6133 	return insn_idx < relo->insn_idx ? -1 : 1;
6134 }
6135 
find_prog_insn_relo(const struct bpf_program * prog,size_t insn_idx)6136 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6137 {
6138 	if (!prog->nr_reloc)
6139 		return NULL;
6140 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6141 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6142 }
6143 
append_subprog_relos(struct bpf_program * main_prog,struct bpf_program * subprog)6144 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6145 {
6146 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6147 	struct reloc_desc *relos;
6148 	int i;
6149 
6150 	if (main_prog == subprog)
6151 		return 0;
6152 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6153 	if (!relos)
6154 		return -ENOMEM;
6155 	if (subprog->nr_reloc)
6156 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6157 		       sizeof(*relos) * subprog->nr_reloc);
6158 
6159 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6160 		relos[i].insn_idx += subprog->sub_insn_off;
6161 	/* After insn_idx adjustment the 'relos' array is still sorted
6162 	 * by insn_idx and doesn't break bsearch.
6163 	 */
6164 	main_prog->reloc_desc = relos;
6165 	main_prog->nr_reloc = new_cnt;
6166 	return 0;
6167 }
6168 
6169 static int
bpf_object__reloc_code(struct bpf_object * obj,struct bpf_program * main_prog,struct bpf_program * prog)6170 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6171 		       struct bpf_program *prog)
6172 {
6173 	size_t sub_insn_idx, insn_idx, new_cnt;
6174 	struct bpf_program *subprog;
6175 	struct bpf_insn *insns, *insn;
6176 	struct reloc_desc *relo;
6177 	int err;
6178 
6179 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6180 	if (err)
6181 		return err;
6182 
6183 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6184 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6185 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6186 			continue;
6187 
6188 		relo = find_prog_insn_relo(prog, insn_idx);
6189 		if (relo && relo->type == RELO_EXTERN_FUNC)
6190 			/* kfunc relocations will be handled later
6191 			 * in bpf_object__relocate_data()
6192 			 */
6193 			continue;
6194 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6195 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6196 				prog->name, insn_idx, relo->type);
6197 			return -LIBBPF_ERRNO__RELOC;
6198 		}
6199 		if (relo) {
6200 			/* sub-program instruction index is a combination of
6201 			 * an offset of a symbol pointed to by relocation and
6202 			 * call instruction's imm field; for global functions,
6203 			 * call always has imm = -1, but for static functions
6204 			 * relocation is against STT_SECTION and insn->imm
6205 			 * points to a start of a static function
6206 			 *
6207 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6208 			 * the byte offset in the corresponding section.
6209 			 */
6210 			if (relo->type == RELO_CALL)
6211 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6212 			else
6213 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6214 		} else if (insn_is_pseudo_func(insn)) {
6215 			/*
6216 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6217 			 * functions are in the same section, so it shouldn't reach here.
6218 			 */
6219 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6220 				prog->name, insn_idx);
6221 			return -LIBBPF_ERRNO__RELOC;
6222 		} else {
6223 			/* if subprogram call is to a static function within
6224 			 * the same ELF section, there won't be any relocation
6225 			 * emitted, but it also means there is no additional
6226 			 * offset necessary, insns->imm is relative to
6227 			 * instruction's original position within the section
6228 			 */
6229 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6230 		}
6231 
6232 		/* we enforce that sub-programs should be in .text section */
6233 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6234 		if (!subprog) {
6235 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6236 				prog->name);
6237 			return -LIBBPF_ERRNO__RELOC;
6238 		}
6239 
6240 		/* if it's the first call instruction calling into this
6241 		 * subprogram (meaning this subprog hasn't been processed
6242 		 * yet) within the context of current main program:
6243 		 *   - append it at the end of main program's instructions blog;
6244 		 *   - process is recursively, while current program is put on hold;
6245 		 *   - if that subprogram calls some other not yet processes
6246 		 *   subprogram, same thing will happen recursively until
6247 		 *   there are no more unprocesses subprograms left to append
6248 		 *   and relocate.
6249 		 */
6250 		if (subprog->sub_insn_off == 0) {
6251 			subprog->sub_insn_off = main_prog->insns_cnt;
6252 
6253 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6254 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6255 			if (!insns) {
6256 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6257 				return -ENOMEM;
6258 			}
6259 			main_prog->insns = insns;
6260 			main_prog->insns_cnt = new_cnt;
6261 
6262 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6263 			       subprog->insns_cnt * sizeof(*insns));
6264 
6265 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6266 				 main_prog->name, subprog->insns_cnt, subprog->name);
6267 
6268 			/* The subprog insns are now appended. Append its relos too. */
6269 			err = append_subprog_relos(main_prog, subprog);
6270 			if (err)
6271 				return err;
6272 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6273 			if (err)
6274 				return err;
6275 		}
6276 
6277 		/* main_prog->insns memory could have been re-allocated, so
6278 		 * calculate pointer again
6279 		 */
6280 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6281 		/* calculate correct instruction position within current main
6282 		 * prog; each main prog can have a different set of
6283 		 * subprograms appended (potentially in different order as
6284 		 * well), so position of any subprog can be different for
6285 		 * different main programs */
6286 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6287 
6288 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6289 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6290 	}
6291 
6292 	return 0;
6293 }
6294 
6295 /*
6296  * Relocate sub-program calls.
6297  *
6298  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6299  * main prog) is processed separately. For each subprog (non-entry functions,
6300  * that can be called from either entry progs or other subprogs) gets their
6301  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6302  * hasn't been yet appended and relocated within current main prog. Once its
6303  * relocated, sub_insn_off will point at the position within current main prog
6304  * where given subprog was appended. This will further be used to relocate all
6305  * the call instructions jumping into this subprog.
6306  *
6307  * We start with main program and process all call instructions. If the call
6308  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6309  * is zero), subprog instructions are appended at the end of main program's
6310  * instruction array. Then main program is "put on hold" while we recursively
6311  * process newly appended subprogram. If that subprogram calls into another
6312  * subprogram that hasn't been appended, new subprogram is appended again to
6313  * the *main* prog's instructions (subprog's instructions are always left
6314  * untouched, as they need to be in unmodified state for subsequent main progs
6315  * and subprog instructions are always sent only as part of a main prog) and
6316  * the process continues recursively. Once all the subprogs called from a main
6317  * prog or any of its subprogs are appended (and relocated), all their
6318  * positions within finalized instructions array are known, so it's easy to
6319  * rewrite call instructions with correct relative offsets, corresponding to
6320  * desired target subprog.
6321  *
6322  * Its important to realize that some subprogs might not be called from some
6323  * main prog and any of its called/used subprogs. Those will keep their
6324  * subprog->sub_insn_off as zero at all times and won't be appended to current
6325  * main prog and won't be relocated within the context of current main prog.
6326  * They might still be used from other main progs later.
6327  *
6328  * Visually this process can be shown as below. Suppose we have two main
6329  * programs mainA and mainB and BPF object contains three subprogs: subA,
6330  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6331  * subC both call subB:
6332  *
6333  *        +--------+ +-------+
6334  *        |        v v       |
6335  *     +--+---+ +--+-+-+ +---+--+
6336  *     | subA | | subB | | subC |
6337  *     +--+---+ +------+ +---+--+
6338  *        ^                  ^
6339  *        |                  |
6340  *    +---+-------+   +------+----+
6341  *    |   mainA   |   |   mainB   |
6342  *    +-----------+   +-----------+
6343  *
6344  * We'll start relocating mainA, will find subA, append it and start
6345  * processing sub A recursively:
6346  *
6347  *    +-----------+------+
6348  *    |   mainA   | subA |
6349  *    +-----------+------+
6350  *
6351  * At this point we notice that subB is used from subA, so we append it and
6352  * relocate (there are no further subcalls from subB):
6353  *
6354  *    +-----------+------+------+
6355  *    |   mainA   | subA | subB |
6356  *    +-----------+------+------+
6357  *
6358  * At this point, we relocate subA calls, then go one level up and finish with
6359  * relocatin mainA calls. mainA is done.
6360  *
6361  * For mainB process is similar but results in different order. We start with
6362  * mainB and skip subA and subB, as mainB never calls them (at least
6363  * directly), but we see subC is needed, so we append and start processing it:
6364  *
6365  *    +-----------+------+
6366  *    |   mainB   | subC |
6367  *    +-----------+------+
6368  * Now we see subC needs subB, so we go back to it, append and relocate it:
6369  *
6370  *    +-----------+------+------+
6371  *    |   mainB   | subC | subB |
6372  *    +-----------+------+------+
6373  *
6374  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6375  */
6376 static int
bpf_object__relocate_calls(struct bpf_object * obj,struct bpf_program * prog)6377 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6378 {
6379 	struct bpf_program *subprog;
6380 	int i, err;
6381 
6382 	/* mark all subprogs as not relocated (yet) within the context of
6383 	 * current main program
6384 	 */
6385 	for (i = 0; i < obj->nr_programs; i++) {
6386 		subprog = &obj->programs[i];
6387 		if (!prog_is_subprog(obj, subprog))
6388 			continue;
6389 
6390 		subprog->sub_insn_off = 0;
6391 	}
6392 
6393 	err = bpf_object__reloc_code(obj, prog, prog);
6394 	if (err)
6395 		return err;
6396 
6397 	return 0;
6398 }
6399 
6400 static void
bpf_object__free_relocs(struct bpf_object * obj)6401 bpf_object__free_relocs(struct bpf_object *obj)
6402 {
6403 	struct bpf_program *prog;
6404 	int i;
6405 
6406 	/* free up relocation descriptors */
6407 	for (i = 0; i < obj->nr_programs; i++) {
6408 		prog = &obj->programs[i];
6409 		zfree(&prog->reloc_desc);
6410 		prog->nr_reloc = 0;
6411 	}
6412 }
6413 
cmp_relocs(const void * _a,const void * _b)6414 static int cmp_relocs(const void *_a, const void *_b)
6415 {
6416 	const struct reloc_desc *a = _a;
6417 	const struct reloc_desc *b = _b;
6418 
6419 	if (a->insn_idx != b->insn_idx)
6420 		return a->insn_idx < b->insn_idx ? -1 : 1;
6421 
6422 	/* no two relocations should have the same insn_idx, but ... */
6423 	if (a->type != b->type)
6424 		return a->type < b->type ? -1 : 1;
6425 
6426 	return 0;
6427 }
6428 
bpf_object__sort_relos(struct bpf_object * obj)6429 static void bpf_object__sort_relos(struct bpf_object *obj)
6430 {
6431 	int i;
6432 
6433 	for (i = 0; i < obj->nr_programs; i++) {
6434 		struct bpf_program *p = &obj->programs[i];
6435 
6436 		if (!p->nr_reloc)
6437 			continue;
6438 
6439 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6440 	}
6441 }
6442 
6443 static int
bpf_object__relocate(struct bpf_object * obj,const char * targ_btf_path)6444 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6445 {
6446 	struct bpf_program *prog;
6447 	size_t i, j;
6448 	int err;
6449 
6450 	if (obj->btf_ext) {
6451 		err = bpf_object__relocate_core(obj, targ_btf_path);
6452 		if (err) {
6453 			pr_warn("failed to perform CO-RE relocations: %d\n",
6454 				err);
6455 			return err;
6456 		}
6457 		bpf_object__sort_relos(obj);
6458 	}
6459 
6460 	/* Before relocating calls pre-process relocations and mark
6461 	 * few ld_imm64 instructions that points to subprogs.
6462 	 * Otherwise bpf_object__reloc_code() later would have to consider
6463 	 * all ld_imm64 insns as relocation candidates. That would
6464 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6465 	 * would increase and most of them will fail to find a relo.
6466 	 */
6467 	for (i = 0; i < obj->nr_programs; i++) {
6468 		prog = &obj->programs[i];
6469 		for (j = 0; j < prog->nr_reloc; j++) {
6470 			struct reloc_desc *relo = &prog->reloc_desc[j];
6471 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6472 
6473 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6474 			if (relo->type == RELO_SUBPROG_ADDR)
6475 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6476 		}
6477 	}
6478 
6479 	/* relocate subprogram calls and append used subprograms to main
6480 	 * programs; each copy of subprogram code needs to be relocated
6481 	 * differently for each main program, because its code location might
6482 	 * have changed.
6483 	 * Append subprog relos to main programs to allow data relos to be
6484 	 * processed after text is completely relocated.
6485 	 */
6486 	for (i = 0; i < obj->nr_programs; i++) {
6487 		prog = &obj->programs[i];
6488 		/* sub-program's sub-calls are relocated within the context of
6489 		 * its main program only
6490 		 */
6491 		if (prog_is_subprog(obj, prog))
6492 			continue;
6493 		if (!prog->autoload)
6494 			continue;
6495 
6496 		err = bpf_object__relocate_calls(obj, prog);
6497 		if (err) {
6498 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6499 				prog->name, err);
6500 			return err;
6501 		}
6502 	}
6503 	/* Process data relos for main programs */
6504 	for (i = 0; i < obj->nr_programs; i++) {
6505 		prog = &obj->programs[i];
6506 		if (prog_is_subprog(obj, prog))
6507 			continue;
6508 		if (!prog->autoload)
6509 			continue;
6510 		err = bpf_object__relocate_data(obj, prog);
6511 		if (err) {
6512 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6513 				prog->name, err);
6514 			return err;
6515 		}
6516 	}
6517 
6518 	return 0;
6519 }
6520 
6521 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6522 					    Elf64_Shdr *shdr, Elf_Data *data);
6523 
bpf_object__collect_map_relos(struct bpf_object * obj,Elf64_Shdr * shdr,Elf_Data * data)6524 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6525 					 Elf64_Shdr *shdr, Elf_Data *data)
6526 {
6527 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6528 	int i, j, nrels, new_sz;
6529 	const struct btf_var_secinfo *vi = NULL;
6530 	const struct btf_type *sec, *var, *def;
6531 	struct bpf_map *map = NULL, *targ_map = NULL;
6532 	struct bpf_program *targ_prog = NULL;
6533 	bool is_prog_array, is_map_in_map;
6534 	const struct btf_member *member;
6535 	const char *name, *mname, *type;
6536 	unsigned int moff;
6537 	Elf64_Sym *sym;
6538 	Elf64_Rel *rel;
6539 	void *tmp;
6540 
6541 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6542 		return -EINVAL;
6543 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6544 	if (!sec)
6545 		return -EINVAL;
6546 
6547 	nrels = shdr->sh_size / shdr->sh_entsize;
6548 	for (i = 0; i < nrels; i++) {
6549 		rel = elf_rel_by_idx(data, i);
6550 		if (!rel) {
6551 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6552 			return -LIBBPF_ERRNO__FORMAT;
6553 		}
6554 
6555 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6556 		if (!sym) {
6557 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6558 				i, (size_t)ELF64_R_SYM(rel->r_info));
6559 			return -LIBBPF_ERRNO__FORMAT;
6560 		}
6561 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6562 
6563 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6564 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6565 			 (size_t)rel->r_offset, sym->st_name, name);
6566 
6567 		for (j = 0; j < obj->nr_maps; j++) {
6568 			map = &obj->maps[j];
6569 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6570 				continue;
6571 
6572 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6573 			if (vi->offset <= rel->r_offset &&
6574 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6575 				break;
6576 		}
6577 		if (j == obj->nr_maps) {
6578 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6579 				i, name, (size_t)rel->r_offset);
6580 			return -EINVAL;
6581 		}
6582 
6583 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6584 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6585 		type = is_map_in_map ? "map" : "prog";
6586 		if (is_map_in_map) {
6587 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6588 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6589 					i, name);
6590 				return -LIBBPF_ERRNO__RELOC;
6591 			}
6592 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6593 			    map->def.key_size != sizeof(int)) {
6594 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6595 					i, map->name, sizeof(int));
6596 				return -EINVAL;
6597 			}
6598 			targ_map = bpf_object__find_map_by_name(obj, name);
6599 			if (!targ_map) {
6600 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6601 					i, name);
6602 				return -ESRCH;
6603 			}
6604 		} else if (is_prog_array) {
6605 			targ_prog = bpf_object__find_program_by_name(obj, name);
6606 			if (!targ_prog) {
6607 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6608 					i, name);
6609 				return -ESRCH;
6610 			}
6611 			if (targ_prog->sec_idx != sym->st_shndx ||
6612 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6613 			    prog_is_subprog(obj, targ_prog)) {
6614 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6615 					i, name);
6616 				return -LIBBPF_ERRNO__RELOC;
6617 			}
6618 		} else {
6619 			return -EINVAL;
6620 		}
6621 
6622 		var = btf__type_by_id(obj->btf, vi->type);
6623 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6624 		if (btf_vlen(def) == 0)
6625 			return -EINVAL;
6626 		member = btf_members(def) + btf_vlen(def) - 1;
6627 		mname = btf__name_by_offset(obj->btf, member->name_off);
6628 		if (strcmp(mname, "values"))
6629 			return -EINVAL;
6630 
6631 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6632 		if (rel->r_offset - vi->offset < moff)
6633 			return -EINVAL;
6634 
6635 		moff = rel->r_offset - vi->offset - moff;
6636 		/* here we use BPF pointer size, which is always 64 bit, as we
6637 		 * are parsing ELF that was built for BPF target
6638 		 */
6639 		if (moff % bpf_ptr_sz)
6640 			return -EINVAL;
6641 		moff /= bpf_ptr_sz;
6642 		if (moff >= map->init_slots_sz) {
6643 			new_sz = moff + 1;
6644 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6645 			if (!tmp)
6646 				return -ENOMEM;
6647 			map->init_slots = tmp;
6648 			memset(map->init_slots + map->init_slots_sz, 0,
6649 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6650 			map->init_slots_sz = new_sz;
6651 		}
6652 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6653 
6654 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6655 			 i, map->name, moff, type, name);
6656 	}
6657 
6658 	return 0;
6659 }
6660 
bpf_object__collect_relos(struct bpf_object * obj)6661 static int bpf_object__collect_relos(struct bpf_object *obj)
6662 {
6663 	int i, err;
6664 
6665 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6666 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6667 		Elf64_Shdr *shdr;
6668 		Elf_Data *data;
6669 		int idx;
6670 
6671 		if (sec_desc->sec_type != SEC_RELO)
6672 			continue;
6673 
6674 		shdr = sec_desc->shdr;
6675 		data = sec_desc->data;
6676 		idx = shdr->sh_info;
6677 
6678 		if (shdr->sh_type != SHT_REL) {
6679 			pr_warn("internal error at %d\n", __LINE__);
6680 			return -LIBBPF_ERRNO__INTERNAL;
6681 		}
6682 
6683 		if (idx == obj->efile.st_ops_shndx)
6684 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6685 		else if (idx == obj->efile.btf_maps_shndx)
6686 			err = bpf_object__collect_map_relos(obj, shdr, data);
6687 		else
6688 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6689 		if (err)
6690 			return err;
6691 	}
6692 
6693 	bpf_object__sort_relos(obj);
6694 	return 0;
6695 }
6696 
insn_is_helper_call(struct bpf_insn * insn,enum bpf_func_id * func_id)6697 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6698 {
6699 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6700 	    BPF_OP(insn->code) == BPF_CALL &&
6701 	    BPF_SRC(insn->code) == BPF_K &&
6702 	    insn->src_reg == 0 &&
6703 	    insn->dst_reg == 0) {
6704 		    *func_id = insn->imm;
6705 		    return true;
6706 	}
6707 	return false;
6708 }
6709 
bpf_object__sanitize_prog(struct bpf_object * obj,struct bpf_program * prog)6710 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6711 {
6712 	struct bpf_insn *insn = prog->insns;
6713 	enum bpf_func_id func_id;
6714 	int i;
6715 
6716 	if (obj->gen_loader)
6717 		return 0;
6718 
6719 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6720 		if (!insn_is_helper_call(insn, &func_id))
6721 			continue;
6722 
6723 		/* on kernels that don't yet support
6724 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6725 		 * to bpf_probe_read() which works well for old kernels
6726 		 */
6727 		switch (func_id) {
6728 		case BPF_FUNC_probe_read_kernel:
6729 		case BPF_FUNC_probe_read_user:
6730 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6731 				insn->imm = BPF_FUNC_probe_read;
6732 			break;
6733 		case BPF_FUNC_probe_read_kernel_str:
6734 		case BPF_FUNC_probe_read_user_str:
6735 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6736 				insn->imm = BPF_FUNC_probe_read_str;
6737 			break;
6738 		default:
6739 			break;
6740 		}
6741 	}
6742 	return 0;
6743 }
6744 
6745 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6746 				     int *btf_obj_fd, int *btf_type_id);
6747 
6748 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
libbpf_prepare_prog_load(struct bpf_program * prog,struct bpf_prog_load_opts * opts,long cookie)6749 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6750 				    struct bpf_prog_load_opts *opts, long cookie)
6751 {
6752 	enum sec_def_flags def = cookie;
6753 
6754 	/* old kernels might not support specifying expected_attach_type */
6755 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6756 		opts->expected_attach_type = 0;
6757 
6758 	if (def & SEC_SLEEPABLE)
6759 		opts->prog_flags |= BPF_F_SLEEPABLE;
6760 
6761 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6762 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6763 
6764 	if (def & SEC_DEPRECATED) {
6765 		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",
6766 			prog->sec_name);
6767 	}
6768 
6769 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6770 		int btf_obj_fd = 0, btf_type_id = 0, err;
6771 		const char *attach_name;
6772 
6773 		attach_name = strchr(prog->sec_name, '/');
6774 		if (!attach_name) {
6775 			/* if BPF program is annotated with just SEC("fentry")
6776 			 * (or similar) without declaratively specifying
6777 			 * target, then it is expected that target will be
6778 			 * specified with bpf_program__set_attach_target() at
6779 			 * runtime before BPF object load step. If not, then
6780 			 * there is nothing to load into the kernel as BPF
6781 			 * verifier won't be able to validate BPF program
6782 			 * correctness anyways.
6783 			 */
6784 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6785 				prog->name);
6786 			return -EINVAL;
6787 		}
6788 		attach_name++; /* skip over / */
6789 
6790 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6791 		if (err)
6792 			return err;
6793 
6794 		/* cache resolved BTF FD and BTF type ID in the prog */
6795 		prog->attach_btf_obj_fd = btf_obj_fd;
6796 		prog->attach_btf_id = btf_type_id;
6797 
6798 		/* but by now libbpf common logic is not utilizing
6799 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6800 		 * this callback is called after opts were populated by
6801 		 * libbpf, so this callback has to update opts explicitly here
6802 		 */
6803 		opts->attach_btf_obj_fd = btf_obj_fd;
6804 		opts->attach_btf_id = btf_type_id;
6805 	}
6806 	return 0;
6807 }
6808 
6809 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6810 
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)6811 static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6812 					 struct bpf_insn *insns, int insns_cnt,
6813 					 const char *license, __u32 kern_version,
6814 					 int *prog_fd)
6815 {
6816 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6817 	const char *prog_name = NULL;
6818 	char *cp, errmsg[STRERR_BUFSIZE];
6819 	size_t log_buf_size = 0;
6820 	char *log_buf = NULL, *tmp;
6821 	int btf_fd, ret, err;
6822 	bool own_log_buf = true;
6823 	__u32 log_level = prog->log_level;
6824 
6825 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6826 		/*
6827 		 * The program type must be set.  Most likely we couldn't find a proper
6828 		 * section definition at load time, and thus we didn't infer the type.
6829 		 */
6830 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6831 			prog->name, prog->sec_name);
6832 		return -EINVAL;
6833 	}
6834 
6835 	if (!insns || !insns_cnt)
6836 		return -EINVAL;
6837 
6838 	load_attr.expected_attach_type = prog->expected_attach_type;
6839 	if (kernel_supports(obj, FEAT_PROG_NAME))
6840 		prog_name = prog->name;
6841 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6842 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6843 	load_attr.attach_btf_id = prog->attach_btf_id;
6844 	load_attr.kern_version = kern_version;
6845 	load_attr.prog_ifindex = prog->prog_ifindex;
6846 
6847 	/* specify func_info/line_info only if kernel supports them */
6848 	btf_fd = bpf_object__btf_fd(obj);
6849 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6850 		load_attr.prog_btf_fd = btf_fd;
6851 		load_attr.func_info = prog->func_info;
6852 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6853 		load_attr.func_info_cnt = prog->func_info_cnt;
6854 		load_attr.line_info = prog->line_info;
6855 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6856 		load_attr.line_info_cnt = prog->line_info_cnt;
6857 	}
6858 	load_attr.log_level = log_level;
6859 	load_attr.prog_flags = prog->prog_flags;
6860 	load_attr.fd_array = obj->fd_array;
6861 
6862 	/* adjust load_attr if sec_def provides custom preload callback */
6863 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6864 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6865 		if (err < 0) {
6866 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6867 				prog->name, err);
6868 			return err;
6869 		}
6870 		insns = prog->insns;
6871 		insns_cnt = prog->insns_cnt;
6872 	}
6873 
6874 	if (obj->gen_loader) {
6875 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6876 				   license, insns, insns_cnt, &load_attr,
6877 				   prog - obj->programs);
6878 		*prog_fd = -1;
6879 		return 0;
6880 	}
6881 
6882 retry_load:
6883 	/* if log_level is zero, we don't request logs initially even if
6884 	 * custom log_buf is specified; if the program load fails, then we'll
6885 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6886 	 * our own and retry the load to get details on what failed
6887 	 */
6888 	if (log_level) {
6889 		if (prog->log_buf) {
6890 			log_buf = prog->log_buf;
6891 			log_buf_size = prog->log_size;
6892 			own_log_buf = false;
6893 		} else if (obj->log_buf) {
6894 			log_buf = obj->log_buf;
6895 			log_buf_size = obj->log_size;
6896 			own_log_buf = false;
6897 		} else {
6898 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6899 			tmp = realloc(log_buf, log_buf_size);
6900 			if (!tmp) {
6901 				ret = -ENOMEM;
6902 				goto out;
6903 			}
6904 			log_buf = tmp;
6905 			log_buf[0] = '\0';
6906 			own_log_buf = true;
6907 		}
6908 	}
6909 
6910 	load_attr.log_buf = log_buf;
6911 	load_attr.log_size = log_buf_size;
6912 	load_attr.log_level = log_level;
6913 
6914 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6915 	if (ret >= 0) {
6916 		if (log_level && own_log_buf) {
6917 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6918 				 prog->name, log_buf);
6919 		}
6920 
6921 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6922 			struct bpf_map *map;
6923 			int i;
6924 
6925 			for (i = 0; i < obj->nr_maps; i++) {
6926 				map = &prog->obj->maps[i];
6927 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6928 					continue;
6929 
6930 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6931 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6932 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6933 						prog->name, map->real_name, cp);
6934 					/* Don't fail hard if can't bind rodata. */
6935 				}
6936 			}
6937 		}
6938 
6939 		*prog_fd = ret;
6940 		ret = 0;
6941 		goto out;
6942 	}
6943 
6944 	if (log_level == 0) {
6945 		log_level = 1;
6946 		goto retry_load;
6947 	}
6948 	/* On ENOSPC, increase log buffer size and retry, unless custom
6949 	 * log_buf is specified.
6950 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6951 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6952 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6953 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6954 	 */
6955 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6956 		goto retry_load;
6957 
6958 	ret = -errno;
6959 
6960 	/* post-process verifier log to improve error descriptions */
6961 	fixup_verifier_log(prog, log_buf, log_buf_size);
6962 
6963 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6964 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6965 	pr_perm_msg(ret);
6966 
6967 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6968 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6969 			prog->name, log_buf);
6970 	}
6971 
6972 out:
6973 	if (own_log_buf)
6974 		free(log_buf);
6975 	return ret;
6976 }
6977 
find_prev_line(char * buf,char * cur)6978 static char *find_prev_line(char *buf, char *cur)
6979 {
6980 	char *p;
6981 
6982 	if (cur == buf) /* end of a log buf */
6983 		return NULL;
6984 
6985 	p = cur - 1;
6986 	while (p - 1 >= buf && *(p - 1) != '\n')
6987 		p--;
6988 
6989 	return p;
6990 }
6991 
patch_log(char * buf,size_t buf_sz,size_t log_sz,char * orig,size_t orig_sz,const char * patch)6992 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6993 		      char *orig, size_t orig_sz, const char *patch)
6994 {
6995 	/* size of the remaining log content to the right from the to-be-replaced part */
6996 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6997 	size_t patch_sz = strlen(patch);
6998 
6999 	if (patch_sz != orig_sz) {
7000 		/* If patch line(s) are longer than original piece of verifier log,
7001 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7002 		 * starting from after to-be-replaced part of the log.
7003 		 *
7004 		 * If patch line(s) are shorter than original piece of verifier log,
7005 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7006 		 * starting from after to-be-replaced part of the log
7007 		 *
7008 		 * We need to be careful about not overflowing available
7009 		 * buf_sz capacity. If that's the case, we'll truncate the end
7010 		 * of the original log, as necessary.
7011 		 */
7012 		if (patch_sz > orig_sz) {
7013 			if (orig + patch_sz >= buf + buf_sz) {
7014 				/* patch is big enough to cover remaining space completely */
7015 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7016 				rem_sz = 0;
7017 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7018 				/* patch causes part of remaining log to be truncated */
7019 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7020 			}
7021 		}
7022 		/* shift remaining log to the right by calculated amount */
7023 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7024 	}
7025 
7026 	memcpy(orig, patch, patch_sz);
7027 }
7028 
fixup_log_failed_core_relo(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7029 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7030 				       char *buf, size_t buf_sz, size_t log_sz,
7031 				       char *line1, char *line2, char *line3)
7032 {
7033 	/* Expected log for failed and not properly guarded CO-RE relocation:
7034 	 * line1 -> 123: (85) call unknown#195896080
7035 	 * line2 -> invalid func unknown#195896080
7036 	 * line3 -> <anything else or end of buffer>
7037 	 *
7038 	 * "123" is the index of the instruction that was poisoned. We extract
7039 	 * instruction index to find corresponding CO-RE relocation and
7040 	 * replace this part of the log with more relevant information about
7041 	 * failed CO-RE relocation.
7042 	 */
7043 	const struct bpf_core_relo *relo;
7044 	struct bpf_core_spec spec;
7045 	char patch[512], spec_buf[256];
7046 	int insn_idx, err, spec_len;
7047 
7048 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7049 		return;
7050 
7051 	relo = find_relo_core(prog, insn_idx);
7052 	if (!relo)
7053 		return;
7054 
7055 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7056 	if (err)
7057 		return;
7058 
7059 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7060 	snprintf(patch, sizeof(patch),
7061 		 "%d: <invalid CO-RE relocation>\n"
7062 		 "failed to resolve CO-RE relocation %s%s\n",
7063 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7064 
7065 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7066 }
7067 
fixup_log_missing_map_load(struct bpf_program * prog,char * buf,size_t buf_sz,size_t log_sz,char * line1,char * line2,char * line3)7068 static void fixup_log_missing_map_load(struct bpf_program *prog,
7069 				       char *buf, size_t buf_sz, size_t log_sz,
7070 				       char *line1, char *line2, char *line3)
7071 {
7072 	/* Expected log for failed and not properly guarded CO-RE relocation:
7073 	 * line1 -> 123: (85) call unknown#2001000345
7074 	 * line2 -> invalid func unknown#2001000345
7075 	 * line3 -> <anything else or end of buffer>
7076 	 *
7077 	 * "123" is the index of the instruction that was poisoned.
7078 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
7079 	 */
7080 	struct bpf_object *obj = prog->obj;
7081 	const struct bpf_map *map;
7082 	int insn_idx, map_idx;
7083 	char patch[128];
7084 
7085 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7086 		return;
7087 
7088 	map_idx -= MAP_LDIMM64_POISON_BASE;
7089 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7090 		return;
7091 	map = &obj->maps[map_idx];
7092 
7093 	snprintf(patch, sizeof(patch),
7094 		 "%d: <invalid BPF map reference>\n"
7095 		 "BPF map '%s' is referenced but wasn't created\n",
7096 		 insn_idx, map->name);
7097 
7098 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7099 }
7100 
fixup_verifier_log(struct bpf_program * prog,char * buf,size_t buf_sz)7101 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7102 {
7103 	/* look for familiar error patterns in last N lines of the log */
7104 	const size_t max_last_line_cnt = 10;
7105 	char *prev_line, *cur_line, *next_line;
7106 	size_t log_sz;
7107 	int i;
7108 
7109 	if (!buf)
7110 		return;
7111 
7112 	log_sz = strlen(buf) + 1;
7113 	next_line = buf + log_sz - 1;
7114 
7115 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7116 		cur_line = find_prev_line(buf, next_line);
7117 		if (!cur_line)
7118 			return;
7119 
7120 		/* failed CO-RE relocation case */
7121 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7122 			prev_line = find_prev_line(buf, cur_line);
7123 			if (!prev_line)
7124 				continue;
7125 
7126 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7127 						   prev_line, cur_line, next_line);
7128 			return;
7129 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7130 			prev_line = find_prev_line(buf, cur_line);
7131 			if (!prev_line)
7132 				continue;
7133 
7134 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7135 						   prev_line, cur_line, next_line);
7136 			return;
7137 		}
7138 	}
7139 }
7140 
bpf_program_record_relos(struct bpf_program * prog)7141 static int bpf_program_record_relos(struct bpf_program *prog)
7142 {
7143 	struct bpf_object *obj = prog->obj;
7144 	int i;
7145 
7146 	for (i = 0; i < prog->nr_reloc; i++) {
7147 		struct reloc_desc *relo = &prog->reloc_desc[i];
7148 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7149 
7150 		switch (relo->type) {
7151 		case RELO_EXTERN_VAR:
7152 			if (ext->type != EXT_KSYM)
7153 				continue;
7154 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7155 					       ext->is_weak, !ext->ksym.type_id,
7156 					       BTF_KIND_VAR, relo->insn_idx);
7157 			break;
7158 		case RELO_EXTERN_FUNC:
7159 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7160 					       ext->is_weak, false, BTF_KIND_FUNC,
7161 					       relo->insn_idx);
7162 			break;
7163 		case RELO_CORE: {
7164 			struct bpf_core_relo cr = {
7165 				.insn_off = relo->insn_idx * 8,
7166 				.type_id = relo->core_relo->type_id,
7167 				.access_str_off = relo->core_relo->access_str_off,
7168 				.kind = relo->core_relo->kind,
7169 			};
7170 
7171 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7172 			break;
7173 		}
7174 		default:
7175 			continue;
7176 		}
7177 	}
7178 	return 0;
7179 }
7180 
bpf_object_load_prog(struct bpf_object * obj,struct bpf_program * prog,const char * license,__u32 kern_ver)7181 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7182 				const char *license, __u32 kern_ver)
7183 {
7184 	int err = 0, fd, i;
7185 
7186 	if (obj->loaded) {
7187 		pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
7188 		return libbpf_err(-EINVAL);
7189 	}
7190 
7191 	if (prog->instances.nr < 0 || !prog->instances.fds) {
7192 		if (prog->preprocessor) {
7193 			pr_warn("Internal error: can't load program '%s'\n",
7194 				prog->name);
7195 			return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
7196 		}
7197 
7198 		prog->instances.fds = malloc(sizeof(int));
7199 		if (!prog->instances.fds) {
7200 			pr_warn("Not enough memory for BPF fds\n");
7201 			return libbpf_err(-ENOMEM);
7202 		}
7203 		prog->instances.nr = 1;
7204 		prog->instances.fds[0] = -1;
7205 	}
7206 
7207 	if (!prog->preprocessor) {
7208 		if (prog->instances.nr != 1) {
7209 			pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
7210 				prog->name, prog->instances.nr);
7211 		}
7212 		if (obj->gen_loader)
7213 			bpf_program_record_relos(prog);
7214 		err = bpf_object_load_prog_instance(obj, prog,
7215 						    prog->insns, prog->insns_cnt,
7216 						    license, kern_ver, &fd);
7217 		if (!err)
7218 			prog->instances.fds[0] = fd;
7219 		goto out;
7220 	}
7221 
7222 	for (i = 0; i < prog->instances.nr; i++) {
7223 		struct bpf_prog_prep_result result;
7224 		bpf_program_prep_t preprocessor = prog->preprocessor;
7225 
7226 		memset(&result, 0, sizeof(result));
7227 		err = preprocessor(prog, i, prog->insns,
7228 				   prog->insns_cnt, &result);
7229 		if (err) {
7230 			pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
7231 				i, prog->name);
7232 			goto out;
7233 		}
7234 
7235 		if (!result.new_insn_ptr || !result.new_insn_cnt) {
7236 			pr_debug("Skip loading the %dth instance of program '%s'\n",
7237 				 i, prog->name);
7238 			prog->instances.fds[i] = -1;
7239 			if (result.pfd)
7240 				*result.pfd = -1;
7241 			continue;
7242 		}
7243 
7244 		err = bpf_object_load_prog_instance(obj, prog,
7245 						    result.new_insn_ptr, result.new_insn_cnt,
7246 						    license, kern_ver, &fd);
7247 		if (err) {
7248 			pr_warn("Loading the %dth instance of program '%s' failed\n",
7249 				i, prog->name);
7250 			goto out;
7251 		}
7252 
7253 		if (result.pfd)
7254 			*result.pfd = fd;
7255 		prog->instances.fds[i] = fd;
7256 	}
7257 out:
7258 	if (err)
7259 		pr_warn("failed to load program '%s'\n", prog->name);
7260 	return libbpf_err(err);
7261 }
7262 
bpf_program__load(struct bpf_program * prog,const char * license,__u32 kern_ver)7263 int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
7264 {
7265 	return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
7266 }
7267 
7268 static int
bpf_object__load_progs(struct bpf_object * obj,int log_level)7269 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7270 {
7271 	struct bpf_program *prog;
7272 	size_t i;
7273 	int err;
7274 
7275 	for (i = 0; i < obj->nr_programs; i++) {
7276 		prog = &obj->programs[i];
7277 		err = bpf_object__sanitize_prog(obj, prog);
7278 		if (err)
7279 			return err;
7280 	}
7281 
7282 	for (i = 0; i < obj->nr_programs; i++) {
7283 		prog = &obj->programs[i];
7284 		if (prog_is_subprog(obj, prog))
7285 			continue;
7286 		if (!prog->autoload) {
7287 			pr_debug("prog '%s': skipped loading\n", prog->name);
7288 			continue;
7289 		}
7290 		prog->log_level |= log_level;
7291 		err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
7292 		if (err)
7293 			return err;
7294 	}
7295 
7296 	bpf_object__free_relocs(obj);
7297 	return 0;
7298 }
7299 
7300 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7301 
bpf_object_init_progs(struct bpf_object * obj,const struct bpf_object_open_opts * opts)7302 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7303 {
7304 	struct bpf_program *prog;
7305 	int err;
7306 
7307 	bpf_object__for_each_program(prog, obj) {
7308 		prog->sec_def = find_sec_def(prog->sec_name);
7309 		if (!prog->sec_def) {
7310 			/* couldn't guess, but user might manually specify */
7311 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7312 				prog->name, prog->sec_name);
7313 			continue;
7314 		}
7315 
7316 		prog->type = prog->sec_def->prog_type;
7317 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7318 
7319 #pragma GCC diagnostic push
7320 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
7321 		if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
7322 		    prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
7323 			prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
7324 #pragma GCC diagnostic pop
7325 
7326 		/* sec_def can have custom callback which should be called
7327 		 * after bpf_program is initialized to adjust its properties
7328 		 */
7329 		if (prog->sec_def->prog_setup_fn) {
7330 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7331 			if (err < 0) {
7332 				pr_warn("prog '%s': failed to initialize: %d\n",
7333 					prog->name, err);
7334 				return err;
7335 			}
7336 		}
7337 	}
7338 
7339 	return 0;
7340 }
7341 
bpf_object_open(const char * path,const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7342 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7343 					  const struct bpf_object_open_opts *opts)
7344 {
7345 	const char *obj_name, *kconfig, *btf_tmp_path;
7346 	struct bpf_object *obj;
7347 	char tmp_name[64];
7348 	int err;
7349 	char *log_buf;
7350 	size_t log_size;
7351 	__u32 log_level;
7352 
7353 	if (elf_version(EV_CURRENT) == EV_NONE) {
7354 		pr_warn("failed to init libelf for %s\n",
7355 			path ? : "(mem buf)");
7356 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7357 	}
7358 
7359 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7360 		return ERR_PTR(-EINVAL);
7361 
7362 	obj_name = OPTS_GET(opts, object_name, NULL);
7363 	if (obj_buf) {
7364 		if (!obj_name) {
7365 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7366 				 (unsigned long)obj_buf,
7367 				 (unsigned long)obj_buf_sz);
7368 			obj_name = tmp_name;
7369 		}
7370 		path = obj_name;
7371 		pr_debug("loading object '%s' from buffer\n", obj_name);
7372 	}
7373 
7374 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7375 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7376 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7377 	if (log_size > UINT_MAX)
7378 		return ERR_PTR(-EINVAL);
7379 	if (log_size && !log_buf)
7380 		return ERR_PTR(-EINVAL);
7381 
7382 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7383 	if (IS_ERR(obj))
7384 		return obj;
7385 
7386 	obj->log_buf = log_buf;
7387 	obj->log_size = log_size;
7388 	obj->log_level = log_level;
7389 
7390 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7391 	if (btf_tmp_path) {
7392 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7393 			err = -ENAMETOOLONG;
7394 			goto out;
7395 		}
7396 		obj->btf_custom_path = strdup(btf_tmp_path);
7397 		if (!obj->btf_custom_path) {
7398 			err = -ENOMEM;
7399 			goto out;
7400 		}
7401 	}
7402 
7403 	kconfig = OPTS_GET(opts, kconfig, NULL);
7404 	if (kconfig) {
7405 		obj->kconfig = strdup(kconfig);
7406 		if (!obj->kconfig) {
7407 			err = -ENOMEM;
7408 			goto out;
7409 		}
7410 	}
7411 
7412 	err = bpf_object__elf_init(obj);
7413 	err = err ? : bpf_object__check_endianness(obj);
7414 	err = err ? : bpf_object__elf_collect(obj);
7415 	err = err ? : bpf_object__collect_externs(obj);
7416 	err = err ? : bpf_object__finalize_btf(obj);
7417 	err = err ? : bpf_object__init_maps(obj, opts);
7418 	err = err ? : bpf_object_init_progs(obj, opts);
7419 	err = err ? : bpf_object__collect_relos(obj);
7420 	if (err)
7421 		goto out;
7422 
7423 	bpf_object__elf_finish(obj);
7424 
7425 	return obj;
7426 out:
7427 	bpf_object__close(obj);
7428 	return ERR_PTR(err);
7429 }
7430 
7431 static struct bpf_object *
__bpf_object__open_xattr(struct bpf_object_open_attr * attr,int flags)7432 __bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
7433 {
7434 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7435 		.relaxed_maps = flags & MAPS_RELAX_COMPAT,
7436 	);
7437 
7438 	/* param validation */
7439 	if (!attr->file)
7440 		return NULL;
7441 
7442 	pr_debug("loading %s\n", attr->file);
7443 	return bpf_object_open(attr->file, NULL, 0, &opts);
7444 }
7445 
bpf_object__open_xattr(struct bpf_object_open_attr * attr)7446 struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7447 {
7448 	return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
7449 }
7450 
bpf_object__open(const char * path)7451 struct bpf_object *bpf_object__open(const char *path)
7452 {
7453 	struct bpf_object_open_attr attr = {
7454 		.file		= path,
7455 		.prog_type	= BPF_PROG_TYPE_UNSPEC,
7456 	};
7457 
7458 	return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
7459 }
7460 
7461 struct bpf_object *
bpf_object__open_file(const char * path,const struct bpf_object_open_opts * opts)7462 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7463 {
7464 	if (!path)
7465 		return libbpf_err_ptr(-EINVAL);
7466 
7467 	pr_debug("loading %s\n", path);
7468 
7469 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7470 }
7471 
7472 struct bpf_object *
bpf_object__open_mem(const void * obj_buf,size_t obj_buf_sz,const struct bpf_object_open_opts * opts)7473 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7474 		     const struct bpf_object_open_opts *opts)
7475 {
7476 	if (!obj_buf || obj_buf_sz == 0)
7477 		return libbpf_err_ptr(-EINVAL);
7478 
7479 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7480 }
7481 
7482 struct bpf_object *
bpf_object__open_buffer(const void * obj_buf,size_t obj_buf_sz,const char * name)7483 bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7484 			const char *name)
7485 {
7486 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7487 		.object_name = name,
7488 		/* wrong default, but backwards-compatible */
7489 		.relaxed_maps = true,
7490 	);
7491 
7492 	/* returning NULL is wrong, but backwards-compatible */
7493 	if (!obj_buf || obj_buf_sz == 0)
7494 		return errno = EINVAL, NULL;
7495 
7496 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
7497 }
7498 
bpf_object_unload(struct bpf_object * obj)7499 static int bpf_object_unload(struct bpf_object *obj)
7500 {
7501 	size_t i;
7502 
7503 	if (!obj)
7504 		return libbpf_err(-EINVAL);
7505 
7506 	for (i = 0; i < obj->nr_maps; i++) {
7507 		zclose(obj->maps[i].fd);
7508 		if (obj->maps[i].st_ops)
7509 			zfree(&obj->maps[i].st_ops->kern_vdata);
7510 	}
7511 
7512 	for (i = 0; i < obj->nr_programs; i++)
7513 		bpf_program__unload(&obj->programs[i]);
7514 
7515 	return 0;
7516 }
7517 
7518 int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7519 
bpf_object__sanitize_maps(struct bpf_object * obj)7520 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7521 {
7522 	struct bpf_map *m;
7523 
7524 	bpf_object__for_each_map(m, obj) {
7525 		if (!bpf_map__is_internal(m))
7526 			continue;
7527 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7528 			m->def.map_flags ^= BPF_F_MMAPABLE;
7529 	}
7530 
7531 	return 0;
7532 }
7533 
libbpf_kallsyms_parse(kallsyms_cb_t cb,void * ctx)7534 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7535 {
7536 	char sym_type, sym_name[500];
7537 	unsigned long long sym_addr;
7538 	int ret, err = 0;
7539 	FILE *f;
7540 
7541 	f = fopen("/proc/kallsyms", "r");
7542 	if (!f) {
7543 		err = -errno;
7544 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7545 		return err;
7546 	}
7547 
7548 	while (true) {
7549 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7550 			     &sym_addr, &sym_type, sym_name);
7551 		if (ret == EOF && feof(f))
7552 			break;
7553 		if (ret != 3) {
7554 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7555 			err = -EINVAL;
7556 			break;
7557 		}
7558 
7559 		err = cb(sym_addr, sym_type, sym_name, ctx);
7560 		if (err)
7561 			break;
7562 	}
7563 
7564 	fclose(f);
7565 	return err;
7566 }
7567 
kallsyms_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)7568 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7569 		       const char *sym_name, void *ctx)
7570 {
7571 	struct bpf_object *obj = ctx;
7572 	const struct btf_type *t;
7573 	struct extern_desc *ext;
7574 
7575 	ext = find_extern_by_name(obj, sym_name);
7576 	if (!ext || ext->type != EXT_KSYM)
7577 		return 0;
7578 
7579 	t = btf__type_by_id(obj->btf, ext->btf_id);
7580 	if (!btf_is_var(t))
7581 		return 0;
7582 
7583 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7584 		pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7585 			sym_name, ext->ksym.addr, sym_addr);
7586 		return -EINVAL;
7587 	}
7588 	if (!ext->is_set) {
7589 		ext->is_set = true;
7590 		ext->ksym.addr = sym_addr;
7591 		pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7592 	}
7593 	return 0;
7594 }
7595 
bpf_object__read_kallsyms_file(struct bpf_object * obj)7596 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7597 {
7598 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7599 }
7600 
find_ksym_btf_id(struct bpf_object * obj,const char * ksym_name,__u16 kind,struct btf ** res_btf,struct module_btf ** res_mod_btf)7601 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7602 			    __u16 kind, struct btf **res_btf,
7603 			    struct module_btf **res_mod_btf)
7604 {
7605 	struct module_btf *mod_btf;
7606 	struct btf *btf;
7607 	int i, id, err;
7608 
7609 	btf = obj->btf_vmlinux;
7610 	mod_btf = NULL;
7611 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7612 
7613 	if (id == -ENOENT) {
7614 		err = load_module_btfs(obj);
7615 		if (err)
7616 			return err;
7617 
7618 		for (i = 0; i < obj->btf_module_cnt; i++) {
7619 			/* we assume module_btf's BTF FD is always >0 */
7620 			mod_btf = &obj->btf_modules[i];
7621 			btf = mod_btf->btf;
7622 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7623 			if (id != -ENOENT)
7624 				break;
7625 		}
7626 	}
7627 	if (id <= 0)
7628 		return -ESRCH;
7629 
7630 	*res_btf = btf;
7631 	*res_mod_btf = mod_btf;
7632 	return id;
7633 }
7634 
bpf_object__resolve_ksym_var_btf_id(struct bpf_object * obj,struct extern_desc * ext)7635 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7636 					       struct extern_desc *ext)
7637 {
7638 	const struct btf_type *targ_var, *targ_type;
7639 	__u32 targ_type_id, local_type_id;
7640 	struct module_btf *mod_btf = NULL;
7641 	const char *targ_var_name;
7642 	struct btf *btf = NULL;
7643 	int id, err;
7644 
7645 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7646 	if (id < 0) {
7647 		if (id == -ESRCH && ext->is_weak)
7648 			return 0;
7649 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7650 			ext->name);
7651 		return id;
7652 	}
7653 
7654 	/* find local type_id */
7655 	local_type_id = ext->ksym.type_id;
7656 
7657 	/* find target type_id */
7658 	targ_var = btf__type_by_id(btf, id);
7659 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7660 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7661 
7662 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7663 					btf, targ_type_id);
7664 	if (err <= 0) {
7665 		const struct btf_type *local_type;
7666 		const char *targ_name, *local_name;
7667 
7668 		local_type = btf__type_by_id(obj->btf, local_type_id);
7669 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7670 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7671 
7672 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7673 			ext->name, local_type_id,
7674 			btf_kind_str(local_type), local_name, targ_type_id,
7675 			btf_kind_str(targ_type), targ_name);
7676 		return -EINVAL;
7677 	}
7678 
7679 	ext->is_set = true;
7680 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7681 	ext->ksym.kernel_btf_id = id;
7682 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7683 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7684 
7685 	return 0;
7686 }
7687 
bpf_object__resolve_ksym_func_btf_id(struct bpf_object * obj,struct extern_desc * ext)7688 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7689 						struct extern_desc *ext)
7690 {
7691 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7692 	struct module_btf *mod_btf = NULL;
7693 	const struct btf_type *kern_func;
7694 	struct btf *kern_btf = NULL;
7695 	int ret;
7696 
7697 	local_func_proto_id = ext->ksym.type_id;
7698 
7699 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7700 	if (kfunc_id < 0) {
7701 		if (kfunc_id == -ESRCH && ext->is_weak)
7702 			return 0;
7703 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7704 			ext->name);
7705 		return kfunc_id;
7706 	}
7707 
7708 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7709 	kfunc_proto_id = kern_func->type;
7710 
7711 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7712 					kern_btf, kfunc_proto_id);
7713 	if (ret <= 0) {
7714 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7715 			ext->name, local_func_proto_id, kfunc_proto_id);
7716 		return -EINVAL;
7717 	}
7718 
7719 	/* set index for module BTF fd in fd_array, if unset */
7720 	if (mod_btf && !mod_btf->fd_array_idx) {
7721 		/* insn->off is s16 */
7722 		if (obj->fd_array_cnt == INT16_MAX) {
7723 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7724 				ext->name, mod_btf->fd_array_idx);
7725 			return -E2BIG;
7726 		}
7727 		/* Cannot use index 0 for module BTF fd */
7728 		if (!obj->fd_array_cnt)
7729 			obj->fd_array_cnt = 1;
7730 
7731 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7732 					obj->fd_array_cnt + 1);
7733 		if (ret)
7734 			return ret;
7735 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7736 		/* we assume module BTF FD is always >0 */
7737 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7738 	}
7739 
7740 	ext->is_set = true;
7741 	ext->ksym.kernel_btf_id = kfunc_id;
7742 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7743 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7744 		 ext->name, kfunc_id);
7745 
7746 	return 0;
7747 }
7748 
bpf_object__resolve_ksyms_btf_id(struct bpf_object * obj)7749 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7750 {
7751 	const struct btf_type *t;
7752 	struct extern_desc *ext;
7753 	int i, err;
7754 
7755 	for (i = 0; i < obj->nr_extern; i++) {
7756 		ext = &obj->externs[i];
7757 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7758 			continue;
7759 
7760 		if (obj->gen_loader) {
7761 			ext->is_set = true;
7762 			ext->ksym.kernel_btf_obj_fd = 0;
7763 			ext->ksym.kernel_btf_id = 0;
7764 			continue;
7765 		}
7766 		t = btf__type_by_id(obj->btf, ext->btf_id);
7767 		if (btf_is_var(t))
7768 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7769 		else
7770 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7771 		if (err)
7772 			return err;
7773 	}
7774 	return 0;
7775 }
7776 
bpf_object__resolve_externs(struct bpf_object * obj,const char * extra_kconfig)7777 static int bpf_object__resolve_externs(struct bpf_object *obj,
7778 				       const char *extra_kconfig)
7779 {
7780 	bool need_config = false, need_kallsyms = false;
7781 	bool need_vmlinux_btf = false;
7782 	struct extern_desc *ext;
7783 	void *kcfg_data = NULL;
7784 	int err, i;
7785 
7786 	if (obj->nr_extern == 0)
7787 		return 0;
7788 
7789 	if (obj->kconfig_map_idx >= 0)
7790 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7791 
7792 	for (i = 0; i < obj->nr_extern; i++) {
7793 		ext = &obj->externs[i];
7794 
7795 		if (ext->type == EXT_KCFG &&
7796 		    strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7797 			void *ext_val = kcfg_data + ext->kcfg.data_off;
7798 			__u32 kver = get_kernel_version();
7799 
7800 			if (!kver) {
7801 				pr_warn("failed to get kernel version\n");
7802 				return -EINVAL;
7803 			}
7804 			err = set_kcfg_value_num(ext, ext_val, kver);
7805 			if (err)
7806 				return err;
7807 			pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
7808 		} else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
7809 			need_config = true;
7810 		} else if (ext->type == EXT_KSYM) {
7811 			if (ext->ksym.type_id)
7812 				need_vmlinux_btf = true;
7813 			else
7814 				need_kallsyms = true;
7815 		} else {
7816 			pr_warn("unrecognized extern '%s'\n", ext->name);
7817 			return -EINVAL;
7818 		}
7819 	}
7820 	if (need_config && extra_kconfig) {
7821 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7822 		if (err)
7823 			return -EINVAL;
7824 		need_config = false;
7825 		for (i = 0; i < obj->nr_extern; i++) {
7826 			ext = &obj->externs[i];
7827 			if (ext->type == EXT_KCFG && !ext->is_set) {
7828 				need_config = true;
7829 				break;
7830 			}
7831 		}
7832 	}
7833 	if (need_config) {
7834 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7835 		if (err)
7836 			return -EINVAL;
7837 	}
7838 	if (need_kallsyms) {
7839 		err = bpf_object__read_kallsyms_file(obj);
7840 		if (err)
7841 			return -EINVAL;
7842 	}
7843 	if (need_vmlinux_btf) {
7844 		err = bpf_object__resolve_ksyms_btf_id(obj);
7845 		if (err)
7846 			return -EINVAL;
7847 	}
7848 	for (i = 0; i < obj->nr_extern; i++) {
7849 		ext = &obj->externs[i];
7850 
7851 		if (!ext->is_set && !ext->is_weak) {
7852 			pr_warn("extern %s (strong) not resolved\n", ext->name);
7853 			return -ESRCH;
7854 		} else if (!ext->is_set) {
7855 			pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7856 				 ext->name);
7857 		}
7858 	}
7859 
7860 	return 0;
7861 }
7862 
bpf_object_load(struct bpf_object * obj,int extra_log_level,const char * target_btf_path)7863 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7864 {
7865 	int err, i;
7866 
7867 	if (!obj)
7868 		return libbpf_err(-EINVAL);
7869 
7870 	if (obj->loaded) {
7871 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7872 		return libbpf_err(-EINVAL);
7873 	}
7874 
7875 	if (obj->gen_loader)
7876 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7877 
7878 	err = bpf_object__probe_loading(obj);
7879 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7880 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7881 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7882 	err = err ? : bpf_object__sanitize_maps(obj);
7883 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7884 	err = err ? : bpf_object__create_maps(obj);
7885 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7886 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7887 	err = err ? : bpf_object_init_prog_arrays(obj);
7888 
7889 	if (obj->gen_loader) {
7890 		/* reset FDs */
7891 		if (obj->btf)
7892 			btf__set_fd(obj->btf, -1);
7893 		for (i = 0; i < obj->nr_maps; i++)
7894 			obj->maps[i].fd = -1;
7895 		if (!err)
7896 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7897 	}
7898 
7899 	/* clean up fd_array */
7900 	zfree(&obj->fd_array);
7901 
7902 	/* clean up module BTFs */
7903 	for (i = 0; i < obj->btf_module_cnt; i++) {
7904 		close(obj->btf_modules[i].fd);
7905 		btf__free(obj->btf_modules[i].btf);
7906 		free(obj->btf_modules[i].name);
7907 	}
7908 	free(obj->btf_modules);
7909 
7910 	/* clean up vmlinux BTF */
7911 	btf__free(obj->btf_vmlinux);
7912 	obj->btf_vmlinux = NULL;
7913 
7914 	obj->loaded = true; /* doesn't matter if successfully or not */
7915 
7916 	if (err)
7917 		goto out;
7918 
7919 	return 0;
7920 out:
7921 	/* unpin any maps that were auto-pinned during load */
7922 	for (i = 0; i < obj->nr_maps; i++)
7923 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7924 			bpf_map__unpin(&obj->maps[i], NULL);
7925 
7926 	bpf_object_unload(obj);
7927 	pr_warn("failed to load object '%s'\n", obj->path);
7928 	return libbpf_err(err);
7929 }
7930 
bpf_object__load_xattr(struct bpf_object_load_attr * attr)7931 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
7932 {
7933 	return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
7934 }
7935 
bpf_object__load(struct bpf_object * obj)7936 int bpf_object__load(struct bpf_object *obj)
7937 {
7938 	return bpf_object_load(obj, 0, NULL);
7939 }
7940 
make_parent_dir(const char * path)7941 static int make_parent_dir(const char *path)
7942 {
7943 	char *cp, errmsg[STRERR_BUFSIZE];
7944 	char *dname, *dir;
7945 	int err = 0;
7946 
7947 	dname = strdup(path);
7948 	if (dname == NULL)
7949 		return -ENOMEM;
7950 
7951 	dir = dirname(dname);
7952 	if (mkdir(dir, 0700) && errno != EEXIST)
7953 		err = -errno;
7954 
7955 	free(dname);
7956 	if (err) {
7957 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7958 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7959 	}
7960 	return err;
7961 }
7962 
check_path(const char * path)7963 static int check_path(const char *path)
7964 {
7965 	char *cp, errmsg[STRERR_BUFSIZE];
7966 	struct statfs st_fs;
7967 	char *dname, *dir;
7968 	int err = 0;
7969 
7970 	if (path == NULL)
7971 		return -EINVAL;
7972 
7973 	dname = strdup(path);
7974 	if (dname == NULL)
7975 		return -ENOMEM;
7976 
7977 	dir = dirname(dname);
7978 	if (statfs(dir, &st_fs)) {
7979 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7980 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7981 		err = -errno;
7982 	}
7983 	free(dname);
7984 
7985 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7986 		pr_warn("specified path %s is not on BPF FS\n", path);
7987 		err = -EINVAL;
7988 	}
7989 
7990 	return err;
7991 }
7992 
bpf_program_pin_instance(struct bpf_program * prog,const char * path,int instance)7993 static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
7994 {
7995 	char *cp, errmsg[STRERR_BUFSIZE];
7996 	int err;
7997 
7998 	err = make_parent_dir(path);
7999 	if (err)
8000 		return libbpf_err(err);
8001 
8002 	err = check_path(path);
8003 	if (err)
8004 		return libbpf_err(err);
8005 
8006 	if (prog == NULL) {
8007 		pr_warn("invalid program pointer\n");
8008 		return libbpf_err(-EINVAL);
8009 	}
8010 
8011 	if (instance < 0 || instance >= prog->instances.nr) {
8012 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8013 			instance, prog->name, prog->instances.nr);
8014 		return libbpf_err(-EINVAL);
8015 	}
8016 
8017 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
8018 		err = -errno;
8019 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8020 		pr_warn("failed to pin program: %s\n", cp);
8021 		return libbpf_err(err);
8022 	}
8023 	pr_debug("pinned program '%s'\n", path);
8024 
8025 	return 0;
8026 }
8027 
bpf_program_unpin_instance(struct bpf_program * prog,const char * path,int instance)8028 static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
8029 {
8030 	int err;
8031 
8032 	err = check_path(path);
8033 	if (err)
8034 		return libbpf_err(err);
8035 
8036 	if (prog == NULL) {
8037 		pr_warn("invalid program pointer\n");
8038 		return libbpf_err(-EINVAL);
8039 	}
8040 
8041 	if (instance < 0 || instance >= prog->instances.nr) {
8042 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
8043 			instance, prog->name, prog->instances.nr);
8044 		return libbpf_err(-EINVAL);
8045 	}
8046 
8047 	err = unlink(path);
8048 	if (err != 0)
8049 		return libbpf_err(-errno);
8050 
8051 	pr_debug("unpinned program '%s'\n", path);
8052 
8053 	return 0;
8054 }
8055 
8056 __attribute__((alias("bpf_program_pin_instance")))
8057 int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
8058 
8059 __attribute__((alias("bpf_program_unpin_instance")))
8060 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
8061 
bpf_program__pin(struct bpf_program * prog,const char * path)8062 int bpf_program__pin(struct bpf_program *prog, const char *path)
8063 {
8064 	int i, err;
8065 
8066 	err = make_parent_dir(path);
8067 	if (err)
8068 		return libbpf_err(err);
8069 
8070 	err = check_path(path);
8071 	if (err)
8072 		return libbpf_err(err);
8073 
8074 	if (prog == NULL) {
8075 		pr_warn("invalid program pointer\n");
8076 		return libbpf_err(-EINVAL);
8077 	}
8078 
8079 	if (prog->instances.nr <= 0) {
8080 		pr_warn("no instances of prog %s to pin\n", prog->name);
8081 		return libbpf_err(-EINVAL);
8082 	}
8083 
8084 	if (prog->instances.nr == 1) {
8085 		/* don't create subdirs when pinning single instance */
8086 		return bpf_program_pin_instance(prog, path, 0);
8087 	}
8088 
8089 	for (i = 0; i < prog->instances.nr; i++) {
8090 		char buf[PATH_MAX];
8091 		int len;
8092 
8093 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8094 		if (len < 0) {
8095 			err = -EINVAL;
8096 			goto err_unpin;
8097 		} else if (len >= PATH_MAX) {
8098 			err = -ENAMETOOLONG;
8099 			goto err_unpin;
8100 		}
8101 
8102 		err = bpf_program_pin_instance(prog, buf, i);
8103 		if (err)
8104 			goto err_unpin;
8105 	}
8106 
8107 	return 0;
8108 
8109 err_unpin:
8110 	for (i = i - 1; i >= 0; i--) {
8111 		char buf[PATH_MAX];
8112 		int len;
8113 
8114 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8115 		if (len < 0)
8116 			continue;
8117 		else if (len >= PATH_MAX)
8118 			continue;
8119 
8120 		bpf_program_unpin_instance(prog, buf, i);
8121 	}
8122 
8123 	rmdir(path);
8124 
8125 	return libbpf_err(err);
8126 }
8127 
bpf_program__unpin(struct bpf_program * prog,const char * path)8128 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8129 {
8130 	int i, err;
8131 
8132 	err = check_path(path);
8133 	if (err)
8134 		return libbpf_err(err);
8135 
8136 	if (prog == NULL) {
8137 		pr_warn("invalid program pointer\n");
8138 		return libbpf_err(-EINVAL);
8139 	}
8140 
8141 	if (prog->instances.nr <= 0) {
8142 		pr_warn("no instances of prog %s to pin\n", prog->name);
8143 		return libbpf_err(-EINVAL);
8144 	}
8145 
8146 	if (prog->instances.nr == 1) {
8147 		/* don't create subdirs when pinning single instance */
8148 		return bpf_program_unpin_instance(prog, path, 0);
8149 	}
8150 
8151 	for (i = 0; i < prog->instances.nr; i++) {
8152 		char buf[PATH_MAX];
8153 		int len;
8154 
8155 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
8156 		if (len < 0)
8157 			return libbpf_err(-EINVAL);
8158 		else if (len >= PATH_MAX)
8159 			return libbpf_err(-ENAMETOOLONG);
8160 
8161 		err = bpf_program_unpin_instance(prog, buf, i);
8162 		if (err)
8163 			return err;
8164 	}
8165 
8166 	err = rmdir(path);
8167 	if (err)
8168 		return libbpf_err(-errno);
8169 
8170 	return 0;
8171 }
8172 
bpf_map__pin(struct bpf_map * map,const char * path)8173 int bpf_map__pin(struct bpf_map *map, const char *path)
8174 {
8175 	char *cp, errmsg[STRERR_BUFSIZE];
8176 	int err;
8177 
8178 	if (map == NULL) {
8179 		pr_warn("invalid map pointer\n");
8180 		return libbpf_err(-EINVAL);
8181 	}
8182 
8183 	if (map->pin_path) {
8184 		if (path && strcmp(path, map->pin_path)) {
8185 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8186 				bpf_map__name(map), map->pin_path, path);
8187 			return libbpf_err(-EINVAL);
8188 		} else if (map->pinned) {
8189 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8190 				 bpf_map__name(map), map->pin_path);
8191 			return 0;
8192 		}
8193 	} else {
8194 		if (!path) {
8195 			pr_warn("missing a path to pin map '%s' at\n",
8196 				bpf_map__name(map));
8197 			return libbpf_err(-EINVAL);
8198 		} else if (map->pinned) {
8199 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8200 			return libbpf_err(-EEXIST);
8201 		}
8202 
8203 		map->pin_path = strdup(path);
8204 		if (!map->pin_path) {
8205 			err = -errno;
8206 			goto out_err;
8207 		}
8208 	}
8209 
8210 	err = make_parent_dir(map->pin_path);
8211 	if (err)
8212 		return libbpf_err(err);
8213 
8214 	err = check_path(map->pin_path);
8215 	if (err)
8216 		return libbpf_err(err);
8217 
8218 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8219 		err = -errno;
8220 		goto out_err;
8221 	}
8222 
8223 	map->pinned = true;
8224 	pr_debug("pinned map '%s'\n", map->pin_path);
8225 
8226 	return 0;
8227 
8228 out_err:
8229 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8230 	pr_warn("failed to pin map: %s\n", cp);
8231 	return libbpf_err(err);
8232 }
8233 
bpf_map__unpin(struct bpf_map * map,const char * path)8234 int bpf_map__unpin(struct bpf_map *map, const char *path)
8235 {
8236 	int err;
8237 
8238 	if (map == NULL) {
8239 		pr_warn("invalid map pointer\n");
8240 		return libbpf_err(-EINVAL);
8241 	}
8242 
8243 	if (map->pin_path) {
8244 		if (path && strcmp(path, map->pin_path)) {
8245 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8246 				bpf_map__name(map), map->pin_path, path);
8247 			return libbpf_err(-EINVAL);
8248 		}
8249 		path = map->pin_path;
8250 	} else if (!path) {
8251 		pr_warn("no path to unpin map '%s' from\n",
8252 			bpf_map__name(map));
8253 		return libbpf_err(-EINVAL);
8254 	}
8255 
8256 	err = check_path(path);
8257 	if (err)
8258 		return libbpf_err(err);
8259 
8260 	err = unlink(path);
8261 	if (err != 0)
8262 		return libbpf_err(-errno);
8263 
8264 	map->pinned = false;
8265 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8266 
8267 	return 0;
8268 }
8269 
bpf_map__set_pin_path(struct bpf_map * map,const char * path)8270 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8271 {
8272 	char *new = NULL;
8273 
8274 	if (path) {
8275 		new = strdup(path);
8276 		if (!new)
8277 			return libbpf_err(-errno);
8278 	}
8279 
8280 	free(map->pin_path);
8281 	map->pin_path = new;
8282 	return 0;
8283 }
8284 
8285 __alias(bpf_map__pin_path)
8286 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8287 
bpf_map__pin_path(const struct bpf_map * map)8288 const char *bpf_map__pin_path(const struct bpf_map *map)
8289 {
8290 	return map->pin_path;
8291 }
8292 
bpf_map__is_pinned(const struct bpf_map * map)8293 bool bpf_map__is_pinned(const struct bpf_map *map)
8294 {
8295 	return map->pinned;
8296 }
8297 
sanitize_pin_path(char * s)8298 static void sanitize_pin_path(char *s)
8299 {
8300 	/* bpffs disallows periods in path names */
8301 	while (*s) {
8302 		if (*s == '.')
8303 			*s = '_';
8304 		s++;
8305 	}
8306 }
8307 
bpf_object__pin_maps(struct bpf_object * obj,const char * path)8308 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8309 {
8310 	struct bpf_map *map;
8311 	int err;
8312 
8313 	if (!obj)
8314 		return libbpf_err(-ENOENT);
8315 
8316 	if (!obj->loaded) {
8317 		pr_warn("object not yet loaded; load it first\n");
8318 		return libbpf_err(-ENOENT);
8319 	}
8320 
8321 	bpf_object__for_each_map(map, obj) {
8322 		char *pin_path = NULL;
8323 		char buf[PATH_MAX];
8324 
8325 		if (!map->autocreate)
8326 			continue;
8327 
8328 		if (path) {
8329 			int len;
8330 
8331 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8332 				       bpf_map__name(map));
8333 			if (len < 0) {
8334 				err = -EINVAL;
8335 				goto err_unpin_maps;
8336 			} else if (len >= PATH_MAX) {
8337 				err = -ENAMETOOLONG;
8338 				goto err_unpin_maps;
8339 			}
8340 			sanitize_pin_path(buf);
8341 			pin_path = buf;
8342 		} else if (!map->pin_path) {
8343 			continue;
8344 		}
8345 
8346 		err = bpf_map__pin(map, pin_path);
8347 		if (err)
8348 			goto err_unpin_maps;
8349 	}
8350 
8351 	return 0;
8352 
8353 err_unpin_maps:
8354 	while ((map = bpf_object__prev_map(obj, map))) {
8355 		if (!map->pin_path)
8356 			continue;
8357 
8358 		bpf_map__unpin(map, NULL);
8359 	}
8360 
8361 	return libbpf_err(err);
8362 }
8363 
bpf_object__unpin_maps(struct bpf_object * obj,const char * path)8364 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8365 {
8366 	struct bpf_map *map;
8367 	int err;
8368 
8369 	if (!obj)
8370 		return libbpf_err(-ENOENT);
8371 
8372 	bpf_object__for_each_map(map, obj) {
8373 		char *pin_path = NULL;
8374 		char buf[PATH_MAX];
8375 
8376 		if (path) {
8377 			int len;
8378 
8379 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8380 				       bpf_map__name(map));
8381 			if (len < 0)
8382 				return libbpf_err(-EINVAL);
8383 			else if (len >= PATH_MAX)
8384 				return libbpf_err(-ENAMETOOLONG);
8385 			sanitize_pin_path(buf);
8386 			pin_path = buf;
8387 		} else if (!map->pin_path) {
8388 			continue;
8389 		}
8390 
8391 		err = bpf_map__unpin(map, pin_path);
8392 		if (err)
8393 			return libbpf_err(err);
8394 	}
8395 
8396 	return 0;
8397 }
8398 
bpf_object__pin_programs(struct bpf_object * obj,const char * path)8399 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8400 {
8401 	struct bpf_program *prog;
8402 	int err;
8403 
8404 	if (!obj)
8405 		return libbpf_err(-ENOENT);
8406 
8407 	if (!obj->loaded) {
8408 		pr_warn("object not yet loaded; load it first\n");
8409 		return libbpf_err(-ENOENT);
8410 	}
8411 
8412 	bpf_object__for_each_program(prog, obj) {
8413 		char buf[PATH_MAX];
8414 		int len;
8415 
8416 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8417 			       prog->pin_name);
8418 		if (len < 0) {
8419 			err = -EINVAL;
8420 			goto err_unpin_programs;
8421 		} else if (len >= PATH_MAX) {
8422 			err = -ENAMETOOLONG;
8423 			goto err_unpin_programs;
8424 		}
8425 
8426 		err = bpf_program__pin(prog, buf);
8427 		if (err)
8428 			goto err_unpin_programs;
8429 	}
8430 
8431 	return 0;
8432 
8433 err_unpin_programs:
8434 	while ((prog = bpf_object__prev_program(obj, prog))) {
8435 		char buf[PATH_MAX];
8436 		int len;
8437 
8438 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8439 			       prog->pin_name);
8440 		if (len < 0)
8441 			continue;
8442 		else if (len >= PATH_MAX)
8443 			continue;
8444 
8445 		bpf_program__unpin(prog, buf);
8446 	}
8447 
8448 	return libbpf_err(err);
8449 }
8450 
bpf_object__unpin_programs(struct bpf_object * obj,const char * path)8451 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8452 {
8453 	struct bpf_program *prog;
8454 	int err;
8455 
8456 	if (!obj)
8457 		return libbpf_err(-ENOENT);
8458 
8459 	bpf_object__for_each_program(prog, obj) {
8460 		char buf[PATH_MAX];
8461 		int len;
8462 
8463 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
8464 			       prog->pin_name);
8465 		if (len < 0)
8466 			return libbpf_err(-EINVAL);
8467 		else if (len >= PATH_MAX)
8468 			return libbpf_err(-ENAMETOOLONG);
8469 
8470 		err = bpf_program__unpin(prog, buf);
8471 		if (err)
8472 			return libbpf_err(err);
8473 	}
8474 
8475 	return 0;
8476 }
8477 
bpf_object__pin(struct bpf_object * obj,const char * path)8478 int bpf_object__pin(struct bpf_object *obj, const char *path)
8479 {
8480 	int err;
8481 
8482 	err = bpf_object__pin_maps(obj, path);
8483 	if (err)
8484 		return libbpf_err(err);
8485 
8486 	err = bpf_object__pin_programs(obj, path);
8487 	if (err) {
8488 		bpf_object__unpin_maps(obj, path);
8489 		return libbpf_err(err);
8490 	}
8491 
8492 	return 0;
8493 }
8494 
bpf_map__destroy(struct bpf_map * map)8495 static void bpf_map__destroy(struct bpf_map *map)
8496 {
8497 	if (map->clear_priv)
8498 		map->clear_priv(map, map->priv);
8499 	map->priv = NULL;
8500 	map->clear_priv = NULL;
8501 
8502 	if (map->inner_map) {
8503 		bpf_map__destroy(map->inner_map);
8504 		zfree(&map->inner_map);
8505 	}
8506 
8507 	zfree(&map->init_slots);
8508 	map->init_slots_sz = 0;
8509 
8510 	if (map->mmaped) {
8511 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8512 		map->mmaped = NULL;
8513 	}
8514 
8515 	if (map->st_ops) {
8516 		zfree(&map->st_ops->data);
8517 		zfree(&map->st_ops->progs);
8518 		zfree(&map->st_ops->kern_func_off);
8519 		zfree(&map->st_ops);
8520 	}
8521 
8522 	zfree(&map->name);
8523 	zfree(&map->real_name);
8524 	zfree(&map->pin_path);
8525 
8526 	if (map->fd >= 0)
8527 		zclose(map->fd);
8528 }
8529 
bpf_object__close(struct bpf_object * obj)8530 void bpf_object__close(struct bpf_object *obj)
8531 {
8532 	size_t i;
8533 
8534 	if (IS_ERR_OR_NULL(obj))
8535 		return;
8536 
8537 	if (obj->clear_priv)
8538 		obj->clear_priv(obj, obj->priv);
8539 
8540 	usdt_manager_free(obj->usdt_man);
8541 	obj->usdt_man = NULL;
8542 
8543 	bpf_gen__free(obj->gen_loader);
8544 	bpf_object__elf_finish(obj);
8545 	bpf_object_unload(obj);
8546 	btf__free(obj->btf);
8547 	btf_ext__free(obj->btf_ext);
8548 
8549 	for (i = 0; i < obj->nr_maps; i++)
8550 		bpf_map__destroy(&obj->maps[i]);
8551 
8552 	zfree(&obj->btf_custom_path);
8553 	zfree(&obj->kconfig);
8554 	zfree(&obj->externs);
8555 	obj->nr_extern = 0;
8556 
8557 	zfree(&obj->maps);
8558 	obj->nr_maps = 0;
8559 
8560 	if (obj->programs && obj->nr_programs) {
8561 		for (i = 0; i < obj->nr_programs; i++)
8562 			bpf_program__exit(&obj->programs[i]);
8563 	}
8564 	zfree(&obj->programs);
8565 
8566 	list_del(&obj->list);
8567 	free(obj);
8568 }
8569 
8570 struct bpf_object *
bpf_object__next(struct bpf_object * prev)8571 bpf_object__next(struct bpf_object *prev)
8572 {
8573 	struct bpf_object *next;
8574 	bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8575 
8576 	if (strict)
8577 		return NULL;
8578 
8579 	if (!prev)
8580 		next = list_first_entry(&bpf_objects_list,
8581 					struct bpf_object,
8582 					list);
8583 	else
8584 		next = list_next_entry(prev, list);
8585 
8586 	/* Empty list is noticed here so don't need checking on entry. */
8587 	if (&next->list == &bpf_objects_list)
8588 		return NULL;
8589 
8590 	return next;
8591 }
8592 
bpf_object__name(const struct bpf_object * obj)8593 const char *bpf_object__name(const struct bpf_object *obj)
8594 {
8595 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8596 }
8597 
bpf_object__kversion(const struct bpf_object * obj)8598 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8599 {
8600 	return obj ? obj->kern_version : 0;
8601 }
8602 
bpf_object__btf(const struct bpf_object * obj)8603 struct btf *bpf_object__btf(const struct bpf_object *obj)
8604 {
8605 	return obj ? obj->btf : NULL;
8606 }
8607 
bpf_object__btf_fd(const struct bpf_object * obj)8608 int bpf_object__btf_fd(const struct bpf_object *obj)
8609 {
8610 	return obj->btf ? btf__fd(obj->btf) : -1;
8611 }
8612 
bpf_object__set_kversion(struct bpf_object * obj,__u32 kern_version)8613 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8614 {
8615 	if (obj->loaded)
8616 		return libbpf_err(-EINVAL);
8617 
8618 	obj->kern_version = kern_version;
8619 
8620 	return 0;
8621 }
8622 
bpf_object__set_priv(struct bpf_object * obj,void * priv,bpf_object_clear_priv_t clear_priv)8623 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8624 			 bpf_object_clear_priv_t clear_priv)
8625 {
8626 	if (obj->priv && obj->clear_priv)
8627 		obj->clear_priv(obj, obj->priv);
8628 
8629 	obj->priv = priv;
8630 	obj->clear_priv = clear_priv;
8631 	return 0;
8632 }
8633 
bpf_object__priv(const struct bpf_object * obj)8634 void *bpf_object__priv(const struct bpf_object *obj)
8635 {
8636 	return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
8637 }
8638 
bpf_object__gen_loader(struct bpf_object * obj,struct gen_loader_opts * opts)8639 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8640 {
8641 	struct bpf_gen *gen;
8642 
8643 	if (!opts)
8644 		return -EFAULT;
8645 	if (!OPTS_VALID(opts, gen_loader_opts))
8646 		return -EINVAL;
8647 	gen = calloc(sizeof(*gen), 1);
8648 	if (!gen)
8649 		return -ENOMEM;
8650 	gen->opts = opts;
8651 	obj->gen_loader = gen;
8652 	return 0;
8653 }
8654 
8655 static struct bpf_program *
__bpf_program__iter(const struct bpf_program * p,const struct bpf_object * obj,bool forward)8656 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8657 		    bool forward)
8658 {
8659 	size_t nr_programs = obj->nr_programs;
8660 	ssize_t idx;
8661 
8662 	if (!nr_programs)
8663 		return NULL;
8664 
8665 	if (!p)
8666 		/* Iter from the beginning */
8667 		return forward ? &obj->programs[0] :
8668 			&obj->programs[nr_programs - 1];
8669 
8670 	if (p->obj != obj) {
8671 		pr_warn("error: program handler doesn't match object\n");
8672 		return errno = EINVAL, NULL;
8673 	}
8674 
8675 	idx = (p - obj->programs) + (forward ? 1 : -1);
8676 	if (idx >= obj->nr_programs || idx < 0)
8677 		return NULL;
8678 	return &obj->programs[idx];
8679 }
8680 
8681 struct bpf_program *
bpf_program__next(struct bpf_program * prev,const struct bpf_object * obj)8682 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
8683 {
8684 	return bpf_object__next_program(obj, prev);
8685 }
8686 
8687 struct bpf_program *
bpf_object__next_program(const struct bpf_object * obj,struct bpf_program * prev)8688 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8689 {
8690 	struct bpf_program *prog = prev;
8691 
8692 	do {
8693 		prog = __bpf_program__iter(prog, obj, true);
8694 	} while (prog && prog_is_subprog(obj, prog));
8695 
8696 	return prog;
8697 }
8698 
8699 struct bpf_program *
bpf_program__prev(struct bpf_program * next,const struct bpf_object * obj)8700 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
8701 {
8702 	return bpf_object__prev_program(obj, next);
8703 }
8704 
8705 struct bpf_program *
bpf_object__prev_program(const struct bpf_object * obj,struct bpf_program * next)8706 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8707 {
8708 	struct bpf_program *prog = next;
8709 
8710 	do {
8711 		prog = __bpf_program__iter(prog, obj, false);
8712 	} while (prog && prog_is_subprog(obj, prog));
8713 
8714 	return prog;
8715 }
8716 
bpf_program__set_priv(struct bpf_program * prog,void * priv,bpf_program_clear_priv_t clear_priv)8717 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8718 			  bpf_program_clear_priv_t clear_priv)
8719 {
8720 	if (prog->priv && prog->clear_priv)
8721 		prog->clear_priv(prog, prog->priv);
8722 
8723 	prog->priv = priv;
8724 	prog->clear_priv = clear_priv;
8725 	return 0;
8726 }
8727 
bpf_program__priv(const struct bpf_program * prog)8728 void *bpf_program__priv(const struct bpf_program *prog)
8729 {
8730 	return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
8731 }
8732 
bpf_program__set_ifindex(struct bpf_program * prog,__u32 ifindex)8733 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8734 {
8735 	prog->prog_ifindex = ifindex;
8736 }
8737 
bpf_program__name(const struct bpf_program * prog)8738 const char *bpf_program__name(const struct bpf_program *prog)
8739 {
8740 	return prog->name;
8741 }
8742 
bpf_program__section_name(const struct bpf_program * prog)8743 const char *bpf_program__section_name(const struct bpf_program *prog)
8744 {
8745 	return prog->sec_name;
8746 }
8747 
bpf_program__title(const struct bpf_program * prog,bool needs_copy)8748 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
8749 {
8750 	const char *title;
8751 
8752 	title = prog->sec_name;
8753 	if (needs_copy) {
8754 		title = strdup(title);
8755 		if (!title) {
8756 			pr_warn("failed to strdup program title\n");
8757 			return libbpf_err_ptr(-ENOMEM);
8758 		}
8759 	}
8760 
8761 	return title;
8762 }
8763 
bpf_program__autoload(const struct bpf_program * prog)8764 bool bpf_program__autoload(const struct bpf_program *prog)
8765 {
8766 	return prog->autoload;
8767 }
8768 
bpf_program__set_autoload(struct bpf_program * prog,bool autoload)8769 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8770 {
8771 	if (prog->obj->loaded)
8772 		return libbpf_err(-EINVAL);
8773 
8774 	prog->autoload = autoload;
8775 	return 0;
8776 }
8777 
8778 static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8779 
bpf_program__fd(const struct bpf_program * prog)8780 int bpf_program__fd(const struct bpf_program *prog)
8781 {
8782 	return bpf_program_nth_fd(prog, 0);
8783 }
8784 
bpf_program__size(const struct bpf_program * prog)8785 size_t bpf_program__size(const struct bpf_program *prog)
8786 {
8787 	return prog->insns_cnt * BPF_INSN_SZ;
8788 }
8789 
bpf_program__insns(const struct bpf_program * prog)8790 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8791 {
8792 	return prog->insns;
8793 }
8794 
bpf_program__insn_cnt(const struct bpf_program * prog)8795 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8796 {
8797 	return prog->insns_cnt;
8798 }
8799 
bpf_program__set_insns(struct bpf_program * prog,struct bpf_insn * new_insns,size_t new_insn_cnt)8800 int bpf_program__set_insns(struct bpf_program *prog,
8801 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8802 {
8803 	struct bpf_insn *insns;
8804 
8805 	if (prog->obj->loaded)
8806 		return -EBUSY;
8807 
8808 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8809 	if (!insns) {
8810 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8811 		return -ENOMEM;
8812 	}
8813 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8814 
8815 	prog->insns = insns;
8816 	prog->insns_cnt = new_insn_cnt;
8817 	return 0;
8818 }
8819 
bpf_program__set_prep(struct bpf_program * prog,int nr_instances,bpf_program_prep_t prep)8820 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8821 			  bpf_program_prep_t prep)
8822 {
8823 	int *instances_fds;
8824 
8825 	if (nr_instances <= 0 || !prep)
8826 		return libbpf_err(-EINVAL);
8827 
8828 	if (prog->instances.nr > 0 || prog->instances.fds) {
8829 		pr_warn("Can't set pre-processor after loading\n");
8830 		return libbpf_err(-EINVAL);
8831 	}
8832 
8833 	instances_fds = malloc(sizeof(int) * nr_instances);
8834 	if (!instances_fds) {
8835 		pr_warn("alloc memory failed for fds\n");
8836 		return libbpf_err(-ENOMEM);
8837 	}
8838 
8839 	/* fill all fd with -1 */
8840 	memset(instances_fds, -1, sizeof(int) * nr_instances);
8841 
8842 	prog->instances.nr = nr_instances;
8843 	prog->instances.fds = instances_fds;
8844 	prog->preprocessor = prep;
8845 	return 0;
8846 }
8847 
8848 __attribute__((alias("bpf_program_nth_fd")))
8849 int bpf_program__nth_fd(const struct bpf_program *prog, int n);
8850 
bpf_program_nth_fd(const struct bpf_program * prog,int n)8851 static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
8852 {
8853 	int fd;
8854 
8855 	if (!prog)
8856 		return libbpf_err(-EINVAL);
8857 
8858 	if (n >= prog->instances.nr || n < 0) {
8859 		pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
8860 			n, prog->name, prog->instances.nr);
8861 		return libbpf_err(-EINVAL);
8862 	}
8863 
8864 	fd = prog->instances.fds[n];
8865 	if (fd < 0) {
8866 		pr_warn("%dth instance of program '%s' is invalid\n",
8867 			n, prog->name);
8868 		return libbpf_err(-ENOENT);
8869 	}
8870 
8871 	return fd;
8872 }
8873 
8874 __alias(bpf_program__type)
8875 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8876 
bpf_program__type(const struct bpf_program * prog)8877 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8878 {
8879 	return prog->type;
8880 }
8881 
bpf_program__set_type(struct bpf_program * prog,enum bpf_prog_type type)8882 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8883 {
8884 	if (prog->obj->loaded)
8885 		return libbpf_err(-EBUSY);
8886 
8887 	prog->type = type;
8888 	return 0;
8889 }
8890 
bpf_program__is_type(const struct bpf_program * prog,enum bpf_prog_type type)8891 static bool bpf_program__is_type(const struct bpf_program *prog,
8892 				 enum bpf_prog_type type)
8893 {
8894 	return prog ? (prog->type == type) : false;
8895 }
8896 
8897 #define BPF_PROG_TYPE_FNS(NAME, TYPE)				\
8898 int bpf_program__set_##NAME(struct bpf_program *prog)		\
8899 {								\
8900 	if (!prog)						\
8901 		return libbpf_err(-EINVAL);			\
8902 	return bpf_program__set_type(prog, TYPE);			\
8903 }								\
8904 								\
8905 bool bpf_program__is_##NAME(const struct bpf_program *prog)	\
8906 {								\
8907 	return bpf_program__is_type(prog, TYPE);		\
8908 }								\
8909 
8910 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
8911 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
8912 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
8913 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8914 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
8915 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
8916 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
8917 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8918 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
8919 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
8920 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
8921 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
8922 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
8923 
8924 __alias(bpf_program__expected_attach_type)
8925 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8926 
bpf_program__expected_attach_type(const struct bpf_program * prog)8927 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8928 {
8929 	return prog->expected_attach_type;
8930 }
8931 
bpf_program__set_expected_attach_type(struct bpf_program * prog,enum bpf_attach_type type)8932 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8933 					   enum bpf_attach_type type)
8934 {
8935 	if (prog->obj->loaded)
8936 		return libbpf_err(-EBUSY);
8937 
8938 	prog->expected_attach_type = type;
8939 	return 0;
8940 }
8941 
bpf_program__flags(const struct bpf_program * prog)8942 __u32 bpf_program__flags(const struct bpf_program *prog)
8943 {
8944 	return prog->prog_flags;
8945 }
8946 
bpf_program__set_flags(struct bpf_program * prog,__u32 flags)8947 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8948 {
8949 	if (prog->obj->loaded)
8950 		return libbpf_err(-EBUSY);
8951 
8952 	prog->prog_flags = flags;
8953 	return 0;
8954 }
8955 
bpf_program__log_level(const struct bpf_program * prog)8956 __u32 bpf_program__log_level(const struct bpf_program *prog)
8957 {
8958 	return prog->log_level;
8959 }
8960 
bpf_program__set_log_level(struct bpf_program * prog,__u32 log_level)8961 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8962 {
8963 	if (prog->obj->loaded)
8964 		return libbpf_err(-EBUSY);
8965 
8966 	prog->log_level = log_level;
8967 	return 0;
8968 }
8969 
bpf_program__log_buf(const struct bpf_program * prog,size_t * log_size)8970 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8971 {
8972 	*log_size = prog->log_size;
8973 	return prog->log_buf;
8974 }
8975 
bpf_program__set_log_buf(struct bpf_program * prog,char * log_buf,size_t log_size)8976 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8977 {
8978 	if (log_size && !log_buf)
8979 		return -EINVAL;
8980 	if (prog->log_size > UINT_MAX)
8981 		return -EINVAL;
8982 	if (prog->obj->loaded)
8983 		return -EBUSY;
8984 
8985 	prog->log_buf = log_buf;
8986 	prog->log_size = log_size;
8987 	return 0;
8988 }
8989 
8990 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8991 	.sec = (char *)sec_pfx,						    \
8992 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8993 	.expected_attach_type = atype,					    \
8994 	.cookie = (long)(flags),					    \
8995 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8996 	__VA_ARGS__							    \
8997 }
8998 
8999 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9000 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9001 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9002 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9003 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9004 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9005 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9006 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9007 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9008 
9009 static const struct bpf_sec_def section_defs[] = {
9010 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
9011 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9012 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9013 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9014 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9015 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9016 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9017 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9018 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9019 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
9020 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
9021 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX | SEC_DEPRECATED),
9022 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9023 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9024 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9025 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9026 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9027 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9028 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9029 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9030 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9031 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9032 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9033 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9034 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9035 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9036 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9037 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9038 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9039 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9040 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9041 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9042 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9043 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9044 	SEC_DEF("xdp_devmap/",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
9045 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9046 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9047 	SEC_DEF("xdp_cpumap/",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
9048 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9049 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9050 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9051 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
9052 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9053 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
9054 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
9055 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9056 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9057 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
9058 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9059 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9060 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9061 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9062 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9063 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9064 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9065 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9066 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9067 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
9068 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9069 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9070 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
9071 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9072 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9073 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9074 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9075 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9076 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9077 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9078 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9079 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9080 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9081 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9082 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9083 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9084 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9085 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9086 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9087 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
9088 };
9089 
9090 static size_t custom_sec_def_cnt;
9091 static struct bpf_sec_def *custom_sec_defs;
9092 static struct bpf_sec_def custom_fallback_def;
9093 static bool has_custom_fallback_def;
9094 
9095 static int last_custom_sec_def_handler_id;
9096 
libbpf_register_prog_handler(const char * sec,enum bpf_prog_type prog_type,enum bpf_attach_type exp_attach_type,const struct libbpf_prog_handler_opts * opts)9097 int libbpf_register_prog_handler(const char *sec,
9098 				 enum bpf_prog_type prog_type,
9099 				 enum bpf_attach_type exp_attach_type,
9100 				 const struct libbpf_prog_handler_opts *opts)
9101 {
9102 	struct bpf_sec_def *sec_def;
9103 
9104 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9105 		return libbpf_err(-EINVAL);
9106 
9107 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9108 		return libbpf_err(-E2BIG);
9109 
9110 	if (sec) {
9111 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9112 					      sizeof(*sec_def));
9113 		if (!sec_def)
9114 			return libbpf_err(-ENOMEM);
9115 
9116 		custom_sec_defs = sec_def;
9117 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9118 	} else {
9119 		if (has_custom_fallback_def)
9120 			return libbpf_err(-EBUSY);
9121 
9122 		sec_def = &custom_fallback_def;
9123 	}
9124 
9125 	sec_def->sec = sec ? strdup(sec) : NULL;
9126 	if (sec && !sec_def->sec)
9127 		return libbpf_err(-ENOMEM);
9128 
9129 	sec_def->prog_type = prog_type;
9130 	sec_def->expected_attach_type = exp_attach_type;
9131 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9132 
9133 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9134 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9135 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9136 
9137 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9138 
9139 	if (sec)
9140 		custom_sec_def_cnt++;
9141 	else
9142 		has_custom_fallback_def = true;
9143 
9144 	return sec_def->handler_id;
9145 }
9146 
libbpf_unregister_prog_handler(int handler_id)9147 int libbpf_unregister_prog_handler(int handler_id)
9148 {
9149 	struct bpf_sec_def *sec_defs;
9150 	int i;
9151 
9152 	if (handler_id <= 0)
9153 		return libbpf_err(-EINVAL);
9154 
9155 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9156 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9157 		has_custom_fallback_def = false;
9158 		return 0;
9159 	}
9160 
9161 	for (i = 0; i < custom_sec_def_cnt; i++) {
9162 		if (custom_sec_defs[i].handler_id == handler_id)
9163 			break;
9164 	}
9165 
9166 	if (i == custom_sec_def_cnt)
9167 		return libbpf_err(-ENOENT);
9168 
9169 	free(custom_sec_defs[i].sec);
9170 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9171 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9172 	custom_sec_def_cnt--;
9173 
9174 	/* try to shrink the array, but it's ok if we couldn't */
9175 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9176 	if (sec_defs)
9177 		custom_sec_defs = sec_defs;
9178 
9179 	return 0;
9180 }
9181 
sec_def_matches(const struct bpf_sec_def * sec_def,const char * sec_name,bool allow_sloppy)9182 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name,
9183 			    bool allow_sloppy)
9184 {
9185 	size_t len = strlen(sec_def->sec);
9186 
9187 	/* "type/" always has to have proper SEC("type/extras") form */
9188 	if (sec_def->sec[len - 1] == '/') {
9189 		if (str_has_pfx(sec_name, sec_def->sec))
9190 			return true;
9191 		return false;
9192 	}
9193 
9194 	/* "type+" means it can be either exact SEC("type") or
9195 	 * well-formed SEC("type/extras") with proper '/' separator
9196 	 */
9197 	if (sec_def->sec[len - 1] == '+') {
9198 		len--;
9199 		/* not even a prefix */
9200 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9201 			return false;
9202 		/* exact match or has '/' separator */
9203 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9204 			return true;
9205 		return false;
9206 	}
9207 
9208 	/* SEC_SLOPPY_PFX definitions are allowed to be just prefix
9209 	 * matches, unless strict section name mode
9210 	 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
9211 	 * match has to be exact.
9212 	 */
9213 	if (allow_sloppy && str_has_pfx(sec_name, sec_def->sec))
9214 		return true;
9215 
9216 	/* Definitions not marked SEC_SLOPPY_PFX (e.g.,
9217 	 * SEC("syscall")) are exact matches in both modes.
9218 	 */
9219 	return strcmp(sec_name, sec_def->sec) == 0;
9220 }
9221 
find_sec_def(const char * sec_name)9222 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9223 {
9224 	const struct bpf_sec_def *sec_def;
9225 	int i, n;
9226 	bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME, allow_sloppy;
9227 
9228 	n = custom_sec_def_cnt;
9229 	for (i = 0; i < n; i++) {
9230 		sec_def = &custom_sec_defs[i];
9231 		if (sec_def_matches(sec_def, sec_name, false))
9232 			return sec_def;
9233 	}
9234 
9235 	n = ARRAY_SIZE(section_defs);
9236 	for (i = 0; i < n; i++) {
9237 		sec_def = &section_defs[i];
9238 		allow_sloppy = (sec_def->cookie & SEC_SLOPPY_PFX) && !strict;
9239 		if (sec_def_matches(sec_def, sec_name, allow_sloppy))
9240 			return sec_def;
9241 	}
9242 
9243 	if (has_custom_fallback_def)
9244 		return &custom_fallback_def;
9245 
9246 	return NULL;
9247 }
9248 
9249 #define MAX_TYPE_NAME_SIZE 32
9250 
libbpf_get_type_names(bool attach_type)9251 static char *libbpf_get_type_names(bool attach_type)
9252 {
9253 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9254 	char *buf;
9255 
9256 	buf = malloc(len);
9257 	if (!buf)
9258 		return NULL;
9259 
9260 	buf[0] = '\0';
9261 	/* Forge string buf with all available names */
9262 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9263 		const struct bpf_sec_def *sec_def = &section_defs[i];
9264 
9265 		if (attach_type) {
9266 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9267 				continue;
9268 
9269 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9270 				continue;
9271 		}
9272 
9273 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9274 			free(buf);
9275 			return NULL;
9276 		}
9277 		strcat(buf, " ");
9278 		strcat(buf, section_defs[i].sec);
9279 	}
9280 
9281 	return buf;
9282 }
9283 
libbpf_prog_type_by_name(const char * name,enum bpf_prog_type * prog_type,enum bpf_attach_type * expected_attach_type)9284 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9285 			     enum bpf_attach_type *expected_attach_type)
9286 {
9287 	const struct bpf_sec_def *sec_def;
9288 	char *type_names;
9289 
9290 	if (!name)
9291 		return libbpf_err(-EINVAL);
9292 
9293 	sec_def = find_sec_def(name);
9294 	if (sec_def) {
9295 		*prog_type = sec_def->prog_type;
9296 		*expected_attach_type = sec_def->expected_attach_type;
9297 		return 0;
9298 	}
9299 
9300 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9301 	type_names = libbpf_get_type_names(false);
9302 	if (type_names != NULL) {
9303 		pr_debug("supported section(type) names are:%s\n", type_names);
9304 		free(type_names);
9305 	}
9306 
9307 	return libbpf_err(-ESRCH);
9308 }
9309 
find_struct_ops_map_by_offset(struct bpf_object * obj,size_t offset)9310 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9311 						     size_t offset)
9312 {
9313 	struct bpf_map *map;
9314 	size_t i;
9315 
9316 	for (i = 0; i < obj->nr_maps; i++) {
9317 		map = &obj->maps[i];
9318 		if (!bpf_map__is_struct_ops(map))
9319 			continue;
9320 		if (map->sec_offset <= offset &&
9321 		    offset - map->sec_offset < map->def.value_size)
9322 			return map;
9323 	}
9324 
9325 	return NULL;
9326 }
9327 
9328 /* 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)9329 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9330 					    Elf64_Shdr *shdr, Elf_Data *data)
9331 {
9332 	const struct btf_member *member;
9333 	struct bpf_struct_ops *st_ops;
9334 	struct bpf_program *prog;
9335 	unsigned int shdr_idx;
9336 	const struct btf *btf;
9337 	struct bpf_map *map;
9338 	unsigned int moff, insn_idx;
9339 	const char *name;
9340 	__u32 member_idx;
9341 	Elf64_Sym *sym;
9342 	Elf64_Rel *rel;
9343 	int i, nrels;
9344 
9345 	btf = obj->btf;
9346 	nrels = shdr->sh_size / shdr->sh_entsize;
9347 	for (i = 0; i < nrels; i++) {
9348 		rel = elf_rel_by_idx(data, i);
9349 		if (!rel) {
9350 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9351 			return -LIBBPF_ERRNO__FORMAT;
9352 		}
9353 
9354 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9355 		if (!sym) {
9356 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9357 				(size_t)ELF64_R_SYM(rel->r_info));
9358 			return -LIBBPF_ERRNO__FORMAT;
9359 		}
9360 
9361 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9362 		map = find_struct_ops_map_by_offset(obj, rel->r_offset);
9363 		if (!map) {
9364 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9365 				(size_t)rel->r_offset);
9366 			return -EINVAL;
9367 		}
9368 
9369 		moff = rel->r_offset - map->sec_offset;
9370 		shdr_idx = sym->st_shndx;
9371 		st_ops = map->st_ops;
9372 		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",
9373 			 map->name,
9374 			 (long long)(rel->r_info >> 32),
9375 			 (long long)sym->st_value,
9376 			 shdr_idx, (size_t)rel->r_offset,
9377 			 map->sec_offset, sym->st_name, name);
9378 
9379 		if (shdr_idx >= SHN_LORESERVE) {
9380 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9381 				map->name, (size_t)rel->r_offset, shdr_idx);
9382 			return -LIBBPF_ERRNO__RELOC;
9383 		}
9384 		if (sym->st_value % BPF_INSN_SZ) {
9385 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9386 				map->name, (unsigned long long)sym->st_value);
9387 			return -LIBBPF_ERRNO__FORMAT;
9388 		}
9389 		insn_idx = sym->st_value / BPF_INSN_SZ;
9390 
9391 		member = find_member_by_offset(st_ops->type, moff * 8);
9392 		if (!member) {
9393 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9394 				map->name, moff);
9395 			return -EINVAL;
9396 		}
9397 		member_idx = member - btf_members(st_ops->type);
9398 		name = btf__name_by_offset(btf, member->name_off);
9399 
9400 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9401 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9402 				map->name, name);
9403 			return -EINVAL;
9404 		}
9405 
9406 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9407 		if (!prog) {
9408 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9409 				map->name, shdr_idx, name);
9410 			return -EINVAL;
9411 		}
9412 
9413 		/* prevent the use of BPF prog with invalid type */
9414 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9415 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9416 				map->name, prog->name);
9417 			return -EINVAL;
9418 		}
9419 
9420 		/* if we haven't yet processed this BPF program, record proper
9421 		 * attach_btf_id and member_idx
9422 		 */
9423 		if (!prog->attach_btf_id) {
9424 			prog->attach_btf_id = st_ops->type_id;
9425 			prog->expected_attach_type = member_idx;
9426 		}
9427 
9428 		/* struct_ops BPF prog can be re-used between multiple
9429 		 * .struct_ops as long as it's the same struct_ops struct
9430 		 * definition and the same function pointer field
9431 		 */
9432 		if (prog->attach_btf_id != st_ops->type_id ||
9433 		    prog->expected_attach_type != member_idx) {
9434 			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",
9435 				map->name, prog->name, prog->sec_name, prog->type,
9436 				prog->attach_btf_id, prog->expected_attach_type, name);
9437 			return -EINVAL;
9438 		}
9439 
9440 		st_ops->progs[member_idx] = prog;
9441 	}
9442 
9443 	return 0;
9444 }
9445 
9446 #define BTF_TRACE_PREFIX "btf_trace_"
9447 #define BTF_LSM_PREFIX "bpf_lsm_"
9448 #define BTF_ITER_PREFIX "bpf_iter_"
9449 #define BTF_MAX_NAME_SIZE 128
9450 
btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,const char ** prefix,int * kind)9451 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9452 				const char **prefix, int *kind)
9453 {
9454 	switch (attach_type) {
9455 	case BPF_TRACE_RAW_TP:
9456 		*prefix = BTF_TRACE_PREFIX;
9457 		*kind = BTF_KIND_TYPEDEF;
9458 		break;
9459 	case BPF_LSM_MAC:
9460 		*prefix = BTF_LSM_PREFIX;
9461 		*kind = BTF_KIND_FUNC;
9462 		break;
9463 	case BPF_TRACE_ITER:
9464 		*prefix = BTF_ITER_PREFIX;
9465 		*kind = BTF_KIND_FUNC;
9466 		break;
9467 	default:
9468 		*prefix = "";
9469 		*kind = BTF_KIND_FUNC;
9470 	}
9471 }
9472 
find_btf_by_prefix_kind(const struct btf * btf,const char * prefix,const char * name,__u32 kind)9473 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9474 				   const char *name, __u32 kind)
9475 {
9476 	char btf_type_name[BTF_MAX_NAME_SIZE];
9477 	int ret;
9478 
9479 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9480 		       "%s%s", prefix, name);
9481 	/* snprintf returns the number of characters written excluding the
9482 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9483 	 * indicates truncation.
9484 	 */
9485 	if (ret < 0 || ret >= sizeof(btf_type_name))
9486 		return -ENAMETOOLONG;
9487 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9488 }
9489 
find_attach_btf_id(struct btf * btf,const char * name,enum bpf_attach_type attach_type)9490 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9491 				     enum bpf_attach_type attach_type)
9492 {
9493 	const char *prefix;
9494 	int kind;
9495 
9496 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9497 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9498 }
9499 
libbpf_find_vmlinux_btf_id(const char * name,enum bpf_attach_type attach_type)9500 int libbpf_find_vmlinux_btf_id(const char *name,
9501 			       enum bpf_attach_type attach_type)
9502 {
9503 	struct btf *btf;
9504 	int err;
9505 
9506 	btf = btf__load_vmlinux_btf();
9507 	err = libbpf_get_error(btf);
9508 	if (err) {
9509 		pr_warn("vmlinux BTF is not found\n");
9510 		return libbpf_err(err);
9511 	}
9512 
9513 	err = find_attach_btf_id(btf, name, attach_type);
9514 	if (err <= 0)
9515 		pr_warn("%s is not found in vmlinux BTF\n", name);
9516 
9517 	btf__free(btf);
9518 	return libbpf_err(err);
9519 }
9520 
libbpf_find_prog_btf_id(const char * name,__u32 attach_prog_fd)9521 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9522 {
9523 	struct bpf_prog_info info = {};
9524 	__u32 info_len = sizeof(info);
9525 	struct btf *btf;
9526 	int err;
9527 
9528 	err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9529 	if (err) {
9530 		pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9531 			attach_prog_fd, err);
9532 		return err;
9533 	}
9534 
9535 	err = -EINVAL;
9536 	if (!info.btf_id) {
9537 		pr_warn("The target program doesn't have BTF\n");
9538 		goto out;
9539 	}
9540 	btf = btf__load_from_kernel_by_id(info.btf_id);
9541 	err = libbpf_get_error(btf);
9542 	if (err) {
9543 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9544 		goto out;
9545 	}
9546 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9547 	btf__free(btf);
9548 	if (err <= 0) {
9549 		pr_warn("%s is not found in prog's BTF\n", name);
9550 		goto out;
9551 	}
9552 out:
9553 	return err;
9554 }
9555 
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)9556 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9557 			      enum bpf_attach_type attach_type,
9558 			      int *btf_obj_fd, int *btf_type_id)
9559 {
9560 	int ret, i;
9561 
9562 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9563 	if (ret > 0) {
9564 		*btf_obj_fd = 0; /* vmlinux BTF */
9565 		*btf_type_id = ret;
9566 		return 0;
9567 	}
9568 	if (ret != -ENOENT)
9569 		return ret;
9570 
9571 	ret = load_module_btfs(obj);
9572 	if (ret)
9573 		return ret;
9574 
9575 	for (i = 0; i < obj->btf_module_cnt; i++) {
9576 		const struct module_btf *mod = &obj->btf_modules[i];
9577 
9578 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9579 		if (ret > 0) {
9580 			*btf_obj_fd = mod->fd;
9581 			*btf_type_id = ret;
9582 			return 0;
9583 		}
9584 		if (ret == -ENOENT)
9585 			continue;
9586 
9587 		return ret;
9588 	}
9589 
9590 	return -ESRCH;
9591 }
9592 
libbpf_find_attach_btf_id(struct bpf_program * prog,const char * attach_name,int * btf_obj_fd,int * btf_type_id)9593 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9594 				     int *btf_obj_fd, int *btf_type_id)
9595 {
9596 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9597 	__u32 attach_prog_fd = prog->attach_prog_fd;
9598 	int err = 0;
9599 
9600 	/* BPF program's BTF ID */
9601 	if (attach_prog_fd) {
9602 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9603 		if (err < 0) {
9604 			pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9605 				 attach_prog_fd, attach_name, err);
9606 			return err;
9607 		}
9608 		*btf_obj_fd = 0;
9609 		*btf_type_id = err;
9610 		return 0;
9611 	}
9612 
9613 	/* kernel/module BTF ID */
9614 	if (prog->obj->gen_loader) {
9615 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9616 		*btf_obj_fd = 0;
9617 		*btf_type_id = 1;
9618 	} else {
9619 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9620 	}
9621 	if (err) {
9622 		pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9623 		return err;
9624 	}
9625 	return 0;
9626 }
9627 
libbpf_attach_type_by_name(const char * name,enum bpf_attach_type * attach_type)9628 int libbpf_attach_type_by_name(const char *name,
9629 			       enum bpf_attach_type *attach_type)
9630 {
9631 	char *type_names;
9632 	const struct bpf_sec_def *sec_def;
9633 
9634 	if (!name)
9635 		return libbpf_err(-EINVAL);
9636 
9637 	sec_def = find_sec_def(name);
9638 	if (!sec_def) {
9639 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9640 		type_names = libbpf_get_type_names(true);
9641 		if (type_names != NULL) {
9642 			pr_debug("attachable section(type) names are:%s\n", type_names);
9643 			free(type_names);
9644 		}
9645 
9646 		return libbpf_err(-EINVAL);
9647 	}
9648 
9649 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9650 		return libbpf_err(-EINVAL);
9651 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9652 		return libbpf_err(-EINVAL);
9653 
9654 	*attach_type = sec_def->expected_attach_type;
9655 	return 0;
9656 }
9657 
bpf_map__fd(const struct bpf_map * map)9658 int bpf_map__fd(const struct bpf_map *map)
9659 {
9660 	return map ? map->fd : libbpf_err(-EINVAL);
9661 }
9662 
bpf_map__def(const struct bpf_map * map)9663 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9664 {
9665 	return map ? &map->def : libbpf_err_ptr(-EINVAL);
9666 }
9667 
map_uses_real_name(const struct bpf_map * map)9668 static bool map_uses_real_name(const struct bpf_map *map)
9669 {
9670 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9671 	 * their user-visible name differs from kernel-visible name. Users see
9672 	 * such map's corresponding ELF section name as a map name.
9673 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9674 	 * maps to know which name has to be returned to the user.
9675 	 */
9676 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9677 		return true;
9678 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9679 		return true;
9680 	return false;
9681 }
9682 
bpf_map__name(const struct bpf_map * map)9683 const char *bpf_map__name(const struct bpf_map *map)
9684 {
9685 	if (!map)
9686 		return NULL;
9687 
9688 	if (map_uses_real_name(map))
9689 		return map->real_name;
9690 
9691 	return map->name;
9692 }
9693 
bpf_map__type(const struct bpf_map * map)9694 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9695 {
9696 	return map->def.type;
9697 }
9698 
bpf_map__set_type(struct bpf_map * map,enum bpf_map_type type)9699 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9700 {
9701 	if (map->fd >= 0)
9702 		return libbpf_err(-EBUSY);
9703 	map->def.type = type;
9704 	return 0;
9705 }
9706 
bpf_map__map_flags(const struct bpf_map * map)9707 __u32 bpf_map__map_flags(const struct bpf_map *map)
9708 {
9709 	return map->def.map_flags;
9710 }
9711 
bpf_map__set_map_flags(struct bpf_map * map,__u32 flags)9712 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9713 {
9714 	if (map->fd >= 0)
9715 		return libbpf_err(-EBUSY);
9716 	map->def.map_flags = flags;
9717 	return 0;
9718 }
9719 
bpf_map__map_extra(const struct bpf_map * map)9720 __u64 bpf_map__map_extra(const struct bpf_map *map)
9721 {
9722 	return map->map_extra;
9723 }
9724 
bpf_map__set_map_extra(struct bpf_map * map,__u64 map_extra)9725 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9726 {
9727 	if (map->fd >= 0)
9728 		return libbpf_err(-EBUSY);
9729 	map->map_extra = map_extra;
9730 	return 0;
9731 }
9732 
bpf_map__numa_node(const struct bpf_map * map)9733 __u32 bpf_map__numa_node(const struct bpf_map *map)
9734 {
9735 	return map->numa_node;
9736 }
9737 
bpf_map__set_numa_node(struct bpf_map * map,__u32 numa_node)9738 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9739 {
9740 	if (map->fd >= 0)
9741 		return libbpf_err(-EBUSY);
9742 	map->numa_node = numa_node;
9743 	return 0;
9744 }
9745 
bpf_map__key_size(const struct bpf_map * map)9746 __u32 bpf_map__key_size(const struct bpf_map *map)
9747 {
9748 	return map->def.key_size;
9749 }
9750 
bpf_map__set_key_size(struct bpf_map * map,__u32 size)9751 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9752 {
9753 	if (map->fd >= 0)
9754 		return libbpf_err(-EBUSY);
9755 	map->def.key_size = size;
9756 	return 0;
9757 }
9758 
bpf_map__value_size(const struct bpf_map * map)9759 __u32 bpf_map__value_size(const struct bpf_map *map)
9760 {
9761 	return map->def.value_size;
9762 }
9763 
bpf_map__set_value_size(struct bpf_map * map,__u32 size)9764 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9765 {
9766 	if (map->fd >= 0)
9767 		return libbpf_err(-EBUSY);
9768 	map->def.value_size = size;
9769 	return 0;
9770 }
9771 
bpf_map__btf_key_type_id(const struct bpf_map * map)9772 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9773 {
9774 	return map ? map->btf_key_type_id : 0;
9775 }
9776 
bpf_map__btf_value_type_id(const struct bpf_map * map)9777 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9778 {
9779 	return map ? map->btf_value_type_id : 0;
9780 }
9781 
bpf_map__set_priv(struct bpf_map * map,void * priv,bpf_map_clear_priv_t clear_priv)9782 int bpf_map__set_priv(struct bpf_map *map, void *priv,
9783 		     bpf_map_clear_priv_t clear_priv)
9784 {
9785 	if (!map)
9786 		return libbpf_err(-EINVAL);
9787 
9788 	if (map->priv) {
9789 		if (map->clear_priv)
9790 			map->clear_priv(map, map->priv);
9791 	}
9792 
9793 	map->priv = priv;
9794 	map->clear_priv = clear_priv;
9795 	return 0;
9796 }
9797 
bpf_map__priv(const struct bpf_map * map)9798 void *bpf_map__priv(const struct bpf_map *map)
9799 {
9800 	return map ? map->priv : libbpf_err_ptr(-EINVAL);
9801 }
9802 
bpf_map__set_initial_value(struct bpf_map * map,const void * data,size_t size)9803 int bpf_map__set_initial_value(struct bpf_map *map,
9804 			       const void *data, size_t size)
9805 {
9806 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9807 	    size != map->def.value_size || map->fd >= 0)
9808 		return libbpf_err(-EINVAL);
9809 
9810 	memcpy(map->mmaped, data, size);
9811 	return 0;
9812 }
9813 
bpf_map__initial_value(struct bpf_map * map,size_t * psize)9814 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9815 {
9816 	if (!map->mmaped)
9817 		return NULL;
9818 	*psize = map->def.value_size;
9819 	return map->mmaped;
9820 }
9821 
bpf_map__is_offload_neutral(const struct bpf_map * map)9822 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
9823 {
9824 	return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9825 }
9826 
bpf_map__is_internal(const struct bpf_map * map)9827 bool bpf_map__is_internal(const struct bpf_map *map)
9828 {
9829 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9830 }
9831 
bpf_map__ifindex(const struct bpf_map * map)9832 __u32 bpf_map__ifindex(const struct bpf_map *map)
9833 {
9834 	return map->map_ifindex;
9835 }
9836 
bpf_map__set_ifindex(struct bpf_map * map,__u32 ifindex)9837 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9838 {
9839 	if (map->fd >= 0)
9840 		return libbpf_err(-EBUSY);
9841 	map->map_ifindex = ifindex;
9842 	return 0;
9843 }
9844 
bpf_map__set_inner_map_fd(struct bpf_map * map,int fd)9845 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9846 {
9847 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9848 		pr_warn("error: unsupported map type\n");
9849 		return libbpf_err(-EINVAL);
9850 	}
9851 	if (map->inner_map_fd != -1) {
9852 		pr_warn("error: inner_map_fd already specified\n");
9853 		return libbpf_err(-EINVAL);
9854 	}
9855 	if (map->inner_map) {
9856 		bpf_map__destroy(map->inner_map);
9857 		zfree(&map->inner_map);
9858 	}
9859 	map->inner_map_fd = fd;
9860 	return 0;
9861 }
9862 
9863 static struct bpf_map *
__bpf_map__iter(const struct bpf_map * m,const struct bpf_object * obj,int i)9864 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9865 {
9866 	ssize_t idx;
9867 	struct bpf_map *s, *e;
9868 
9869 	if (!obj || !obj->maps)
9870 		return errno = EINVAL, NULL;
9871 
9872 	s = obj->maps;
9873 	e = obj->maps + obj->nr_maps;
9874 
9875 	if ((m < s) || (m >= e)) {
9876 		pr_warn("error in %s: map handler doesn't belong to object\n",
9877 			 __func__);
9878 		return errno = EINVAL, NULL;
9879 	}
9880 
9881 	idx = (m - obj->maps) + i;
9882 	if (idx >= obj->nr_maps || idx < 0)
9883 		return NULL;
9884 	return &obj->maps[idx];
9885 }
9886 
9887 struct bpf_map *
bpf_map__next(const struct bpf_map * prev,const struct bpf_object * obj)9888 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
9889 {
9890 	return bpf_object__next_map(obj, prev);
9891 }
9892 
9893 struct bpf_map *
bpf_object__next_map(const struct bpf_object * obj,const struct bpf_map * prev)9894 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9895 {
9896 	if (prev == NULL)
9897 		return obj->maps;
9898 
9899 	return __bpf_map__iter(prev, obj, 1);
9900 }
9901 
9902 struct bpf_map *
bpf_map__prev(const struct bpf_map * next,const struct bpf_object * obj)9903 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
9904 {
9905 	return bpf_object__prev_map(obj, next);
9906 }
9907 
9908 struct bpf_map *
bpf_object__prev_map(const struct bpf_object * obj,const struct bpf_map * next)9909 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9910 {
9911 	if (next == NULL) {
9912 		if (!obj->nr_maps)
9913 			return NULL;
9914 		return obj->maps + obj->nr_maps - 1;
9915 	}
9916 
9917 	return __bpf_map__iter(next, obj, -1);
9918 }
9919 
9920 struct bpf_map *
bpf_object__find_map_by_name(const struct bpf_object * obj,const char * name)9921 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9922 {
9923 	struct bpf_map *pos;
9924 
9925 	bpf_object__for_each_map(pos, obj) {
9926 		/* if it's a special internal map name (which always starts
9927 		 * with dot) then check if that special name matches the
9928 		 * real map name (ELF section name)
9929 		 */
9930 		if (name[0] == '.') {
9931 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9932 				return pos;
9933 			continue;
9934 		}
9935 		/* otherwise map name has to be an exact match */
9936 		if (map_uses_real_name(pos)) {
9937 			if (strcmp(pos->real_name, name) == 0)
9938 				return pos;
9939 			continue;
9940 		}
9941 		if (strcmp(pos->name, name) == 0)
9942 			return pos;
9943 	}
9944 	return errno = ENOENT, NULL;
9945 }
9946 
9947 int
bpf_object__find_map_fd_by_name(const struct bpf_object * obj,const char * name)9948 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9949 {
9950 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9951 }
9952 
9953 struct bpf_map *
bpf_object__find_map_by_offset(struct bpf_object * obj,size_t offset)9954 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9955 {
9956 	return libbpf_err_ptr(-ENOTSUP);
9957 }
9958 
validate_map_op(const struct bpf_map * map,size_t key_sz,size_t value_sz,bool check_value_sz)9959 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9960 			   size_t value_sz, bool check_value_sz)
9961 {
9962 	if (map->fd <= 0)
9963 		return -ENOENT;
9964 
9965 	if (map->def.key_size != key_sz) {
9966 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9967 			map->name, key_sz, map->def.key_size);
9968 		return -EINVAL;
9969 	}
9970 
9971 	if (!check_value_sz)
9972 		return 0;
9973 
9974 	switch (map->def.type) {
9975 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9976 	case BPF_MAP_TYPE_PERCPU_HASH:
9977 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9978 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9979 		int num_cpu = libbpf_num_possible_cpus();
9980 		size_t elem_sz = roundup(map->def.value_size, 8);
9981 
9982 		if (value_sz != num_cpu * elem_sz) {
9983 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9984 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9985 			return -EINVAL;
9986 		}
9987 		break;
9988 	}
9989 	default:
9990 		if (map->def.value_size != value_sz) {
9991 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9992 				map->name, value_sz, map->def.value_size);
9993 			return -EINVAL;
9994 		}
9995 		break;
9996 	}
9997 	return 0;
9998 }
9999 
bpf_map__lookup_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)10000 int bpf_map__lookup_elem(const struct bpf_map *map,
10001 			 const void *key, size_t key_sz,
10002 			 void *value, size_t value_sz, __u64 flags)
10003 {
10004 	int err;
10005 
10006 	err = validate_map_op(map, key_sz, value_sz, true);
10007 	if (err)
10008 		return libbpf_err(err);
10009 
10010 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10011 }
10012 
bpf_map__update_elem(const struct bpf_map * map,const void * key,size_t key_sz,const void * value,size_t value_sz,__u64 flags)10013 int bpf_map__update_elem(const struct bpf_map *map,
10014 			 const void *key, size_t key_sz,
10015 			 const void *value, size_t value_sz, __u64 flags)
10016 {
10017 	int err;
10018 
10019 	err = validate_map_op(map, key_sz, value_sz, true);
10020 	if (err)
10021 		return libbpf_err(err);
10022 
10023 	return bpf_map_update_elem(map->fd, key, value, flags);
10024 }
10025 
bpf_map__delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,__u64 flags)10026 int bpf_map__delete_elem(const struct bpf_map *map,
10027 			 const void *key, size_t key_sz, __u64 flags)
10028 {
10029 	int err;
10030 
10031 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10032 	if (err)
10033 		return libbpf_err(err);
10034 
10035 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10036 }
10037 
bpf_map__lookup_and_delete_elem(const struct bpf_map * map,const void * key,size_t key_sz,void * value,size_t value_sz,__u64 flags)10038 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10039 				    const void *key, size_t key_sz,
10040 				    void *value, size_t value_sz, __u64 flags)
10041 {
10042 	int err;
10043 
10044 	err = validate_map_op(map, key_sz, value_sz, true);
10045 	if (err)
10046 		return libbpf_err(err);
10047 
10048 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10049 }
10050 
bpf_map__get_next_key(const struct bpf_map * map,const void * cur_key,void * next_key,size_t key_sz)10051 int bpf_map__get_next_key(const struct bpf_map *map,
10052 			  const void *cur_key, void *next_key, size_t key_sz)
10053 {
10054 	int err;
10055 
10056 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10057 	if (err)
10058 		return libbpf_err(err);
10059 
10060 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10061 }
10062 
libbpf_get_error(const void * ptr)10063 long libbpf_get_error(const void *ptr)
10064 {
10065 	if (!IS_ERR_OR_NULL(ptr))
10066 		return 0;
10067 
10068 	if (IS_ERR(ptr))
10069 		errno = -PTR_ERR(ptr);
10070 
10071 	/* If ptr == NULL, then errno should be already set by the failing
10072 	 * API, because libbpf never returns NULL on success and it now always
10073 	 * sets errno on error. So no extra errno handling for ptr == NULL
10074 	 * case.
10075 	 */
10076 	return -errno;
10077 }
10078 
10079 __attribute__((alias("bpf_prog_load_xattr2")))
10080 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
10081 			struct bpf_object **pobj, int *prog_fd);
10082 
bpf_prog_load_xattr2(const struct bpf_prog_load_attr * attr,struct bpf_object ** pobj,int * prog_fd)10083 static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
10084 				struct bpf_object **pobj, int *prog_fd)
10085 {
10086 	struct bpf_object_open_attr open_attr = {};
10087 	struct bpf_program *prog, *first_prog = NULL;
10088 	struct bpf_object *obj;
10089 	struct bpf_map *map;
10090 	int err;
10091 
10092 	if (!attr)
10093 		return libbpf_err(-EINVAL);
10094 	if (!attr->file)
10095 		return libbpf_err(-EINVAL);
10096 
10097 	open_attr.file = attr->file;
10098 	open_attr.prog_type = attr->prog_type;
10099 
10100 	obj = __bpf_object__open_xattr(&open_attr, 0);
10101 	err = libbpf_get_error(obj);
10102 	if (err)
10103 		return libbpf_err(-ENOENT);
10104 
10105 	bpf_object__for_each_program(prog, obj) {
10106 		enum bpf_attach_type attach_type = attr->expected_attach_type;
10107 		/*
10108 		 * to preserve backwards compatibility, bpf_prog_load treats
10109 		 * attr->prog_type, if specified, as an override to whatever
10110 		 * bpf_object__open guessed
10111 		 */
10112 		if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
10113 			prog->type = attr->prog_type;
10114 			prog->expected_attach_type = attach_type;
10115 		}
10116 		if (bpf_program__type(prog) == BPF_PROG_TYPE_UNSPEC) {
10117 			/*
10118 			 * we haven't guessed from section name and user
10119 			 * didn't provide a fallback type, too bad...
10120 			 */
10121 			bpf_object__close(obj);
10122 			return libbpf_err(-EINVAL);
10123 		}
10124 
10125 		prog->prog_ifindex = attr->ifindex;
10126 		prog->log_level = attr->log_level;
10127 		prog->prog_flags |= attr->prog_flags;
10128 		if (!first_prog)
10129 			first_prog = prog;
10130 	}
10131 
10132 	bpf_object__for_each_map(map, obj) {
10133 		if (map->def.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10134 			map->map_ifindex = attr->ifindex;
10135 	}
10136 
10137 	if (!first_prog) {
10138 		pr_warn("object file doesn't contain bpf program\n");
10139 		bpf_object__close(obj);
10140 		return libbpf_err(-ENOENT);
10141 	}
10142 
10143 	err = bpf_object__load(obj);
10144 	if (err) {
10145 		bpf_object__close(obj);
10146 		return libbpf_err(err);
10147 	}
10148 
10149 	*pobj = obj;
10150 	*prog_fd = bpf_program__fd(first_prog);
10151 	return 0;
10152 }
10153 
10154 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)10155 int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
10156 			     struct bpf_object **pobj, int *prog_fd)
10157 {
10158 	struct bpf_prog_load_attr attr;
10159 
10160 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
10161 	attr.file = file;
10162 	attr.prog_type = type;
10163 	attr.expected_attach_type = 0;
10164 
10165 	return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
10166 }
10167 
10168 /* Replace link's underlying BPF program with the new one */
bpf_link__update_program(struct bpf_link * link,struct bpf_program * prog)10169 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10170 {
10171 	int ret;
10172 
10173 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10174 	return libbpf_err_errno(ret);
10175 }
10176 
10177 /* Release "ownership" of underlying BPF resource (typically, BPF program
10178  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10179  * link, when destructed through bpf_link__destroy() call won't attempt to
10180  * detach/unregisted that BPF resource. This is useful in situations where,
10181  * say, attached BPF program has to outlive userspace program that attached it
10182  * in the system. Depending on type of BPF program, though, there might be
10183  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10184  * exit of userspace program doesn't trigger automatic detachment and clean up
10185  * inside the kernel.
10186  */
bpf_link__disconnect(struct bpf_link * link)10187 void bpf_link__disconnect(struct bpf_link *link)
10188 {
10189 	link->disconnected = true;
10190 }
10191 
bpf_link__destroy(struct bpf_link * link)10192 int bpf_link__destroy(struct bpf_link *link)
10193 {
10194 	int err = 0;
10195 
10196 	if (IS_ERR_OR_NULL(link))
10197 		return 0;
10198 
10199 	if (!link->disconnected && link->detach)
10200 		err = link->detach(link);
10201 	if (link->pin_path)
10202 		free(link->pin_path);
10203 	if (link->dealloc)
10204 		link->dealloc(link);
10205 	else
10206 		free(link);
10207 
10208 	return libbpf_err(err);
10209 }
10210 
bpf_link__fd(const struct bpf_link * link)10211 int bpf_link__fd(const struct bpf_link *link)
10212 {
10213 	return link->fd;
10214 }
10215 
bpf_link__pin_path(const struct bpf_link * link)10216 const char *bpf_link__pin_path(const struct bpf_link *link)
10217 {
10218 	return link->pin_path;
10219 }
10220 
bpf_link__detach_fd(struct bpf_link * link)10221 static int bpf_link__detach_fd(struct bpf_link *link)
10222 {
10223 	return libbpf_err_errno(close(link->fd));
10224 }
10225 
bpf_link__open(const char * path)10226 struct bpf_link *bpf_link__open(const char *path)
10227 {
10228 	struct bpf_link *link;
10229 	int fd;
10230 
10231 	fd = bpf_obj_get(path);
10232 	if (fd < 0) {
10233 		fd = -errno;
10234 		pr_warn("failed to open link at %s: %d\n", path, fd);
10235 		return libbpf_err_ptr(fd);
10236 	}
10237 
10238 	link = calloc(1, sizeof(*link));
10239 	if (!link) {
10240 		close(fd);
10241 		return libbpf_err_ptr(-ENOMEM);
10242 	}
10243 	link->detach = &bpf_link__detach_fd;
10244 	link->fd = fd;
10245 
10246 	link->pin_path = strdup(path);
10247 	if (!link->pin_path) {
10248 		bpf_link__destroy(link);
10249 		return libbpf_err_ptr(-ENOMEM);
10250 	}
10251 
10252 	return link;
10253 }
10254 
bpf_link__detach(struct bpf_link * link)10255 int bpf_link__detach(struct bpf_link *link)
10256 {
10257 	return bpf_link_detach(link->fd) ? -errno : 0;
10258 }
10259 
bpf_link__pin(struct bpf_link * link,const char * path)10260 int bpf_link__pin(struct bpf_link *link, const char *path)
10261 {
10262 	int err;
10263 
10264 	if (link->pin_path)
10265 		return libbpf_err(-EBUSY);
10266 	err = make_parent_dir(path);
10267 	if (err)
10268 		return libbpf_err(err);
10269 	err = check_path(path);
10270 	if (err)
10271 		return libbpf_err(err);
10272 
10273 	link->pin_path = strdup(path);
10274 	if (!link->pin_path)
10275 		return libbpf_err(-ENOMEM);
10276 
10277 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10278 		err = -errno;
10279 		zfree(&link->pin_path);
10280 		return libbpf_err(err);
10281 	}
10282 
10283 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10284 	return 0;
10285 }
10286 
bpf_link__unpin(struct bpf_link * link)10287 int bpf_link__unpin(struct bpf_link *link)
10288 {
10289 	int err;
10290 
10291 	if (!link->pin_path)
10292 		return libbpf_err(-EINVAL);
10293 
10294 	err = unlink(link->pin_path);
10295 	if (err != 0)
10296 		return -errno;
10297 
10298 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10299 	zfree(&link->pin_path);
10300 	return 0;
10301 }
10302 
10303 struct bpf_link_perf {
10304 	struct bpf_link link;
10305 	int perf_event_fd;
10306 	/* legacy kprobe support: keep track of probe identifier and type */
10307 	char *legacy_probe_name;
10308 	bool legacy_is_kprobe;
10309 	bool legacy_is_retprobe;
10310 };
10311 
10312 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10313 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10314 
bpf_link_perf_detach(struct bpf_link * link)10315 static int bpf_link_perf_detach(struct bpf_link *link)
10316 {
10317 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10318 	int err = 0;
10319 
10320 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10321 		err = -errno;
10322 
10323 	if (perf_link->perf_event_fd != link->fd)
10324 		close(perf_link->perf_event_fd);
10325 	close(link->fd);
10326 
10327 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10328 	if (perf_link->legacy_probe_name) {
10329 		if (perf_link->legacy_is_kprobe) {
10330 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10331 							 perf_link->legacy_is_retprobe);
10332 		} else {
10333 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10334 							 perf_link->legacy_is_retprobe);
10335 		}
10336 	}
10337 
10338 	return err;
10339 }
10340 
bpf_link_perf_dealloc(struct bpf_link * link)10341 static void bpf_link_perf_dealloc(struct bpf_link *link)
10342 {
10343 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10344 
10345 	free(perf_link->legacy_probe_name);
10346 	free(perf_link);
10347 }
10348 
bpf_program__attach_perf_event_opts(const struct bpf_program * prog,int pfd,const struct bpf_perf_event_opts * opts)10349 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10350 						     const struct bpf_perf_event_opts *opts)
10351 {
10352 	char errmsg[STRERR_BUFSIZE];
10353 	struct bpf_link_perf *link;
10354 	int prog_fd, link_fd = -1, err;
10355 
10356 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10357 		return libbpf_err_ptr(-EINVAL);
10358 
10359 	if (pfd < 0) {
10360 		pr_warn("prog '%s': invalid perf event FD %d\n",
10361 			prog->name, pfd);
10362 		return libbpf_err_ptr(-EINVAL);
10363 	}
10364 	prog_fd = bpf_program__fd(prog);
10365 	if (prog_fd < 0) {
10366 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10367 			prog->name);
10368 		return libbpf_err_ptr(-EINVAL);
10369 	}
10370 
10371 	link = calloc(1, sizeof(*link));
10372 	if (!link)
10373 		return libbpf_err_ptr(-ENOMEM);
10374 	link->link.detach = &bpf_link_perf_detach;
10375 	link->link.dealloc = &bpf_link_perf_dealloc;
10376 	link->perf_event_fd = pfd;
10377 
10378 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
10379 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10380 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10381 
10382 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10383 		if (link_fd < 0) {
10384 			err = -errno;
10385 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10386 				prog->name, pfd,
10387 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10388 			goto err_out;
10389 		}
10390 		link->link.fd = link_fd;
10391 	} else {
10392 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10393 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10394 			err = -EOPNOTSUPP;
10395 			goto err_out;
10396 		}
10397 
10398 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10399 			err = -errno;
10400 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10401 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10402 			if (err == -EPROTO)
10403 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10404 					prog->name, pfd);
10405 			goto err_out;
10406 		}
10407 		link->link.fd = pfd;
10408 	}
10409 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10410 		err = -errno;
10411 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10412 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10413 		goto err_out;
10414 	}
10415 
10416 	return &link->link;
10417 err_out:
10418 	if (link_fd >= 0)
10419 		close(link_fd);
10420 	free(link);
10421 	return libbpf_err_ptr(err);
10422 }
10423 
bpf_program__attach_perf_event(const struct bpf_program * prog,int pfd)10424 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10425 {
10426 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10427 }
10428 
10429 /*
10430  * this function is expected to parse integer in the range of [0, 2^31-1] from
10431  * given file using scanf format string fmt. If actual parsed value is
10432  * negative, the result might be indistinguishable from error
10433  */
parse_uint_from_file(const char * file,const char * fmt)10434 static int parse_uint_from_file(const char *file, const char *fmt)
10435 {
10436 	char buf[STRERR_BUFSIZE];
10437 	int err, ret;
10438 	FILE *f;
10439 
10440 	f = fopen(file, "r");
10441 	if (!f) {
10442 		err = -errno;
10443 		pr_debug("failed to open '%s': %s\n", file,
10444 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10445 		return err;
10446 	}
10447 	err = fscanf(f, fmt, &ret);
10448 	if (err != 1) {
10449 		err = err == EOF ? -EIO : -errno;
10450 		pr_debug("failed to parse '%s': %s\n", file,
10451 			libbpf_strerror_r(err, buf, sizeof(buf)));
10452 		fclose(f);
10453 		return err;
10454 	}
10455 	fclose(f);
10456 	return ret;
10457 }
10458 
determine_kprobe_perf_type(void)10459 static int determine_kprobe_perf_type(void)
10460 {
10461 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10462 
10463 	return parse_uint_from_file(file, "%d\n");
10464 }
10465 
determine_uprobe_perf_type(void)10466 static int determine_uprobe_perf_type(void)
10467 {
10468 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10469 
10470 	return parse_uint_from_file(file, "%d\n");
10471 }
10472 
determine_kprobe_retprobe_bit(void)10473 static int determine_kprobe_retprobe_bit(void)
10474 {
10475 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10476 
10477 	return parse_uint_from_file(file, "config:%d\n");
10478 }
10479 
determine_uprobe_retprobe_bit(void)10480 static int determine_uprobe_retprobe_bit(void)
10481 {
10482 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10483 
10484 	return parse_uint_from_file(file, "config:%d\n");
10485 }
10486 
10487 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10488 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10489 
perf_event_open_probe(bool uprobe,bool retprobe,const char * name,uint64_t offset,int pid,size_t ref_ctr_off)10490 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10491 				 uint64_t offset, int pid, size_t ref_ctr_off)
10492 {
10493 	struct perf_event_attr attr = {};
10494 	char errmsg[STRERR_BUFSIZE];
10495 	int type, pfd, err;
10496 
10497 	if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10498 		return -EINVAL;
10499 
10500 	type = uprobe ? determine_uprobe_perf_type()
10501 		      : determine_kprobe_perf_type();
10502 	if (type < 0) {
10503 		pr_warn("failed to determine %s perf type: %s\n",
10504 			uprobe ? "uprobe" : "kprobe",
10505 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10506 		return type;
10507 	}
10508 	if (retprobe) {
10509 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10510 				 : determine_kprobe_retprobe_bit();
10511 
10512 		if (bit < 0) {
10513 			pr_warn("failed to determine %s retprobe bit: %s\n",
10514 				uprobe ? "uprobe" : "kprobe",
10515 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10516 			return bit;
10517 		}
10518 		attr.config |= 1 << bit;
10519 	}
10520 	attr.size = sizeof(attr);
10521 	attr.type = type;
10522 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10523 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10524 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10525 
10526 	/* pid filter is meaningful only for uprobes */
10527 	pfd = syscall(__NR_perf_event_open, &attr,
10528 		      pid < 0 ? -1 : pid /* pid */,
10529 		      pid == -1 ? 0 : -1 /* cpu */,
10530 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10531 	if (pfd < 0) {
10532 		err = -errno;
10533 		pr_warn("%s perf_event_open() failed: %s\n",
10534 			uprobe ? "uprobe" : "kprobe",
10535 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10536 		return err;
10537 	}
10538 	return pfd;
10539 }
10540 
append_to_file(const char * file,const char * fmt,...)10541 static int append_to_file(const char *file, const char *fmt, ...)
10542 {
10543 	int fd, n, err = 0;
10544 	va_list ap;
10545 
10546 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10547 	if (fd < 0)
10548 		return -errno;
10549 
10550 	va_start(ap, fmt);
10551 	n = vdprintf(fd, fmt, ap);
10552 	va_end(ap);
10553 
10554 	if (n < 0)
10555 		err = -errno;
10556 
10557 	close(fd);
10558 	return err;
10559 }
10560 
gen_kprobe_legacy_event_name(char * buf,size_t buf_sz,const char * kfunc_name,size_t offset)10561 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10562 					 const char *kfunc_name, size_t offset)
10563 {
10564 	static int index = 0;
10565 
10566 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10567 		 __sync_fetch_and_add(&index, 1));
10568 }
10569 
add_kprobe_event_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset)10570 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10571 				   const char *kfunc_name, size_t offset)
10572 {
10573 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10574 
10575 	return append_to_file(file, "%c:%s/%s %s+0x%zx",
10576 			      retprobe ? 'r' : 'p',
10577 			      retprobe ? "kretprobes" : "kprobes",
10578 			      probe_name, kfunc_name, offset);
10579 }
10580 
remove_kprobe_event_legacy(const char * probe_name,bool retprobe)10581 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10582 {
10583 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10584 
10585 	return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
10586 }
10587 
determine_kprobe_perf_type_legacy(const char * probe_name,bool retprobe)10588 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10589 {
10590 	char file[256];
10591 
10592 	snprintf(file, sizeof(file),
10593 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
10594 		 retprobe ? "kretprobes" : "kprobes", probe_name);
10595 
10596 	return parse_uint_from_file(file, "%d\n");
10597 }
10598 
perf_event_kprobe_open_legacy(const char * probe_name,bool retprobe,const char * kfunc_name,size_t offset,int pid)10599 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10600 					 const char *kfunc_name, size_t offset, int pid)
10601 {
10602 	struct perf_event_attr attr = {};
10603 	char errmsg[STRERR_BUFSIZE];
10604 	int type, pfd, err;
10605 
10606 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10607 	if (err < 0) {
10608 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10609 			kfunc_name, offset,
10610 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10611 		return err;
10612 	}
10613 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10614 	if (type < 0) {
10615 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10616 			kfunc_name, offset,
10617 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10618 		return type;
10619 	}
10620 	attr.size = sizeof(attr);
10621 	attr.config = type;
10622 	attr.type = PERF_TYPE_TRACEPOINT;
10623 
10624 	pfd = syscall(__NR_perf_event_open, &attr,
10625 		      pid < 0 ? -1 : pid, /* pid */
10626 		      pid == -1 ? 0 : -1, /* cpu */
10627 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10628 	if (pfd < 0) {
10629 		err = -errno;
10630 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10631 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10632 		return err;
10633 	}
10634 	return pfd;
10635 }
10636 
10637 struct bpf_link *
bpf_program__attach_kprobe_opts(const struct bpf_program * prog,const char * func_name,const struct bpf_kprobe_opts * opts)10638 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10639 				const char *func_name,
10640 				const struct bpf_kprobe_opts *opts)
10641 {
10642 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10643 	char errmsg[STRERR_BUFSIZE];
10644 	char *legacy_probe = NULL;
10645 	struct bpf_link *link;
10646 	size_t offset;
10647 	bool retprobe, legacy;
10648 	int pfd, err;
10649 
10650 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10651 		return libbpf_err_ptr(-EINVAL);
10652 
10653 	retprobe = OPTS_GET(opts, retprobe, false);
10654 	offset = OPTS_GET(opts, offset, 0);
10655 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10656 
10657 	legacy = determine_kprobe_perf_type() < 0;
10658 	if (!legacy) {
10659 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10660 					    func_name, offset,
10661 					    -1 /* pid */, 0 /* ref_ctr_off */);
10662 	} else {
10663 		char probe_name[256];
10664 
10665 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10666 					     func_name, offset);
10667 
10668 		legacy_probe = strdup(probe_name);
10669 		if (!legacy_probe)
10670 			return libbpf_err_ptr(-ENOMEM);
10671 
10672 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10673 						    offset, -1 /* pid */);
10674 	}
10675 	if (pfd < 0) {
10676 		err = -errno;
10677 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10678 			prog->name, retprobe ? "kretprobe" : "kprobe",
10679 			func_name, offset,
10680 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10681 		goto err_out;
10682 	}
10683 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10684 	err = libbpf_get_error(link);
10685 	if (err) {
10686 		close(pfd);
10687 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10688 			prog->name, retprobe ? "kretprobe" : "kprobe",
10689 			func_name, offset,
10690 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10691 		goto err_out;
10692 	}
10693 	if (legacy) {
10694 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10695 
10696 		perf_link->legacy_probe_name = legacy_probe;
10697 		perf_link->legacy_is_kprobe = true;
10698 		perf_link->legacy_is_retprobe = retprobe;
10699 	}
10700 
10701 	return link;
10702 err_out:
10703 	free(legacy_probe);
10704 	return libbpf_err_ptr(err);
10705 }
10706 
bpf_program__attach_kprobe(const struct bpf_program * prog,bool retprobe,const char * func_name)10707 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10708 					    bool retprobe,
10709 					    const char *func_name)
10710 {
10711 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10712 		.retprobe = retprobe,
10713 	);
10714 
10715 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10716 }
10717 
10718 /* Adapted from perf/util/string.c */
glob_match(const char * str,const char * pat)10719 static bool glob_match(const char *str, const char *pat)
10720 {
10721 	while (*str && *pat && *pat != '*') {
10722 		if (*pat == '?') {      /* Matches any single character */
10723 			str++;
10724 			pat++;
10725 			continue;
10726 		}
10727 		if (*str != *pat)
10728 			return false;
10729 		str++;
10730 		pat++;
10731 	}
10732 	/* Check wild card */
10733 	if (*pat == '*') {
10734 		while (*pat == '*')
10735 			pat++;
10736 		if (!*pat) /* Tail wild card matches all */
10737 			return true;
10738 		while (*str)
10739 			if (glob_match(str++, pat))
10740 				return true;
10741 	}
10742 	return !*str && !*pat;
10743 }
10744 
10745 struct kprobe_multi_resolve {
10746 	const char *pattern;
10747 	unsigned long *addrs;
10748 	size_t cap;
10749 	size_t cnt;
10750 };
10751 
10752 static int
resolve_kprobe_multi_cb(unsigned long long sym_addr,char sym_type,const char * sym_name,void * ctx)10753 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10754 			const char *sym_name, void *ctx)
10755 {
10756 	struct kprobe_multi_resolve *res = ctx;
10757 	int err;
10758 
10759 	if (!glob_match(sym_name, res->pattern))
10760 		return 0;
10761 
10762 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10763 				res->cnt + 1);
10764 	if (err)
10765 		return err;
10766 
10767 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10768 	return 0;
10769 }
10770 
10771 struct bpf_link *
bpf_program__attach_kprobe_multi_opts(const struct bpf_program * prog,const char * pattern,const struct bpf_kprobe_multi_opts * opts)10772 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10773 				      const char *pattern,
10774 				      const struct bpf_kprobe_multi_opts *opts)
10775 {
10776 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10777 	struct kprobe_multi_resolve res = {
10778 		.pattern = pattern,
10779 	};
10780 	struct bpf_link *link = NULL;
10781 	char errmsg[STRERR_BUFSIZE];
10782 	const unsigned long *addrs;
10783 	int err, link_fd, prog_fd;
10784 	const __u64 *cookies;
10785 	const char **syms;
10786 	bool retprobe;
10787 	size_t cnt;
10788 
10789 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10790 		return libbpf_err_ptr(-EINVAL);
10791 
10792 	syms    = OPTS_GET(opts, syms, false);
10793 	addrs   = OPTS_GET(opts, addrs, false);
10794 	cnt     = OPTS_GET(opts, cnt, false);
10795 	cookies = OPTS_GET(opts, cookies, false);
10796 
10797 	if (!pattern && !addrs && !syms)
10798 		return libbpf_err_ptr(-EINVAL);
10799 	if (pattern && (addrs || syms || cookies || cnt))
10800 		return libbpf_err_ptr(-EINVAL);
10801 	if (!pattern && !cnt)
10802 		return libbpf_err_ptr(-EINVAL);
10803 	if (addrs && syms)
10804 		return libbpf_err_ptr(-EINVAL);
10805 
10806 	if (pattern) {
10807 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10808 		if (err)
10809 			goto error;
10810 		if (!res.cnt) {
10811 			err = -ENOENT;
10812 			goto error;
10813 		}
10814 		addrs = res.addrs;
10815 		cnt = res.cnt;
10816 	}
10817 
10818 	retprobe = OPTS_GET(opts, retprobe, false);
10819 
10820 	lopts.kprobe_multi.syms = syms;
10821 	lopts.kprobe_multi.addrs = addrs;
10822 	lopts.kprobe_multi.cookies = cookies;
10823 	lopts.kprobe_multi.cnt = cnt;
10824 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10825 
10826 	link = calloc(1, sizeof(*link));
10827 	if (!link) {
10828 		err = -ENOMEM;
10829 		goto error;
10830 	}
10831 	link->detach = &bpf_link__detach_fd;
10832 
10833 	prog_fd = bpf_program__fd(prog);
10834 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10835 	if (link_fd < 0) {
10836 		err = -errno;
10837 		pr_warn("prog '%s': failed to attach: %s\n",
10838 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10839 		goto error;
10840 	}
10841 	link->fd = link_fd;
10842 	free(res.addrs);
10843 	return link;
10844 
10845 error:
10846 	free(link);
10847 	free(res.addrs);
10848 	return libbpf_err_ptr(err);
10849 }
10850 
attach_kprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10851 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10852 {
10853 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10854 	unsigned long offset = 0;
10855 	const char *func_name;
10856 	char *func;
10857 	int n;
10858 
10859 	*link = NULL;
10860 
10861 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10862 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10863 		return 0;
10864 
10865 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10866 	if (opts.retprobe)
10867 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10868 	else
10869 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10870 
10871 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10872 	if (n < 1) {
10873 		pr_warn("kprobe name is invalid: %s\n", func_name);
10874 		return -EINVAL;
10875 	}
10876 	if (opts.retprobe && offset != 0) {
10877 		free(func);
10878 		pr_warn("kretprobes do not support offset specification\n");
10879 		return -EINVAL;
10880 	}
10881 
10882 	opts.offset = offset;
10883 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10884 	free(func);
10885 	return libbpf_get_error(*link);
10886 }
10887 
attach_kprobe_multi(const struct bpf_program * prog,long cookie,struct bpf_link ** link)10888 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10889 {
10890 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10891 	const char *spec;
10892 	char *pattern;
10893 	int n;
10894 
10895 	*link = NULL;
10896 
10897 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10898 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10899 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10900 		return 0;
10901 
10902 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10903 	if (opts.retprobe)
10904 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10905 	else
10906 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10907 
10908 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10909 	if (n < 1) {
10910 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10911 		return -EINVAL;
10912 	}
10913 
10914 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10915 	free(pattern);
10916 	return libbpf_get_error(*link);
10917 }
10918 
gen_uprobe_legacy_event_name(char * buf,size_t buf_sz,const char * binary_path,uint64_t offset)10919 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10920 					 const char *binary_path, uint64_t offset)
10921 {
10922 	int i;
10923 
10924 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10925 
10926 	/* sanitize binary_path in the probe name */
10927 	for (i = 0; buf[i]; i++) {
10928 		if (!isalnum(buf[i]))
10929 			buf[i] = '_';
10930 	}
10931 }
10932 
add_uprobe_event_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset)10933 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10934 					  const char *binary_path, size_t offset)
10935 {
10936 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10937 
10938 	return append_to_file(file, "%c:%s/%s %s:0x%zx",
10939 			      retprobe ? 'r' : 'p',
10940 			      retprobe ? "uretprobes" : "uprobes",
10941 			      probe_name, binary_path, offset);
10942 }
10943 
remove_uprobe_event_legacy(const char * probe_name,bool retprobe)10944 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10945 {
10946 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10947 
10948 	return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
10949 }
10950 
determine_uprobe_perf_type_legacy(const char * probe_name,bool retprobe)10951 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10952 {
10953 	char file[512];
10954 
10955 	snprintf(file, sizeof(file),
10956 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
10957 		 retprobe ? "uretprobes" : "uprobes", probe_name);
10958 
10959 	return parse_uint_from_file(file, "%d\n");
10960 }
10961 
perf_event_uprobe_open_legacy(const char * probe_name,bool retprobe,const char * binary_path,size_t offset,int pid)10962 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10963 					 const char *binary_path, size_t offset, int pid)
10964 {
10965 	struct perf_event_attr attr;
10966 	int type, pfd, err;
10967 
10968 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10969 	if (err < 0) {
10970 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10971 			binary_path, (size_t)offset, err);
10972 		return err;
10973 	}
10974 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10975 	if (type < 0) {
10976 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10977 			binary_path, offset, err);
10978 		return type;
10979 	}
10980 
10981 	memset(&attr, 0, sizeof(attr));
10982 	attr.size = sizeof(attr);
10983 	attr.config = type;
10984 	attr.type = PERF_TYPE_TRACEPOINT;
10985 
10986 	pfd = syscall(__NR_perf_event_open, &attr,
10987 		      pid < 0 ? -1 : pid, /* pid */
10988 		      pid == -1 ? 0 : -1, /* cpu */
10989 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10990 	if (pfd < 0) {
10991 		err = -errno;
10992 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10993 		return err;
10994 	}
10995 	return pfd;
10996 }
10997 
10998 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
elf_find_next_scn_by_type(Elf * elf,int sh_type,Elf_Scn * scn)10999 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
11000 {
11001 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
11002 		GElf_Shdr sh;
11003 
11004 		if (!gelf_getshdr(scn, &sh))
11005 			continue;
11006 		if (sh.sh_type == sh_type)
11007 			return scn;
11008 	}
11009 	return NULL;
11010 }
11011 
11012 /* Find offset of function name in object specified by path.  "name" matches
11013  * symbol name or name@@LIB for library functions.
11014  */
elf_find_func_offset(const char * binary_path,const char * name)11015 static long elf_find_func_offset(const char *binary_path, const char *name)
11016 {
11017 	int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
11018 	bool is_shared_lib, is_name_qualified;
11019 	char errmsg[STRERR_BUFSIZE];
11020 	long ret = -ENOENT;
11021 	size_t name_len;
11022 	GElf_Ehdr ehdr;
11023 	Elf *elf;
11024 
11025 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
11026 	if (fd < 0) {
11027 		ret = -errno;
11028 		pr_warn("failed to open %s: %s\n", binary_path,
11029 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
11030 		return ret;
11031 	}
11032 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
11033 	if (!elf) {
11034 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
11035 		close(fd);
11036 		return -LIBBPF_ERRNO__FORMAT;
11037 	}
11038 	if (!gelf_getehdr(elf, &ehdr)) {
11039 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
11040 		ret = -LIBBPF_ERRNO__FORMAT;
11041 		goto out;
11042 	}
11043 	/* for shared lib case, we do not need to calculate relative offset */
11044 	is_shared_lib = ehdr.e_type == ET_DYN;
11045 
11046 	name_len = strlen(name);
11047 	/* Does name specify "@@LIB"? */
11048 	is_name_qualified = strstr(name, "@@") != NULL;
11049 
11050 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol.  This search order is used because if
11051 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
11052 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
11053 	 * reported as a warning/error.
11054 	 */
11055 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
11056 		size_t nr_syms, strtabidx, idx;
11057 		Elf_Data *symbols = NULL;
11058 		Elf_Scn *scn = NULL;
11059 		int last_bind = -1;
11060 		const char *sname;
11061 		GElf_Shdr sh;
11062 
11063 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
11064 		if (!scn) {
11065 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
11066 				 binary_path);
11067 			continue;
11068 		}
11069 		if (!gelf_getshdr(scn, &sh))
11070 			continue;
11071 		strtabidx = sh.sh_link;
11072 		symbols = elf_getdata(scn, 0);
11073 		if (!symbols) {
11074 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
11075 				binary_path, elf_errmsg(-1));
11076 			ret = -LIBBPF_ERRNO__FORMAT;
11077 			goto out;
11078 		}
11079 		nr_syms = symbols->d_size / sh.sh_entsize;
11080 
11081 		for (idx = 0; idx < nr_syms; idx++) {
11082 			int curr_bind;
11083 			GElf_Sym sym;
11084 			Elf_Scn *sym_scn;
11085 			GElf_Shdr sym_sh;
11086 
11087 			if (!gelf_getsym(symbols, idx, &sym))
11088 				continue;
11089 
11090 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
11091 				continue;
11092 
11093 			sname = elf_strptr(elf, strtabidx, sym.st_name);
11094 			if (!sname)
11095 				continue;
11096 
11097 			curr_bind = GELF_ST_BIND(sym.st_info);
11098 
11099 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
11100 			if (strncmp(sname, name, name_len) != 0)
11101 				continue;
11102 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
11103 			 * additional characters in sname should be of the form "@@LIB".
11104 			 */
11105 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
11106 				continue;
11107 
11108 			if (ret >= 0) {
11109 				/* handle multiple matches */
11110 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
11111 					/* Only accept one non-weak bind. */
11112 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
11113 						sname, name, binary_path);
11114 					ret = -LIBBPF_ERRNO__FORMAT;
11115 					goto out;
11116 				} else if (curr_bind == STB_WEAK) {
11117 					/* already have a non-weak bind, and
11118 					 * this is a weak bind, so ignore.
11119 					 */
11120 					continue;
11121 				}
11122 			}
11123 
11124 			/* Transform symbol's virtual address (absolute for
11125 			 * binaries and relative for shared libs) into file
11126 			 * offset, which is what kernel is expecting for
11127 			 * uprobe/uretprobe attachment.
11128 			 * See Documentation/trace/uprobetracer.rst for more
11129 			 * details.
11130 			 * This is done by looking up symbol's containing
11131 			 * section's header and using it's virtual address
11132 			 * (sh_addr) and corresponding file offset (sh_offset)
11133 			 * to transform sym.st_value (virtual address) into
11134 			 * desired final file offset.
11135 			 */
11136 			sym_scn = elf_getscn(elf, sym.st_shndx);
11137 			if (!sym_scn)
11138 				continue;
11139 			if (!gelf_getshdr(sym_scn, &sym_sh))
11140 				continue;
11141 
11142 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
11143 			last_bind = curr_bind;
11144 		}
11145 		if (ret > 0)
11146 			break;
11147 	}
11148 
11149 	if (ret > 0) {
11150 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
11151 			 ret);
11152 	} else {
11153 		if (ret == 0) {
11154 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
11155 				is_shared_lib ? "should not be 0 in a shared library" :
11156 						"try using shared library path instead");
11157 			ret = -ENOENT;
11158 		} else {
11159 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
11160 		}
11161 	}
11162 out:
11163 	elf_end(elf);
11164 	close(fd);
11165 	return ret;
11166 }
11167 
arch_specific_lib_paths(void)11168 static const char *arch_specific_lib_paths(void)
11169 {
11170 	/*
11171 	 * Based on https://packages.debian.org/sid/libc6.
11172 	 *
11173 	 * Assume that the traced program is built for the same architecture
11174 	 * as libbpf, which should cover the vast majority of cases.
11175 	 */
11176 #if defined(__x86_64__)
11177 	return "/lib/x86_64-linux-gnu";
11178 #elif defined(__i386__)
11179 	return "/lib/i386-linux-gnu";
11180 #elif defined(__s390x__)
11181 	return "/lib/s390x-linux-gnu";
11182 #elif defined(__s390__)
11183 	return "/lib/s390-linux-gnu";
11184 #elif defined(__arm__) && defined(__SOFTFP__)
11185 	return "/lib/arm-linux-gnueabi";
11186 #elif defined(__arm__) && !defined(__SOFTFP__)
11187 	return "/lib/arm-linux-gnueabihf";
11188 #elif defined(__aarch64__)
11189 	return "/lib/aarch64-linux-gnu";
11190 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11191 	return "/lib/mips64el-linux-gnuabi64";
11192 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11193 	return "/lib/mipsel-linux-gnu";
11194 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11195 	return "/lib/powerpc64le-linux-gnu";
11196 #elif defined(__sparc__) && defined(__arch64__)
11197 	return "/lib/sparc64-linux-gnu";
11198 #elif defined(__riscv) && __riscv_xlen == 64
11199 	return "/lib/riscv64-linux-gnu";
11200 #else
11201 	return NULL;
11202 #endif
11203 }
11204 
11205 /* Get full path to program/shared library. */
resolve_full_path(const char * file,char * result,size_t result_sz)11206 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11207 {
11208 	const char *search_paths[3] = {};
11209 	int i;
11210 
11211 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11212 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11213 		search_paths[1] = "/usr/lib64:/usr/lib";
11214 		search_paths[2] = arch_specific_lib_paths();
11215 	} else {
11216 		search_paths[0] = getenv("PATH");
11217 		search_paths[1] = "/usr/bin:/usr/sbin";
11218 	}
11219 
11220 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11221 		const char *s;
11222 
11223 		if (!search_paths[i])
11224 			continue;
11225 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11226 			char *next_path;
11227 			int seg_len;
11228 
11229 			if (s[0] == ':')
11230 				s++;
11231 			next_path = strchr(s, ':');
11232 			seg_len = next_path ? next_path - s : strlen(s);
11233 			if (!seg_len)
11234 				continue;
11235 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11236 			/* ensure it is an executable file/link */
11237 			if (access(result, R_OK | X_OK) < 0)
11238 				continue;
11239 			pr_debug("resolved '%s' to '%s'\n", file, result);
11240 			return 0;
11241 		}
11242 	}
11243 	return -ENOENT;
11244 }
11245 
11246 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)11247 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11248 				const char *binary_path, size_t func_offset,
11249 				const struct bpf_uprobe_opts *opts)
11250 {
11251 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11252 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11253 	char full_binary_path[PATH_MAX];
11254 	struct bpf_link *link;
11255 	size_t ref_ctr_off;
11256 	int pfd, err;
11257 	bool retprobe, legacy;
11258 	const char *func_name;
11259 
11260 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11261 		return libbpf_err_ptr(-EINVAL);
11262 
11263 	retprobe = OPTS_GET(opts, retprobe, false);
11264 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11265 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11266 
11267 	if (binary_path && !strchr(binary_path, '/')) {
11268 		err = resolve_full_path(binary_path, full_binary_path,
11269 					sizeof(full_binary_path));
11270 		if (err) {
11271 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11272 				prog->name, binary_path, err);
11273 			return libbpf_err_ptr(err);
11274 		}
11275 		binary_path = full_binary_path;
11276 	}
11277 	func_name = OPTS_GET(opts, func_name, NULL);
11278 	if (func_name) {
11279 		long sym_off;
11280 
11281 		if (!binary_path) {
11282 			pr_warn("prog '%s': name-based attach requires binary_path\n",
11283 				prog->name);
11284 			return libbpf_err_ptr(-EINVAL);
11285 		}
11286 		sym_off = elf_find_func_offset(binary_path, func_name);
11287 		if (sym_off < 0)
11288 			return libbpf_err_ptr(sym_off);
11289 		func_offset += sym_off;
11290 	}
11291 
11292 	legacy = determine_uprobe_perf_type() < 0;
11293 	if (!legacy) {
11294 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11295 					    func_offset, pid, ref_ctr_off);
11296 	} else {
11297 		char probe_name[PATH_MAX + 64];
11298 
11299 		if (ref_ctr_off)
11300 			return libbpf_err_ptr(-EINVAL);
11301 
11302 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11303 					     binary_path, func_offset);
11304 
11305 		legacy_probe = strdup(probe_name);
11306 		if (!legacy_probe)
11307 			return libbpf_err_ptr(-ENOMEM);
11308 
11309 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11310 						    binary_path, func_offset, pid);
11311 	}
11312 	if (pfd < 0) {
11313 		err = -errno;
11314 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11315 			prog->name, retprobe ? "uretprobe" : "uprobe",
11316 			binary_path, func_offset,
11317 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11318 		goto err_out;
11319 	}
11320 
11321 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11322 	err = libbpf_get_error(link);
11323 	if (err) {
11324 		close(pfd);
11325 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11326 			prog->name, retprobe ? "uretprobe" : "uprobe",
11327 			binary_path, func_offset,
11328 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11329 		goto err_out;
11330 	}
11331 	if (legacy) {
11332 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11333 
11334 		perf_link->legacy_probe_name = legacy_probe;
11335 		perf_link->legacy_is_kprobe = false;
11336 		perf_link->legacy_is_retprobe = retprobe;
11337 	}
11338 	return link;
11339 err_out:
11340 	free(legacy_probe);
11341 	return libbpf_err_ptr(err);
11342 
11343 }
11344 
11345 /* Format of u[ret]probe section definition supporting auto-attach:
11346  * u[ret]probe/binary:function[+offset]
11347  *
11348  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11349  * full binary path via bpf_program__attach_uprobe_opts.
11350  *
11351  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11352  * specified (and auto-attach is not possible) or the above format is specified for
11353  * auto-attach.
11354  */
attach_uprobe(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11355 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11356 {
11357 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11358 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11359 	int n, ret = -EINVAL;
11360 	long offset = 0;
11361 
11362 	*link = NULL;
11363 
11364 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11365 		   &probe_type, &binary_path, &func_name, &offset);
11366 	switch (n) {
11367 	case 1:
11368 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11369 		ret = 0;
11370 		break;
11371 	case 2:
11372 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11373 			prog->name, prog->sec_name);
11374 		break;
11375 	case 3:
11376 	case 4:
11377 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0;
11378 		if (opts.retprobe && offset != 0) {
11379 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11380 				prog->name);
11381 			break;
11382 		}
11383 		opts.func_name = func_name;
11384 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11385 		ret = libbpf_get_error(*link);
11386 		break;
11387 	default:
11388 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11389 			prog->sec_name);
11390 		break;
11391 	}
11392 	free(probe_type);
11393 	free(binary_path);
11394 	free(func_name);
11395 
11396 	return ret;
11397 }
11398 
bpf_program__attach_uprobe(const struct bpf_program * prog,bool retprobe,pid_t pid,const char * binary_path,size_t func_offset)11399 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11400 					    bool retprobe, pid_t pid,
11401 					    const char *binary_path,
11402 					    size_t func_offset)
11403 {
11404 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11405 
11406 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11407 }
11408 
bpf_program__attach_usdt(const struct bpf_program * prog,pid_t pid,const char * binary_path,const char * usdt_provider,const char * usdt_name,const struct bpf_usdt_opts * opts)11409 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11410 					  pid_t pid, const char *binary_path,
11411 					  const char *usdt_provider, const char *usdt_name,
11412 					  const struct bpf_usdt_opts *opts)
11413 {
11414 	char resolved_path[512];
11415 	struct bpf_object *obj = prog->obj;
11416 	struct bpf_link *link;
11417 	__u64 usdt_cookie;
11418 	int err;
11419 
11420 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11421 		return libbpf_err_ptr(-EINVAL);
11422 
11423 	if (bpf_program__fd(prog) < 0) {
11424 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11425 			prog->name);
11426 		return libbpf_err_ptr(-EINVAL);
11427 	}
11428 
11429 	if (!strchr(binary_path, '/')) {
11430 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11431 		if (err) {
11432 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11433 				prog->name, binary_path, err);
11434 			return libbpf_err_ptr(err);
11435 		}
11436 		binary_path = resolved_path;
11437 	}
11438 
11439 	/* USDT manager is instantiated lazily on first USDT attach. It will
11440 	 * be destroyed together with BPF object in bpf_object__close().
11441 	 */
11442 	if (IS_ERR(obj->usdt_man))
11443 		return libbpf_ptr(obj->usdt_man);
11444 	if (!obj->usdt_man) {
11445 		obj->usdt_man = usdt_manager_new(obj);
11446 		if (IS_ERR(obj->usdt_man))
11447 			return libbpf_ptr(obj->usdt_man);
11448 	}
11449 
11450 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11451 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11452 				        usdt_provider, usdt_name, usdt_cookie);
11453 	err = libbpf_get_error(link);
11454 	if (err)
11455 		return libbpf_err_ptr(err);
11456 	return link;
11457 }
11458 
attach_usdt(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11459 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11460 {
11461 	char *path = NULL, *provider = NULL, *name = NULL;
11462 	const char *sec_name;
11463 	int n, err;
11464 
11465 	sec_name = bpf_program__section_name(prog);
11466 	if (strcmp(sec_name, "usdt") == 0) {
11467 		/* no auto-attach for just SEC("usdt") */
11468 		*link = NULL;
11469 		return 0;
11470 	}
11471 
11472 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11473 	if (n != 3) {
11474 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11475 			sec_name);
11476 		err = -EINVAL;
11477 	} else {
11478 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11479 						 provider, name, NULL);
11480 		err = libbpf_get_error(*link);
11481 	}
11482 	free(path);
11483 	free(provider);
11484 	free(name);
11485 	return err;
11486 }
11487 
determine_tracepoint_id(const char * tp_category,const char * tp_name)11488 static int determine_tracepoint_id(const char *tp_category,
11489 				   const char *tp_name)
11490 {
11491 	char file[PATH_MAX];
11492 	int ret;
11493 
11494 	ret = snprintf(file, sizeof(file),
11495 		       "/sys/kernel/debug/tracing/events/%s/%s/id",
11496 		       tp_category, tp_name);
11497 	if (ret < 0)
11498 		return -errno;
11499 	if (ret >= sizeof(file)) {
11500 		pr_debug("tracepoint %s/%s path is too long\n",
11501 			 tp_category, tp_name);
11502 		return -E2BIG;
11503 	}
11504 	return parse_uint_from_file(file, "%d\n");
11505 }
11506 
perf_event_open_tracepoint(const char * tp_category,const char * tp_name)11507 static int perf_event_open_tracepoint(const char *tp_category,
11508 				      const char *tp_name)
11509 {
11510 	struct perf_event_attr attr = {};
11511 	char errmsg[STRERR_BUFSIZE];
11512 	int tp_id, pfd, err;
11513 
11514 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11515 	if (tp_id < 0) {
11516 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11517 			tp_category, tp_name,
11518 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11519 		return tp_id;
11520 	}
11521 
11522 	attr.type = PERF_TYPE_TRACEPOINT;
11523 	attr.size = sizeof(attr);
11524 	attr.config = tp_id;
11525 
11526 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11527 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11528 	if (pfd < 0) {
11529 		err = -errno;
11530 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11531 			tp_category, tp_name,
11532 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11533 		return err;
11534 	}
11535 	return pfd;
11536 }
11537 
bpf_program__attach_tracepoint_opts(const struct bpf_program * prog,const char * tp_category,const char * tp_name,const struct bpf_tracepoint_opts * opts)11538 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11539 						     const char *tp_category,
11540 						     const char *tp_name,
11541 						     const struct bpf_tracepoint_opts *opts)
11542 {
11543 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11544 	char errmsg[STRERR_BUFSIZE];
11545 	struct bpf_link *link;
11546 	int pfd, err;
11547 
11548 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11549 		return libbpf_err_ptr(-EINVAL);
11550 
11551 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11552 
11553 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11554 	if (pfd < 0) {
11555 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11556 			prog->name, tp_category, tp_name,
11557 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11558 		return libbpf_err_ptr(pfd);
11559 	}
11560 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11561 	err = libbpf_get_error(link);
11562 	if (err) {
11563 		close(pfd);
11564 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11565 			prog->name, tp_category, tp_name,
11566 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11567 		return libbpf_err_ptr(err);
11568 	}
11569 	return link;
11570 }
11571 
bpf_program__attach_tracepoint(const struct bpf_program * prog,const char * tp_category,const char * tp_name)11572 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11573 						const char *tp_category,
11574 						const char *tp_name)
11575 {
11576 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11577 }
11578 
attach_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11579 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11580 {
11581 	char *sec_name, *tp_cat, *tp_name;
11582 
11583 	*link = NULL;
11584 
11585 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11586 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11587 		return 0;
11588 
11589 	sec_name = strdup(prog->sec_name);
11590 	if (!sec_name)
11591 		return -ENOMEM;
11592 
11593 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11594 	if (str_has_pfx(prog->sec_name, "tp/"))
11595 		tp_cat = sec_name + sizeof("tp/") - 1;
11596 	else
11597 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11598 	tp_name = strchr(tp_cat, '/');
11599 	if (!tp_name) {
11600 		free(sec_name);
11601 		return -EINVAL;
11602 	}
11603 	*tp_name = '\0';
11604 	tp_name++;
11605 
11606 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11607 	free(sec_name);
11608 	return libbpf_get_error(*link);
11609 }
11610 
bpf_program__attach_raw_tracepoint(const struct bpf_program * prog,const char * tp_name)11611 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11612 						    const char *tp_name)
11613 {
11614 	char errmsg[STRERR_BUFSIZE];
11615 	struct bpf_link *link;
11616 	int prog_fd, pfd;
11617 
11618 	prog_fd = bpf_program__fd(prog);
11619 	if (prog_fd < 0) {
11620 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11621 		return libbpf_err_ptr(-EINVAL);
11622 	}
11623 
11624 	link = calloc(1, sizeof(*link));
11625 	if (!link)
11626 		return libbpf_err_ptr(-ENOMEM);
11627 	link->detach = &bpf_link__detach_fd;
11628 
11629 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11630 	if (pfd < 0) {
11631 		pfd = -errno;
11632 		free(link);
11633 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11634 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11635 		return libbpf_err_ptr(pfd);
11636 	}
11637 	link->fd = pfd;
11638 	return link;
11639 }
11640 
attach_raw_tp(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11641 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11642 {
11643 	static const char *const prefixes[] = {
11644 		"raw_tp",
11645 		"raw_tracepoint",
11646 		"raw_tp.w",
11647 		"raw_tracepoint.w",
11648 	};
11649 	size_t i;
11650 	const char *tp_name = NULL;
11651 
11652 	*link = NULL;
11653 
11654 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11655 		size_t pfx_len;
11656 
11657 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11658 			continue;
11659 
11660 		pfx_len = strlen(prefixes[i]);
11661 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11662 		if (prog->sec_name[pfx_len] == '\0')
11663 			return 0;
11664 
11665 		if (prog->sec_name[pfx_len] != '/')
11666 			continue;
11667 
11668 		tp_name = prog->sec_name + pfx_len + 1;
11669 		break;
11670 	}
11671 
11672 	if (!tp_name) {
11673 		pr_warn("prog '%s': invalid section name '%s'\n",
11674 			prog->name, prog->sec_name);
11675 		return -EINVAL;
11676 	}
11677 
11678 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11679 	return libbpf_get_error(link);
11680 }
11681 
11682 /* Common logic for all BPF program types that attach to a btf_id */
bpf_program__attach_btf_id(const struct bpf_program * prog,const struct bpf_trace_opts * opts)11683 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11684 						   const struct bpf_trace_opts *opts)
11685 {
11686 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11687 	char errmsg[STRERR_BUFSIZE];
11688 	struct bpf_link *link;
11689 	int prog_fd, pfd;
11690 
11691 	if (!OPTS_VALID(opts, bpf_trace_opts))
11692 		return libbpf_err_ptr(-EINVAL);
11693 
11694 	prog_fd = bpf_program__fd(prog);
11695 	if (prog_fd < 0) {
11696 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11697 		return libbpf_err_ptr(-EINVAL);
11698 	}
11699 
11700 	link = calloc(1, sizeof(*link));
11701 	if (!link)
11702 		return libbpf_err_ptr(-ENOMEM);
11703 	link->detach = &bpf_link__detach_fd;
11704 
11705 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11706 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11707 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11708 	if (pfd < 0) {
11709 		pfd = -errno;
11710 		free(link);
11711 		pr_warn("prog '%s': failed to attach: %s\n",
11712 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11713 		return libbpf_err_ptr(pfd);
11714 	}
11715 	link->fd = pfd;
11716 	return link;
11717 }
11718 
bpf_program__attach_trace(const struct bpf_program * prog)11719 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11720 {
11721 	return bpf_program__attach_btf_id(prog, NULL);
11722 }
11723 
bpf_program__attach_trace_opts(const struct bpf_program * prog,const struct bpf_trace_opts * opts)11724 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11725 						const struct bpf_trace_opts *opts)
11726 {
11727 	return bpf_program__attach_btf_id(prog, opts);
11728 }
11729 
bpf_program__attach_lsm(const struct bpf_program * prog)11730 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11731 {
11732 	return bpf_program__attach_btf_id(prog, NULL);
11733 }
11734 
attach_trace(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11735 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11736 {
11737 	*link = bpf_program__attach_trace(prog);
11738 	return libbpf_get_error(*link);
11739 }
11740 
attach_lsm(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11741 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11742 {
11743 	*link = bpf_program__attach_lsm(prog);
11744 	return libbpf_get_error(*link);
11745 }
11746 
11747 static struct bpf_link *
bpf_program__attach_fd(const struct bpf_program * prog,int target_fd,int btf_id,const char * target_name)11748 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11749 		       const char *target_name)
11750 {
11751 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11752 			    .target_btf_id = btf_id);
11753 	enum bpf_attach_type attach_type;
11754 	char errmsg[STRERR_BUFSIZE];
11755 	struct bpf_link *link;
11756 	int prog_fd, link_fd;
11757 
11758 	prog_fd = bpf_program__fd(prog);
11759 	if (prog_fd < 0) {
11760 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11761 		return libbpf_err_ptr(-EINVAL);
11762 	}
11763 
11764 	link = calloc(1, sizeof(*link));
11765 	if (!link)
11766 		return libbpf_err_ptr(-ENOMEM);
11767 	link->detach = &bpf_link__detach_fd;
11768 
11769 	attach_type = bpf_program__expected_attach_type(prog);
11770 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11771 	if (link_fd < 0) {
11772 		link_fd = -errno;
11773 		free(link);
11774 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11775 			prog->name, target_name,
11776 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11777 		return libbpf_err_ptr(link_fd);
11778 	}
11779 	link->fd = link_fd;
11780 	return link;
11781 }
11782 
11783 struct bpf_link *
bpf_program__attach_cgroup(const struct bpf_program * prog,int cgroup_fd)11784 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11785 {
11786 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11787 }
11788 
11789 struct bpf_link *
bpf_program__attach_netns(const struct bpf_program * prog,int netns_fd)11790 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11791 {
11792 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11793 }
11794 
bpf_program__attach_xdp(const struct bpf_program * prog,int ifindex)11795 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11796 {
11797 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11798 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11799 }
11800 
bpf_program__attach_freplace(const struct bpf_program * prog,int target_fd,const char * attach_func_name)11801 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11802 					      int target_fd,
11803 					      const char *attach_func_name)
11804 {
11805 	int btf_id;
11806 
11807 	if (!!target_fd != !!attach_func_name) {
11808 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11809 			prog->name);
11810 		return libbpf_err_ptr(-EINVAL);
11811 	}
11812 
11813 	if (prog->type != BPF_PROG_TYPE_EXT) {
11814 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11815 			prog->name);
11816 		return libbpf_err_ptr(-EINVAL);
11817 	}
11818 
11819 	if (target_fd) {
11820 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11821 		if (btf_id < 0)
11822 			return libbpf_err_ptr(btf_id);
11823 
11824 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11825 	} else {
11826 		/* no target, so use raw_tracepoint_open for compatibility
11827 		 * with old kernels
11828 		 */
11829 		return bpf_program__attach_trace(prog);
11830 	}
11831 }
11832 
11833 struct bpf_link *
bpf_program__attach_iter(const struct bpf_program * prog,const struct bpf_iter_attach_opts * opts)11834 bpf_program__attach_iter(const struct bpf_program *prog,
11835 			 const struct bpf_iter_attach_opts *opts)
11836 {
11837 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11838 	char errmsg[STRERR_BUFSIZE];
11839 	struct bpf_link *link;
11840 	int prog_fd, link_fd;
11841 	__u32 target_fd = 0;
11842 
11843 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11844 		return libbpf_err_ptr(-EINVAL);
11845 
11846 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11847 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11848 
11849 	prog_fd = bpf_program__fd(prog);
11850 	if (prog_fd < 0) {
11851 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11852 		return libbpf_err_ptr(-EINVAL);
11853 	}
11854 
11855 	link = calloc(1, sizeof(*link));
11856 	if (!link)
11857 		return libbpf_err_ptr(-ENOMEM);
11858 	link->detach = &bpf_link__detach_fd;
11859 
11860 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11861 				  &link_create_opts);
11862 	if (link_fd < 0) {
11863 		link_fd = -errno;
11864 		free(link);
11865 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11866 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11867 		return libbpf_err_ptr(link_fd);
11868 	}
11869 	link->fd = link_fd;
11870 	return link;
11871 }
11872 
attach_iter(const struct bpf_program * prog,long cookie,struct bpf_link ** link)11873 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11874 {
11875 	*link = bpf_program__attach_iter(prog, NULL);
11876 	return libbpf_get_error(*link);
11877 }
11878 
bpf_program__attach(const struct bpf_program * prog)11879 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11880 {
11881 	struct bpf_link *link = NULL;
11882 	int err;
11883 
11884 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11885 		return libbpf_err_ptr(-EOPNOTSUPP);
11886 
11887 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11888 	if (err)
11889 		return libbpf_err_ptr(err);
11890 
11891 	/* When calling bpf_program__attach() explicitly, auto-attach support
11892 	 * is expected to work, so NULL returned link is considered an error.
11893 	 * This is different for skeleton's attach, see comment in
11894 	 * bpf_object__attach_skeleton().
11895 	 */
11896 	if (!link)
11897 		return libbpf_err_ptr(-EOPNOTSUPP);
11898 
11899 	return link;
11900 }
11901 
bpf_link__detach_struct_ops(struct bpf_link * link)11902 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11903 {
11904 	__u32 zero = 0;
11905 
11906 	if (bpf_map_delete_elem(link->fd, &zero))
11907 		return -errno;
11908 
11909 	return 0;
11910 }
11911 
bpf_map__attach_struct_ops(const struct bpf_map * map)11912 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11913 {
11914 	struct bpf_struct_ops *st_ops;
11915 	struct bpf_link *link;
11916 	__u32 i, zero = 0;
11917 	int err;
11918 
11919 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11920 		return libbpf_err_ptr(-EINVAL);
11921 
11922 	link = calloc(1, sizeof(*link));
11923 	if (!link)
11924 		return libbpf_err_ptr(-EINVAL);
11925 
11926 	st_ops = map->st_ops;
11927 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
11928 		struct bpf_program *prog = st_ops->progs[i];
11929 		void *kern_data;
11930 		int prog_fd;
11931 
11932 		if (!prog)
11933 			continue;
11934 
11935 		prog_fd = bpf_program__fd(prog);
11936 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
11937 		*(unsigned long *)kern_data = prog_fd;
11938 	}
11939 
11940 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
11941 	if (err) {
11942 		err = -errno;
11943 		free(link);
11944 		return libbpf_err_ptr(err);
11945 	}
11946 
11947 	link->detach = bpf_link__detach_struct_ops;
11948 	link->fd = map->fd;
11949 
11950 	return link;
11951 }
11952 
11953 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)11954 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11955 		       void **copy_mem, size_t *copy_size,
11956 		       bpf_perf_event_print_t fn, void *private_data)
11957 {
11958 	struct perf_event_mmap_page *header = mmap_mem;
11959 	__u64 data_head = ring_buffer_read_head(header);
11960 	__u64 data_tail = header->data_tail;
11961 	void *base = ((__u8 *)header) + page_size;
11962 	int ret = LIBBPF_PERF_EVENT_CONT;
11963 	struct perf_event_header *ehdr;
11964 	size_t ehdr_size;
11965 
11966 	while (data_head != data_tail) {
11967 		ehdr = base + (data_tail & (mmap_size - 1));
11968 		ehdr_size = ehdr->size;
11969 
11970 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11971 			void *copy_start = ehdr;
11972 			size_t len_first = base + mmap_size - copy_start;
11973 			size_t len_secnd = ehdr_size - len_first;
11974 
11975 			if (*copy_size < ehdr_size) {
11976 				free(*copy_mem);
11977 				*copy_mem = malloc(ehdr_size);
11978 				if (!*copy_mem) {
11979 					*copy_size = 0;
11980 					ret = LIBBPF_PERF_EVENT_ERROR;
11981 					break;
11982 				}
11983 				*copy_size = ehdr_size;
11984 			}
11985 
11986 			memcpy(*copy_mem, copy_start, len_first);
11987 			memcpy(*copy_mem + len_first, base, len_secnd);
11988 			ehdr = *copy_mem;
11989 		}
11990 
11991 		ret = fn(ehdr, private_data);
11992 		data_tail += ehdr_size;
11993 		if (ret != LIBBPF_PERF_EVENT_CONT)
11994 			break;
11995 	}
11996 
11997 	ring_buffer_write_tail(header, data_tail);
11998 	return libbpf_err(ret);
11999 }
12000 
12001 __attribute__((alias("perf_event_read_simple")))
12002 enum bpf_perf_event_ret
12003 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12004 			   void **copy_mem, size_t *copy_size,
12005 			   bpf_perf_event_print_t fn, void *private_data);
12006 
12007 struct perf_buffer;
12008 
12009 struct perf_buffer_params {
12010 	struct perf_event_attr *attr;
12011 	/* if event_cb is specified, it takes precendence */
12012 	perf_buffer_event_fn event_cb;
12013 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12014 	perf_buffer_sample_fn sample_cb;
12015 	perf_buffer_lost_fn lost_cb;
12016 	void *ctx;
12017 	int cpu_cnt;
12018 	int *cpus;
12019 	int *map_keys;
12020 };
12021 
12022 struct perf_cpu_buf {
12023 	struct perf_buffer *pb;
12024 	void *base; /* mmap()'ed memory */
12025 	void *buf; /* for reconstructing segmented data */
12026 	size_t buf_size;
12027 	int fd;
12028 	int cpu;
12029 	int map_key;
12030 };
12031 
12032 struct perf_buffer {
12033 	perf_buffer_event_fn event_cb;
12034 	perf_buffer_sample_fn sample_cb;
12035 	perf_buffer_lost_fn lost_cb;
12036 	void *ctx; /* passed into callbacks */
12037 
12038 	size_t page_size;
12039 	size_t mmap_size;
12040 	struct perf_cpu_buf **cpu_bufs;
12041 	struct epoll_event *events;
12042 	int cpu_cnt; /* number of allocated CPU buffers */
12043 	int epoll_fd; /* perf event FD */
12044 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12045 };
12046 
perf_buffer__free_cpu_buf(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12047 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12048 				      struct perf_cpu_buf *cpu_buf)
12049 {
12050 	if (!cpu_buf)
12051 		return;
12052 	if (cpu_buf->base &&
12053 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12054 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12055 	if (cpu_buf->fd >= 0) {
12056 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12057 		close(cpu_buf->fd);
12058 	}
12059 	free(cpu_buf->buf);
12060 	free(cpu_buf);
12061 }
12062 
perf_buffer__free(struct perf_buffer * pb)12063 void perf_buffer__free(struct perf_buffer *pb)
12064 {
12065 	int i;
12066 
12067 	if (IS_ERR_OR_NULL(pb))
12068 		return;
12069 	if (pb->cpu_bufs) {
12070 		for (i = 0; i < pb->cpu_cnt; i++) {
12071 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12072 
12073 			if (!cpu_buf)
12074 				continue;
12075 
12076 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12077 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12078 		}
12079 		free(pb->cpu_bufs);
12080 	}
12081 	if (pb->epoll_fd >= 0)
12082 		close(pb->epoll_fd);
12083 	free(pb->events);
12084 	free(pb);
12085 }
12086 
12087 static struct perf_cpu_buf *
perf_buffer__open_cpu_buf(struct perf_buffer * pb,struct perf_event_attr * attr,int cpu,int map_key)12088 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12089 			  int cpu, int map_key)
12090 {
12091 	struct perf_cpu_buf *cpu_buf;
12092 	char msg[STRERR_BUFSIZE];
12093 	int err;
12094 
12095 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12096 	if (!cpu_buf)
12097 		return ERR_PTR(-ENOMEM);
12098 
12099 	cpu_buf->pb = pb;
12100 	cpu_buf->cpu = cpu;
12101 	cpu_buf->map_key = map_key;
12102 
12103 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12104 			      -1, PERF_FLAG_FD_CLOEXEC);
12105 	if (cpu_buf->fd < 0) {
12106 		err = -errno;
12107 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12108 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12109 		goto error;
12110 	}
12111 
12112 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12113 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12114 			     cpu_buf->fd, 0);
12115 	if (cpu_buf->base == MAP_FAILED) {
12116 		cpu_buf->base = NULL;
12117 		err = -errno;
12118 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12119 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12120 		goto error;
12121 	}
12122 
12123 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12124 		err = -errno;
12125 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12126 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12127 		goto error;
12128 	}
12129 
12130 	return cpu_buf;
12131 
12132 error:
12133 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12134 	return (struct perf_cpu_buf *)ERR_PTR(err);
12135 }
12136 
12137 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12138 					      struct perf_buffer_params *p);
12139 
12140 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)12141 struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
12142 					    perf_buffer_sample_fn sample_cb,
12143 					    perf_buffer_lost_fn lost_cb,
12144 					    void *ctx,
12145 					    const struct perf_buffer_opts *opts)
12146 {
12147 	struct perf_buffer_params p = {};
12148 	struct perf_event_attr attr = {};
12149 
12150 	if (!OPTS_VALID(opts, perf_buffer_opts))
12151 		return libbpf_err_ptr(-EINVAL);
12152 
12153 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12154 	attr.type = PERF_TYPE_SOFTWARE;
12155 	attr.sample_type = PERF_SAMPLE_RAW;
12156 	attr.sample_period = 1;
12157 	attr.wakeup_events = 1;
12158 
12159 	p.attr = &attr;
12160 	p.sample_cb = sample_cb;
12161 	p.lost_cb = lost_cb;
12162 	p.ctx = ctx;
12163 
12164 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12165 }
12166 
12167 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)12168 struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
12169 						const struct perf_buffer_opts *opts)
12170 {
12171 	return perf_buffer__new_v0_6_0(map_fd, page_cnt,
12172 				       opts ? opts->sample_cb : NULL,
12173 				       opts ? opts->lost_cb : NULL,
12174 				       opts ? opts->ctx : NULL,
12175 				       NULL);
12176 }
12177 
12178 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)12179 struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
12180 						struct perf_event_attr *attr,
12181 						perf_buffer_event_fn event_cb, void *ctx,
12182 						const struct perf_buffer_raw_opts *opts)
12183 {
12184 	struct perf_buffer_params p = {};
12185 
12186 	if (!attr)
12187 		return libbpf_err_ptr(-EINVAL);
12188 
12189 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12190 		return libbpf_err_ptr(-EINVAL);
12191 
12192 	p.attr = attr;
12193 	p.event_cb = event_cb;
12194 	p.ctx = ctx;
12195 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12196 	p.cpus = OPTS_GET(opts, cpus, NULL);
12197 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12198 
12199 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12200 }
12201 
12202 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)12203 struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
12204 						    const struct perf_buffer_raw_opts *opts)
12205 {
12206 	LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
12207 		.cpu_cnt = opts->cpu_cnt,
12208 		.cpus = opts->cpus,
12209 		.map_keys = opts->map_keys,
12210 	);
12211 
12212 	return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
12213 					   opts->event_cb, opts->ctx, &inner_opts);
12214 }
12215 
__perf_buffer__new(int map_fd,size_t page_cnt,struct perf_buffer_params * p)12216 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12217 					      struct perf_buffer_params *p)
12218 {
12219 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12220 	struct bpf_map_info map;
12221 	char msg[STRERR_BUFSIZE];
12222 	struct perf_buffer *pb;
12223 	bool *online = NULL;
12224 	__u32 map_info_len;
12225 	int err, i, j, n;
12226 
12227 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12228 		pr_warn("page count should be power of two, but is %zu\n",
12229 			page_cnt);
12230 		return ERR_PTR(-EINVAL);
12231 	}
12232 
12233 	/* best-effort sanity checks */
12234 	memset(&map, 0, sizeof(map));
12235 	map_info_len = sizeof(map);
12236 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
12237 	if (err) {
12238 		err = -errno;
12239 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12240 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12241 		 */
12242 		if (err != -EINVAL) {
12243 			pr_warn("failed to get map info for map FD %d: %s\n",
12244 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12245 			return ERR_PTR(err);
12246 		}
12247 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12248 			 map_fd);
12249 	} else {
12250 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12251 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12252 				map.name);
12253 			return ERR_PTR(-EINVAL);
12254 		}
12255 	}
12256 
12257 	pb = calloc(1, sizeof(*pb));
12258 	if (!pb)
12259 		return ERR_PTR(-ENOMEM);
12260 
12261 	pb->event_cb = p->event_cb;
12262 	pb->sample_cb = p->sample_cb;
12263 	pb->lost_cb = p->lost_cb;
12264 	pb->ctx = p->ctx;
12265 
12266 	pb->page_size = getpagesize();
12267 	pb->mmap_size = pb->page_size * page_cnt;
12268 	pb->map_fd = map_fd;
12269 
12270 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12271 	if (pb->epoll_fd < 0) {
12272 		err = -errno;
12273 		pr_warn("failed to create epoll instance: %s\n",
12274 			libbpf_strerror_r(err, msg, sizeof(msg)));
12275 		goto error;
12276 	}
12277 
12278 	if (p->cpu_cnt > 0) {
12279 		pb->cpu_cnt = p->cpu_cnt;
12280 	} else {
12281 		pb->cpu_cnt = libbpf_num_possible_cpus();
12282 		if (pb->cpu_cnt < 0) {
12283 			err = pb->cpu_cnt;
12284 			goto error;
12285 		}
12286 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12287 			pb->cpu_cnt = map.max_entries;
12288 	}
12289 
12290 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12291 	if (!pb->events) {
12292 		err = -ENOMEM;
12293 		pr_warn("failed to allocate events: out of memory\n");
12294 		goto error;
12295 	}
12296 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12297 	if (!pb->cpu_bufs) {
12298 		err = -ENOMEM;
12299 		pr_warn("failed to allocate buffers: out of memory\n");
12300 		goto error;
12301 	}
12302 
12303 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12304 	if (err) {
12305 		pr_warn("failed to get online CPU mask: %d\n", err);
12306 		goto error;
12307 	}
12308 
12309 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12310 		struct perf_cpu_buf *cpu_buf;
12311 		int cpu, map_key;
12312 
12313 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12314 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12315 
12316 		/* in case user didn't explicitly requested particular CPUs to
12317 		 * be attached to, skip offline/not present CPUs
12318 		 */
12319 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12320 			continue;
12321 
12322 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12323 		if (IS_ERR(cpu_buf)) {
12324 			err = PTR_ERR(cpu_buf);
12325 			goto error;
12326 		}
12327 
12328 		pb->cpu_bufs[j] = cpu_buf;
12329 
12330 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12331 					  &cpu_buf->fd, 0);
12332 		if (err) {
12333 			err = -errno;
12334 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12335 				cpu, map_key, cpu_buf->fd,
12336 				libbpf_strerror_r(err, msg, sizeof(msg)));
12337 			goto error;
12338 		}
12339 
12340 		pb->events[j].events = EPOLLIN;
12341 		pb->events[j].data.ptr = cpu_buf;
12342 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12343 			      &pb->events[j]) < 0) {
12344 			err = -errno;
12345 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12346 				cpu, cpu_buf->fd,
12347 				libbpf_strerror_r(err, msg, sizeof(msg)));
12348 			goto error;
12349 		}
12350 		j++;
12351 	}
12352 	pb->cpu_cnt = j;
12353 	free(online);
12354 
12355 	return pb;
12356 
12357 error:
12358 	free(online);
12359 	if (pb)
12360 		perf_buffer__free(pb);
12361 	return ERR_PTR(err);
12362 }
12363 
12364 struct perf_sample_raw {
12365 	struct perf_event_header header;
12366 	uint32_t size;
12367 	char data[];
12368 };
12369 
12370 struct perf_sample_lost {
12371 	struct perf_event_header header;
12372 	uint64_t id;
12373 	uint64_t lost;
12374 	uint64_t sample_id;
12375 };
12376 
12377 static enum bpf_perf_event_ret
perf_buffer__process_record(struct perf_event_header * e,void * ctx)12378 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12379 {
12380 	struct perf_cpu_buf *cpu_buf = ctx;
12381 	struct perf_buffer *pb = cpu_buf->pb;
12382 	void *data = e;
12383 
12384 	/* user wants full control over parsing perf event */
12385 	if (pb->event_cb)
12386 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12387 
12388 	switch (e->type) {
12389 	case PERF_RECORD_SAMPLE: {
12390 		struct perf_sample_raw *s = data;
12391 
12392 		if (pb->sample_cb)
12393 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12394 		break;
12395 	}
12396 	case PERF_RECORD_LOST: {
12397 		struct perf_sample_lost *s = data;
12398 
12399 		if (pb->lost_cb)
12400 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12401 		break;
12402 	}
12403 	default:
12404 		pr_warn("unknown perf sample type %d\n", e->type);
12405 		return LIBBPF_PERF_EVENT_ERROR;
12406 	}
12407 	return LIBBPF_PERF_EVENT_CONT;
12408 }
12409 
perf_buffer__process_records(struct perf_buffer * pb,struct perf_cpu_buf * cpu_buf)12410 static int perf_buffer__process_records(struct perf_buffer *pb,
12411 					struct perf_cpu_buf *cpu_buf)
12412 {
12413 	enum bpf_perf_event_ret ret;
12414 
12415 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12416 				     pb->page_size, &cpu_buf->buf,
12417 				     &cpu_buf->buf_size,
12418 				     perf_buffer__process_record, cpu_buf);
12419 	if (ret != LIBBPF_PERF_EVENT_CONT)
12420 		return ret;
12421 	return 0;
12422 }
12423 
perf_buffer__epoll_fd(const struct perf_buffer * pb)12424 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12425 {
12426 	return pb->epoll_fd;
12427 }
12428 
perf_buffer__poll(struct perf_buffer * pb,int timeout_ms)12429 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12430 {
12431 	int i, cnt, err;
12432 
12433 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12434 	if (cnt < 0)
12435 		return -errno;
12436 
12437 	for (i = 0; i < cnt; i++) {
12438 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12439 
12440 		err = perf_buffer__process_records(pb, cpu_buf);
12441 		if (err) {
12442 			pr_warn("error while processing records: %d\n", err);
12443 			return libbpf_err(err);
12444 		}
12445 	}
12446 	return cnt;
12447 }
12448 
12449 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12450  * manager.
12451  */
perf_buffer__buffer_cnt(const struct perf_buffer * pb)12452 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12453 {
12454 	return pb->cpu_cnt;
12455 }
12456 
12457 /*
12458  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12459  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12460  * select()/poll()/epoll() Linux syscalls.
12461  */
perf_buffer__buffer_fd(const struct perf_buffer * pb,size_t buf_idx)12462 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12463 {
12464 	struct perf_cpu_buf *cpu_buf;
12465 
12466 	if (buf_idx >= pb->cpu_cnt)
12467 		return libbpf_err(-EINVAL);
12468 
12469 	cpu_buf = pb->cpu_bufs[buf_idx];
12470 	if (!cpu_buf)
12471 		return libbpf_err(-ENOENT);
12472 
12473 	return cpu_buf->fd;
12474 }
12475 
12476 /*
12477  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12478  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12479  * consume, do nothing and return success.
12480  * Returns:
12481  *   - 0 on success;
12482  *   - <0 on failure.
12483  */
perf_buffer__consume_buffer(struct perf_buffer * pb,size_t buf_idx)12484 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12485 {
12486 	struct perf_cpu_buf *cpu_buf;
12487 
12488 	if (buf_idx >= pb->cpu_cnt)
12489 		return libbpf_err(-EINVAL);
12490 
12491 	cpu_buf = pb->cpu_bufs[buf_idx];
12492 	if (!cpu_buf)
12493 		return libbpf_err(-ENOENT);
12494 
12495 	return perf_buffer__process_records(pb, cpu_buf);
12496 }
12497 
perf_buffer__consume(struct perf_buffer * pb)12498 int perf_buffer__consume(struct perf_buffer *pb)
12499 {
12500 	int i, err;
12501 
12502 	for (i = 0; i < pb->cpu_cnt; i++) {
12503 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12504 
12505 		if (!cpu_buf)
12506 			continue;
12507 
12508 		err = perf_buffer__process_records(pb, cpu_buf);
12509 		if (err) {
12510 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12511 			return libbpf_err(err);
12512 		}
12513 	}
12514 	return 0;
12515 }
12516 
12517 struct bpf_prog_info_array_desc {
12518 	int	array_offset;	/* e.g. offset of jited_prog_insns */
12519 	int	count_offset;	/* e.g. offset of jited_prog_len */
12520 	int	size_offset;	/* > 0: offset of rec size,
12521 				 * < 0: fix size of -size_offset
12522 				 */
12523 };
12524 
12525 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
12526 	[BPF_PROG_INFO_JITED_INSNS] = {
12527 		offsetof(struct bpf_prog_info, jited_prog_insns),
12528 		offsetof(struct bpf_prog_info, jited_prog_len),
12529 		-1,
12530 	},
12531 	[BPF_PROG_INFO_XLATED_INSNS] = {
12532 		offsetof(struct bpf_prog_info, xlated_prog_insns),
12533 		offsetof(struct bpf_prog_info, xlated_prog_len),
12534 		-1,
12535 	},
12536 	[BPF_PROG_INFO_MAP_IDS] = {
12537 		offsetof(struct bpf_prog_info, map_ids),
12538 		offsetof(struct bpf_prog_info, nr_map_ids),
12539 		-(int)sizeof(__u32),
12540 	},
12541 	[BPF_PROG_INFO_JITED_KSYMS] = {
12542 		offsetof(struct bpf_prog_info, jited_ksyms),
12543 		offsetof(struct bpf_prog_info, nr_jited_ksyms),
12544 		-(int)sizeof(__u64),
12545 	},
12546 	[BPF_PROG_INFO_JITED_FUNC_LENS] = {
12547 		offsetof(struct bpf_prog_info, jited_func_lens),
12548 		offsetof(struct bpf_prog_info, nr_jited_func_lens),
12549 		-(int)sizeof(__u32),
12550 	},
12551 	[BPF_PROG_INFO_FUNC_INFO] = {
12552 		offsetof(struct bpf_prog_info, func_info),
12553 		offsetof(struct bpf_prog_info, nr_func_info),
12554 		offsetof(struct bpf_prog_info, func_info_rec_size),
12555 	},
12556 	[BPF_PROG_INFO_LINE_INFO] = {
12557 		offsetof(struct bpf_prog_info, line_info),
12558 		offsetof(struct bpf_prog_info, nr_line_info),
12559 		offsetof(struct bpf_prog_info, line_info_rec_size),
12560 	},
12561 	[BPF_PROG_INFO_JITED_LINE_INFO] = {
12562 		offsetof(struct bpf_prog_info, jited_line_info),
12563 		offsetof(struct bpf_prog_info, nr_jited_line_info),
12564 		offsetof(struct bpf_prog_info, jited_line_info_rec_size),
12565 	},
12566 	[BPF_PROG_INFO_PROG_TAGS] = {
12567 		offsetof(struct bpf_prog_info, prog_tags),
12568 		offsetof(struct bpf_prog_info, nr_prog_tags),
12569 		-(int)sizeof(__u8) * BPF_TAG_SIZE,
12570 	},
12571 
12572 };
12573 
bpf_prog_info_read_offset_u32(struct bpf_prog_info * info,int offset)12574 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
12575 					   int offset)
12576 {
12577 	__u32 *array = (__u32 *)info;
12578 
12579 	if (offset >= 0)
12580 		return array[offset / sizeof(__u32)];
12581 	return -(int)offset;
12582 }
12583 
bpf_prog_info_read_offset_u64(struct bpf_prog_info * info,int offset)12584 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
12585 					   int offset)
12586 {
12587 	__u64 *array = (__u64 *)info;
12588 
12589 	if (offset >= 0)
12590 		return array[offset / sizeof(__u64)];
12591 	return -(int)offset;
12592 }
12593 
bpf_prog_info_set_offset_u32(struct bpf_prog_info * info,int offset,__u32 val)12594 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
12595 					 __u32 val)
12596 {
12597 	__u32 *array = (__u32 *)info;
12598 
12599 	if (offset >= 0)
12600 		array[offset / sizeof(__u32)] = val;
12601 }
12602 
bpf_prog_info_set_offset_u64(struct bpf_prog_info * info,int offset,__u64 val)12603 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
12604 					 __u64 val)
12605 {
12606 	__u64 *array = (__u64 *)info;
12607 
12608 	if (offset >= 0)
12609 		array[offset / sizeof(__u64)] = val;
12610 }
12611 
12612 struct bpf_prog_info_linear *
bpf_program__get_prog_info_linear(int fd,__u64 arrays)12613 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
12614 {
12615 	struct bpf_prog_info_linear *info_linear;
12616 	struct bpf_prog_info info = {};
12617 	__u32 info_len = sizeof(info);
12618 	__u32 data_len = 0;
12619 	int i, err;
12620 	void *ptr;
12621 
12622 	if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
12623 		return libbpf_err_ptr(-EINVAL);
12624 
12625 	/* step 1: get array dimensions */
12626 	err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
12627 	if (err) {
12628 		pr_debug("can't get prog info: %s", strerror(errno));
12629 		return libbpf_err_ptr(-EFAULT);
12630 	}
12631 
12632 	/* step 2: calculate total size of all arrays */
12633 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12634 		bool include_array = (arrays & (1UL << i)) > 0;
12635 		struct bpf_prog_info_array_desc *desc;
12636 		__u32 count, size;
12637 
12638 		desc = bpf_prog_info_array_desc + i;
12639 
12640 		/* kernel is too old to support this field */
12641 		if (info_len < desc->array_offset + sizeof(__u32) ||
12642 		    info_len < desc->count_offset + sizeof(__u32) ||
12643 		    (desc->size_offset > 0 && info_len < desc->size_offset))
12644 			include_array = false;
12645 
12646 		if (!include_array) {
12647 			arrays &= ~(1UL << i);	/* clear the bit */
12648 			continue;
12649 		}
12650 
12651 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12652 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12653 
12654 		data_len += count * size;
12655 	}
12656 
12657 	/* step 3: allocate continuous memory */
12658 	data_len = roundup(data_len, sizeof(__u64));
12659 	info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
12660 	if (!info_linear)
12661 		return libbpf_err_ptr(-ENOMEM);
12662 
12663 	/* step 4: fill data to info_linear->info */
12664 	info_linear->arrays = arrays;
12665 	memset(&info_linear->info, 0, sizeof(info));
12666 	ptr = info_linear->data;
12667 
12668 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12669 		struct bpf_prog_info_array_desc *desc;
12670 		__u32 count, size;
12671 
12672 		if ((arrays & (1UL << i)) == 0)
12673 			continue;
12674 
12675 		desc  = bpf_prog_info_array_desc + i;
12676 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12677 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12678 		bpf_prog_info_set_offset_u32(&info_linear->info,
12679 					     desc->count_offset, count);
12680 		bpf_prog_info_set_offset_u32(&info_linear->info,
12681 					     desc->size_offset, size);
12682 		bpf_prog_info_set_offset_u64(&info_linear->info,
12683 					     desc->array_offset,
12684 					     ptr_to_u64(ptr));
12685 		ptr += count * size;
12686 	}
12687 
12688 	/* step 5: call syscall again to get required arrays */
12689 	err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
12690 	if (err) {
12691 		pr_debug("can't get prog info: %s", strerror(errno));
12692 		free(info_linear);
12693 		return libbpf_err_ptr(-EFAULT);
12694 	}
12695 
12696 	/* step 6: verify the data */
12697 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12698 		struct bpf_prog_info_array_desc *desc;
12699 		__u32 v1, v2;
12700 
12701 		if ((arrays & (1UL << i)) == 0)
12702 			continue;
12703 
12704 		desc = bpf_prog_info_array_desc + i;
12705 		v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12706 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12707 						   desc->count_offset);
12708 		if (v1 != v2)
12709 			pr_warn("%s: mismatch in element count\n", __func__);
12710 
12711 		v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12712 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12713 						   desc->size_offset);
12714 		if (v1 != v2)
12715 			pr_warn("%s: mismatch in rec size\n", __func__);
12716 	}
12717 
12718 	/* step 7: update info_len and data_len */
12719 	info_linear->info_len = sizeof(struct bpf_prog_info);
12720 	info_linear->data_len = data_len;
12721 
12722 	return info_linear;
12723 }
12724 
bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear * info_linear)12725 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
12726 {
12727 	int i;
12728 
12729 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12730 		struct bpf_prog_info_array_desc *desc;
12731 		__u64 addr, offs;
12732 
12733 		if ((info_linear->arrays & (1UL << i)) == 0)
12734 			continue;
12735 
12736 		desc = bpf_prog_info_array_desc + i;
12737 		addr = bpf_prog_info_read_offset_u64(&info_linear->info,
12738 						     desc->array_offset);
12739 		offs = addr - ptr_to_u64(info_linear->data);
12740 		bpf_prog_info_set_offset_u64(&info_linear->info,
12741 					     desc->array_offset, offs);
12742 	}
12743 }
12744 
bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear * info_linear)12745 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
12746 {
12747 	int i;
12748 
12749 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12750 		struct bpf_prog_info_array_desc *desc;
12751 		__u64 addr, offs;
12752 
12753 		if ((info_linear->arrays & (1UL << i)) == 0)
12754 			continue;
12755 
12756 		desc = bpf_prog_info_array_desc + i;
12757 		offs = bpf_prog_info_read_offset_u64(&info_linear->info,
12758 						     desc->array_offset);
12759 		addr = offs + ptr_to_u64(info_linear->data);
12760 		bpf_prog_info_set_offset_u64(&info_linear->info,
12761 					     desc->array_offset, addr);
12762 	}
12763 }
12764 
bpf_program__set_attach_target(struct bpf_program * prog,int attach_prog_fd,const char * attach_func_name)12765 int bpf_program__set_attach_target(struct bpf_program *prog,
12766 				   int attach_prog_fd,
12767 				   const char *attach_func_name)
12768 {
12769 	int btf_obj_fd = 0, btf_id = 0, err;
12770 
12771 	if (!prog || attach_prog_fd < 0)
12772 		return libbpf_err(-EINVAL);
12773 
12774 	if (prog->obj->loaded)
12775 		return libbpf_err(-EINVAL);
12776 
12777 	if (attach_prog_fd && !attach_func_name) {
12778 		/* remember attach_prog_fd and let bpf_program__load() find
12779 		 * BTF ID during the program load
12780 		 */
12781 		prog->attach_prog_fd = attach_prog_fd;
12782 		return 0;
12783 	}
12784 
12785 	if (attach_prog_fd) {
12786 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12787 						 attach_prog_fd);
12788 		if (btf_id < 0)
12789 			return libbpf_err(btf_id);
12790 	} else {
12791 		if (!attach_func_name)
12792 			return libbpf_err(-EINVAL);
12793 
12794 		/* load btf_vmlinux, if not yet */
12795 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12796 		if (err)
12797 			return libbpf_err(err);
12798 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12799 					 prog->expected_attach_type,
12800 					 &btf_obj_fd, &btf_id);
12801 		if (err)
12802 			return libbpf_err(err);
12803 	}
12804 
12805 	prog->attach_btf_id = btf_id;
12806 	prog->attach_btf_obj_fd = btf_obj_fd;
12807 	prog->attach_prog_fd = attach_prog_fd;
12808 	return 0;
12809 }
12810 
parse_cpu_mask_str(const char * s,bool ** mask,int * mask_sz)12811 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12812 {
12813 	int err = 0, n, len, start, end = -1;
12814 	bool *tmp;
12815 
12816 	*mask = NULL;
12817 	*mask_sz = 0;
12818 
12819 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12820 	while (*s) {
12821 		if (*s == ',' || *s == '\n') {
12822 			s++;
12823 			continue;
12824 		}
12825 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12826 		if (n <= 0 || n > 2) {
12827 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12828 			err = -EINVAL;
12829 			goto cleanup;
12830 		} else if (n == 1) {
12831 			end = start;
12832 		}
12833 		if (start < 0 || start > end) {
12834 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12835 				start, end, s);
12836 			err = -EINVAL;
12837 			goto cleanup;
12838 		}
12839 		tmp = realloc(*mask, end + 1);
12840 		if (!tmp) {
12841 			err = -ENOMEM;
12842 			goto cleanup;
12843 		}
12844 		*mask = tmp;
12845 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12846 		memset(tmp + start, 1, end - start + 1);
12847 		*mask_sz = end + 1;
12848 		s += len;
12849 	}
12850 	if (!*mask_sz) {
12851 		pr_warn("Empty CPU range\n");
12852 		return -EINVAL;
12853 	}
12854 	return 0;
12855 cleanup:
12856 	free(*mask);
12857 	*mask = NULL;
12858 	return err;
12859 }
12860 
parse_cpu_mask_file(const char * fcpu,bool ** mask,int * mask_sz)12861 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12862 {
12863 	int fd, err = 0, len;
12864 	char buf[128];
12865 
12866 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12867 	if (fd < 0) {
12868 		err = -errno;
12869 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12870 		return err;
12871 	}
12872 	len = read(fd, buf, sizeof(buf));
12873 	close(fd);
12874 	if (len <= 0) {
12875 		err = len ? -errno : -EINVAL;
12876 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12877 		return err;
12878 	}
12879 	if (len >= sizeof(buf)) {
12880 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12881 		return -E2BIG;
12882 	}
12883 	buf[len] = '\0';
12884 
12885 	return parse_cpu_mask_str(buf, mask, mask_sz);
12886 }
12887 
libbpf_num_possible_cpus(void)12888 int libbpf_num_possible_cpus(void)
12889 {
12890 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12891 	static int cpus;
12892 	int err, n, i, tmp_cpus;
12893 	bool *mask;
12894 
12895 	tmp_cpus = READ_ONCE(cpus);
12896 	if (tmp_cpus > 0)
12897 		return tmp_cpus;
12898 
12899 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12900 	if (err)
12901 		return libbpf_err(err);
12902 
12903 	tmp_cpus = 0;
12904 	for (i = 0; i < n; i++) {
12905 		if (mask[i])
12906 			tmp_cpus++;
12907 	}
12908 	free(mask);
12909 
12910 	WRITE_ONCE(cpus, tmp_cpus);
12911 	return tmp_cpus;
12912 }
12913 
populate_skeleton_maps(const struct bpf_object * obj,struct bpf_map_skeleton * maps,size_t map_cnt)12914 static int populate_skeleton_maps(const struct bpf_object *obj,
12915 				  struct bpf_map_skeleton *maps,
12916 				  size_t map_cnt)
12917 {
12918 	int i;
12919 
12920 	for (i = 0; i < map_cnt; i++) {
12921 		struct bpf_map **map = maps[i].map;
12922 		const char *name = maps[i].name;
12923 		void **mmaped = maps[i].mmaped;
12924 
12925 		*map = bpf_object__find_map_by_name(obj, name);
12926 		if (!*map) {
12927 			pr_warn("failed to find skeleton map '%s'\n", name);
12928 			return -ESRCH;
12929 		}
12930 
12931 		/* externs shouldn't be pre-setup from user code */
12932 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12933 			*mmaped = (*map)->mmaped;
12934 	}
12935 	return 0;
12936 }
12937 
populate_skeleton_progs(const struct bpf_object * obj,struct bpf_prog_skeleton * progs,size_t prog_cnt)12938 static int populate_skeleton_progs(const struct bpf_object *obj,
12939 				   struct bpf_prog_skeleton *progs,
12940 				   size_t prog_cnt)
12941 {
12942 	int i;
12943 
12944 	for (i = 0; i < prog_cnt; i++) {
12945 		struct bpf_program **prog = progs[i].prog;
12946 		const char *name = progs[i].name;
12947 
12948 		*prog = bpf_object__find_program_by_name(obj, name);
12949 		if (!*prog) {
12950 			pr_warn("failed to find skeleton program '%s'\n", name);
12951 			return -ESRCH;
12952 		}
12953 	}
12954 	return 0;
12955 }
12956 
bpf_object__open_skeleton(struct bpf_object_skeleton * s,const struct bpf_object_open_opts * opts)12957 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12958 			      const struct bpf_object_open_opts *opts)
12959 {
12960 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12961 		.object_name = s->name,
12962 	);
12963 	struct bpf_object *obj;
12964 	int err;
12965 
12966 	/* Attempt to preserve opts->object_name, unless overriden by user
12967 	 * explicitly. Overwriting object name for skeletons is discouraged,
12968 	 * as it breaks global data maps, because they contain object name
12969 	 * prefix as their own map name prefix. When skeleton is generated,
12970 	 * bpftool is making an assumption that this name will stay the same.
12971 	 */
12972 	if (opts) {
12973 		memcpy(&skel_opts, opts, sizeof(*opts));
12974 		if (!opts->object_name)
12975 			skel_opts.object_name = s->name;
12976 	}
12977 
12978 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12979 	err = libbpf_get_error(obj);
12980 	if (err) {
12981 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12982 			s->name, err);
12983 		return libbpf_err(err);
12984 	}
12985 
12986 	*s->obj = obj;
12987 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12988 	if (err) {
12989 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12990 		return libbpf_err(err);
12991 	}
12992 
12993 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12994 	if (err) {
12995 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12996 		return libbpf_err(err);
12997 	}
12998 
12999 	return 0;
13000 }
13001 
bpf_object__open_subskeleton(struct bpf_object_subskeleton * s)13002 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13003 {
13004 	int err, len, var_idx, i;
13005 	const char *var_name;
13006 	const struct bpf_map *map;
13007 	struct btf *btf;
13008 	__u32 map_type_id;
13009 	const struct btf_type *map_type, *var_type;
13010 	const struct bpf_var_skeleton *var_skel;
13011 	struct btf_var_secinfo *var;
13012 
13013 	if (!s->obj)
13014 		return libbpf_err(-EINVAL);
13015 
13016 	btf = bpf_object__btf(s->obj);
13017 	if (!btf) {
13018 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13019 		        bpf_object__name(s->obj));
13020 		return libbpf_err(-errno);
13021 	}
13022 
13023 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13024 	if (err) {
13025 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13026 		return libbpf_err(err);
13027 	}
13028 
13029 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13030 	if (err) {
13031 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13032 		return libbpf_err(err);
13033 	}
13034 
13035 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13036 		var_skel = &s->vars[var_idx];
13037 		map = *var_skel->map;
13038 		map_type_id = bpf_map__btf_value_type_id(map);
13039 		map_type = btf__type_by_id(btf, map_type_id);
13040 
13041 		if (!btf_is_datasec(map_type)) {
13042 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13043 				bpf_map__name(map),
13044 				__btf_kind_str(btf_kind(map_type)));
13045 			return libbpf_err(-EINVAL);
13046 		}
13047 
13048 		len = btf_vlen(map_type);
13049 		var = btf_var_secinfos(map_type);
13050 		for (i = 0; i < len; i++, var++) {
13051 			var_type = btf__type_by_id(btf, var->type);
13052 			var_name = btf__name_by_offset(btf, var_type->name_off);
13053 			if (strcmp(var_name, var_skel->name) == 0) {
13054 				*var_skel->addr = map->mmaped + var->offset;
13055 				break;
13056 			}
13057 		}
13058 	}
13059 	return 0;
13060 }
13061 
bpf_object__destroy_subskeleton(struct bpf_object_subskeleton * s)13062 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13063 {
13064 	if (!s)
13065 		return;
13066 	free(s->maps);
13067 	free(s->progs);
13068 	free(s->vars);
13069 	free(s);
13070 }
13071 
bpf_object__load_skeleton(struct bpf_object_skeleton * s)13072 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13073 {
13074 	int i, err;
13075 
13076 	err = bpf_object__load(*s->obj);
13077 	if (err) {
13078 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13079 		return libbpf_err(err);
13080 	}
13081 
13082 	for (i = 0; i < s->map_cnt; i++) {
13083 		struct bpf_map *map = *s->maps[i].map;
13084 		size_t mmap_sz = bpf_map_mmap_sz(map);
13085 		int prot, map_fd = bpf_map__fd(map);
13086 		void **mmaped = s->maps[i].mmaped;
13087 
13088 		if (!mmaped)
13089 			continue;
13090 
13091 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13092 			*mmaped = NULL;
13093 			continue;
13094 		}
13095 
13096 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13097 			prot = PROT_READ;
13098 		else
13099 			prot = PROT_READ | PROT_WRITE;
13100 
13101 		/* Remap anonymous mmap()-ed "map initialization image" as
13102 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13103 		 * memory address. This will cause kernel to change process'
13104 		 * page table to point to a different piece of kernel memory,
13105 		 * but from userspace point of view memory address (and its
13106 		 * contents, being identical at this point) will stay the
13107 		 * same. This mapping will be released by bpf_object__close()
13108 		 * as per normal clean up procedure, so we don't need to worry
13109 		 * about it from skeleton's clean up perspective.
13110 		 */
13111 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
13112 				MAP_SHARED | MAP_FIXED, map_fd, 0);
13113 		if (*mmaped == MAP_FAILED) {
13114 			err = -errno;
13115 			*mmaped = NULL;
13116 			pr_warn("failed to re-mmap() map '%s': %d\n",
13117 				 bpf_map__name(map), err);
13118 			return libbpf_err(err);
13119 		}
13120 	}
13121 
13122 	return 0;
13123 }
13124 
bpf_object__attach_skeleton(struct bpf_object_skeleton * s)13125 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13126 {
13127 	int i, err;
13128 
13129 	for (i = 0; i < s->prog_cnt; i++) {
13130 		struct bpf_program *prog = *s->progs[i].prog;
13131 		struct bpf_link **link = s->progs[i].link;
13132 
13133 		if (!prog->autoload)
13134 			continue;
13135 
13136 		/* auto-attaching not supported for this program */
13137 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13138 			continue;
13139 
13140 		/* if user already set the link manually, don't attempt auto-attach */
13141 		if (*link)
13142 			continue;
13143 
13144 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13145 		if (err) {
13146 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13147 				bpf_program__name(prog), err);
13148 			return libbpf_err(err);
13149 		}
13150 
13151 		/* It's possible that for some SEC() definitions auto-attach
13152 		 * is supported in some cases (e.g., if definition completely
13153 		 * specifies target information), but is not in other cases.
13154 		 * SEC("uprobe") is one such case. If user specified target
13155 		 * binary and function name, such BPF program can be
13156 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13157 		 * attach to fail. It should just be skipped.
13158 		 * attach_fn signals such case with returning 0 (no error) and
13159 		 * setting link to NULL.
13160 		 */
13161 	}
13162 
13163 	return 0;
13164 }
13165 
bpf_object__detach_skeleton(struct bpf_object_skeleton * s)13166 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13167 {
13168 	int i;
13169 
13170 	for (i = 0; i < s->prog_cnt; i++) {
13171 		struct bpf_link **link = s->progs[i].link;
13172 
13173 		bpf_link__destroy(*link);
13174 		*link = NULL;
13175 	}
13176 }
13177 
bpf_object__destroy_skeleton(struct bpf_object_skeleton * s)13178 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13179 {
13180 	if (!s)
13181 		return;
13182 
13183 	if (s->progs)
13184 		bpf_object__detach_skeleton(s);
13185 	if (s->obj)
13186 		bpf_object__close(*s->obj);
13187 	free(s->maps);
13188 	free(s->progs);
13189 	free(s);
13190 }
13191