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