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