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