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