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