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