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