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