xref: /linux/tools/lib/bpf/libbpf.c (revision eb63cfcd2ee8ec3805f6881f43341f589c3d2278)
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 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 static int bpf_object__sanitize_maps(struct bpf_object *obj)
6695 {
6696 	struct bpf_map *m;
6697 
6698 	bpf_object__for_each_map(m, obj) {
6699 		if (!bpf_map__is_internal(m))
6700 			continue;
6701 		if (!kernel_supports(obj, FEAT_GLOBAL_DATA)) {
6702 			pr_warn("kernel doesn't support global data\n");
6703 			return -ENOTSUP;
6704 		}
6705 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
6706 			m->def.map_flags ^= BPF_F_MMAPABLE;
6707 	}
6708 
6709 	return 0;
6710 }
6711 
6712 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
6713 {
6714 	char sym_type, sym_name[500];
6715 	unsigned long long sym_addr;
6716 	const struct btf_type *t;
6717 	struct extern_desc *ext;
6718 	int ret, err = 0;
6719 	FILE *f;
6720 
6721 	f = fopen("/proc/kallsyms", "r");
6722 	if (!f) {
6723 		err = -errno;
6724 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
6725 		return err;
6726 	}
6727 
6728 	while (true) {
6729 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
6730 			     &sym_addr, &sym_type, sym_name);
6731 		if (ret == EOF && feof(f))
6732 			break;
6733 		if (ret != 3) {
6734 			pr_warn("failed to read kallsyms entry: %d\n", ret);
6735 			err = -EINVAL;
6736 			goto out;
6737 		}
6738 
6739 		ext = find_extern_by_name(obj, sym_name);
6740 		if (!ext || ext->type != EXT_KSYM)
6741 			continue;
6742 
6743 		t = btf__type_by_id(obj->btf, ext->btf_id);
6744 		if (!btf_is_var(t))
6745 			continue;
6746 
6747 		if (ext->is_set && ext->ksym.addr != sym_addr) {
6748 			pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
6749 				sym_name, ext->ksym.addr, sym_addr);
6750 			err = -EINVAL;
6751 			goto out;
6752 		}
6753 		if (!ext->is_set) {
6754 			ext->is_set = true;
6755 			ext->ksym.addr = sym_addr;
6756 			pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
6757 		}
6758 	}
6759 
6760 out:
6761 	fclose(f);
6762 	return err;
6763 }
6764 
6765 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
6766 			    __u16 kind, struct btf **res_btf,
6767 			    struct module_btf **res_mod_btf)
6768 {
6769 	struct module_btf *mod_btf;
6770 	struct btf *btf;
6771 	int i, id, err;
6772 
6773 	btf = obj->btf_vmlinux;
6774 	mod_btf = NULL;
6775 	id = btf__find_by_name_kind(btf, ksym_name, kind);
6776 
6777 	if (id == -ENOENT) {
6778 		err = load_module_btfs(obj);
6779 		if (err)
6780 			return err;
6781 
6782 		for (i = 0; i < obj->btf_module_cnt; i++) {
6783 			/* we assume module_btf's BTF FD is always >0 */
6784 			mod_btf = &obj->btf_modules[i];
6785 			btf = mod_btf->btf;
6786 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
6787 			if (id != -ENOENT)
6788 				break;
6789 		}
6790 	}
6791 	if (id <= 0)
6792 		return -ESRCH;
6793 
6794 	*res_btf = btf;
6795 	*res_mod_btf = mod_btf;
6796 	return id;
6797 }
6798 
6799 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
6800 					       struct extern_desc *ext)
6801 {
6802 	const struct btf_type *targ_var, *targ_type;
6803 	__u32 targ_type_id, local_type_id;
6804 	struct module_btf *mod_btf = NULL;
6805 	const char *targ_var_name;
6806 	struct btf *btf = NULL;
6807 	int id, err;
6808 
6809 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
6810 	if (id < 0) {
6811 		if (id == -ESRCH && ext->is_weak)
6812 			return 0;
6813 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
6814 			ext->name);
6815 		return id;
6816 	}
6817 
6818 	/* find local type_id */
6819 	local_type_id = ext->ksym.type_id;
6820 
6821 	/* find target type_id */
6822 	targ_var = btf__type_by_id(btf, id);
6823 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
6824 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
6825 
6826 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
6827 					btf, targ_type_id);
6828 	if (err <= 0) {
6829 		const struct btf_type *local_type;
6830 		const char *targ_name, *local_name;
6831 
6832 		local_type = btf__type_by_id(obj->btf, local_type_id);
6833 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
6834 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
6835 
6836 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
6837 			ext->name, local_type_id,
6838 			btf_kind_str(local_type), local_name, targ_type_id,
6839 			btf_kind_str(targ_type), targ_name);
6840 		return -EINVAL;
6841 	}
6842 
6843 	ext->is_set = true;
6844 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
6845 	ext->ksym.kernel_btf_id = id;
6846 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
6847 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
6848 
6849 	return 0;
6850 }
6851 
6852 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
6853 						struct extern_desc *ext)
6854 {
6855 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
6856 	struct module_btf *mod_btf = NULL;
6857 	const struct btf_type *kern_func;
6858 	struct btf *kern_btf = NULL;
6859 	int ret;
6860 
6861 	local_func_proto_id = ext->ksym.type_id;
6862 
6863 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
6864 	if (kfunc_id < 0) {
6865 		if (kfunc_id == -ESRCH && ext->is_weak)
6866 			return 0;
6867 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
6868 			ext->name);
6869 		return kfunc_id;
6870 	}
6871 
6872 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
6873 	kfunc_proto_id = kern_func->type;
6874 
6875 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
6876 					kern_btf, kfunc_proto_id);
6877 	if (ret <= 0) {
6878 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
6879 			ext->name, local_func_proto_id, kfunc_proto_id);
6880 		return -EINVAL;
6881 	}
6882 
6883 	/* set index for module BTF fd in fd_array, if unset */
6884 	if (mod_btf && !mod_btf->fd_array_idx) {
6885 		/* insn->off is s16 */
6886 		if (obj->fd_array_cnt == INT16_MAX) {
6887 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
6888 				ext->name, mod_btf->fd_array_idx);
6889 			return -E2BIG;
6890 		}
6891 		/* Cannot use index 0 for module BTF fd */
6892 		if (!obj->fd_array_cnt)
6893 			obj->fd_array_cnt = 1;
6894 
6895 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
6896 					obj->fd_array_cnt + 1);
6897 		if (ret)
6898 			return ret;
6899 		mod_btf->fd_array_idx = obj->fd_array_cnt;
6900 		/* we assume module BTF FD is always >0 */
6901 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
6902 	}
6903 
6904 	ext->is_set = true;
6905 	ext->ksym.kernel_btf_id = kfunc_id;
6906 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
6907 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
6908 		 ext->name, kfunc_id);
6909 
6910 	return 0;
6911 }
6912 
6913 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
6914 {
6915 	const struct btf_type *t;
6916 	struct extern_desc *ext;
6917 	int i, err;
6918 
6919 	for (i = 0; i < obj->nr_extern; i++) {
6920 		ext = &obj->externs[i];
6921 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
6922 			continue;
6923 
6924 		if (obj->gen_loader) {
6925 			ext->is_set = true;
6926 			ext->ksym.kernel_btf_obj_fd = 0;
6927 			ext->ksym.kernel_btf_id = 0;
6928 			continue;
6929 		}
6930 		t = btf__type_by_id(obj->btf, ext->btf_id);
6931 		if (btf_is_var(t))
6932 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
6933 		else
6934 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
6935 		if (err)
6936 			return err;
6937 	}
6938 	return 0;
6939 }
6940 
6941 static int bpf_object__resolve_externs(struct bpf_object *obj,
6942 				       const char *extra_kconfig)
6943 {
6944 	bool need_config = false, need_kallsyms = false;
6945 	bool need_vmlinux_btf = false;
6946 	struct extern_desc *ext;
6947 	void *kcfg_data = NULL;
6948 	int err, i;
6949 
6950 	if (obj->nr_extern == 0)
6951 		return 0;
6952 
6953 	if (obj->kconfig_map_idx >= 0)
6954 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
6955 
6956 	for (i = 0; i < obj->nr_extern; i++) {
6957 		ext = &obj->externs[i];
6958 
6959 		if (ext->type == EXT_KCFG &&
6960 		    strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
6961 			void *ext_val = kcfg_data + ext->kcfg.data_off;
6962 			__u32 kver = get_kernel_version();
6963 
6964 			if (!kver) {
6965 				pr_warn("failed to get kernel version\n");
6966 				return -EINVAL;
6967 			}
6968 			err = set_kcfg_value_num(ext, ext_val, kver);
6969 			if (err)
6970 				return err;
6971 			pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
6972 		} else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
6973 			need_config = true;
6974 		} else if (ext->type == EXT_KSYM) {
6975 			if (ext->ksym.type_id)
6976 				need_vmlinux_btf = true;
6977 			else
6978 				need_kallsyms = true;
6979 		} else {
6980 			pr_warn("unrecognized extern '%s'\n", ext->name);
6981 			return -EINVAL;
6982 		}
6983 	}
6984 	if (need_config && extra_kconfig) {
6985 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
6986 		if (err)
6987 			return -EINVAL;
6988 		need_config = false;
6989 		for (i = 0; i < obj->nr_extern; i++) {
6990 			ext = &obj->externs[i];
6991 			if (ext->type == EXT_KCFG && !ext->is_set) {
6992 				need_config = true;
6993 				break;
6994 			}
6995 		}
6996 	}
6997 	if (need_config) {
6998 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
6999 		if (err)
7000 			return -EINVAL;
7001 	}
7002 	if (need_kallsyms) {
7003 		err = bpf_object__read_kallsyms_file(obj);
7004 		if (err)
7005 			return -EINVAL;
7006 	}
7007 	if (need_vmlinux_btf) {
7008 		err = bpf_object__resolve_ksyms_btf_id(obj);
7009 		if (err)
7010 			return -EINVAL;
7011 	}
7012 	for (i = 0; i < obj->nr_extern; i++) {
7013 		ext = &obj->externs[i];
7014 
7015 		if (!ext->is_set && !ext->is_weak) {
7016 			pr_warn("extern %s (strong) not resolved\n", ext->name);
7017 			return -ESRCH;
7018 		} else if (!ext->is_set) {
7019 			pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7020 				 ext->name);
7021 		}
7022 	}
7023 
7024 	return 0;
7025 }
7026 
7027 int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
7028 {
7029 	struct bpf_object *obj;
7030 	int err, i;
7031 
7032 	if (!attr)
7033 		return libbpf_err(-EINVAL);
7034 	obj = attr->obj;
7035 	if (!obj)
7036 		return libbpf_err(-EINVAL);
7037 
7038 	if (obj->loaded) {
7039 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7040 		return libbpf_err(-EINVAL);
7041 	}
7042 
7043 	if (obj->gen_loader)
7044 		bpf_gen__init(obj->gen_loader, attr->log_level);
7045 
7046 	err = bpf_object__probe_loading(obj);
7047 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7048 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7049 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7050 	err = err ? : bpf_object__sanitize_maps(obj);
7051 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7052 	err = err ? : bpf_object__create_maps(obj);
7053 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : attr->target_btf_path);
7054 	err = err ? : bpf_object__load_progs(obj, attr->log_level);
7055 
7056 	if (obj->gen_loader) {
7057 		/* reset FDs */
7058 		btf__set_fd(obj->btf, -1);
7059 		for (i = 0; i < obj->nr_maps; i++)
7060 			obj->maps[i].fd = -1;
7061 		if (!err)
7062 			err = bpf_gen__finish(obj->gen_loader);
7063 	}
7064 
7065 	/* clean up fd_array */
7066 	zfree(&obj->fd_array);
7067 
7068 	/* clean up module BTFs */
7069 	for (i = 0; i < obj->btf_module_cnt; i++) {
7070 		close(obj->btf_modules[i].fd);
7071 		btf__free(obj->btf_modules[i].btf);
7072 		free(obj->btf_modules[i].name);
7073 	}
7074 	free(obj->btf_modules);
7075 
7076 	/* clean up vmlinux BTF */
7077 	btf__free(obj->btf_vmlinux);
7078 	obj->btf_vmlinux = NULL;
7079 
7080 	obj->loaded = true; /* doesn't matter if successfully or not */
7081 
7082 	if (err)
7083 		goto out;
7084 
7085 	return 0;
7086 out:
7087 	/* unpin any maps that were auto-pinned during load */
7088 	for (i = 0; i < obj->nr_maps; i++)
7089 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7090 			bpf_map__unpin(&obj->maps[i], NULL);
7091 
7092 	bpf_object__unload(obj);
7093 	pr_warn("failed to load object '%s'\n", obj->path);
7094 	return libbpf_err(err);
7095 }
7096 
7097 int bpf_object__load(struct bpf_object *obj)
7098 {
7099 	struct bpf_object_load_attr attr = {
7100 		.obj = obj,
7101 	};
7102 
7103 	return bpf_object__load_xattr(&attr);
7104 }
7105 
7106 static int make_parent_dir(const char *path)
7107 {
7108 	char *cp, errmsg[STRERR_BUFSIZE];
7109 	char *dname, *dir;
7110 	int err = 0;
7111 
7112 	dname = strdup(path);
7113 	if (dname == NULL)
7114 		return -ENOMEM;
7115 
7116 	dir = dirname(dname);
7117 	if (mkdir(dir, 0700) && errno != EEXIST)
7118 		err = -errno;
7119 
7120 	free(dname);
7121 	if (err) {
7122 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7123 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7124 	}
7125 	return err;
7126 }
7127 
7128 static int check_path(const char *path)
7129 {
7130 	char *cp, errmsg[STRERR_BUFSIZE];
7131 	struct statfs st_fs;
7132 	char *dname, *dir;
7133 	int err = 0;
7134 
7135 	if (path == NULL)
7136 		return -EINVAL;
7137 
7138 	dname = strdup(path);
7139 	if (dname == NULL)
7140 		return -ENOMEM;
7141 
7142 	dir = dirname(dname);
7143 	if (statfs(dir, &st_fs)) {
7144 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7145 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7146 		err = -errno;
7147 	}
7148 	free(dname);
7149 
7150 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7151 		pr_warn("specified path %s is not on BPF FS\n", path);
7152 		err = -EINVAL;
7153 	}
7154 
7155 	return err;
7156 }
7157 
7158 int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
7159 			      int instance)
7160 {
7161 	char *cp, errmsg[STRERR_BUFSIZE];
7162 	int err;
7163 
7164 	err = make_parent_dir(path);
7165 	if (err)
7166 		return libbpf_err(err);
7167 
7168 	err = check_path(path);
7169 	if (err)
7170 		return libbpf_err(err);
7171 
7172 	if (prog == NULL) {
7173 		pr_warn("invalid program pointer\n");
7174 		return libbpf_err(-EINVAL);
7175 	}
7176 
7177 	if (instance < 0 || instance >= prog->instances.nr) {
7178 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7179 			instance, prog->name, prog->instances.nr);
7180 		return libbpf_err(-EINVAL);
7181 	}
7182 
7183 	if (bpf_obj_pin(prog->instances.fds[instance], path)) {
7184 		err = -errno;
7185 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7186 		pr_warn("failed to pin program: %s\n", cp);
7187 		return libbpf_err(err);
7188 	}
7189 	pr_debug("pinned program '%s'\n", path);
7190 
7191 	return 0;
7192 }
7193 
7194 int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
7195 				int instance)
7196 {
7197 	int err;
7198 
7199 	err = check_path(path);
7200 	if (err)
7201 		return libbpf_err(err);
7202 
7203 	if (prog == NULL) {
7204 		pr_warn("invalid program pointer\n");
7205 		return libbpf_err(-EINVAL);
7206 	}
7207 
7208 	if (instance < 0 || instance >= prog->instances.nr) {
7209 		pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7210 			instance, prog->name, prog->instances.nr);
7211 		return libbpf_err(-EINVAL);
7212 	}
7213 
7214 	err = unlink(path);
7215 	if (err != 0)
7216 		return libbpf_err(-errno);
7217 
7218 	pr_debug("unpinned program '%s'\n", path);
7219 
7220 	return 0;
7221 }
7222 
7223 int bpf_program__pin(struct bpf_program *prog, const char *path)
7224 {
7225 	int i, err;
7226 
7227 	err = make_parent_dir(path);
7228 	if (err)
7229 		return libbpf_err(err);
7230 
7231 	err = check_path(path);
7232 	if (err)
7233 		return libbpf_err(err);
7234 
7235 	if (prog == NULL) {
7236 		pr_warn("invalid program pointer\n");
7237 		return libbpf_err(-EINVAL);
7238 	}
7239 
7240 	if (prog->instances.nr <= 0) {
7241 		pr_warn("no instances of prog %s to pin\n", prog->name);
7242 		return libbpf_err(-EINVAL);
7243 	}
7244 
7245 	if (prog->instances.nr == 1) {
7246 		/* don't create subdirs when pinning single instance */
7247 		return bpf_program__pin_instance(prog, path, 0);
7248 	}
7249 
7250 	for (i = 0; i < prog->instances.nr; i++) {
7251 		char buf[PATH_MAX];
7252 		int len;
7253 
7254 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7255 		if (len < 0) {
7256 			err = -EINVAL;
7257 			goto err_unpin;
7258 		} else if (len >= PATH_MAX) {
7259 			err = -ENAMETOOLONG;
7260 			goto err_unpin;
7261 		}
7262 
7263 		err = bpf_program__pin_instance(prog, buf, i);
7264 		if (err)
7265 			goto err_unpin;
7266 	}
7267 
7268 	return 0;
7269 
7270 err_unpin:
7271 	for (i = i - 1; i >= 0; i--) {
7272 		char buf[PATH_MAX];
7273 		int len;
7274 
7275 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7276 		if (len < 0)
7277 			continue;
7278 		else if (len >= PATH_MAX)
7279 			continue;
7280 
7281 		bpf_program__unpin_instance(prog, buf, i);
7282 	}
7283 
7284 	rmdir(path);
7285 
7286 	return libbpf_err(err);
7287 }
7288 
7289 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7290 {
7291 	int i, err;
7292 
7293 	err = check_path(path);
7294 	if (err)
7295 		return libbpf_err(err);
7296 
7297 	if (prog == NULL) {
7298 		pr_warn("invalid program pointer\n");
7299 		return libbpf_err(-EINVAL);
7300 	}
7301 
7302 	if (prog->instances.nr <= 0) {
7303 		pr_warn("no instances of prog %s to pin\n", prog->name);
7304 		return libbpf_err(-EINVAL);
7305 	}
7306 
7307 	if (prog->instances.nr == 1) {
7308 		/* don't create subdirs when pinning single instance */
7309 		return bpf_program__unpin_instance(prog, path, 0);
7310 	}
7311 
7312 	for (i = 0; i < prog->instances.nr; i++) {
7313 		char buf[PATH_MAX];
7314 		int len;
7315 
7316 		len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7317 		if (len < 0)
7318 			return libbpf_err(-EINVAL);
7319 		else if (len >= PATH_MAX)
7320 			return libbpf_err(-ENAMETOOLONG);
7321 
7322 		err = bpf_program__unpin_instance(prog, buf, i);
7323 		if (err)
7324 			return err;
7325 	}
7326 
7327 	err = rmdir(path);
7328 	if (err)
7329 		return libbpf_err(-errno);
7330 
7331 	return 0;
7332 }
7333 
7334 int bpf_map__pin(struct bpf_map *map, const char *path)
7335 {
7336 	char *cp, errmsg[STRERR_BUFSIZE];
7337 	int err;
7338 
7339 	if (map == NULL) {
7340 		pr_warn("invalid map pointer\n");
7341 		return libbpf_err(-EINVAL);
7342 	}
7343 
7344 	if (map->pin_path) {
7345 		if (path && strcmp(path, map->pin_path)) {
7346 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7347 				bpf_map__name(map), map->pin_path, path);
7348 			return libbpf_err(-EINVAL);
7349 		} else if (map->pinned) {
7350 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7351 				 bpf_map__name(map), map->pin_path);
7352 			return 0;
7353 		}
7354 	} else {
7355 		if (!path) {
7356 			pr_warn("missing a path to pin map '%s' at\n",
7357 				bpf_map__name(map));
7358 			return libbpf_err(-EINVAL);
7359 		} else if (map->pinned) {
7360 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7361 			return libbpf_err(-EEXIST);
7362 		}
7363 
7364 		map->pin_path = strdup(path);
7365 		if (!map->pin_path) {
7366 			err = -errno;
7367 			goto out_err;
7368 		}
7369 	}
7370 
7371 	err = make_parent_dir(map->pin_path);
7372 	if (err)
7373 		return libbpf_err(err);
7374 
7375 	err = check_path(map->pin_path);
7376 	if (err)
7377 		return libbpf_err(err);
7378 
7379 	if (bpf_obj_pin(map->fd, map->pin_path)) {
7380 		err = -errno;
7381 		goto out_err;
7382 	}
7383 
7384 	map->pinned = true;
7385 	pr_debug("pinned map '%s'\n", map->pin_path);
7386 
7387 	return 0;
7388 
7389 out_err:
7390 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7391 	pr_warn("failed to pin map: %s\n", cp);
7392 	return libbpf_err(err);
7393 }
7394 
7395 int bpf_map__unpin(struct bpf_map *map, const char *path)
7396 {
7397 	int err;
7398 
7399 	if (map == NULL) {
7400 		pr_warn("invalid map pointer\n");
7401 		return libbpf_err(-EINVAL);
7402 	}
7403 
7404 	if (map->pin_path) {
7405 		if (path && strcmp(path, map->pin_path)) {
7406 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7407 				bpf_map__name(map), map->pin_path, path);
7408 			return libbpf_err(-EINVAL);
7409 		}
7410 		path = map->pin_path;
7411 	} else if (!path) {
7412 		pr_warn("no path to unpin map '%s' from\n",
7413 			bpf_map__name(map));
7414 		return libbpf_err(-EINVAL);
7415 	}
7416 
7417 	err = check_path(path);
7418 	if (err)
7419 		return libbpf_err(err);
7420 
7421 	err = unlink(path);
7422 	if (err != 0)
7423 		return libbpf_err(-errno);
7424 
7425 	map->pinned = false;
7426 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7427 
7428 	return 0;
7429 }
7430 
7431 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7432 {
7433 	char *new = NULL;
7434 
7435 	if (path) {
7436 		new = strdup(path);
7437 		if (!new)
7438 			return libbpf_err(-errno);
7439 	}
7440 
7441 	free(map->pin_path);
7442 	map->pin_path = new;
7443 	return 0;
7444 }
7445 
7446 const char *bpf_map__get_pin_path(const struct bpf_map *map)
7447 {
7448 	return map->pin_path;
7449 }
7450 
7451 const char *bpf_map__pin_path(const struct bpf_map *map)
7452 {
7453 	return map->pin_path;
7454 }
7455 
7456 bool bpf_map__is_pinned(const struct bpf_map *map)
7457 {
7458 	return map->pinned;
7459 }
7460 
7461 static void sanitize_pin_path(char *s)
7462 {
7463 	/* bpffs disallows periods in path names */
7464 	while (*s) {
7465 		if (*s == '.')
7466 			*s = '_';
7467 		s++;
7468 	}
7469 }
7470 
7471 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7472 {
7473 	struct bpf_map *map;
7474 	int err;
7475 
7476 	if (!obj)
7477 		return libbpf_err(-ENOENT);
7478 
7479 	if (!obj->loaded) {
7480 		pr_warn("object not yet loaded; load it first\n");
7481 		return libbpf_err(-ENOENT);
7482 	}
7483 
7484 	bpf_object__for_each_map(map, obj) {
7485 		char *pin_path = NULL;
7486 		char buf[PATH_MAX];
7487 
7488 		if (path) {
7489 			int len;
7490 
7491 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
7492 				       bpf_map__name(map));
7493 			if (len < 0) {
7494 				err = -EINVAL;
7495 				goto err_unpin_maps;
7496 			} else if (len >= PATH_MAX) {
7497 				err = -ENAMETOOLONG;
7498 				goto err_unpin_maps;
7499 			}
7500 			sanitize_pin_path(buf);
7501 			pin_path = buf;
7502 		} else if (!map->pin_path) {
7503 			continue;
7504 		}
7505 
7506 		err = bpf_map__pin(map, pin_path);
7507 		if (err)
7508 			goto err_unpin_maps;
7509 	}
7510 
7511 	return 0;
7512 
7513 err_unpin_maps:
7514 	while ((map = bpf_map__prev(map, obj))) {
7515 		if (!map->pin_path)
7516 			continue;
7517 
7518 		bpf_map__unpin(map, NULL);
7519 	}
7520 
7521 	return libbpf_err(err);
7522 }
7523 
7524 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7525 {
7526 	struct bpf_map *map;
7527 	int err;
7528 
7529 	if (!obj)
7530 		return libbpf_err(-ENOENT);
7531 
7532 	bpf_object__for_each_map(map, obj) {
7533 		char *pin_path = NULL;
7534 		char buf[PATH_MAX];
7535 
7536 		if (path) {
7537 			int len;
7538 
7539 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
7540 				       bpf_map__name(map));
7541 			if (len < 0)
7542 				return libbpf_err(-EINVAL);
7543 			else if (len >= PATH_MAX)
7544 				return libbpf_err(-ENAMETOOLONG);
7545 			sanitize_pin_path(buf);
7546 			pin_path = buf;
7547 		} else if (!map->pin_path) {
7548 			continue;
7549 		}
7550 
7551 		err = bpf_map__unpin(map, pin_path);
7552 		if (err)
7553 			return libbpf_err(err);
7554 	}
7555 
7556 	return 0;
7557 }
7558 
7559 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
7560 {
7561 	struct bpf_program *prog;
7562 	int err;
7563 
7564 	if (!obj)
7565 		return libbpf_err(-ENOENT);
7566 
7567 	if (!obj->loaded) {
7568 		pr_warn("object not yet loaded; load it first\n");
7569 		return libbpf_err(-ENOENT);
7570 	}
7571 
7572 	bpf_object__for_each_program(prog, obj) {
7573 		char buf[PATH_MAX];
7574 		int len;
7575 
7576 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
7577 			       prog->pin_name);
7578 		if (len < 0) {
7579 			err = -EINVAL;
7580 			goto err_unpin_programs;
7581 		} else if (len >= PATH_MAX) {
7582 			err = -ENAMETOOLONG;
7583 			goto err_unpin_programs;
7584 		}
7585 
7586 		err = bpf_program__pin(prog, buf);
7587 		if (err)
7588 			goto err_unpin_programs;
7589 	}
7590 
7591 	return 0;
7592 
7593 err_unpin_programs:
7594 	while ((prog = bpf_program__prev(prog, obj))) {
7595 		char buf[PATH_MAX];
7596 		int len;
7597 
7598 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
7599 			       prog->pin_name);
7600 		if (len < 0)
7601 			continue;
7602 		else if (len >= PATH_MAX)
7603 			continue;
7604 
7605 		bpf_program__unpin(prog, buf);
7606 	}
7607 
7608 	return libbpf_err(err);
7609 }
7610 
7611 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
7612 {
7613 	struct bpf_program *prog;
7614 	int err;
7615 
7616 	if (!obj)
7617 		return libbpf_err(-ENOENT);
7618 
7619 	bpf_object__for_each_program(prog, obj) {
7620 		char buf[PATH_MAX];
7621 		int len;
7622 
7623 		len = snprintf(buf, PATH_MAX, "%s/%s", path,
7624 			       prog->pin_name);
7625 		if (len < 0)
7626 			return libbpf_err(-EINVAL);
7627 		else if (len >= PATH_MAX)
7628 			return libbpf_err(-ENAMETOOLONG);
7629 
7630 		err = bpf_program__unpin(prog, buf);
7631 		if (err)
7632 			return libbpf_err(err);
7633 	}
7634 
7635 	return 0;
7636 }
7637 
7638 int bpf_object__pin(struct bpf_object *obj, const char *path)
7639 {
7640 	int err;
7641 
7642 	err = bpf_object__pin_maps(obj, path);
7643 	if (err)
7644 		return libbpf_err(err);
7645 
7646 	err = bpf_object__pin_programs(obj, path);
7647 	if (err) {
7648 		bpf_object__unpin_maps(obj, path);
7649 		return libbpf_err(err);
7650 	}
7651 
7652 	return 0;
7653 }
7654 
7655 static void bpf_map__destroy(struct bpf_map *map)
7656 {
7657 	if (map->clear_priv)
7658 		map->clear_priv(map, map->priv);
7659 	map->priv = NULL;
7660 	map->clear_priv = NULL;
7661 
7662 	if (map->inner_map) {
7663 		bpf_map__destroy(map->inner_map);
7664 		zfree(&map->inner_map);
7665 	}
7666 
7667 	zfree(&map->init_slots);
7668 	map->init_slots_sz = 0;
7669 
7670 	if (map->mmaped) {
7671 		munmap(map->mmaped, bpf_map_mmap_sz(map));
7672 		map->mmaped = NULL;
7673 	}
7674 
7675 	if (map->st_ops) {
7676 		zfree(&map->st_ops->data);
7677 		zfree(&map->st_ops->progs);
7678 		zfree(&map->st_ops->kern_func_off);
7679 		zfree(&map->st_ops);
7680 	}
7681 
7682 	zfree(&map->name);
7683 	zfree(&map->pin_path);
7684 
7685 	if (map->fd >= 0)
7686 		zclose(map->fd);
7687 }
7688 
7689 void bpf_object__close(struct bpf_object *obj)
7690 {
7691 	size_t i;
7692 
7693 	if (IS_ERR_OR_NULL(obj))
7694 		return;
7695 
7696 	if (obj->clear_priv)
7697 		obj->clear_priv(obj, obj->priv);
7698 
7699 	bpf_gen__free(obj->gen_loader);
7700 	bpf_object__elf_finish(obj);
7701 	bpf_object__unload(obj);
7702 	btf__free(obj->btf);
7703 	btf_ext__free(obj->btf_ext);
7704 
7705 	for (i = 0; i < obj->nr_maps; i++)
7706 		bpf_map__destroy(&obj->maps[i]);
7707 
7708 	zfree(&obj->btf_custom_path);
7709 	zfree(&obj->kconfig);
7710 	zfree(&obj->externs);
7711 	obj->nr_extern = 0;
7712 
7713 	zfree(&obj->maps);
7714 	obj->nr_maps = 0;
7715 
7716 	if (obj->programs && obj->nr_programs) {
7717 		for (i = 0; i < obj->nr_programs; i++)
7718 			bpf_program__exit(&obj->programs[i]);
7719 	}
7720 	zfree(&obj->programs);
7721 
7722 	list_del(&obj->list);
7723 	free(obj);
7724 }
7725 
7726 struct bpf_object *
7727 bpf_object__next(struct bpf_object *prev)
7728 {
7729 	struct bpf_object *next;
7730 
7731 	if (!prev)
7732 		next = list_first_entry(&bpf_objects_list,
7733 					struct bpf_object,
7734 					list);
7735 	else
7736 		next = list_next_entry(prev, list);
7737 
7738 	/* Empty list is noticed here so don't need checking on entry. */
7739 	if (&next->list == &bpf_objects_list)
7740 		return NULL;
7741 
7742 	return next;
7743 }
7744 
7745 const char *bpf_object__name(const struct bpf_object *obj)
7746 {
7747 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
7748 }
7749 
7750 unsigned int bpf_object__kversion(const struct bpf_object *obj)
7751 {
7752 	return obj ? obj->kern_version : 0;
7753 }
7754 
7755 struct btf *bpf_object__btf(const struct bpf_object *obj)
7756 {
7757 	return obj ? obj->btf : NULL;
7758 }
7759 
7760 int bpf_object__btf_fd(const struct bpf_object *obj)
7761 {
7762 	return obj->btf ? btf__fd(obj->btf) : -1;
7763 }
7764 
7765 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
7766 {
7767 	if (obj->loaded)
7768 		return libbpf_err(-EINVAL);
7769 
7770 	obj->kern_version = kern_version;
7771 
7772 	return 0;
7773 }
7774 
7775 int bpf_object__set_priv(struct bpf_object *obj, void *priv,
7776 			 bpf_object_clear_priv_t clear_priv)
7777 {
7778 	if (obj->priv && obj->clear_priv)
7779 		obj->clear_priv(obj, obj->priv);
7780 
7781 	obj->priv = priv;
7782 	obj->clear_priv = clear_priv;
7783 	return 0;
7784 }
7785 
7786 void *bpf_object__priv(const struct bpf_object *obj)
7787 {
7788 	return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
7789 }
7790 
7791 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
7792 {
7793 	struct bpf_gen *gen;
7794 
7795 	if (!opts)
7796 		return -EFAULT;
7797 	if (!OPTS_VALID(opts, gen_loader_opts))
7798 		return -EINVAL;
7799 	gen = calloc(sizeof(*gen), 1);
7800 	if (!gen)
7801 		return -ENOMEM;
7802 	gen->opts = opts;
7803 	obj->gen_loader = gen;
7804 	return 0;
7805 }
7806 
7807 static struct bpf_program *
7808 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
7809 		    bool forward)
7810 {
7811 	size_t nr_programs = obj->nr_programs;
7812 	ssize_t idx;
7813 
7814 	if (!nr_programs)
7815 		return NULL;
7816 
7817 	if (!p)
7818 		/* Iter from the beginning */
7819 		return forward ? &obj->programs[0] :
7820 			&obj->programs[nr_programs - 1];
7821 
7822 	if (p->obj != obj) {
7823 		pr_warn("error: program handler doesn't match object\n");
7824 		return errno = EINVAL, NULL;
7825 	}
7826 
7827 	idx = (p - obj->programs) + (forward ? 1 : -1);
7828 	if (idx >= obj->nr_programs || idx < 0)
7829 		return NULL;
7830 	return &obj->programs[idx];
7831 }
7832 
7833 struct bpf_program *
7834 bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
7835 {
7836 	struct bpf_program *prog = prev;
7837 
7838 	do {
7839 		prog = __bpf_program__iter(prog, obj, true);
7840 	} while (prog && prog_is_subprog(obj, prog));
7841 
7842 	return prog;
7843 }
7844 
7845 struct bpf_program *
7846 bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
7847 {
7848 	struct bpf_program *prog = next;
7849 
7850 	do {
7851 		prog = __bpf_program__iter(prog, obj, false);
7852 	} while (prog && prog_is_subprog(obj, prog));
7853 
7854 	return prog;
7855 }
7856 
7857 int bpf_program__set_priv(struct bpf_program *prog, void *priv,
7858 			  bpf_program_clear_priv_t clear_priv)
7859 {
7860 	if (prog->priv && prog->clear_priv)
7861 		prog->clear_priv(prog, prog->priv);
7862 
7863 	prog->priv = priv;
7864 	prog->clear_priv = clear_priv;
7865 	return 0;
7866 }
7867 
7868 void *bpf_program__priv(const struct bpf_program *prog)
7869 {
7870 	return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
7871 }
7872 
7873 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
7874 {
7875 	prog->prog_ifindex = ifindex;
7876 }
7877 
7878 const char *bpf_program__name(const struct bpf_program *prog)
7879 {
7880 	return prog->name;
7881 }
7882 
7883 const char *bpf_program__section_name(const struct bpf_program *prog)
7884 {
7885 	return prog->sec_name;
7886 }
7887 
7888 const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
7889 {
7890 	const char *title;
7891 
7892 	title = prog->sec_name;
7893 	if (needs_copy) {
7894 		title = strdup(title);
7895 		if (!title) {
7896 			pr_warn("failed to strdup program title\n");
7897 			return libbpf_err_ptr(-ENOMEM);
7898 		}
7899 	}
7900 
7901 	return title;
7902 }
7903 
7904 bool bpf_program__autoload(const struct bpf_program *prog)
7905 {
7906 	return prog->load;
7907 }
7908 
7909 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
7910 {
7911 	if (prog->obj->loaded)
7912 		return libbpf_err(-EINVAL);
7913 
7914 	prog->load = autoload;
7915 	return 0;
7916 }
7917 
7918 int bpf_program__fd(const struct bpf_program *prog)
7919 {
7920 	return bpf_program__nth_fd(prog, 0);
7921 }
7922 
7923 size_t bpf_program__size(const struct bpf_program *prog)
7924 {
7925 	return prog->insns_cnt * BPF_INSN_SZ;
7926 }
7927 
7928 int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
7929 			  bpf_program_prep_t prep)
7930 {
7931 	int *instances_fds;
7932 
7933 	if (nr_instances <= 0 || !prep)
7934 		return libbpf_err(-EINVAL);
7935 
7936 	if (prog->instances.nr > 0 || prog->instances.fds) {
7937 		pr_warn("Can't set pre-processor after loading\n");
7938 		return libbpf_err(-EINVAL);
7939 	}
7940 
7941 	instances_fds = malloc(sizeof(int) * nr_instances);
7942 	if (!instances_fds) {
7943 		pr_warn("alloc memory failed for fds\n");
7944 		return libbpf_err(-ENOMEM);
7945 	}
7946 
7947 	/* fill all fd with -1 */
7948 	memset(instances_fds, -1, sizeof(int) * nr_instances);
7949 
7950 	prog->instances.nr = nr_instances;
7951 	prog->instances.fds = instances_fds;
7952 	prog->preprocessor = prep;
7953 	return 0;
7954 }
7955 
7956 int bpf_program__nth_fd(const struct bpf_program *prog, int n)
7957 {
7958 	int fd;
7959 
7960 	if (!prog)
7961 		return libbpf_err(-EINVAL);
7962 
7963 	if (n >= prog->instances.nr || n < 0) {
7964 		pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
7965 			n, prog->name, prog->instances.nr);
7966 		return libbpf_err(-EINVAL);
7967 	}
7968 
7969 	fd = prog->instances.fds[n];
7970 	if (fd < 0) {
7971 		pr_warn("%dth instance of program '%s' is invalid\n",
7972 			n, prog->name);
7973 		return libbpf_err(-ENOENT);
7974 	}
7975 
7976 	return fd;
7977 }
7978 
7979 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
7980 {
7981 	return prog->type;
7982 }
7983 
7984 void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
7985 {
7986 	prog->type = type;
7987 }
7988 
7989 static bool bpf_program__is_type(const struct bpf_program *prog,
7990 				 enum bpf_prog_type type)
7991 {
7992 	return prog ? (prog->type == type) : false;
7993 }
7994 
7995 #define BPF_PROG_TYPE_FNS(NAME, TYPE)				\
7996 int bpf_program__set_##NAME(struct bpf_program *prog)		\
7997 {								\
7998 	if (!prog)						\
7999 		return libbpf_err(-EINVAL);			\
8000 	bpf_program__set_type(prog, TYPE);			\
8001 	return 0;						\
8002 }								\
8003 								\
8004 bool bpf_program__is_##NAME(const struct bpf_program *prog)	\
8005 {								\
8006 	return bpf_program__is_type(prog, TYPE);		\
8007 }								\
8008 
8009 BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
8010 BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
8011 BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
8012 BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8013 BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
8014 BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
8015 BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
8016 BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8017 BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
8018 BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
8019 BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
8020 BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
8021 BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
8022 
8023 enum bpf_attach_type
8024 bpf_program__get_expected_attach_type(const struct bpf_program *prog)
8025 {
8026 	return prog->expected_attach_type;
8027 }
8028 
8029 void bpf_program__set_expected_attach_type(struct bpf_program *prog,
8030 					   enum bpf_attach_type type)
8031 {
8032 	prog->expected_attach_type = type;
8033 }
8034 
8035 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8036 	.sec = sec_pfx,							    \
8037 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8038 	.expected_attach_type = atype,					    \
8039 	.cookie = (long)(flags),					    \
8040 	.preload_fn = libbpf_preload_prog,				    \
8041 	__VA_ARGS__							    \
8042 }
8043 
8044 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie);
8045 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie);
8046 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie);
8047 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie);
8048 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie);
8049 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie);
8050 
8051 static const struct bpf_sec_def section_defs[] = {
8052 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
8053 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8054 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8055 	SEC_DEF("kprobe/",		KPROBE,	0, SEC_NONE, attach_kprobe),
8056 	SEC_DEF("uprobe/",		KPROBE,	0, SEC_NONE),
8057 	SEC_DEF("kretprobe/",		KPROBE, 0, SEC_NONE, attach_kprobe),
8058 	SEC_DEF("uretprobe/",		KPROBE, 0, SEC_NONE),
8059 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8060 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX),
8061 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8062 	SEC_DEF("tracepoint/",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8063 	SEC_DEF("tp/",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8064 	SEC_DEF("raw_tracepoint/",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8065 	SEC_DEF("raw_tp/",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8066 	SEC_DEF("tp_btf/",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8067 	SEC_DEF("fentry/",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8068 	SEC_DEF("fmod_ret/",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8069 	SEC_DEF("fexit/",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8070 	SEC_DEF("fentry.s/",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8071 	SEC_DEF("fmod_ret.s/",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8072 	SEC_DEF("fexit.s/",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8073 	SEC_DEF("freplace/",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8074 	SEC_DEF("lsm/",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8075 	SEC_DEF("lsm.s/",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8076 	SEC_DEF("iter/",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8077 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8078 	SEC_DEF("xdp_devmap/",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8079 	SEC_DEF("xdp_cpumap/",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8080 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8081 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8082 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
8083 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8084 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8085 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
8086 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8087 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8088 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8089 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8090 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8091 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8092 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8093 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8094 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8095 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8096 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8097 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8098 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8099 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8100 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8101 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8102 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8103 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8104 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8105 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8106 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8107 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8108 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8109 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8110 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8111 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8112 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8113 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8114 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8115 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8116 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8117 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8118 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8119 };
8120 
8121 #define MAX_TYPE_NAME_SIZE 32
8122 
8123 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8124 {
8125 	const struct bpf_sec_def *sec_def;
8126 	enum sec_def_flags sec_flags;
8127 	int i, n = ARRAY_SIZE(section_defs), len;
8128 	bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME;
8129 
8130 	for (i = 0; i < n; i++) {
8131 		sec_def = &section_defs[i];
8132 		sec_flags = sec_def->cookie;
8133 		len = strlen(sec_def->sec);
8134 
8135 		/* "type/" always has to have proper SEC("type/extras") form */
8136 		if (sec_def->sec[len - 1] == '/') {
8137 			if (str_has_pfx(sec_name, sec_def->sec))
8138 				return sec_def;
8139 			continue;
8140 		}
8141 
8142 		/* "type+" means it can be either exact SEC("type") or
8143 		 * well-formed SEC("type/extras") with proper '/' separator
8144 		 */
8145 		if (sec_def->sec[len - 1] == '+') {
8146 			len--;
8147 			/* not even a prefix */
8148 			if (strncmp(sec_name, sec_def->sec, len) != 0)
8149 				continue;
8150 			/* exact match or has '/' separator */
8151 			if (sec_name[len] == '\0' || sec_name[len] == '/')
8152 				return sec_def;
8153 			continue;
8154 		}
8155 
8156 		/* SEC_SLOPPY_PFX definitions are allowed to be just prefix
8157 		 * matches, unless strict section name mode
8158 		 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
8159 		 * match has to be exact.
8160 		 */
8161 		if ((sec_flags & SEC_SLOPPY_PFX) && !strict)  {
8162 			if (str_has_pfx(sec_name, sec_def->sec))
8163 				return sec_def;
8164 			continue;
8165 		}
8166 
8167 		/* Definitions not marked SEC_SLOPPY_PFX (e.g.,
8168 		 * SEC("syscall")) are exact matches in both modes.
8169 		 */
8170 		if (strcmp(sec_name, sec_def->sec) == 0)
8171 			return sec_def;
8172 	}
8173 	return NULL;
8174 }
8175 
8176 static char *libbpf_get_type_names(bool attach_type)
8177 {
8178 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8179 	char *buf;
8180 
8181 	buf = malloc(len);
8182 	if (!buf)
8183 		return NULL;
8184 
8185 	buf[0] = '\0';
8186 	/* Forge string buf with all available names */
8187 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8188 		const struct bpf_sec_def *sec_def = &section_defs[i];
8189 
8190 		if (attach_type) {
8191 			if (sec_def->preload_fn != libbpf_preload_prog)
8192 				continue;
8193 
8194 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8195 				continue;
8196 		}
8197 
8198 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8199 			free(buf);
8200 			return NULL;
8201 		}
8202 		strcat(buf, " ");
8203 		strcat(buf, section_defs[i].sec);
8204 	}
8205 
8206 	return buf;
8207 }
8208 
8209 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8210 			     enum bpf_attach_type *expected_attach_type)
8211 {
8212 	const struct bpf_sec_def *sec_def;
8213 	char *type_names;
8214 
8215 	if (!name)
8216 		return libbpf_err(-EINVAL);
8217 
8218 	sec_def = find_sec_def(name);
8219 	if (sec_def) {
8220 		*prog_type = sec_def->prog_type;
8221 		*expected_attach_type = sec_def->expected_attach_type;
8222 		return 0;
8223 	}
8224 
8225 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8226 	type_names = libbpf_get_type_names(false);
8227 	if (type_names != NULL) {
8228 		pr_debug("supported section(type) names are:%s\n", type_names);
8229 		free(type_names);
8230 	}
8231 
8232 	return libbpf_err(-ESRCH);
8233 }
8234 
8235 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8236 						     size_t offset)
8237 {
8238 	struct bpf_map *map;
8239 	size_t i;
8240 
8241 	for (i = 0; i < obj->nr_maps; i++) {
8242 		map = &obj->maps[i];
8243 		if (!bpf_map__is_struct_ops(map))
8244 			continue;
8245 		if (map->sec_offset <= offset &&
8246 		    offset - map->sec_offset < map->def.value_size)
8247 			return map;
8248 	}
8249 
8250 	return NULL;
8251 }
8252 
8253 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8254 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8255 					    GElf_Shdr *shdr, Elf_Data *data)
8256 {
8257 	const struct btf_member *member;
8258 	struct bpf_struct_ops *st_ops;
8259 	struct bpf_program *prog;
8260 	unsigned int shdr_idx;
8261 	const struct btf *btf;
8262 	struct bpf_map *map;
8263 	Elf_Data *symbols;
8264 	unsigned int moff, insn_idx;
8265 	const char *name;
8266 	__u32 member_idx;
8267 	GElf_Sym sym;
8268 	GElf_Rel rel;
8269 	int i, nrels;
8270 
8271 	symbols = obj->efile.symbols;
8272 	btf = obj->btf;
8273 	nrels = shdr->sh_size / shdr->sh_entsize;
8274 	for (i = 0; i < nrels; i++) {
8275 		if (!gelf_getrel(data, i, &rel)) {
8276 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8277 			return -LIBBPF_ERRNO__FORMAT;
8278 		}
8279 
8280 		if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
8281 			pr_warn("struct_ops reloc: symbol %zx not found\n",
8282 				(size_t)GELF_R_SYM(rel.r_info));
8283 			return -LIBBPF_ERRNO__FORMAT;
8284 		}
8285 
8286 		name = elf_sym_str(obj, sym.st_name) ?: "<?>";
8287 		map = find_struct_ops_map_by_offset(obj, rel.r_offset);
8288 		if (!map) {
8289 			pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
8290 				(size_t)rel.r_offset);
8291 			return -EINVAL;
8292 		}
8293 
8294 		moff = rel.r_offset - map->sec_offset;
8295 		shdr_idx = sym.st_shndx;
8296 		st_ops = map->st_ops;
8297 		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",
8298 			 map->name,
8299 			 (long long)(rel.r_info >> 32),
8300 			 (long long)sym.st_value,
8301 			 shdr_idx, (size_t)rel.r_offset,
8302 			 map->sec_offset, sym.st_name, name);
8303 
8304 		if (shdr_idx >= SHN_LORESERVE) {
8305 			pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
8306 				map->name, (size_t)rel.r_offset, shdr_idx);
8307 			return -LIBBPF_ERRNO__RELOC;
8308 		}
8309 		if (sym.st_value % BPF_INSN_SZ) {
8310 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8311 				map->name, (unsigned long long)sym.st_value);
8312 			return -LIBBPF_ERRNO__FORMAT;
8313 		}
8314 		insn_idx = sym.st_value / BPF_INSN_SZ;
8315 
8316 		member = find_member_by_offset(st_ops->type, moff * 8);
8317 		if (!member) {
8318 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8319 				map->name, moff);
8320 			return -EINVAL;
8321 		}
8322 		member_idx = member - btf_members(st_ops->type);
8323 		name = btf__name_by_offset(btf, member->name_off);
8324 
8325 		if (!resolve_func_ptr(btf, member->type, NULL)) {
8326 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8327 				map->name, name);
8328 			return -EINVAL;
8329 		}
8330 
8331 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8332 		if (!prog) {
8333 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8334 				map->name, shdr_idx, name);
8335 			return -EINVAL;
8336 		}
8337 
8338 		/* prevent the use of BPF prog with invalid type */
8339 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8340 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8341 				map->name, prog->name);
8342 			return -EINVAL;
8343 		}
8344 
8345 		/* if we haven't yet processed this BPF program, record proper
8346 		 * attach_btf_id and member_idx
8347 		 */
8348 		if (!prog->attach_btf_id) {
8349 			prog->attach_btf_id = st_ops->type_id;
8350 			prog->expected_attach_type = member_idx;
8351 		}
8352 
8353 		/* struct_ops BPF prog can be re-used between multiple
8354 		 * .struct_ops as long as it's the same struct_ops struct
8355 		 * definition and the same function pointer field
8356 		 */
8357 		if (prog->attach_btf_id != st_ops->type_id ||
8358 		    prog->expected_attach_type != member_idx) {
8359 			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",
8360 				map->name, prog->name, prog->sec_name, prog->type,
8361 				prog->attach_btf_id, prog->expected_attach_type, name);
8362 			return -EINVAL;
8363 		}
8364 
8365 		st_ops->progs[member_idx] = prog;
8366 	}
8367 
8368 	return 0;
8369 }
8370 
8371 #define BTF_TRACE_PREFIX "btf_trace_"
8372 #define BTF_LSM_PREFIX "bpf_lsm_"
8373 #define BTF_ITER_PREFIX "bpf_iter_"
8374 #define BTF_MAX_NAME_SIZE 128
8375 
8376 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8377 				const char **prefix, int *kind)
8378 {
8379 	switch (attach_type) {
8380 	case BPF_TRACE_RAW_TP:
8381 		*prefix = BTF_TRACE_PREFIX;
8382 		*kind = BTF_KIND_TYPEDEF;
8383 		break;
8384 	case BPF_LSM_MAC:
8385 		*prefix = BTF_LSM_PREFIX;
8386 		*kind = BTF_KIND_FUNC;
8387 		break;
8388 	case BPF_TRACE_ITER:
8389 		*prefix = BTF_ITER_PREFIX;
8390 		*kind = BTF_KIND_FUNC;
8391 		break;
8392 	default:
8393 		*prefix = "";
8394 		*kind = BTF_KIND_FUNC;
8395 	}
8396 }
8397 
8398 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8399 				   const char *name, __u32 kind)
8400 {
8401 	char btf_type_name[BTF_MAX_NAME_SIZE];
8402 	int ret;
8403 
8404 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
8405 		       "%s%s", prefix, name);
8406 	/* snprintf returns the number of characters written excluding the
8407 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8408 	 * indicates truncation.
8409 	 */
8410 	if (ret < 0 || ret >= sizeof(btf_type_name))
8411 		return -ENAMETOOLONG;
8412 	return btf__find_by_name_kind(btf, btf_type_name, kind);
8413 }
8414 
8415 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8416 				     enum bpf_attach_type attach_type)
8417 {
8418 	const char *prefix;
8419 	int kind;
8420 
8421 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8422 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
8423 }
8424 
8425 int libbpf_find_vmlinux_btf_id(const char *name,
8426 			       enum bpf_attach_type attach_type)
8427 {
8428 	struct btf *btf;
8429 	int err;
8430 
8431 	btf = btf__load_vmlinux_btf();
8432 	err = libbpf_get_error(btf);
8433 	if (err) {
8434 		pr_warn("vmlinux BTF is not found\n");
8435 		return libbpf_err(err);
8436 	}
8437 
8438 	err = find_attach_btf_id(btf, name, attach_type);
8439 	if (err <= 0)
8440 		pr_warn("%s is not found in vmlinux BTF\n", name);
8441 
8442 	btf__free(btf);
8443 	return libbpf_err(err);
8444 }
8445 
8446 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8447 {
8448 	struct bpf_prog_info_linear *info_linear;
8449 	struct bpf_prog_info *info;
8450 	struct btf *btf;
8451 	int err;
8452 
8453 	info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
8454 	err = libbpf_get_error(info_linear);
8455 	if (err) {
8456 		pr_warn("failed get_prog_info_linear for FD %d\n",
8457 			attach_prog_fd);
8458 		return err;
8459 	}
8460 
8461 	err = -EINVAL;
8462 	info = &info_linear->info;
8463 	if (!info->btf_id) {
8464 		pr_warn("The target program doesn't have BTF\n");
8465 		goto out;
8466 	}
8467 	btf = btf__load_from_kernel_by_id(info->btf_id);
8468 	if (libbpf_get_error(btf)) {
8469 		pr_warn("Failed to get BTF of the program\n");
8470 		goto out;
8471 	}
8472 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
8473 	btf__free(btf);
8474 	if (err <= 0) {
8475 		pr_warn("%s is not found in prog's BTF\n", name);
8476 		goto out;
8477 	}
8478 out:
8479 	free(info_linear);
8480 	return err;
8481 }
8482 
8483 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
8484 			      enum bpf_attach_type attach_type,
8485 			      int *btf_obj_fd, int *btf_type_id)
8486 {
8487 	int ret, i;
8488 
8489 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
8490 	if (ret > 0) {
8491 		*btf_obj_fd = 0; /* vmlinux BTF */
8492 		*btf_type_id = ret;
8493 		return 0;
8494 	}
8495 	if (ret != -ENOENT)
8496 		return ret;
8497 
8498 	ret = load_module_btfs(obj);
8499 	if (ret)
8500 		return ret;
8501 
8502 	for (i = 0; i < obj->btf_module_cnt; i++) {
8503 		const struct module_btf *mod = &obj->btf_modules[i];
8504 
8505 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
8506 		if (ret > 0) {
8507 			*btf_obj_fd = mod->fd;
8508 			*btf_type_id = ret;
8509 			return 0;
8510 		}
8511 		if (ret == -ENOENT)
8512 			continue;
8513 
8514 		return ret;
8515 	}
8516 
8517 	return -ESRCH;
8518 }
8519 
8520 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
8521 				     int *btf_obj_fd, int *btf_type_id)
8522 {
8523 	enum bpf_attach_type attach_type = prog->expected_attach_type;
8524 	__u32 attach_prog_fd = prog->attach_prog_fd;
8525 	int err = 0;
8526 
8527 	/* BPF program's BTF ID */
8528 	if (attach_prog_fd) {
8529 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
8530 		if (err < 0) {
8531 			pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
8532 				 attach_prog_fd, attach_name, err);
8533 			return err;
8534 		}
8535 		*btf_obj_fd = 0;
8536 		*btf_type_id = err;
8537 		return 0;
8538 	}
8539 
8540 	/* kernel/module BTF ID */
8541 	if (prog->obj->gen_loader) {
8542 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
8543 		*btf_obj_fd = 0;
8544 		*btf_type_id = 1;
8545 	} else {
8546 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
8547 	}
8548 	if (err) {
8549 		pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
8550 		return err;
8551 	}
8552 	return 0;
8553 }
8554 
8555 int libbpf_attach_type_by_name(const char *name,
8556 			       enum bpf_attach_type *attach_type)
8557 {
8558 	char *type_names;
8559 	const struct bpf_sec_def *sec_def;
8560 
8561 	if (!name)
8562 		return libbpf_err(-EINVAL);
8563 
8564 	sec_def = find_sec_def(name);
8565 	if (!sec_def) {
8566 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
8567 		type_names = libbpf_get_type_names(true);
8568 		if (type_names != NULL) {
8569 			pr_debug("attachable section(type) names are:%s\n", type_names);
8570 			free(type_names);
8571 		}
8572 
8573 		return libbpf_err(-EINVAL);
8574 	}
8575 
8576 	if (sec_def->preload_fn != libbpf_preload_prog)
8577 		return libbpf_err(-EINVAL);
8578 	if (!(sec_def->cookie & SEC_ATTACHABLE))
8579 		return libbpf_err(-EINVAL);
8580 
8581 	*attach_type = sec_def->expected_attach_type;
8582 	return 0;
8583 }
8584 
8585 int bpf_map__fd(const struct bpf_map *map)
8586 {
8587 	return map ? map->fd : libbpf_err(-EINVAL);
8588 }
8589 
8590 const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
8591 {
8592 	return map ? &map->def : libbpf_err_ptr(-EINVAL);
8593 }
8594 
8595 const char *bpf_map__name(const struct bpf_map *map)
8596 {
8597 	return map ? map->name : NULL;
8598 }
8599 
8600 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
8601 {
8602 	return map->def.type;
8603 }
8604 
8605 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
8606 {
8607 	if (map->fd >= 0)
8608 		return libbpf_err(-EBUSY);
8609 	map->def.type = type;
8610 	return 0;
8611 }
8612 
8613 __u32 bpf_map__map_flags(const struct bpf_map *map)
8614 {
8615 	return map->def.map_flags;
8616 }
8617 
8618 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
8619 {
8620 	if (map->fd >= 0)
8621 		return libbpf_err(-EBUSY);
8622 	map->def.map_flags = flags;
8623 	return 0;
8624 }
8625 
8626 __u32 bpf_map__numa_node(const struct bpf_map *map)
8627 {
8628 	return map->numa_node;
8629 }
8630 
8631 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
8632 {
8633 	if (map->fd >= 0)
8634 		return libbpf_err(-EBUSY);
8635 	map->numa_node = numa_node;
8636 	return 0;
8637 }
8638 
8639 __u32 bpf_map__key_size(const struct bpf_map *map)
8640 {
8641 	return map->def.key_size;
8642 }
8643 
8644 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
8645 {
8646 	if (map->fd >= 0)
8647 		return libbpf_err(-EBUSY);
8648 	map->def.key_size = size;
8649 	return 0;
8650 }
8651 
8652 __u32 bpf_map__value_size(const struct bpf_map *map)
8653 {
8654 	return map->def.value_size;
8655 }
8656 
8657 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
8658 {
8659 	if (map->fd >= 0)
8660 		return libbpf_err(-EBUSY);
8661 	map->def.value_size = size;
8662 	return 0;
8663 }
8664 
8665 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8666 {
8667 	return map ? map->btf_key_type_id : 0;
8668 }
8669 
8670 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8671 {
8672 	return map ? map->btf_value_type_id : 0;
8673 }
8674 
8675 int bpf_map__set_priv(struct bpf_map *map, void *priv,
8676 		     bpf_map_clear_priv_t clear_priv)
8677 {
8678 	if (!map)
8679 		return libbpf_err(-EINVAL);
8680 
8681 	if (map->priv) {
8682 		if (map->clear_priv)
8683 			map->clear_priv(map, map->priv);
8684 	}
8685 
8686 	map->priv = priv;
8687 	map->clear_priv = clear_priv;
8688 	return 0;
8689 }
8690 
8691 void *bpf_map__priv(const struct bpf_map *map)
8692 {
8693 	return map ? map->priv : libbpf_err_ptr(-EINVAL);
8694 }
8695 
8696 int bpf_map__set_initial_value(struct bpf_map *map,
8697 			       const void *data, size_t size)
8698 {
8699 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
8700 	    size != map->def.value_size || map->fd >= 0)
8701 		return libbpf_err(-EINVAL);
8702 
8703 	memcpy(map->mmaped, data, size);
8704 	return 0;
8705 }
8706 
8707 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
8708 {
8709 	if (!map->mmaped)
8710 		return NULL;
8711 	*psize = map->def.value_size;
8712 	return map->mmaped;
8713 }
8714 
8715 bool bpf_map__is_offload_neutral(const struct bpf_map *map)
8716 {
8717 	return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
8718 }
8719 
8720 bool bpf_map__is_internal(const struct bpf_map *map)
8721 {
8722 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
8723 }
8724 
8725 __u32 bpf_map__ifindex(const struct bpf_map *map)
8726 {
8727 	return map->map_ifindex;
8728 }
8729 
8730 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
8731 {
8732 	if (map->fd >= 0)
8733 		return libbpf_err(-EBUSY);
8734 	map->map_ifindex = ifindex;
8735 	return 0;
8736 }
8737 
8738 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
8739 {
8740 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
8741 		pr_warn("error: unsupported map type\n");
8742 		return libbpf_err(-EINVAL);
8743 	}
8744 	if (map->inner_map_fd != -1) {
8745 		pr_warn("error: inner_map_fd already specified\n");
8746 		return libbpf_err(-EINVAL);
8747 	}
8748 	zfree(&map->inner_map);
8749 	map->inner_map_fd = fd;
8750 	return 0;
8751 }
8752 
8753 static struct bpf_map *
8754 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
8755 {
8756 	ssize_t idx;
8757 	struct bpf_map *s, *e;
8758 
8759 	if (!obj || !obj->maps)
8760 		return errno = EINVAL, NULL;
8761 
8762 	s = obj->maps;
8763 	e = obj->maps + obj->nr_maps;
8764 
8765 	if ((m < s) || (m >= e)) {
8766 		pr_warn("error in %s: map handler doesn't belong to object\n",
8767 			 __func__);
8768 		return errno = EINVAL, NULL;
8769 	}
8770 
8771 	idx = (m - obj->maps) + i;
8772 	if (idx >= obj->nr_maps || idx < 0)
8773 		return NULL;
8774 	return &obj->maps[idx];
8775 }
8776 
8777 struct bpf_map *
8778 bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
8779 {
8780 	if (prev == NULL)
8781 		return obj->maps;
8782 
8783 	return __bpf_map__iter(prev, obj, 1);
8784 }
8785 
8786 struct bpf_map *
8787 bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
8788 {
8789 	if (next == NULL) {
8790 		if (!obj->nr_maps)
8791 			return NULL;
8792 		return obj->maps + obj->nr_maps - 1;
8793 	}
8794 
8795 	return __bpf_map__iter(next, obj, -1);
8796 }
8797 
8798 struct bpf_map *
8799 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
8800 {
8801 	struct bpf_map *pos;
8802 
8803 	bpf_object__for_each_map(pos, obj) {
8804 		if (pos->name && !strcmp(pos->name, name))
8805 			return pos;
8806 	}
8807 	return errno = ENOENT, NULL;
8808 }
8809 
8810 int
8811 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
8812 {
8813 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
8814 }
8815 
8816 struct bpf_map *
8817 bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
8818 {
8819 	return libbpf_err_ptr(-ENOTSUP);
8820 }
8821 
8822 long libbpf_get_error(const void *ptr)
8823 {
8824 	if (!IS_ERR_OR_NULL(ptr))
8825 		return 0;
8826 
8827 	if (IS_ERR(ptr))
8828 		errno = -PTR_ERR(ptr);
8829 
8830 	/* If ptr == NULL, then errno should be already set by the failing
8831 	 * API, because libbpf never returns NULL on success and it now always
8832 	 * sets errno on error. So no extra errno handling for ptr == NULL
8833 	 * case.
8834 	 */
8835 	return -errno;
8836 }
8837 
8838 int bpf_prog_load(const char *file, enum bpf_prog_type type,
8839 		  struct bpf_object **pobj, int *prog_fd)
8840 {
8841 	struct bpf_prog_load_attr attr;
8842 
8843 	memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
8844 	attr.file = file;
8845 	attr.prog_type = type;
8846 	attr.expected_attach_type = 0;
8847 
8848 	return bpf_prog_load_xattr(&attr, pobj, prog_fd);
8849 }
8850 
8851 int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
8852 			struct bpf_object **pobj, int *prog_fd)
8853 {
8854 	struct bpf_object_open_attr open_attr = {};
8855 	struct bpf_program *prog, *first_prog = NULL;
8856 	struct bpf_object *obj;
8857 	struct bpf_map *map;
8858 	int err;
8859 
8860 	if (!attr)
8861 		return libbpf_err(-EINVAL);
8862 	if (!attr->file)
8863 		return libbpf_err(-EINVAL);
8864 
8865 	open_attr.file = attr->file;
8866 	open_attr.prog_type = attr->prog_type;
8867 
8868 	obj = bpf_object__open_xattr(&open_attr);
8869 	err = libbpf_get_error(obj);
8870 	if (err)
8871 		return libbpf_err(-ENOENT);
8872 
8873 	bpf_object__for_each_program(prog, obj) {
8874 		enum bpf_attach_type attach_type = attr->expected_attach_type;
8875 		/*
8876 		 * to preserve backwards compatibility, bpf_prog_load treats
8877 		 * attr->prog_type, if specified, as an override to whatever
8878 		 * bpf_object__open guessed
8879 		 */
8880 		if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
8881 			bpf_program__set_type(prog, attr->prog_type);
8882 			bpf_program__set_expected_attach_type(prog,
8883 							      attach_type);
8884 		}
8885 		if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
8886 			/*
8887 			 * we haven't guessed from section name and user
8888 			 * didn't provide a fallback type, too bad...
8889 			 */
8890 			bpf_object__close(obj);
8891 			return libbpf_err(-EINVAL);
8892 		}
8893 
8894 		prog->prog_ifindex = attr->ifindex;
8895 		prog->log_level = attr->log_level;
8896 		prog->prog_flags |= attr->prog_flags;
8897 		if (!first_prog)
8898 			first_prog = prog;
8899 	}
8900 
8901 	bpf_object__for_each_map(map, obj) {
8902 		if (!bpf_map__is_offload_neutral(map))
8903 			map->map_ifindex = attr->ifindex;
8904 	}
8905 
8906 	if (!first_prog) {
8907 		pr_warn("object file doesn't contain bpf program\n");
8908 		bpf_object__close(obj);
8909 		return libbpf_err(-ENOENT);
8910 	}
8911 
8912 	err = bpf_object__load(obj);
8913 	if (err) {
8914 		bpf_object__close(obj);
8915 		return libbpf_err(err);
8916 	}
8917 
8918 	*pobj = obj;
8919 	*prog_fd = bpf_program__fd(first_prog);
8920 	return 0;
8921 }
8922 
8923 struct bpf_link {
8924 	int (*detach)(struct bpf_link *link);
8925 	void (*dealloc)(struct bpf_link *link);
8926 	char *pin_path;		/* NULL, if not pinned */
8927 	int fd;			/* hook FD, -1 if not applicable */
8928 	bool disconnected;
8929 };
8930 
8931 /* Replace link's underlying BPF program with the new one */
8932 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
8933 {
8934 	int ret;
8935 
8936 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
8937 	return libbpf_err_errno(ret);
8938 }
8939 
8940 /* Release "ownership" of underlying BPF resource (typically, BPF program
8941  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
8942  * link, when destructed through bpf_link__destroy() call won't attempt to
8943  * detach/unregisted that BPF resource. This is useful in situations where,
8944  * say, attached BPF program has to outlive userspace program that attached it
8945  * in the system. Depending on type of BPF program, though, there might be
8946  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
8947  * exit of userspace program doesn't trigger automatic detachment and clean up
8948  * inside the kernel.
8949  */
8950 void bpf_link__disconnect(struct bpf_link *link)
8951 {
8952 	link->disconnected = true;
8953 }
8954 
8955 int bpf_link__destroy(struct bpf_link *link)
8956 {
8957 	int err = 0;
8958 
8959 	if (IS_ERR_OR_NULL(link))
8960 		return 0;
8961 
8962 	if (!link->disconnected && link->detach)
8963 		err = link->detach(link);
8964 	if (link->pin_path)
8965 		free(link->pin_path);
8966 	if (link->dealloc)
8967 		link->dealloc(link);
8968 	else
8969 		free(link);
8970 
8971 	return libbpf_err(err);
8972 }
8973 
8974 int bpf_link__fd(const struct bpf_link *link)
8975 {
8976 	return link->fd;
8977 }
8978 
8979 const char *bpf_link__pin_path(const struct bpf_link *link)
8980 {
8981 	return link->pin_path;
8982 }
8983 
8984 static int bpf_link__detach_fd(struct bpf_link *link)
8985 {
8986 	return libbpf_err_errno(close(link->fd));
8987 }
8988 
8989 struct bpf_link *bpf_link__open(const char *path)
8990 {
8991 	struct bpf_link *link;
8992 	int fd;
8993 
8994 	fd = bpf_obj_get(path);
8995 	if (fd < 0) {
8996 		fd = -errno;
8997 		pr_warn("failed to open link at %s: %d\n", path, fd);
8998 		return libbpf_err_ptr(fd);
8999 	}
9000 
9001 	link = calloc(1, sizeof(*link));
9002 	if (!link) {
9003 		close(fd);
9004 		return libbpf_err_ptr(-ENOMEM);
9005 	}
9006 	link->detach = &bpf_link__detach_fd;
9007 	link->fd = fd;
9008 
9009 	link->pin_path = strdup(path);
9010 	if (!link->pin_path) {
9011 		bpf_link__destroy(link);
9012 		return libbpf_err_ptr(-ENOMEM);
9013 	}
9014 
9015 	return link;
9016 }
9017 
9018 int bpf_link__detach(struct bpf_link *link)
9019 {
9020 	return bpf_link_detach(link->fd) ? -errno : 0;
9021 }
9022 
9023 int bpf_link__pin(struct bpf_link *link, const char *path)
9024 {
9025 	int err;
9026 
9027 	if (link->pin_path)
9028 		return libbpf_err(-EBUSY);
9029 	err = make_parent_dir(path);
9030 	if (err)
9031 		return libbpf_err(err);
9032 	err = check_path(path);
9033 	if (err)
9034 		return libbpf_err(err);
9035 
9036 	link->pin_path = strdup(path);
9037 	if (!link->pin_path)
9038 		return libbpf_err(-ENOMEM);
9039 
9040 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9041 		err = -errno;
9042 		zfree(&link->pin_path);
9043 		return libbpf_err(err);
9044 	}
9045 
9046 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9047 	return 0;
9048 }
9049 
9050 int bpf_link__unpin(struct bpf_link *link)
9051 {
9052 	int err;
9053 
9054 	if (!link->pin_path)
9055 		return libbpf_err(-EINVAL);
9056 
9057 	err = unlink(link->pin_path);
9058 	if (err != 0)
9059 		return -errno;
9060 
9061 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9062 	zfree(&link->pin_path);
9063 	return 0;
9064 }
9065 
9066 struct bpf_link_perf {
9067 	struct bpf_link link;
9068 	int perf_event_fd;
9069 	/* legacy kprobe support: keep track of probe identifier and type */
9070 	char *legacy_probe_name;
9071 	bool legacy_is_kprobe;
9072 	bool legacy_is_retprobe;
9073 };
9074 
9075 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9076 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9077 
9078 static int bpf_link_perf_detach(struct bpf_link *link)
9079 {
9080 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9081 	int err = 0;
9082 
9083 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9084 		err = -errno;
9085 
9086 	if (perf_link->perf_event_fd != link->fd)
9087 		close(perf_link->perf_event_fd);
9088 	close(link->fd);
9089 
9090 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9091 	if (perf_link->legacy_probe_name) {
9092 		if (perf_link->legacy_is_kprobe) {
9093 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9094 							 perf_link->legacy_is_retprobe);
9095 		} else {
9096 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9097 							 perf_link->legacy_is_retprobe);
9098 		}
9099 	}
9100 
9101 	return err;
9102 }
9103 
9104 static void bpf_link_perf_dealloc(struct bpf_link *link)
9105 {
9106 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9107 
9108 	free(perf_link->legacy_probe_name);
9109 	free(perf_link);
9110 }
9111 
9112 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9113 						     const struct bpf_perf_event_opts *opts)
9114 {
9115 	char errmsg[STRERR_BUFSIZE];
9116 	struct bpf_link_perf *link;
9117 	int prog_fd, link_fd = -1, err;
9118 
9119 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
9120 		return libbpf_err_ptr(-EINVAL);
9121 
9122 	if (pfd < 0) {
9123 		pr_warn("prog '%s': invalid perf event FD %d\n",
9124 			prog->name, pfd);
9125 		return libbpf_err_ptr(-EINVAL);
9126 	}
9127 	prog_fd = bpf_program__fd(prog);
9128 	if (prog_fd < 0) {
9129 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9130 			prog->name);
9131 		return libbpf_err_ptr(-EINVAL);
9132 	}
9133 
9134 	link = calloc(1, sizeof(*link));
9135 	if (!link)
9136 		return libbpf_err_ptr(-ENOMEM);
9137 	link->link.detach = &bpf_link_perf_detach;
9138 	link->link.dealloc = &bpf_link_perf_dealloc;
9139 	link->perf_event_fd = pfd;
9140 
9141 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9142 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9143 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9144 
9145 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9146 		if (link_fd < 0) {
9147 			err = -errno;
9148 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9149 				prog->name, pfd,
9150 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9151 			goto err_out;
9152 		}
9153 		link->link.fd = link_fd;
9154 	} else {
9155 		if (OPTS_GET(opts, bpf_cookie, 0)) {
9156 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
9157 			err = -EOPNOTSUPP;
9158 			goto err_out;
9159 		}
9160 
9161 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9162 			err = -errno;
9163 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9164 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9165 			if (err == -EPROTO)
9166 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9167 					prog->name, pfd);
9168 			goto err_out;
9169 		}
9170 		link->link.fd = pfd;
9171 	}
9172 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9173 		err = -errno;
9174 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9175 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9176 		goto err_out;
9177 	}
9178 
9179 	return &link->link;
9180 err_out:
9181 	if (link_fd >= 0)
9182 		close(link_fd);
9183 	free(link);
9184 	return libbpf_err_ptr(err);
9185 }
9186 
9187 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9188 {
9189 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9190 }
9191 
9192 /*
9193  * this function is expected to parse integer in the range of [0, 2^31-1] from
9194  * given file using scanf format string fmt. If actual parsed value is
9195  * negative, the result might be indistinguishable from error
9196  */
9197 static int parse_uint_from_file(const char *file, const char *fmt)
9198 {
9199 	char buf[STRERR_BUFSIZE];
9200 	int err, ret;
9201 	FILE *f;
9202 
9203 	f = fopen(file, "r");
9204 	if (!f) {
9205 		err = -errno;
9206 		pr_debug("failed to open '%s': %s\n", file,
9207 			 libbpf_strerror_r(err, buf, sizeof(buf)));
9208 		return err;
9209 	}
9210 	err = fscanf(f, fmt, &ret);
9211 	if (err != 1) {
9212 		err = err == EOF ? -EIO : -errno;
9213 		pr_debug("failed to parse '%s': %s\n", file,
9214 			libbpf_strerror_r(err, buf, sizeof(buf)));
9215 		fclose(f);
9216 		return err;
9217 	}
9218 	fclose(f);
9219 	return ret;
9220 }
9221 
9222 static int determine_kprobe_perf_type(void)
9223 {
9224 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
9225 
9226 	return parse_uint_from_file(file, "%d\n");
9227 }
9228 
9229 static int determine_uprobe_perf_type(void)
9230 {
9231 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
9232 
9233 	return parse_uint_from_file(file, "%d\n");
9234 }
9235 
9236 static int determine_kprobe_retprobe_bit(void)
9237 {
9238 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9239 
9240 	return parse_uint_from_file(file, "config:%d\n");
9241 }
9242 
9243 static int determine_uprobe_retprobe_bit(void)
9244 {
9245 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9246 
9247 	return parse_uint_from_file(file, "config:%d\n");
9248 }
9249 
9250 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9251 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9252 
9253 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9254 				 uint64_t offset, int pid, size_t ref_ctr_off)
9255 {
9256 	struct perf_event_attr attr = {};
9257 	char errmsg[STRERR_BUFSIZE];
9258 	int type, pfd, err;
9259 
9260 	if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9261 		return -EINVAL;
9262 
9263 	type = uprobe ? determine_uprobe_perf_type()
9264 		      : determine_kprobe_perf_type();
9265 	if (type < 0) {
9266 		pr_warn("failed to determine %s perf type: %s\n",
9267 			uprobe ? "uprobe" : "kprobe",
9268 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9269 		return type;
9270 	}
9271 	if (retprobe) {
9272 		int bit = uprobe ? determine_uprobe_retprobe_bit()
9273 				 : determine_kprobe_retprobe_bit();
9274 
9275 		if (bit < 0) {
9276 			pr_warn("failed to determine %s retprobe bit: %s\n",
9277 				uprobe ? "uprobe" : "kprobe",
9278 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9279 			return bit;
9280 		}
9281 		attr.config |= 1 << bit;
9282 	}
9283 	attr.size = sizeof(attr);
9284 	attr.type = type;
9285 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9286 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9287 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
9288 
9289 	/* pid filter is meaningful only for uprobes */
9290 	pfd = syscall(__NR_perf_event_open, &attr,
9291 		      pid < 0 ? -1 : pid /* pid */,
9292 		      pid == -1 ? 0 : -1 /* cpu */,
9293 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9294 	if (pfd < 0) {
9295 		err = -errno;
9296 		pr_warn("%s perf_event_open() failed: %s\n",
9297 			uprobe ? "uprobe" : "kprobe",
9298 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9299 		return err;
9300 	}
9301 	return pfd;
9302 }
9303 
9304 static int append_to_file(const char *file, const char *fmt, ...)
9305 {
9306 	int fd, n, err = 0;
9307 	va_list ap;
9308 
9309 	fd = open(file, O_WRONLY | O_APPEND, 0);
9310 	if (fd < 0)
9311 		return -errno;
9312 
9313 	va_start(ap, fmt);
9314 	n = vdprintf(fd, fmt, ap);
9315 	va_end(ap);
9316 
9317 	if (n < 0)
9318 		err = -errno;
9319 
9320 	close(fd);
9321 	return err;
9322 }
9323 
9324 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9325 					 const char *kfunc_name, size_t offset)
9326 {
9327 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), kfunc_name, offset);
9328 }
9329 
9330 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9331 				   const char *kfunc_name, size_t offset)
9332 {
9333 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9334 
9335 	return append_to_file(file, "%c:%s/%s %s+0x%zx",
9336 			      retprobe ? 'r' : 'p',
9337 			      retprobe ? "kretprobes" : "kprobes",
9338 			      probe_name, kfunc_name, offset);
9339 }
9340 
9341 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9342 {
9343 	const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9344 
9345 	return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
9346 }
9347 
9348 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9349 {
9350 	char file[256];
9351 
9352 	snprintf(file, sizeof(file),
9353 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
9354 		 retprobe ? "kretprobes" : "kprobes", probe_name);
9355 
9356 	return parse_uint_from_file(file, "%d\n");
9357 }
9358 
9359 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9360 					 const char *kfunc_name, size_t offset, int pid)
9361 {
9362 	struct perf_event_attr attr = {};
9363 	char errmsg[STRERR_BUFSIZE];
9364 	int type, pfd, err;
9365 
9366 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
9367 	if (err < 0) {
9368 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9369 			kfunc_name, offset,
9370 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9371 		return err;
9372 	}
9373 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
9374 	if (type < 0) {
9375 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
9376 			kfunc_name, offset,
9377 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9378 		return type;
9379 	}
9380 	attr.size = sizeof(attr);
9381 	attr.config = type;
9382 	attr.type = PERF_TYPE_TRACEPOINT;
9383 
9384 	pfd = syscall(__NR_perf_event_open, &attr,
9385 		      pid < 0 ? -1 : pid, /* pid */
9386 		      pid == -1 ? 0 : -1, /* cpu */
9387 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
9388 	if (pfd < 0) {
9389 		err = -errno;
9390 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
9391 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9392 		return err;
9393 	}
9394 	return pfd;
9395 }
9396 
9397 struct bpf_link *
9398 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
9399 				const char *func_name,
9400 				const struct bpf_kprobe_opts *opts)
9401 {
9402 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9403 	char errmsg[STRERR_BUFSIZE];
9404 	char *legacy_probe = NULL;
9405 	struct bpf_link *link;
9406 	size_t offset;
9407 	bool retprobe, legacy;
9408 	int pfd, err;
9409 
9410 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
9411 		return libbpf_err_ptr(-EINVAL);
9412 
9413 	retprobe = OPTS_GET(opts, retprobe, false);
9414 	offset = OPTS_GET(opts, offset, 0);
9415 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9416 
9417 	legacy = determine_kprobe_perf_type() < 0;
9418 	if (!legacy) {
9419 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
9420 					    func_name, offset,
9421 					    -1 /* pid */, 0 /* ref_ctr_off */);
9422 	} else {
9423 		char probe_name[256];
9424 
9425 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
9426 					     func_name, offset);
9427 
9428 		legacy_probe = strdup(func_name);
9429 		if (!legacy_probe)
9430 			return libbpf_err_ptr(-ENOMEM);
9431 
9432 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
9433 						    offset, -1 /* pid */);
9434 	}
9435 	if (pfd < 0) {
9436 		err = -errno;
9437 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
9438 			prog->name, retprobe ? "kretprobe" : "kprobe",
9439 			func_name, offset,
9440 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9441 		goto err_out;
9442 	}
9443 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9444 	err = libbpf_get_error(link);
9445 	if (err) {
9446 		close(pfd);
9447 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
9448 			prog->name, retprobe ? "kretprobe" : "kprobe",
9449 			func_name, offset,
9450 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9451 		goto err_out;
9452 	}
9453 	if (legacy) {
9454 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9455 
9456 		perf_link->legacy_probe_name = legacy_probe;
9457 		perf_link->legacy_is_kprobe = true;
9458 		perf_link->legacy_is_retprobe = retprobe;
9459 	}
9460 
9461 	return link;
9462 err_out:
9463 	free(legacy_probe);
9464 	return libbpf_err_ptr(err);
9465 }
9466 
9467 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
9468 					    bool retprobe,
9469 					    const char *func_name)
9470 {
9471 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
9472 		.retprobe = retprobe,
9473 	);
9474 
9475 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
9476 }
9477 
9478 static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie)
9479 {
9480 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
9481 	unsigned long offset = 0;
9482 	struct bpf_link *link;
9483 	const char *func_name;
9484 	char *func;
9485 	int n, err;
9486 
9487 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
9488 	if (opts.retprobe)
9489 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
9490 	else
9491 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
9492 
9493 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
9494 	if (n < 1) {
9495 		err = -EINVAL;
9496 		pr_warn("kprobe name is invalid: %s\n", func_name);
9497 		return libbpf_err_ptr(err);
9498 	}
9499 	if (opts.retprobe && offset != 0) {
9500 		free(func);
9501 		err = -EINVAL;
9502 		pr_warn("kretprobes do not support offset specification\n");
9503 		return libbpf_err_ptr(err);
9504 	}
9505 
9506 	opts.offset = offset;
9507 	link = bpf_program__attach_kprobe_opts(prog, func, &opts);
9508 	free(func);
9509 	return link;
9510 }
9511 
9512 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
9513 					 const char *binary_path, uint64_t offset)
9514 {
9515 	int i;
9516 
9517 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
9518 
9519 	/* sanitize binary_path in the probe name */
9520 	for (i = 0; buf[i]; i++) {
9521 		if (!isalnum(buf[i]))
9522 			buf[i] = '_';
9523 	}
9524 }
9525 
9526 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
9527 					  const char *binary_path, size_t offset)
9528 {
9529 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
9530 
9531 	return append_to_file(file, "%c:%s/%s %s:0x%zx",
9532 			      retprobe ? 'r' : 'p',
9533 			      retprobe ? "uretprobes" : "uprobes",
9534 			      probe_name, binary_path, offset);
9535 }
9536 
9537 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
9538 {
9539 	const char *file = "/sys/kernel/debug/tracing/uprobe_events";
9540 
9541 	return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
9542 }
9543 
9544 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9545 {
9546 	char file[512];
9547 
9548 	snprintf(file, sizeof(file),
9549 		 "/sys/kernel/debug/tracing/events/%s/%s/id",
9550 		 retprobe ? "uretprobes" : "uprobes", probe_name);
9551 
9552 	return parse_uint_from_file(file, "%d\n");
9553 }
9554 
9555 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
9556 					 const char *binary_path, size_t offset, int pid)
9557 {
9558 	struct perf_event_attr attr;
9559 	int type, pfd, err;
9560 
9561 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
9562 	if (err < 0) {
9563 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
9564 			binary_path, (size_t)offset, err);
9565 		return err;
9566 	}
9567 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
9568 	if (type < 0) {
9569 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
9570 			binary_path, offset, err);
9571 		return type;
9572 	}
9573 
9574 	memset(&attr, 0, sizeof(attr));
9575 	attr.size = sizeof(attr);
9576 	attr.config = type;
9577 	attr.type = PERF_TYPE_TRACEPOINT;
9578 
9579 	pfd = syscall(__NR_perf_event_open, &attr,
9580 		      pid < 0 ? -1 : pid, /* pid */
9581 		      pid == -1 ? 0 : -1, /* cpu */
9582 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
9583 	if (pfd < 0) {
9584 		err = -errno;
9585 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
9586 		return err;
9587 	}
9588 	return pfd;
9589 }
9590 
9591 LIBBPF_API struct bpf_link *
9592 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
9593 				const char *binary_path, size_t func_offset,
9594 				const struct bpf_uprobe_opts *opts)
9595 {
9596 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9597 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
9598 	struct bpf_link *link;
9599 	size_t ref_ctr_off;
9600 	int pfd, err;
9601 	bool retprobe, legacy;
9602 
9603 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
9604 		return libbpf_err_ptr(-EINVAL);
9605 
9606 	retprobe = OPTS_GET(opts, retprobe, false);
9607 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
9608 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9609 
9610 	legacy = determine_uprobe_perf_type() < 0;
9611 	if (!legacy) {
9612 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
9613 					    func_offset, pid, ref_ctr_off);
9614 	} else {
9615 		char probe_name[512];
9616 
9617 		if (ref_ctr_off)
9618 			return libbpf_err_ptr(-EINVAL);
9619 
9620 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
9621 					     binary_path, func_offset);
9622 
9623 		legacy_probe = strdup(probe_name);
9624 		if (!legacy_probe)
9625 			return libbpf_err_ptr(-ENOMEM);
9626 
9627 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
9628 						    binary_path, func_offset, pid);
9629 	}
9630 	if (pfd < 0) {
9631 		err = -errno;
9632 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
9633 			prog->name, retprobe ? "uretprobe" : "uprobe",
9634 			binary_path, func_offset,
9635 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9636 		goto err_out;
9637 	}
9638 
9639 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9640 	err = libbpf_get_error(link);
9641 	if (err) {
9642 		close(pfd);
9643 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
9644 			prog->name, retprobe ? "uretprobe" : "uprobe",
9645 			binary_path, func_offset,
9646 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9647 		goto err_out;
9648 	}
9649 	if (legacy) {
9650 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9651 
9652 		perf_link->legacy_probe_name = legacy_probe;
9653 		perf_link->legacy_is_kprobe = false;
9654 		perf_link->legacy_is_retprobe = retprobe;
9655 	}
9656 	return link;
9657 err_out:
9658 	free(legacy_probe);
9659 	return libbpf_err_ptr(err);
9660 
9661 }
9662 
9663 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
9664 					    bool retprobe, pid_t pid,
9665 					    const char *binary_path,
9666 					    size_t func_offset)
9667 {
9668 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
9669 
9670 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
9671 }
9672 
9673 static int determine_tracepoint_id(const char *tp_category,
9674 				   const char *tp_name)
9675 {
9676 	char file[PATH_MAX];
9677 	int ret;
9678 
9679 	ret = snprintf(file, sizeof(file),
9680 		       "/sys/kernel/debug/tracing/events/%s/%s/id",
9681 		       tp_category, tp_name);
9682 	if (ret < 0)
9683 		return -errno;
9684 	if (ret >= sizeof(file)) {
9685 		pr_debug("tracepoint %s/%s path is too long\n",
9686 			 tp_category, tp_name);
9687 		return -E2BIG;
9688 	}
9689 	return parse_uint_from_file(file, "%d\n");
9690 }
9691 
9692 static int perf_event_open_tracepoint(const char *tp_category,
9693 				      const char *tp_name)
9694 {
9695 	struct perf_event_attr attr = {};
9696 	char errmsg[STRERR_BUFSIZE];
9697 	int tp_id, pfd, err;
9698 
9699 	tp_id = determine_tracepoint_id(tp_category, tp_name);
9700 	if (tp_id < 0) {
9701 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
9702 			tp_category, tp_name,
9703 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
9704 		return tp_id;
9705 	}
9706 
9707 	attr.type = PERF_TYPE_TRACEPOINT;
9708 	attr.size = sizeof(attr);
9709 	attr.config = tp_id;
9710 
9711 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
9712 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9713 	if (pfd < 0) {
9714 		err = -errno;
9715 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
9716 			tp_category, tp_name,
9717 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9718 		return err;
9719 	}
9720 	return pfd;
9721 }
9722 
9723 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
9724 						     const char *tp_category,
9725 						     const char *tp_name,
9726 						     const struct bpf_tracepoint_opts *opts)
9727 {
9728 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
9729 	char errmsg[STRERR_BUFSIZE];
9730 	struct bpf_link *link;
9731 	int pfd, err;
9732 
9733 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
9734 		return libbpf_err_ptr(-EINVAL);
9735 
9736 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
9737 
9738 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
9739 	if (pfd < 0) {
9740 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
9741 			prog->name, tp_category, tp_name,
9742 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9743 		return libbpf_err_ptr(pfd);
9744 	}
9745 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
9746 	err = libbpf_get_error(link);
9747 	if (err) {
9748 		close(pfd);
9749 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
9750 			prog->name, tp_category, tp_name,
9751 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9752 		return libbpf_err_ptr(err);
9753 	}
9754 	return link;
9755 }
9756 
9757 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
9758 						const char *tp_category,
9759 						const char *tp_name)
9760 {
9761 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
9762 }
9763 
9764 static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie)
9765 {
9766 	char *sec_name, *tp_cat, *tp_name;
9767 	struct bpf_link *link;
9768 
9769 	sec_name = strdup(prog->sec_name);
9770 	if (!sec_name)
9771 		return libbpf_err_ptr(-ENOMEM);
9772 
9773 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
9774 	if (str_has_pfx(prog->sec_name, "tp/"))
9775 		tp_cat = sec_name + sizeof("tp/") - 1;
9776 	else
9777 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
9778 	tp_name = strchr(tp_cat, '/');
9779 	if (!tp_name) {
9780 		free(sec_name);
9781 		return libbpf_err_ptr(-EINVAL);
9782 	}
9783 	*tp_name = '\0';
9784 	tp_name++;
9785 
9786 	link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
9787 	free(sec_name);
9788 	return link;
9789 }
9790 
9791 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
9792 						    const char *tp_name)
9793 {
9794 	char errmsg[STRERR_BUFSIZE];
9795 	struct bpf_link *link;
9796 	int prog_fd, pfd;
9797 
9798 	prog_fd = bpf_program__fd(prog);
9799 	if (prog_fd < 0) {
9800 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9801 		return libbpf_err_ptr(-EINVAL);
9802 	}
9803 
9804 	link = calloc(1, sizeof(*link));
9805 	if (!link)
9806 		return libbpf_err_ptr(-ENOMEM);
9807 	link->detach = &bpf_link__detach_fd;
9808 
9809 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
9810 	if (pfd < 0) {
9811 		pfd = -errno;
9812 		free(link);
9813 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
9814 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9815 		return libbpf_err_ptr(pfd);
9816 	}
9817 	link->fd = pfd;
9818 	return link;
9819 }
9820 
9821 static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie)
9822 {
9823 	const char *tp_name;
9824 
9825 	if (str_has_pfx(prog->sec_name, "raw_tp/"))
9826 		tp_name = prog->sec_name + sizeof("raw_tp/") - 1;
9827 	else
9828 		tp_name = prog->sec_name + sizeof("raw_tracepoint/") - 1;
9829 
9830 	return bpf_program__attach_raw_tracepoint(prog, tp_name);
9831 }
9832 
9833 /* Common logic for all BPF program types that attach to a btf_id */
9834 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog)
9835 {
9836 	char errmsg[STRERR_BUFSIZE];
9837 	struct bpf_link *link;
9838 	int prog_fd, pfd;
9839 
9840 	prog_fd = bpf_program__fd(prog);
9841 	if (prog_fd < 0) {
9842 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9843 		return libbpf_err_ptr(-EINVAL);
9844 	}
9845 
9846 	link = calloc(1, sizeof(*link));
9847 	if (!link)
9848 		return libbpf_err_ptr(-ENOMEM);
9849 	link->detach = &bpf_link__detach_fd;
9850 
9851 	pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
9852 	if (pfd < 0) {
9853 		pfd = -errno;
9854 		free(link);
9855 		pr_warn("prog '%s': failed to attach: %s\n",
9856 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9857 		return libbpf_err_ptr(pfd);
9858 	}
9859 	link->fd = pfd;
9860 	return (struct bpf_link *)link;
9861 }
9862 
9863 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
9864 {
9865 	return bpf_program__attach_btf_id(prog);
9866 }
9867 
9868 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
9869 {
9870 	return bpf_program__attach_btf_id(prog);
9871 }
9872 
9873 static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie)
9874 {
9875 	return bpf_program__attach_trace(prog);
9876 }
9877 
9878 static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie)
9879 {
9880 	return bpf_program__attach_lsm(prog);
9881 }
9882 
9883 static struct bpf_link *
9884 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
9885 		       const char *target_name)
9886 {
9887 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
9888 			    .target_btf_id = btf_id);
9889 	enum bpf_attach_type attach_type;
9890 	char errmsg[STRERR_BUFSIZE];
9891 	struct bpf_link *link;
9892 	int prog_fd, link_fd;
9893 
9894 	prog_fd = bpf_program__fd(prog);
9895 	if (prog_fd < 0) {
9896 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9897 		return libbpf_err_ptr(-EINVAL);
9898 	}
9899 
9900 	link = calloc(1, sizeof(*link));
9901 	if (!link)
9902 		return libbpf_err_ptr(-ENOMEM);
9903 	link->detach = &bpf_link__detach_fd;
9904 
9905 	attach_type = bpf_program__get_expected_attach_type(prog);
9906 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
9907 	if (link_fd < 0) {
9908 		link_fd = -errno;
9909 		free(link);
9910 		pr_warn("prog '%s': failed to attach to %s: %s\n",
9911 			prog->name, target_name,
9912 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9913 		return libbpf_err_ptr(link_fd);
9914 	}
9915 	link->fd = link_fd;
9916 	return link;
9917 }
9918 
9919 struct bpf_link *
9920 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
9921 {
9922 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
9923 }
9924 
9925 struct bpf_link *
9926 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
9927 {
9928 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
9929 }
9930 
9931 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
9932 {
9933 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
9934 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
9935 }
9936 
9937 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
9938 					      int target_fd,
9939 					      const char *attach_func_name)
9940 {
9941 	int btf_id;
9942 
9943 	if (!!target_fd != !!attach_func_name) {
9944 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
9945 			prog->name);
9946 		return libbpf_err_ptr(-EINVAL);
9947 	}
9948 
9949 	if (prog->type != BPF_PROG_TYPE_EXT) {
9950 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
9951 			prog->name);
9952 		return libbpf_err_ptr(-EINVAL);
9953 	}
9954 
9955 	if (target_fd) {
9956 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
9957 		if (btf_id < 0)
9958 			return libbpf_err_ptr(btf_id);
9959 
9960 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
9961 	} else {
9962 		/* no target, so use raw_tracepoint_open for compatibility
9963 		 * with old kernels
9964 		 */
9965 		return bpf_program__attach_trace(prog);
9966 	}
9967 }
9968 
9969 struct bpf_link *
9970 bpf_program__attach_iter(const struct bpf_program *prog,
9971 			 const struct bpf_iter_attach_opts *opts)
9972 {
9973 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
9974 	char errmsg[STRERR_BUFSIZE];
9975 	struct bpf_link *link;
9976 	int prog_fd, link_fd;
9977 	__u32 target_fd = 0;
9978 
9979 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
9980 		return libbpf_err_ptr(-EINVAL);
9981 
9982 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
9983 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
9984 
9985 	prog_fd = bpf_program__fd(prog);
9986 	if (prog_fd < 0) {
9987 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9988 		return libbpf_err_ptr(-EINVAL);
9989 	}
9990 
9991 	link = calloc(1, sizeof(*link));
9992 	if (!link)
9993 		return libbpf_err_ptr(-ENOMEM);
9994 	link->detach = &bpf_link__detach_fd;
9995 
9996 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
9997 				  &link_create_opts);
9998 	if (link_fd < 0) {
9999 		link_fd = -errno;
10000 		free(link);
10001 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
10002 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
10003 		return libbpf_err_ptr(link_fd);
10004 	}
10005 	link->fd = link_fd;
10006 	return link;
10007 }
10008 
10009 static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)
10010 {
10011 	return bpf_program__attach_iter(prog, NULL);
10012 }
10013 
10014 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
10015 {
10016 	if (!prog->sec_def || !prog->sec_def->attach_fn)
10017 		return libbpf_err_ptr(-ESRCH);
10018 
10019 	return prog->sec_def->attach_fn(prog, prog->sec_def->cookie);
10020 }
10021 
10022 static int bpf_link__detach_struct_ops(struct bpf_link *link)
10023 {
10024 	__u32 zero = 0;
10025 
10026 	if (bpf_map_delete_elem(link->fd, &zero))
10027 		return -errno;
10028 
10029 	return 0;
10030 }
10031 
10032 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
10033 {
10034 	struct bpf_struct_ops *st_ops;
10035 	struct bpf_link *link;
10036 	__u32 i, zero = 0;
10037 	int err;
10038 
10039 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
10040 		return libbpf_err_ptr(-EINVAL);
10041 
10042 	link = calloc(1, sizeof(*link));
10043 	if (!link)
10044 		return libbpf_err_ptr(-EINVAL);
10045 
10046 	st_ops = map->st_ops;
10047 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
10048 		struct bpf_program *prog = st_ops->progs[i];
10049 		void *kern_data;
10050 		int prog_fd;
10051 
10052 		if (!prog)
10053 			continue;
10054 
10055 		prog_fd = bpf_program__fd(prog);
10056 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
10057 		*(unsigned long *)kern_data = prog_fd;
10058 	}
10059 
10060 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
10061 	if (err) {
10062 		err = -errno;
10063 		free(link);
10064 		return libbpf_err_ptr(err);
10065 	}
10066 
10067 	link->detach = bpf_link__detach_struct_ops;
10068 	link->fd = map->fd;
10069 
10070 	return link;
10071 }
10072 
10073 enum bpf_perf_event_ret
10074 bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10075 			   void **copy_mem, size_t *copy_size,
10076 			   bpf_perf_event_print_t fn, void *private_data)
10077 {
10078 	struct perf_event_mmap_page *header = mmap_mem;
10079 	__u64 data_head = ring_buffer_read_head(header);
10080 	__u64 data_tail = header->data_tail;
10081 	void *base = ((__u8 *)header) + page_size;
10082 	int ret = LIBBPF_PERF_EVENT_CONT;
10083 	struct perf_event_header *ehdr;
10084 	size_t ehdr_size;
10085 
10086 	while (data_head != data_tail) {
10087 		ehdr = base + (data_tail & (mmap_size - 1));
10088 		ehdr_size = ehdr->size;
10089 
10090 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
10091 			void *copy_start = ehdr;
10092 			size_t len_first = base + mmap_size - copy_start;
10093 			size_t len_secnd = ehdr_size - len_first;
10094 
10095 			if (*copy_size < ehdr_size) {
10096 				free(*copy_mem);
10097 				*copy_mem = malloc(ehdr_size);
10098 				if (!*copy_mem) {
10099 					*copy_size = 0;
10100 					ret = LIBBPF_PERF_EVENT_ERROR;
10101 					break;
10102 				}
10103 				*copy_size = ehdr_size;
10104 			}
10105 
10106 			memcpy(*copy_mem, copy_start, len_first);
10107 			memcpy(*copy_mem + len_first, base, len_secnd);
10108 			ehdr = *copy_mem;
10109 		}
10110 
10111 		ret = fn(ehdr, private_data);
10112 		data_tail += ehdr_size;
10113 		if (ret != LIBBPF_PERF_EVENT_CONT)
10114 			break;
10115 	}
10116 
10117 	ring_buffer_write_tail(header, data_tail);
10118 	return libbpf_err(ret);
10119 }
10120 
10121 struct perf_buffer;
10122 
10123 struct perf_buffer_params {
10124 	struct perf_event_attr *attr;
10125 	/* if event_cb is specified, it takes precendence */
10126 	perf_buffer_event_fn event_cb;
10127 	/* sample_cb and lost_cb are higher-level common-case callbacks */
10128 	perf_buffer_sample_fn sample_cb;
10129 	perf_buffer_lost_fn lost_cb;
10130 	void *ctx;
10131 	int cpu_cnt;
10132 	int *cpus;
10133 	int *map_keys;
10134 };
10135 
10136 struct perf_cpu_buf {
10137 	struct perf_buffer *pb;
10138 	void *base; /* mmap()'ed memory */
10139 	void *buf; /* for reconstructing segmented data */
10140 	size_t buf_size;
10141 	int fd;
10142 	int cpu;
10143 	int map_key;
10144 };
10145 
10146 struct perf_buffer {
10147 	perf_buffer_event_fn event_cb;
10148 	perf_buffer_sample_fn sample_cb;
10149 	perf_buffer_lost_fn lost_cb;
10150 	void *ctx; /* passed into callbacks */
10151 
10152 	size_t page_size;
10153 	size_t mmap_size;
10154 	struct perf_cpu_buf **cpu_bufs;
10155 	struct epoll_event *events;
10156 	int cpu_cnt; /* number of allocated CPU buffers */
10157 	int epoll_fd; /* perf event FD */
10158 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
10159 };
10160 
10161 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
10162 				      struct perf_cpu_buf *cpu_buf)
10163 {
10164 	if (!cpu_buf)
10165 		return;
10166 	if (cpu_buf->base &&
10167 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
10168 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
10169 	if (cpu_buf->fd >= 0) {
10170 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
10171 		close(cpu_buf->fd);
10172 	}
10173 	free(cpu_buf->buf);
10174 	free(cpu_buf);
10175 }
10176 
10177 void perf_buffer__free(struct perf_buffer *pb)
10178 {
10179 	int i;
10180 
10181 	if (IS_ERR_OR_NULL(pb))
10182 		return;
10183 	if (pb->cpu_bufs) {
10184 		for (i = 0; i < pb->cpu_cnt; i++) {
10185 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10186 
10187 			if (!cpu_buf)
10188 				continue;
10189 
10190 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10191 			perf_buffer__free_cpu_buf(pb, cpu_buf);
10192 		}
10193 		free(pb->cpu_bufs);
10194 	}
10195 	if (pb->epoll_fd >= 0)
10196 		close(pb->epoll_fd);
10197 	free(pb->events);
10198 	free(pb);
10199 }
10200 
10201 static struct perf_cpu_buf *
10202 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10203 			  int cpu, int map_key)
10204 {
10205 	struct perf_cpu_buf *cpu_buf;
10206 	char msg[STRERR_BUFSIZE];
10207 	int err;
10208 
10209 	cpu_buf = calloc(1, sizeof(*cpu_buf));
10210 	if (!cpu_buf)
10211 		return ERR_PTR(-ENOMEM);
10212 
10213 	cpu_buf->pb = pb;
10214 	cpu_buf->cpu = cpu;
10215 	cpu_buf->map_key = map_key;
10216 
10217 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10218 			      -1, PERF_FLAG_FD_CLOEXEC);
10219 	if (cpu_buf->fd < 0) {
10220 		err = -errno;
10221 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10222 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10223 		goto error;
10224 	}
10225 
10226 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10227 			     PROT_READ | PROT_WRITE, MAP_SHARED,
10228 			     cpu_buf->fd, 0);
10229 	if (cpu_buf->base == MAP_FAILED) {
10230 		cpu_buf->base = NULL;
10231 		err = -errno;
10232 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
10233 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10234 		goto error;
10235 	}
10236 
10237 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10238 		err = -errno;
10239 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
10240 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
10241 		goto error;
10242 	}
10243 
10244 	return cpu_buf;
10245 
10246 error:
10247 	perf_buffer__free_cpu_buf(pb, cpu_buf);
10248 	return (struct perf_cpu_buf *)ERR_PTR(err);
10249 }
10250 
10251 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10252 					      struct perf_buffer_params *p);
10253 
10254 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
10255 				     const struct perf_buffer_opts *opts)
10256 {
10257 	struct perf_buffer_params p = {};
10258 	struct perf_event_attr attr = { 0, };
10259 
10260 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
10261 	attr.type = PERF_TYPE_SOFTWARE;
10262 	attr.sample_type = PERF_SAMPLE_RAW;
10263 	attr.sample_period = 1;
10264 	attr.wakeup_events = 1;
10265 
10266 	p.attr = &attr;
10267 	p.sample_cb = opts ? opts->sample_cb : NULL;
10268 	p.lost_cb = opts ? opts->lost_cb : NULL;
10269 	p.ctx = opts ? opts->ctx : NULL;
10270 
10271 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10272 }
10273 
10274 struct perf_buffer *
10275 perf_buffer__new_raw(int map_fd, size_t page_cnt,
10276 		     const struct perf_buffer_raw_opts *opts)
10277 {
10278 	struct perf_buffer_params p = {};
10279 
10280 	p.attr = opts->attr;
10281 	p.event_cb = opts->event_cb;
10282 	p.ctx = opts->ctx;
10283 	p.cpu_cnt = opts->cpu_cnt;
10284 	p.cpus = opts->cpus;
10285 	p.map_keys = opts->map_keys;
10286 
10287 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
10288 }
10289 
10290 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10291 					      struct perf_buffer_params *p)
10292 {
10293 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
10294 	struct bpf_map_info map;
10295 	char msg[STRERR_BUFSIZE];
10296 	struct perf_buffer *pb;
10297 	bool *online = NULL;
10298 	__u32 map_info_len;
10299 	int err, i, j, n;
10300 
10301 	if (page_cnt & (page_cnt - 1)) {
10302 		pr_warn("page count should be power of two, but is %zu\n",
10303 			page_cnt);
10304 		return ERR_PTR(-EINVAL);
10305 	}
10306 
10307 	/* best-effort sanity checks */
10308 	memset(&map, 0, sizeof(map));
10309 	map_info_len = sizeof(map);
10310 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
10311 	if (err) {
10312 		err = -errno;
10313 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
10314 		 * -EBADFD, -EFAULT, or -E2BIG on real error
10315 		 */
10316 		if (err != -EINVAL) {
10317 			pr_warn("failed to get map info for map FD %d: %s\n",
10318 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
10319 			return ERR_PTR(err);
10320 		}
10321 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
10322 			 map_fd);
10323 	} else {
10324 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
10325 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
10326 				map.name);
10327 			return ERR_PTR(-EINVAL);
10328 		}
10329 	}
10330 
10331 	pb = calloc(1, sizeof(*pb));
10332 	if (!pb)
10333 		return ERR_PTR(-ENOMEM);
10334 
10335 	pb->event_cb = p->event_cb;
10336 	pb->sample_cb = p->sample_cb;
10337 	pb->lost_cb = p->lost_cb;
10338 	pb->ctx = p->ctx;
10339 
10340 	pb->page_size = getpagesize();
10341 	pb->mmap_size = pb->page_size * page_cnt;
10342 	pb->map_fd = map_fd;
10343 
10344 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
10345 	if (pb->epoll_fd < 0) {
10346 		err = -errno;
10347 		pr_warn("failed to create epoll instance: %s\n",
10348 			libbpf_strerror_r(err, msg, sizeof(msg)));
10349 		goto error;
10350 	}
10351 
10352 	if (p->cpu_cnt > 0) {
10353 		pb->cpu_cnt = p->cpu_cnt;
10354 	} else {
10355 		pb->cpu_cnt = libbpf_num_possible_cpus();
10356 		if (pb->cpu_cnt < 0) {
10357 			err = pb->cpu_cnt;
10358 			goto error;
10359 		}
10360 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
10361 			pb->cpu_cnt = map.max_entries;
10362 	}
10363 
10364 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
10365 	if (!pb->events) {
10366 		err = -ENOMEM;
10367 		pr_warn("failed to allocate events: out of memory\n");
10368 		goto error;
10369 	}
10370 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
10371 	if (!pb->cpu_bufs) {
10372 		err = -ENOMEM;
10373 		pr_warn("failed to allocate buffers: out of memory\n");
10374 		goto error;
10375 	}
10376 
10377 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
10378 	if (err) {
10379 		pr_warn("failed to get online CPU mask: %d\n", err);
10380 		goto error;
10381 	}
10382 
10383 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
10384 		struct perf_cpu_buf *cpu_buf;
10385 		int cpu, map_key;
10386 
10387 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
10388 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
10389 
10390 		/* in case user didn't explicitly requested particular CPUs to
10391 		 * be attached to, skip offline/not present CPUs
10392 		 */
10393 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
10394 			continue;
10395 
10396 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
10397 		if (IS_ERR(cpu_buf)) {
10398 			err = PTR_ERR(cpu_buf);
10399 			goto error;
10400 		}
10401 
10402 		pb->cpu_bufs[j] = cpu_buf;
10403 
10404 		err = bpf_map_update_elem(pb->map_fd, &map_key,
10405 					  &cpu_buf->fd, 0);
10406 		if (err) {
10407 			err = -errno;
10408 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
10409 				cpu, map_key, cpu_buf->fd,
10410 				libbpf_strerror_r(err, msg, sizeof(msg)));
10411 			goto error;
10412 		}
10413 
10414 		pb->events[j].events = EPOLLIN;
10415 		pb->events[j].data.ptr = cpu_buf;
10416 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
10417 			      &pb->events[j]) < 0) {
10418 			err = -errno;
10419 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
10420 				cpu, cpu_buf->fd,
10421 				libbpf_strerror_r(err, msg, sizeof(msg)));
10422 			goto error;
10423 		}
10424 		j++;
10425 	}
10426 	pb->cpu_cnt = j;
10427 	free(online);
10428 
10429 	return pb;
10430 
10431 error:
10432 	free(online);
10433 	if (pb)
10434 		perf_buffer__free(pb);
10435 	return ERR_PTR(err);
10436 }
10437 
10438 struct perf_sample_raw {
10439 	struct perf_event_header header;
10440 	uint32_t size;
10441 	char data[];
10442 };
10443 
10444 struct perf_sample_lost {
10445 	struct perf_event_header header;
10446 	uint64_t id;
10447 	uint64_t lost;
10448 	uint64_t sample_id;
10449 };
10450 
10451 static enum bpf_perf_event_ret
10452 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
10453 {
10454 	struct perf_cpu_buf *cpu_buf = ctx;
10455 	struct perf_buffer *pb = cpu_buf->pb;
10456 	void *data = e;
10457 
10458 	/* user wants full control over parsing perf event */
10459 	if (pb->event_cb)
10460 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
10461 
10462 	switch (e->type) {
10463 	case PERF_RECORD_SAMPLE: {
10464 		struct perf_sample_raw *s = data;
10465 
10466 		if (pb->sample_cb)
10467 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
10468 		break;
10469 	}
10470 	case PERF_RECORD_LOST: {
10471 		struct perf_sample_lost *s = data;
10472 
10473 		if (pb->lost_cb)
10474 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
10475 		break;
10476 	}
10477 	default:
10478 		pr_warn("unknown perf sample type %d\n", e->type);
10479 		return LIBBPF_PERF_EVENT_ERROR;
10480 	}
10481 	return LIBBPF_PERF_EVENT_CONT;
10482 }
10483 
10484 static int perf_buffer__process_records(struct perf_buffer *pb,
10485 					struct perf_cpu_buf *cpu_buf)
10486 {
10487 	enum bpf_perf_event_ret ret;
10488 
10489 	ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
10490 					 pb->page_size, &cpu_buf->buf,
10491 					 &cpu_buf->buf_size,
10492 					 perf_buffer__process_record, cpu_buf);
10493 	if (ret != LIBBPF_PERF_EVENT_CONT)
10494 		return ret;
10495 	return 0;
10496 }
10497 
10498 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
10499 {
10500 	return pb->epoll_fd;
10501 }
10502 
10503 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
10504 {
10505 	int i, cnt, err;
10506 
10507 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
10508 	if (cnt < 0)
10509 		return -errno;
10510 
10511 	for (i = 0; i < cnt; i++) {
10512 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
10513 
10514 		err = perf_buffer__process_records(pb, cpu_buf);
10515 		if (err) {
10516 			pr_warn("error while processing records: %d\n", err);
10517 			return libbpf_err(err);
10518 		}
10519 	}
10520 	return cnt;
10521 }
10522 
10523 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
10524  * manager.
10525  */
10526 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
10527 {
10528 	return pb->cpu_cnt;
10529 }
10530 
10531 /*
10532  * Return perf_event FD of a ring buffer in *buf_idx* slot of
10533  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
10534  * select()/poll()/epoll() Linux syscalls.
10535  */
10536 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
10537 {
10538 	struct perf_cpu_buf *cpu_buf;
10539 
10540 	if (buf_idx >= pb->cpu_cnt)
10541 		return libbpf_err(-EINVAL);
10542 
10543 	cpu_buf = pb->cpu_bufs[buf_idx];
10544 	if (!cpu_buf)
10545 		return libbpf_err(-ENOENT);
10546 
10547 	return cpu_buf->fd;
10548 }
10549 
10550 /*
10551  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
10552  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
10553  * consume, do nothing and return success.
10554  * Returns:
10555  *   - 0 on success;
10556  *   - <0 on failure.
10557  */
10558 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
10559 {
10560 	struct perf_cpu_buf *cpu_buf;
10561 
10562 	if (buf_idx >= pb->cpu_cnt)
10563 		return libbpf_err(-EINVAL);
10564 
10565 	cpu_buf = pb->cpu_bufs[buf_idx];
10566 	if (!cpu_buf)
10567 		return libbpf_err(-ENOENT);
10568 
10569 	return perf_buffer__process_records(pb, cpu_buf);
10570 }
10571 
10572 int perf_buffer__consume(struct perf_buffer *pb)
10573 {
10574 	int i, err;
10575 
10576 	for (i = 0; i < pb->cpu_cnt; i++) {
10577 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10578 
10579 		if (!cpu_buf)
10580 			continue;
10581 
10582 		err = perf_buffer__process_records(pb, cpu_buf);
10583 		if (err) {
10584 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
10585 			return libbpf_err(err);
10586 		}
10587 	}
10588 	return 0;
10589 }
10590 
10591 struct bpf_prog_info_array_desc {
10592 	int	array_offset;	/* e.g. offset of jited_prog_insns */
10593 	int	count_offset;	/* e.g. offset of jited_prog_len */
10594 	int	size_offset;	/* > 0: offset of rec size,
10595 				 * < 0: fix size of -size_offset
10596 				 */
10597 };
10598 
10599 static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
10600 	[BPF_PROG_INFO_JITED_INSNS] = {
10601 		offsetof(struct bpf_prog_info, jited_prog_insns),
10602 		offsetof(struct bpf_prog_info, jited_prog_len),
10603 		-1,
10604 	},
10605 	[BPF_PROG_INFO_XLATED_INSNS] = {
10606 		offsetof(struct bpf_prog_info, xlated_prog_insns),
10607 		offsetof(struct bpf_prog_info, xlated_prog_len),
10608 		-1,
10609 	},
10610 	[BPF_PROG_INFO_MAP_IDS] = {
10611 		offsetof(struct bpf_prog_info, map_ids),
10612 		offsetof(struct bpf_prog_info, nr_map_ids),
10613 		-(int)sizeof(__u32),
10614 	},
10615 	[BPF_PROG_INFO_JITED_KSYMS] = {
10616 		offsetof(struct bpf_prog_info, jited_ksyms),
10617 		offsetof(struct bpf_prog_info, nr_jited_ksyms),
10618 		-(int)sizeof(__u64),
10619 	},
10620 	[BPF_PROG_INFO_JITED_FUNC_LENS] = {
10621 		offsetof(struct bpf_prog_info, jited_func_lens),
10622 		offsetof(struct bpf_prog_info, nr_jited_func_lens),
10623 		-(int)sizeof(__u32),
10624 	},
10625 	[BPF_PROG_INFO_FUNC_INFO] = {
10626 		offsetof(struct bpf_prog_info, func_info),
10627 		offsetof(struct bpf_prog_info, nr_func_info),
10628 		offsetof(struct bpf_prog_info, func_info_rec_size),
10629 	},
10630 	[BPF_PROG_INFO_LINE_INFO] = {
10631 		offsetof(struct bpf_prog_info, line_info),
10632 		offsetof(struct bpf_prog_info, nr_line_info),
10633 		offsetof(struct bpf_prog_info, line_info_rec_size),
10634 	},
10635 	[BPF_PROG_INFO_JITED_LINE_INFO] = {
10636 		offsetof(struct bpf_prog_info, jited_line_info),
10637 		offsetof(struct bpf_prog_info, nr_jited_line_info),
10638 		offsetof(struct bpf_prog_info, jited_line_info_rec_size),
10639 	},
10640 	[BPF_PROG_INFO_PROG_TAGS] = {
10641 		offsetof(struct bpf_prog_info, prog_tags),
10642 		offsetof(struct bpf_prog_info, nr_prog_tags),
10643 		-(int)sizeof(__u8) * BPF_TAG_SIZE,
10644 	},
10645 
10646 };
10647 
10648 static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
10649 					   int offset)
10650 {
10651 	__u32 *array = (__u32 *)info;
10652 
10653 	if (offset >= 0)
10654 		return array[offset / sizeof(__u32)];
10655 	return -(int)offset;
10656 }
10657 
10658 static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
10659 					   int offset)
10660 {
10661 	__u64 *array = (__u64 *)info;
10662 
10663 	if (offset >= 0)
10664 		return array[offset / sizeof(__u64)];
10665 	return -(int)offset;
10666 }
10667 
10668 static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
10669 					 __u32 val)
10670 {
10671 	__u32 *array = (__u32 *)info;
10672 
10673 	if (offset >= 0)
10674 		array[offset / sizeof(__u32)] = val;
10675 }
10676 
10677 static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
10678 					 __u64 val)
10679 {
10680 	__u64 *array = (__u64 *)info;
10681 
10682 	if (offset >= 0)
10683 		array[offset / sizeof(__u64)] = val;
10684 }
10685 
10686 struct bpf_prog_info_linear *
10687 bpf_program__get_prog_info_linear(int fd, __u64 arrays)
10688 {
10689 	struct bpf_prog_info_linear *info_linear;
10690 	struct bpf_prog_info info = {};
10691 	__u32 info_len = sizeof(info);
10692 	__u32 data_len = 0;
10693 	int i, err;
10694 	void *ptr;
10695 
10696 	if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
10697 		return libbpf_err_ptr(-EINVAL);
10698 
10699 	/* step 1: get array dimensions */
10700 	err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
10701 	if (err) {
10702 		pr_debug("can't get prog info: %s", strerror(errno));
10703 		return libbpf_err_ptr(-EFAULT);
10704 	}
10705 
10706 	/* step 2: calculate total size of all arrays */
10707 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10708 		bool include_array = (arrays & (1UL << i)) > 0;
10709 		struct bpf_prog_info_array_desc *desc;
10710 		__u32 count, size;
10711 
10712 		desc = bpf_prog_info_array_desc + i;
10713 
10714 		/* kernel is too old to support this field */
10715 		if (info_len < desc->array_offset + sizeof(__u32) ||
10716 		    info_len < desc->count_offset + sizeof(__u32) ||
10717 		    (desc->size_offset > 0 && info_len < desc->size_offset))
10718 			include_array = false;
10719 
10720 		if (!include_array) {
10721 			arrays &= ~(1UL << i);	/* clear the bit */
10722 			continue;
10723 		}
10724 
10725 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10726 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10727 
10728 		data_len += count * size;
10729 	}
10730 
10731 	/* step 3: allocate continuous memory */
10732 	data_len = roundup(data_len, sizeof(__u64));
10733 	info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
10734 	if (!info_linear)
10735 		return libbpf_err_ptr(-ENOMEM);
10736 
10737 	/* step 4: fill data to info_linear->info */
10738 	info_linear->arrays = arrays;
10739 	memset(&info_linear->info, 0, sizeof(info));
10740 	ptr = info_linear->data;
10741 
10742 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10743 		struct bpf_prog_info_array_desc *desc;
10744 		__u32 count, size;
10745 
10746 		if ((arrays & (1UL << i)) == 0)
10747 			continue;
10748 
10749 		desc  = bpf_prog_info_array_desc + i;
10750 		count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10751 		size  = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10752 		bpf_prog_info_set_offset_u32(&info_linear->info,
10753 					     desc->count_offset, count);
10754 		bpf_prog_info_set_offset_u32(&info_linear->info,
10755 					     desc->size_offset, size);
10756 		bpf_prog_info_set_offset_u64(&info_linear->info,
10757 					     desc->array_offset,
10758 					     ptr_to_u64(ptr));
10759 		ptr += count * size;
10760 	}
10761 
10762 	/* step 5: call syscall again to get required arrays */
10763 	err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
10764 	if (err) {
10765 		pr_debug("can't get prog info: %s", strerror(errno));
10766 		free(info_linear);
10767 		return libbpf_err_ptr(-EFAULT);
10768 	}
10769 
10770 	/* step 6: verify the data */
10771 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10772 		struct bpf_prog_info_array_desc *desc;
10773 		__u32 v1, v2;
10774 
10775 		if ((arrays & (1UL << i)) == 0)
10776 			continue;
10777 
10778 		desc = bpf_prog_info_array_desc + i;
10779 		v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10780 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10781 						   desc->count_offset);
10782 		if (v1 != v2)
10783 			pr_warn("%s: mismatch in element count\n", __func__);
10784 
10785 		v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10786 		v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10787 						   desc->size_offset);
10788 		if (v1 != v2)
10789 			pr_warn("%s: mismatch in rec size\n", __func__);
10790 	}
10791 
10792 	/* step 7: update info_len and data_len */
10793 	info_linear->info_len = sizeof(struct bpf_prog_info);
10794 	info_linear->data_len = data_len;
10795 
10796 	return info_linear;
10797 }
10798 
10799 void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
10800 {
10801 	int i;
10802 
10803 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10804 		struct bpf_prog_info_array_desc *desc;
10805 		__u64 addr, offs;
10806 
10807 		if ((info_linear->arrays & (1UL << i)) == 0)
10808 			continue;
10809 
10810 		desc = bpf_prog_info_array_desc + i;
10811 		addr = bpf_prog_info_read_offset_u64(&info_linear->info,
10812 						     desc->array_offset);
10813 		offs = addr - ptr_to_u64(info_linear->data);
10814 		bpf_prog_info_set_offset_u64(&info_linear->info,
10815 					     desc->array_offset, offs);
10816 	}
10817 }
10818 
10819 void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
10820 {
10821 	int i;
10822 
10823 	for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10824 		struct bpf_prog_info_array_desc *desc;
10825 		__u64 addr, offs;
10826 
10827 		if ((info_linear->arrays & (1UL << i)) == 0)
10828 			continue;
10829 
10830 		desc = bpf_prog_info_array_desc + i;
10831 		offs = bpf_prog_info_read_offset_u64(&info_linear->info,
10832 						     desc->array_offset);
10833 		addr = offs + ptr_to_u64(info_linear->data);
10834 		bpf_prog_info_set_offset_u64(&info_linear->info,
10835 					     desc->array_offset, addr);
10836 	}
10837 }
10838 
10839 int bpf_program__set_attach_target(struct bpf_program *prog,
10840 				   int attach_prog_fd,
10841 				   const char *attach_func_name)
10842 {
10843 	int btf_obj_fd = 0, btf_id = 0, err;
10844 
10845 	if (!prog || attach_prog_fd < 0)
10846 		return libbpf_err(-EINVAL);
10847 
10848 	if (prog->obj->loaded)
10849 		return libbpf_err(-EINVAL);
10850 
10851 	if (attach_prog_fd && !attach_func_name) {
10852 		/* remember attach_prog_fd and let bpf_program__load() find
10853 		 * BTF ID during the program load
10854 		 */
10855 		prog->attach_prog_fd = attach_prog_fd;
10856 		return 0;
10857 	}
10858 
10859 	if (attach_prog_fd) {
10860 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
10861 						 attach_prog_fd);
10862 		if (btf_id < 0)
10863 			return libbpf_err(btf_id);
10864 	} else {
10865 		if (!attach_func_name)
10866 			return libbpf_err(-EINVAL);
10867 
10868 		/* load btf_vmlinux, if not yet */
10869 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
10870 		if (err)
10871 			return libbpf_err(err);
10872 		err = find_kernel_btf_id(prog->obj, attach_func_name,
10873 					 prog->expected_attach_type,
10874 					 &btf_obj_fd, &btf_id);
10875 		if (err)
10876 			return libbpf_err(err);
10877 	}
10878 
10879 	prog->attach_btf_id = btf_id;
10880 	prog->attach_btf_obj_fd = btf_obj_fd;
10881 	prog->attach_prog_fd = attach_prog_fd;
10882 	return 0;
10883 }
10884 
10885 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
10886 {
10887 	int err = 0, n, len, start, end = -1;
10888 	bool *tmp;
10889 
10890 	*mask = NULL;
10891 	*mask_sz = 0;
10892 
10893 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
10894 	while (*s) {
10895 		if (*s == ',' || *s == '\n') {
10896 			s++;
10897 			continue;
10898 		}
10899 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
10900 		if (n <= 0 || n > 2) {
10901 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
10902 			err = -EINVAL;
10903 			goto cleanup;
10904 		} else if (n == 1) {
10905 			end = start;
10906 		}
10907 		if (start < 0 || start > end) {
10908 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
10909 				start, end, s);
10910 			err = -EINVAL;
10911 			goto cleanup;
10912 		}
10913 		tmp = realloc(*mask, end + 1);
10914 		if (!tmp) {
10915 			err = -ENOMEM;
10916 			goto cleanup;
10917 		}
10918 		*mask = tmp;
10919 		memset(tmp + *mask_sz, 0, start - *mask_sz);
10920 		memset(tmp + start, 1, end - start + 1);
10921 		*mask_sz = end + 1;
10922 		s += len;
10923 	}
10924 	if (!*mask_sz) {
10925 		pr_warn("Empty CPU range\n");
10926 		return -EINVAL;
10927 	}
10928 	return 0;
10929 cleanup:
10930 	free(*mask);
10931 	*mask = NULL;
10932 	return err;
10933 }
10934 
10935 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
10936 {
10937 	int fd, err = 0, len;
10938 	char buf[128];
10939 
10940 	fd = open(fcpu, O_RDONLY);
10941 	if (fd < 0) {
10942 		err = -errno;
10943 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
10944 		return err;
10945 	}
10946 	len = read(fd, buf, sizeof(buf));
10947 	close(fd);
10948 	if (len <= 0) {
10949 		err = len ? -errno : -EINVAL;
10950 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
10951 		return err;
10952 	}
10953 	if (len >= sizeof(buf)) {
10954 		pr_warn("CPU mask is too big in file %s\n", fcpu);
10955 		return -E2BIG;
10956 	}
10957 	buf[len] = '\0';
10958 
10959 	return parse_cpu_mask_str(buf, mask, mask_sz);
10960 }
10961 
10962 int libbpf_num_possible_cpus(void)
10963 {
10964 	static const char *fcpu = "/sys/devices/system/cpu/possible";
10965 	static int cpus;
10966 	int err, n, i, tmp_cpus;
10967 	bool *mask;
10968 
10969 	tmp_cpus = READ_ONCE(cpus);
10970 	if (tmp_cpus > 0)
10971 		return tmp_cpus;
10972 
10973 	err = parse_cpu_mask_file(fcpu, &mask, &n);
10974 	if (err)
10975 		return libbpf_err(err);
10976 
10977 	tmp_cpus = 0;
10978 	for (i = 0; i < n; i++) {
10979 		if (mask[i])
10980 			tmp_cpus++;
10981 	}
10982 	free(mask);
10983 
10984 	WRITE_ONCE(cpus, tmp_cpus);
10985 	return tmp_cpus;
10986 }
10987 
10988 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
10989 			      const struct bpf_object_open_opts *opts)
10990 {
10991 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
10992 		.object_name = s->name,
10993 	);
10994 	struct bpf_object *obj;
10995 	int i, err;
10996 
10997 	/* Attempt to preserve opts->object_name, unless overriden by user
10998 	 * explicitly. Overwriting object name for skeletons is discouraged,
10999 	 * as it breaks global data maps, because they contain object name
11000 	 * prefix as their own map name prefix. When skeleton is generated,
11001 	 * bpftool is making an assumption that this name will stay the same.
11002 	 */
11003 	if (opts) {
11004 		memcpy(&skel_opts, opts, sizeof(*opts));
11005 		if (!opts->object_name)
11006 			skel_opts.object_name = s->name;
11007 	}
11008 
11009 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
11010 	err = libbpf_get_error(obj);
11011 	if (err) {
11012 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
11013 			s->name, err);
11014 		return libbpf_err(err);
11015 	}
11016 
11017 	*s->obj = obj;
11018 
11019 	for (i = 0; i < s->map_cnt; i++) {
11020 		struct bpf_map **map = s->maps[i].map;
11021 		const char *name = s->maps[i].name;
11022 		void **mmaped = s->maps[i].mmaped;
11023 
11024 		*map = bpf_object__find_map_by_name(obj, name);
11025 		if (!*map) {
11026 			pr_warn("failed to find skeleton map '%s'\n", name);
11027 			return libbpf_err(-ESRCH);
11028 		}
11029 
11030 		/* externs shouldn't be pre-setup from user code */
11031 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
11032 			*mmaped = (*map)->mmaped;
11033 	}
11034 
11035 	for (i = 0; i < s->prog_cnt; i++) {
11036 		struct bpf_program **prog = s->progs[i].prog;
11037 		const char *name = s->progs[i].name;
11038 
11039 		*prog = bpf_object__find_program_by_name(obj, name);
11040 		if (!*prog) {
11041 			pr_warn("failed to find skeleton program '%s'\n", name);
11042 			return libbpf_err(-ESRCH);
11043 		}
11044 	}
11045 
11046 	return 0;
11047 }
11048 
11049 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
11050 {
11051 	int i, err;
11052 
11053 	err = bpf_object__load(*s->obj);
11054 	if (err) {
11055 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
11056 		return libbpf_err(err);
11057 	}
11058 
11059 	for (i = 0; i < s->map_cnt; i++) {
11060 		struct bpf_map *map = *s->maps[i].map;
11061 		size_t mmap_sz = bpf_map_mmap_sz(map);
11062 		int prot, map_fd = bpf_map__fd(map);
11063 		void **mmaped = s->maps[i].mmaped;
11064 
11065 		if (!mmaped)
11066 			continue;
11067 
11068 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
11069 			*mmaped = NULL;
11070 			continue;
11071 		}
11072 
11073 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
11074 			prot = PROT_READ;
11075 		else
11076 			prot = PROT_READ | PROT_WRITE;
11077 
11078 		/* Remap anonymous mmap()-ed "map initialization image" as
11079 		 * a BPF map-backed mmap()-ed memory, but preserving the same
11080 		 * memory address. This will cause kernel to change process'
11081 		 * page table to point to a different piece of kernel memory,
11082 		 * but from userspace point of view memory address (and its
11083 		 * contents, being identical at this point) will stay the
11084 		 * same. This mapping will be released by bpf_object__close()
11085 		 * as per normal clean up procedure, so we don't need to worry
11086 		 * about it from skeleton's clean up perspective.
11087 		 */
11088 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
11089 				MAP_SHARED | MAP_FIXED, map_fd, 0);
11090 		if (*mmaped == MAP_FAILED) {
11091 			err = -errno;
11092 			*mmaped = NULL;
11093 			pr_warn("failed to re-mmap() map '%s': %d\n",
11094 				 bpf_map__name(map), err);
11095 			return libbpf_err(err);
11096 		}
11097 	}
11098 
11099 	return 0;
11100 }
11101 
11102 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
11103 {
11104 	int i, err;
11105 
11106 	for (i = 0; i < s->prog_cnt; i++) {
11107 		struct bpf_program *prog = *s->progs[i].prog;
11108 		struct bpf_link **link = s->progs[i].link;
11109 
11110 		if (!prog->load)
11111 			continue;
11112 
11113 		/* auto-attaching not supported for this program */
11114 		if (!prog->sec_def || !prog->sec_def->attach_fn)
11115 			continue;
11116 
11117 		*link = bpf_program__attach(prog);
11118 		err = libbpf_get_error(*link);
11119 		if (err) {
11120 			pr_warn("failed to auto-attach program '%s': %d\n",
11121 				bpf_program__name(prog), err);
11122 			return libbpf_err(err);
11123 		}
11124 	}
11125 
11126 	return 0;
11127 }
11128 
11129 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
11130 {
11131 	int i;
11132 
11133 	for (i = 0; i < s->prog_cnt; i++) {
11134 		struct bpf_link **link = s->progs[i].link;
11135 
11136 		bpf_link__destroy(*link);
11137 		*link = NULL;
11138 	}
11139 }
11140 
11141 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
11142 {
11143 	if (s->progs)
11144 		bpf_object__detach_skeleton(s);
11145 	if (s->obj)
11146 		bpf_object__close(*s->obj);
11147 	free(s->maps);
11148 	free(s->progs);
11149 	free(s);
11150 }
11151