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