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