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