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