xref: /linux/tools/bpf/resolve_btfids/main.c (revision a8471eb0747f083ae5bde949e667d3d799d65cf7)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * resolve_btfids scans ELF object for .BTF_ids section and resolves
5  * its symbols with BTF ID values.
6  *
7  * Each symbol points to 4 bytes data and is expected to have
8  * following name syntax:
9  *
10  * __BTF_ID__<type>__<symbol>[__<id>]
11  *
12  * type is:
13  *
14  *   func    - lookup BTF_KIND_FUNC symbol with <symbol> name
15  *             and store its ID into the data:
16  *
17  *             __BTF_ID__func__vfs_close__1:
18  *             .zero 4
19  *
20  *   struct  - lookup BTF_KIND_STRUCT symbol with <symbol> name
21  *             and store its ID into the data:
22  *
23  *             __BTF_ID__struct__sk_buff__1:
24  *             .zero 4
25  *
26  *   union   - lookup BTF_KIND_UNION symbol with <symbol> name
27  *             and store its ID into the data:
28  *
29  *             __BTF_ID__union__thread_union__1:
30  *             .zero 4
31  *
32  *   typedef - lookup BTF_KIND_TYPEDEF symbol with <symbol> name
33  *             and store its ID into the data:
34  *
35  *             __BTF_ID__typedef__pid_t__1:
36  *             .zero 4
37  *
38  *   set     - store symbol size into first 4 bytes and sort following
39  *             ID list
40  *
41  *             __BTF_ID__set__list:
42  *             .zero 4
43  *             list:
44  *             __BTF_ID__func__vfs_getattr__3:
45  *             .zero 4
46  *             __BTF_ID__func__vfs_fallocate__4:
47  *             .zero 4
48  *
49  *   set8    - store symbol size into first 4 bytes and sort following
50  *             ID list
51  *
52  *             __BTF_ID__set8__list:
53  *             .zero 8
54  *             list:
55  *             __BTF_ID__func__vfs_getattr__3:
56  *             .zero 4
57  *	       .word (1 << 0) | (1 << 2)
58  *             __BTF_ID__func__vfs_fallocate__5:
59  *             .zero 4
60  *	       .word (1 << 3) | (1 << 1) | (1 << 2)
61  *
62  * In addition to resolving BTF IDs, resolve_btfids performs kernel-specific
63  * BTF-to-BTF transformations for kfuncs found in BTF_SET8_KFUNCS sets. For
64  * each such kfunc it:
65  *
66  *   - emits a "bpf_kfunc" decl tag, and "bpf_fastcall" when KF_FASTCALL is set;
67  *   - wraps the return value and/or arguments that use arena pointers
68  *     with the "address_space(1)" type attribute;
69  *   - rewrites the prototype of KF_IMPLICIT_ARGS kfuncs.
70  *
71  * These kfunc annotations were historically produced by pahole.
72  */
73 
74 #define  _GNU_SOURCE
75 #include <stdio.h>
76 #include <string.h>
77 #include <unistd.h>
78 #include <stdlib.h>
79 #include <libelf.h>
80 #include <gelf.h>
81 #include <sys/stat.h>
82 #include <fcntl.h>
83 #include <errno.h>
84 #include <linux/btf_ids.h>
85 #include <linux/kallsyms.h>
86 #include <linux/rbtree.h>
87 #include <linux/zalloc.h>
88 #include <linux/err.h>
89 #include <linux/limits.h>
90 #include <bpf/btf.h>
91 #include <bpf/libbpf.h>
92 #include "btf_colors.h"
93 #include <subcmd/parse-options.h>
94 
95 #define BTF_IDS_SECTION	".BTF_ids"
96 #define BTF_LINK_MODULE_NAME_MAX	64
97 #define BTF_ID_PREFIX	"__BTF_ID__"
98 
99 #define BTF_STRUCT	"struct"
100 #define BTF_UNION	"union"
101 #define BTF_TYPEDEF	"typedef"
102 #define BTF_FUNC	"func"
103 #define BTF_SET		"set"
104 #define BTF_SET8	"set8"
105 
106 #define ADDR_CNT	100
107 
108 #if __BYTE_ORDER == __LITTLE_ENDIAN
109 # define ELFDATANATIVE	ELFDATA2LSB
110 #elif __BYTE_ORDER == __BIG_ENDIAN
111 # define ELFDATANATIVE	ELFDATA2MSB
112 #else
113 # error "Unknown machine endianness!"
114 #endif
115 
116 enum btf_id_kind {
117 	BTF_ID_KIND_NONE,
118 	BTF_ID_KIND_SYM,
119 	BTF_ID_KIND_SET,
120 	BTF_ID_KIND_SET8
121 };
122 
123 struct btf_id {
124 	struct rb_node	 rb_node;
125 	char		*name;
126 	union {
127 		int	 id;
128 		int	 cnt;
129 	};
130 	enum btf_id_kind kind;
131 	int		 addr_cnt;
132 	Elf64_Addr	 addr[ADDR_CNT];
133 };
134 
135 struct addr_sym {
136 	Elf64_Addr	 addr;
137 	const char	*name;
138 };
139 
140 struct object {
141 	const char *path;
142 	const char *btf_path;
143 	const char *base_btf_path;
144 
145 	struct btf *btf;
146 	struct btf *base_btf;
147 	struct btf *inline_btf;
148 	struct btf *orig_btf;
149 	bool distill_base;
150 	bool extract_inline;
151 
152 	struct {
153 		int		 fd;
154 		Elf		*elf;
155 		Elf_Data	*symbols;
156 		Elf_Data	*idlist;
157 		int		 symbols_shndx;
158 		int		 idlist_shndx;
159 		size_t		 strtabidx;
160 		unsigned long	 idlist_addr;
161 		int		 encoding;
162 		int		 elf_class;
163 		const char	**func_symbols;
164 		u32		 func_symbols_cnt;
165 		u32		 func_symbols_cap;
166 		bool		 func_symbols_collected;
167 	} efile;
168 
169 	struct rb_root	sets;
170 	struct rb_root	structs;
171 	struct rb_root	unions;
172 	struct rb_root	typedefs;
173 	struct rb_root	funcs;
174 
175 	int nr_funcs;
176 	int nr_structs;
177 	int nr_unions;
178 	int nr_typedefs;
179 
180 	struct addr_sym *addr_syms;
181 	u32 addr_syms_cnt;
182 	u32 addr_syms_cap;
183 };
184 
185 struct btf_link {
186 	char *value;
187 	char *section;
188 	char *module;
189 	char *btf_path;
190 };
191 
192 struct btf_links {
193 	struct btf_link *links;
194 	u32 cnt;
195 	u32 cap;
196 };
197 
198 #define DECL_TAG_FASTCALL "bpf_fastcall"
199 #define DECL_TAG_KFUNC "bpf_kfunc"
200 
201 #define KF_FASTCALL	(1 << 12)
202 #define KF_ARENA_RET	(1 << 13)
203 #define KF_ARENA_ARG1	(1 << 14)
204 #define KF_ARENA_ARG2	(1 << 15)
205 #define KF_IMPLICIT_ARGS (1 << 16)
206 #define KF_IMPL_SUFFIX "_impl"
207 #define TYPE_ATTR_ARENA "address_space(1)"
208 #define PARAM_SUFFIX_ARENA "__arena"
209 #define PARAM_SUFFIX_ARENA_NULLABLE "__arena__nullable"
210 
211 struct kfunc {
212 	struct rb_node rb_node;
213 	const char *name;
214 	u32 btf_id;
215 	u32 flags;
216 };
217 
218 struct btf2btf_context {
219 	struct btf *btf;
220 	u32 *decl_tags;
221 	u32 nr_decl_tags;
222 	u32 max_decl_tags;
223 	struct rb_root kfuncs;
224 };
225 
226 static int verbose;
227 static int warnings;
228 
229 static int eprintf(int level, int var, const char *fmt, ...)
230 {
231 	va_list args;
232 	int ret = 0;
233 
234 	if (var >= level) {
235 		va_start(args, fmt);
236 		ret = vfprintf(stderr, fmt, args);
237 		va_end(args);
238 	}
239 	return ret;
240 }
241 
242 #ifndef pr_fmt
243 #define pr_fmt(fmt) fmt
244 #endif
245 
246 #define pr_debug(fmt, ...) \
247 	eprintf(1, verbose, pr_fmt(fmt), ##__VA_ARGS__)
248 #define pr_debugN(n, fmt, ...) \
249 	eprintf(n, verbose, pr_fmt(fmt), ##__VA_ARGS__)
250 #define pr_debug2(fmt, ...) pr_debugN(2, pr_fmt(fmt), ##__VA_ARGS__)
251 #define pr_err(fmt, ...) \
252 	eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
253 #define pr_info(fmt, ...) \
254 	eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
255 
256 /*
257  * Grow *data so it can hold at least cnt elements of elem_sz bytes each.
258  * *cap is the capacity in elements and is updated on growth.
259  */
260 static int __ensure_mem(void **data, u32 *cap, u32 cnt, size_t elem_sz)
261 {
262 	u32 new_cap, old_cap = *cap;
263 	void *arr;
264 
265 	if (cnt <= old_cap)
266 		return 0;
267 
268 	new_cap = max(old_cap + 256, old_cap * 2);
269 	if (new_cap < cnt)
270 		new_cap = cnt;
271 
272 	arr = realloc(*data, elem_sz * new_cap);
273 	if (!arr)
274 		return -ENOMEM;
275 
276 	*data = arr;
277 	*cap = new_cap;
278 
279 	return 0;
280 }
281 
282 #define ensure_mem(arr_ptr, cap_ptr, cnt) \
283 	__ensure_mem((void **)(arr_ptr), (cap_ptr), (cnt), sizeof(**(arr_ptr)))
284 
285 static int parse_btf_link(const struct option *opt, const char *arg, int unset)
286 {
287 	struct btf_links *links = opt->value;
288 	struct btf_link *link;
289 	char *separator;
290 
291 	if (unset)
292 		return -EINVAL;
293 	if (__ensure_mem((void **)&links->links, &links->cap, links->cnt + 1,
294 			 sizeof(*links->links)))
295 		return -ENOMEM;
296 	link = &links->links[links->cnt];
297 	memset(link, 0, sizeof(*link));
298 	link->value = strdup(arg);
299 	if (!link->value)
300 		return -ENOMEM;
301 	link->section = link->value;
302 	separator = strchr(link->section, ':');
303 	if (!separator || separator == link->section)
304 		goto err_value;
305 	*separator++ = '\0';
306 	link->module = separator;
307 	separator = strchr(link->module, ':');
308 	if (!separator || separator == link->module || !separator[1])
309 		goto err_value;
310 	*separator++ = '\0';
311 	link->btf_path = separator;
312 	links->cnt++;
313 	return 0;
314 err_value:
315 	free(link->value);
316 	return -EINVAL;
317 }
318 
319 static void free_btf_links(struct btf_links *links)
320 {
321 	u32 i;
322 
323 	for (i = 0; i < links->cnt; i++)
324 		free(links->links[i].value);
325 	free(links->links);
326 }
327 
328 static bool is_btf_id(const char *name)
329 {
330 	return name && !strncmp(name, BTF_ID_PREFIX, sizeof(BTF_ID_PREFIX) - 1);
331 }
332 
333 static struct btf_id *btf_id__find(struct rb_root *root, const char *name)
334 {
335 	struct rb_node *p = root->rb_node;
336 	struct btf_id *id;
337 	int cmp;
338 
339 	while (p) {
340 		id = rb_entry(p, struct btf_id, rb_node);
341 		cmp = strcmp(id->name, name);
342 		if (cmp < 0)
343 			p = p->rb_left;
344 		else if (cmp > 0)
345 			p = p->rb_right;
346 		else
347 			return id;
348 	}
349 	return NULL;
350 }
351 
352 static struct btf_id *__btf_id__add(struct rb_root *root,
353 				    const char *name,
354 				    enum btf_id_kind kind,
355 				    bool unique)
356 {
357 	struct rb_node **p = &root->rb_node;
358 	struct rb_node *parent = NULL;
359 	struct btf_id *id;
360 	int cmp;
361 
362 	while (*p != NULL) {
363 		parent = *p;
364 		id = rb_entry(parent, struct btf_id, rb_node);
365 		cmp = strcmp(id->name, name);
366 		if (cmp < 0)
367 			p = &(*p)->rb_left;
368 		else if (cmp > 0)
369 			p = &(*p)->rb_right;
370 		else
371 			return unique ? NULL : id;
372 	}
373 
374 	id = zalloc(sizeof(*id));
375 	if (id) {
376 		pr_debug("adding symbol %s\n", name);
377 		id->name = strdup(name);
378 		if (!id->name) {
379 			free(id);
380 			return NULL;
381 		}
382 		id->kind = kind;
383 		rb_link_node(&id->rb_node, parent, p);
384 		rb_insert_color(&id->rb_node, root);
385 	}
386 	return id;
387 }
388 
389 static inline struct btf_id *btf_id__add(struct rb_root *root,
390 					 const char *name,
391 					 enum btf_id_kind kind)
392 {
393 	return __btf_id__add(root, name, kind, false);
394 }
395 
396 static inline struct btf_id *btf_id__add_unique(struct rb_root *root,
397 						const char *name,
398 						enum btf_id_kind kind)
399 {
400 	return __btf_id__add(root, name, kind, true);
401 }
402 
403 static int get_id(const char *prefix_end, char *buf, size_t buf_sz)
404 {
405 	/*
406 	 * __BTF_ID__func__vfs_truncate__0
407 	 * prefix_end =  ^
408 	 * pos        =    ^
409 	 */
410 	int len = strlen(prefix_end);
411 	int pos = sizeof("__") - 1;
412 	char *p;
413 
414 	if (pos >= len)
415 		return -1;
416 
417 	if (len - pos >= buf_sz)
418 		return -1;
419 
420 	strcpy(buf, prefix_end + pos);
421 	/*
422 	 * __BTF_ID__func__vfs_truncate__0
423 	 * buf =           ^
424 	 *
425 	 * cut the unique id part
426 	 */
427 	p = strrchr(buf, '_');
428 	p--;
429 	if (*p != '_')
430 		return -1;
431 	*p = '\0';
432 
433 	return 0;
434 }
435 
436 static struct btf_id *add_set(struct object *obj, char *name, enum btf_id_kind kind)
437 {
438 	int len = strlen(name);
439 	int prefixlen;
440 	char *id;
441 
442 	/*
443 	 * __BTF_ID__set__name
444 	 * name =    ^
445 	 * id   =         ^
446 	 */
447 	switch (kind) {
448 	case BTF_ID_KIND_SET:
449 		prefixlen = sizeof(BTF_SET "__") - 1;
450 		break;
451 	case BTF_ID_KIND_SET8:
452 		prefixlen = sizeof(BTF_SET8 "__") - 1;
453 		break;
454 	default:
455 		pr_err("Unexpected kind %d passed to %s() for symbol %s\n", kind, __func__, name);
456 		return NULL;
457 	}
458 
459 	id = name + prefixlen;
460 	if (id >= name + len) {
461 		pr_err("FAILED to parse set name: %s\n", name);
462 		return NULL;
463 	}
464 
465 	return btf_id__add_unique(&obj->sets, id, kind);
466 }
467 
468 static struct btf_id *add_symbol(struct rb_root *root, char *name, size_t size)
469 {
470 	char id[KSYM_NAME_LEN];
471 
472 	if (get_id(name + size, id, sizeof(id))) {
473 		pr_err("FAILED to parse symbol name: %s\n", name);
474 		return NULL;
475 	}
476 
477 	return btf_id__add(root, id, BTF_ID_KIND_SYM);
478 }
479 
480 static void btf_id__free_all(struct rb_root *root)
481 {
482 	struct rb_node *next;
483 	struct btf_id *id;
484 
485 	next = rb_first(root);
486 	while (next) {
487 		id = rb_entry(next, struct btf_id, rb_node);
488 		next = rb_next(&id->rb_node);
489 		rb_erase(&id->rb_node, root);
490 		free(id->name);
491 		free(id);
492 	}
493 }
494 
495 static void bswap_32_data(void *data, u32 nr_bytes)
496 {
497 	u32 cnt, i;
498 	u32 *ptr;
499 
500 	cnt = nr_bytes / sizeof(u32);
501 	ptr = data;
502 
503 	for (i = 0; i < cnt; i++)
504 		ptr[i] = bswap_32(ptr[i]);
505 }
506 
507 static int elf_collect(struct object *obj)
508 {
509 	Elf_Scn *scn = NULL;
510 	size_t shdrstrndx;
511 	GElf_Ehdr ehdr;
512 	int idx = 0;
513 	Elf *elf;
514 	int fd;
515 
516 	fd = open(obj->path, O_RDWR, 0666);
517 	if (fd == -1) {
518 		pr_err("FAILED cannot open %s: %s\n",
519 			obj->path, strerror(errno));
520 		return -1;
521 	}
522 
523 	elf_version(EV_CURRENT);
524 
525 	elf = elf_begin(fd, ELF_C_READ_MMAP_PRIVATE, NULL);
526 	if (!elf) {
527 		close(fd);
528 		pr_err("FAILED cannot create ELF descriptor: %s\n",
529 			elf_errmsg(-1));
530 		return -1;
531 	}
532 
533 	obj->efile.fd  = fd;
534 	obj->efile.elf = elf;
535 
536 	elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
537 
538 	if (elf_getshdrstrndx(elf, &shdrstrndx) != 0) {
539 		pr_err("FAILED cannot get shdr str ndx\n");
540 		return -1;
541 	}
542 
543 	if (gelf_getehdr(obj->efile.elf, &ehdr) == NULL) {
544 		pr_err("FAILED cannot get ELF header: %s\n",
545 			elf_errmsg(-1));
546 		return -1;
547 	}
548 	obj->efile.encoding = ehdr.e_ident[EI_DATA];
549 	obj->efile.elf_class = ehdr.e_ident[EI_CLASS];
550 
551 	/*
552 	 * Scan all the elf sections and look for save data
553 	 * from .BTF_ids section and symbols.
554 	 */
555 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
556 		Elf_Data *data;
557 		GElf_Shdr sh;
558 		char *name;
559 
560 		idx++;
561 		if (gelf_getshdr(scn, &sh) != &sh) {
562 			pr_err("FAILED get section(%d) header\n", idx);
563 			return -1;
564 		}
565 
566 		name = elf_strptr(elf, shdrstrndx, sh.sh_name);
567 		if (!name) {
568 			pr_err("FAILED get section(%d) name\n", idx);
569 			return -1;
570 		}
571 
572 		data = elf_getdata(scn, 0);
573 		if (!data) {
574 			pr_err("FAILED to get section(%d) data from %s\n",
575 				idx, name);
576 			return -1;
577 		}
578 
579 		pr_debug2("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
580 			  idx, name, (unsigned long) data->d_size,
581 			  (int) sh.sh_link, (unsigned long) sh.sh_flags,
582 			  (int) sh.sh_type);
583 
584 		if (sh.sh_type == SHT_SYMTAB) {
585 			obj->efile.symbols       = data;
586 			obj->efile.symbols_shndx = idx;
587 			obj->efile.strtabidx     = sh.sh_link;
588 		} else if (!strcmp(name, BTF_IDS_SECTION)) {
589 			/*
590 			 * If target endianness differs from host, we need to bswap32
591 			 * the .BTF_ids section data on load, because .BTF_ids has
592 			 * Elf_Type = ELF_T_BYTE, and so libelf returns data buffer in
593 			 * the target endianness. We repeat this on dump.
594 			 */
595 			if (obj->efile.encoding != ELFDATANATIVE) {
596 				pr_debug("bswap_32 .BTF_ids data from target to host endianness\n");
597 				bswap_32_data(data->d_buf, data->d_size);
598 			}
599 			obj->efile.idlist       = data;
600 			obj->efile.idlist_shndx = idx;
601 			obj->efile.idlist_addr  = sh.sh_addr;
602 		}
603 	}
604 
605 	return 0;
606 }
607 
608 static int push_addr_sym(struct object *obj, Elf64_Addr addr, const char *name)
609 {
610 	if (ensure_mem(&obj->addr_syms, &obj->addr_syms_cap, obj->addr_syms_cnt + 1))
611 		return -ENOMEM;
612 
613 	obj->addr_syms[obj->addr_syms_cnt++] = (struct addr_sym){
614 		.addr = addr,
615 		.name = name,
616 	};
617 
618 	return 0;
619 }
620 
621 static int cmp_addr_sym(const void *a, const void *b)
622 {
623 	Elf64_Addr aa = ((const struct addr_sym *)a)->addr;
624 	Elf64_Addr ab = ((const struct addr_sym *)b)->addr;
625 
626 	return (aa > ab) - (aa < ab);
627 }
628 
629 static const char *find_name_by_addr(struct object *obj, Elf64_Addr addr)
630 {
631 	struct addr_sym key = { .addr = addr };
632 	struct addr_sym *res;
633 
634 	if (!obj->addr_syms_cnt)
635 		return NULL;
636 
637 	res = bsearch(&key, obj->addr_syms, obj->addr_syms_cnt,
638 		      sizeof(*obj->addr_syms), cmp_addr_sym);
639 	return res ? res->name : NULL;
640 }
641 
642 static int cmp_func_symbol(const void *a, const void *b)
643 {
644 	const char * const *name = a;
645 	const char * const *other = b;
646 
647 	return strcmp(*name, *other);
648 }
649 
650 static int collect_func_symbols(struct object *obj)
651 {
652 	Elf_Scn *scn;
653 	GElf_Shdr sh;
654 	int n, i;
655 
656 	if (obj->efile.symbols_shndx == -1)
657 		return 0;
658 
659 	scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
660 	if (!scn || gelf_getshdr(scn, &sh) != &sh || !sh.sh_entsize)
661 		return -EINVAL;
662 	n = sh.sh_size / sh.sh_entsize;
663 
664 	for (i = 0; i < n; i++) {
665 		GElf_Sym sym;
666 		const char *name;
667 
668 		if (!gelf_getsym(obj->efile.symbols, i, &sym))
669 			return -EINVAL;
670 		if (GELF_ST_TYPE(sym.st_info) != STT_FUNC ||
671 		    sym.st_shndx == SHN_UNDEF || !sym.st_name)
672 			continue;
673 		name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, sym.st_name);
674 		if (!name)
675 			return -EINVAL;
676 		if (ensure_mem(&obj->efile.func_symbols, &obj->efile.func_symbols_cap,
677 			       obj->efile.func_symbols_cnt + 1))
678 			return -ENOMEM;
679 		obj->efile.func_symbols[obj->efile.func_symbols_cnt++] = name;
680 	}
681 
682 	qsort(obj->efile.func_symbols, obj->efile.func_symbols_cnt,
683 	      sizeof(*obj->efile.func_symbols), cmp_func_symbol);
684 	obj->efile.func_symbols_collected = true;
685 	return 0;
686 }
687 
688 static bool has_func_symbol(const struct object *obj, const char *name)
689 {
690 	return bsearch(&name, obj->efile.func_symbols, obj->efile.func_symbols_cnt,
691 		       sizeof(*obj->efile.func_symbols), cmp_func_symbol) != NULL;
692 }
693 
694 static int symbols_collect(struct object *obj)
695 {
696 	Elf_Scn *scn = NULL;
697 	int n, i;
698 	GElf_Shdr sh;
699 	char *name;
700 
701 	scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
702 	if (!scn)
703 		return -1;
704 
705 	if (gelf_getshdr(scn, &sh) != &sh)
706 		return -1;
707 
708 	n = sh.sh_size / sh.sh_entsize;
709 
710 	/*
711 	 * Scan symbols and look for the ones starting with
712 	 * __BTF_ID__* over .BTF_ids section.
713 	 */
714 	for (i = 0; i < n; i++) {
715 		char *prefix;
716 		struct btf_id *id;
717 		GElf_Sym sym;
718 
719 		if (!gelf_getsym(obj->efile.symbols, i, &sym))
720 			return -1;
721 
722 		if (sym.st_shndx != obj->efile.idlist_shndx)
723 			continue;
724 
725 		name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
726 				  sym.st_name);
727 
728 		if (!is_btf_id(name))
729 			continue;
730 
731 		/*
732 		 * __BTF_ID__TYPE__vfs_truncate__0
733 		 * prefix =  ^
734 		 */
735 		prefix = name + sizeof(BTF_ID_PREFIX) - 1;
736 
737 		/* struct */
738 		if (!strncmp(prefix, BTF_STRUCT, sizeof(BTF_STRUCT) - 1)) {
739 			obj->nr_structs++;
740 			id = add_symbol(&obj->structs, prefix, sizeof(BTF_STRUCT) - 1);
741 		/* union  */
742 		} else if (!strncmp(prefix, BTF_UNION, sizeof(BTF_UNION) - 1)) {
743 			obj->nr_unions++;
744 			id = add_symbol(&obj->unions, prefix, sizeof(BTF_UNION) - 1);
745 		/* typedef */
746 		} else if (!strncmp(prefix, BTF_TYPEDEF, sizeof(BTF_TYPEDEF) - 1)) {
747 			obj->nr_typedefs++;
748 			id = add_symbol(&obj->typedefs, prefix, sizeof(BTF_TYPEDEF) - 1);
749 		/* func */
750 		} else if (!strncmp(prefix, BTF_FUNC, sizeof(BTF_FUNC) - 1)) {
751 			obj->nr_funcs++;
752 			id = add_symbol(&obj->funcs, prefix, sizeof(BTF_FUNC) - 1);
753 		/* set8 */
754 		} else if (!strncmp(prefix, BTF_SET8, sizeof(BTF_SET8) - 1)) {
755 			id = add_set(obj, prefix, BTF_ID_KIND_SET8);
756 			/*
757 			 * SET8 objects store list's count, which is encoded
758 			 * in symbol's size, together with 'cnt' field hence
759 			 * that - 1.
760 			 */
761 			if (id)
762 				id->cnt = sym.st_size / sizeof(uint64_t) - 1;
763 		/* set */
764 		} else if (!strncmp(prefix, BTF_SET, sizeof(BTF_SET) - 1)) {
765 			id = add_set(obj, prefix, BTF_ID_KIND_SET);
766 			/*
767 			 * SET objects store list's count, which is encoded
768 			 * in symbol's size, together with 'cnt' field hence
769 			 * that - 1.
770 			 */
771 			if (id)
772 				id->cnt = sym.st_size / sizeof(int) - 1;
773 		} else {
774 			pr_err("FAILED unsupported prefix %s\n", prefix);
775 			return -1;
776 		}
777 
778 		if (!id)
779 			return -EINVAL;
780 
781 		if (id->addr_cnt >= ADDR_CNT) {
782 			pr_err("FAILED symbol %s crossed the number of allowed lists\n",
783 				id->name);
784 			return -1;
785 		}
786 		id->addr[id->addr_cnt++] = sym.st_value;
787 
788 		if (push_addr_sym(obj, sym.st_value, id->name))
789 			return -1;
790 	}
791 
792 	if (obj->addr_syms_cnt)
793 		qsort(obj->addr_syms, obj->addr_syms_cnt,
794 		      sizeof(*obj->addr_syms), cmp_addr_sym);
795 
796 	return 0;
797 }
798 
799 static int load_btf(struct object *obj)
800 {
801 	struct btf *base_btf = NULL, *btf = NULL;
802 	int err;
803 
804 	if (obj->base_btf_path) {
805 		base_btf = btf__parse(obj->base_btf_path, NULL);
806 		err = libbpf_get_error(base_btf);
807 		if (err) {
808 			pr_err("FAILED: load base BTF from %s: %s\n",
809 			       obj->base_btf_path, strerror(-err));
810 			return err;
811 		}
812 		obj->base_btf = base_btf;
813 	}
814 
815 	btf = btf__parse_split(obj->btf_path ?: obj->path, base_btf);
816 	err = libbpf_get_error(btf);
817 	if (err) {
818 		pr_err("FAILED: load BTF from %s: %s\n",
819 			obj->btf_path ?: obj->path, strerror(-err));
820 		return err;
821 	}
822 
823 	obj->btf = btf;
824 
825 	return 0;
826 }
827 
828 static int symbols_resolve(struct object *obj)
829 {
830 	int nr_typedefs = obj->nr_typedefs;
831 	int nr_structs  = obj->nr_structs;
832 	int nr_unions   = obj->nr_unions;
833 	int nr_funcs    = obj->nr_funcs;
834 	struct btf *btf = obj->btf;
835 	int err, type_id;
836 	__u32 nr_types;
837 
838 	err = -1;
839 	nr_types = btf__type_cnt(btf);
840 
841 	/*
842 	 * Iterate all the BTF types and search for collected symbol IDs.
843 	 */
844 	for (type_id = 1; type_id < nr_types; type_id++) {
845 		const struct btf_type *type;
846 		struct rb_root *root;
847 		struct btf_id *id;
848 		const char *str;
849 		int *nr;
850 
851 		type = btf__type_by_id(btf, type_id);
852 		if (!type) {
853 			pr_err("FAILED: malformed BTF, can't resolve type for ID %d\n",
854 				type_id);
855 			goto out;
856 		}
857 
858 		if (btf_is_func(type) && nr_funcs) {
859 			nr   = &nr_funcs;
860 			root = &obj->funcs;
861 		} else if (btf_is_struct(type) && nr_structs) {
862 			nr   = &nr_structs;
863 			root = &obj->structs;
864 		} else if (btf_is_union(type) && nr_unions) {
865 			nr   = &nr_unions;
866 			root = &obj->unions;
867 		} else if (btf_is_typedef(type) && nr_typedefs) {
868 			nr   = &nr_typedefs;
869 			root = &obj->typedefs;
870 		} else
871 			continue;
872 
873 		str = btf__name_by_offset(btf, type->name_off);
874 		if (!str) {
875 			pr_err("FAILED: malformed BTF, can't resolve name for ID %d\n",
876 				type_id);
877 			goto out;
878 		}
879 
880 		id = btf_id__find(root, str);
881 		if (id) {
882 			if (id->id) {
883 				pr_info("WARN: multiple IDs found for '%s': %d, %d - using %d\n",
884 					str, id->id, type_id, id->id);
885 				warnings++;
886 			} else {
887 				id->id = type_id;
888 				(*nr)--;
889 			}
890 		}
891 	}
892 
893 	err = 0;
894 out:
895 	return err;
896 }
897 
898 static int id_patch(struct object *obj, struct btf_id *id)
899 {
900 	Elf_Data *data = obj->efile.idlist;
901 	int *ptr = data->d_buf;
902 	int i;
903 
904 	/* For set, set8, id->id may be 0 */
905 	if (!id->id && id->kind != BTF_ID_KIND_SET && id->kind != BTF_ID_KIND_SET8) {
906 		pr_err("WARN: resolve_btfids: unresolved symbol %s\n", id->name);
907 		warnings++;
908 	}
909 
910 	for (i = 0; i < id->addr_cnt; i++) {
911 		unsigned long addr = id->addr[i];
912 		unsigned long idx = addr - obj->efile.idlist_addr;
913 
914 		pr_debug("patching addr %5lu: ID %7d [%s]\n",
915 			 idx, id->id, id->name);
916 
917 		if (idx >= data->d_size) {
918 			pr_err("FAILED patching index %lu out of bounds %lu\n",
919 				idx, data->d_size);
920 			return -1;
921 		}
922 
923 		idx = idx / sizeof(int);
924 		ptr[idx] = id->id;
925 	}
926 
927 	return 0;
928 }
929 
930 static int __symbols_patch(struct object *obj, struct rb_root *root)
931 {
932 	struct rb_node *next;
933 	struct btf_id *id;
934 
935 	next = rb_first(root);
936 	while (next) {
937 		id = rb_entry(next, struct btf_id, rb_node);
938 
939 		if (id_patch(obj, id))
940 			return -1;
941 
942 		next = rb_next(next);
943 	}
944 	return 0;
945 }
946 
947 static int cmp_id(const void *pa, const void *pb)
948 {
949 	const int *a = pa, *b = pb;
950 
951 	return *a - *b;
952 }
953 
954 static int sets_patch(struct object *obj)
955 {
956 	Elf_Data *data = obj->efile.idlist;
957 	struct rb_node *next;
958 	int cnt;
959 
960 	next = rb_first(&obj->sets);
961 	while (next) {
962 		struct btf_id_set8 *set8 = NULL;
963 		struct btf_id_set *set = NULL;
964 		unsigned long addr, off;
965 		struct btf_id *id;
966 
967 		id   = rb_entry(next, struct btf_id, rb_node);
968 		addr = id->addr[0];
969 		off = addr - obj->efile.idlist_addr;
970 
971 		/* sets are unique */
972 		if (id->addr_cnt != 1) {
973 			pr_err("FAILED malformed data for set '%s'\n",
974 				id->name);
975 			return -1;
976 		}
977 
978 		switch (id->kind) {
979 		case BTF_ID_KIND_SET:
980 			set = data->d_buf + off;
981 			cnt = set->cnt;
982 			qsort(set->ids, set->cnt, sizeof(set->ids[0]), cmp_id);
983 			break;
984 		case BTF_ID_KIND_SET8:
985 			set8 = data->d_buf + off;
986 			cnt = set8->cnt;
987 			/*
988 			 * Make sure id is at the beginning of the pairs
989 			 * struct, otherwise the below qsort would not work.
990 			 */
991 			BUILD_BUG_ON((u32 *)set8->pairs != &set8->pairs[0].id);
992 			qsort(set8->pairs, set8->cnt, sizeof(set8->pairs[0]), cmp_id);
993 			break;
994 		default:
995 			pr_err("Unexpected btf_id_kind %d for set '%s'\n", id->kind, id->name);
996 			return -1;
997 		}
998 
999 		pr_debug("sorting  addr %5lu: cnt %6d [%s]\n", off, cnt, id->name);
1000 
1001 		next = rb_next(next);
1002 	}
1003 	return 0;
1004 }
1005 
1006 static int symbols_patch(struct object *obj)
1007 {
1008 	if (__symbols_patch(obj, &obj->structs)  ||
1009 	    __symbols_patch(obj, &obj->unions)   ||
1010 	    __symbols_patch(obj, &obj->typedefs) ||
1011 	    __symbols_patch(obj, &obj->funcs)    ||
1012 	    __symbols_patch(obj, &obj->sets))
1013 		return -1;
1014 
1015 	if (sets_patch(obj))
1016 		return -1;
1017 
1018 	return 0;
1019 }
1020 
1021 static int dump_raw_data(const char *out_path, const void *data, u32 size)
1022 {
1023 	size_t written;
1024 	FILE *file;
1025 
1026 	file = fopen(out_path, "wb");
1027 	if (!file) {
1028 		pr_err("Couldn't open %s for writing\n", out_path);
1029 		return -1;
1030 	}
1031 
1032 	written = fwrite(data, 1, size, file);
1033 	if (written != size) {
1034 		pr_err("Failed to write data to %s\n", out_path);
1035 		fclose(file);
1036 		unlink(out_path);
1037 		return -1;
1038 	}
1039 
1040 	fclose(file);
1041 	pr_debug("Dumped %lu bytes of data to %s\n", size, out_path);
1042 
1043 	return 0;
1044 }
1045 
1046 static int dump_raw_btf_ids(struct object *obj, const char *out_path)
1047 {
1048 	Elf_Data *data = obj->efile.idlist;
1049 	int err;
1050 
1051 	if (!data || !data->d_buf) {
1052 		pr_debug("%s has no BTF_ids data to dump\n", obj->path);
1053 		return 0;
1054 	}
1055 
1056 	/*
1057 	 * If target endianness differs from host, we need to bswap32 the
1058 	 * .BTF_ids section data before dumping so that the output is in
1059 	 * target endianness.
1060 	 */
1061 	if (obj->efile.encoding != ELFDATANATIVE) {
1062 		pr_debug("bswap_32 .BTF_ids data from host to target endianness\n");
1063 		bswap_32_data(data->d_buf, data->d_size);
1064 	}
1065 
1066 	err = dump_raw_data(out_path, data->d_buf, data->d_size);
1067 	if (err)
1068 		return -1;
1069 
1070 	return 0;
1071 }
1072 
1073 static int dump_raw_btf(struct btf *btf, const char *out_path)
1074 {
1075 	const void *raw_btf_data;
1076 	u32 raw_btf_size;
1077 	int err;
1078 
1079 	raw_btf_data = btf__raw_data(btf, &raw_btf_size);
1080 	if (!raw_btf_data) {
1081 		pr_err("btf__raw_data() failed\n");
1082 		return -1;
1083 	}
1084 
1085 	err = dump_raw_data(out_path, raw_btf_data, raw_btf_size);
1086 	if (err)
1087 		return -1;
1088 
1089 	return 0;
1090 }
1091 
1092 static int patch_btf_link(struct object *obj, const struct btf_link *link)
1093 {
1094 	char section[128];
1095 	void *raw_btf_data = NULL;
1096 	size_t shdrstrndx, module_name_len;
1097 	int fd = -1, len, err = -1;
1098 	FILE *btf_file = NULL;
1099 	Elf_Scn *scn = NULL;
1100 	u32 raw_btf_size;
1101 	struct stat st;
1102 	Elf_Data *data;
1103 	GElf_Shdr sh;
1104 	char *name;
1105 	Elf *elf = NULL;
1106 	u8 *size;
1107 
1108 	if (stat(link->btf_path, &st)) {
1109 		err = -errno;
1110 		pr_err("FAILED to stat BTF file %s: %s\n",
1111 		       link->btf_path, strerror(errno));
1112 		return err;
1113 	}
1114 	if (!S_ISREG(st.st_mode) || st.st_size <= 0 || st.st_size > UINT_MAX) {
1115 		pr_err("FAILED: invalid BTF file size or type: %s\n", link->btf_path);
1116 		return -EINVAL;
1117 	}
1118 	raw_btf_size = st.st_size;
1119 	raw_btf_data = malloc(raw_btf_size);
1120 	if (!raw_btf_data) {
1121 		pr_err("FAILED to allocate %u bytes for BTF file %s\n",
1122 		       raw_btf_size, link->btf_path);
1123 		return -ENOMEM;
1124 	}
1125 	btf_file = fopen(link->btf_path, "rb");
1126 	if (!btf_file) {
1127 		err = -errno;
1128 		pr_err("FAILED to open BTF file %s: %s\n",
1129 		       link->btf_path, strerror(errno));
1130 		goto out;
1131 	}
1132 	if (fread(raw_btf_data, raw_btf_size, 1, btf_file) != 1) {
1133 		err = -EIO;
1134 		pr_err("FAILED to read BTF file %s\n", link->btf_path);
1135 		goto out;
1136 	}
1137 	fclose(btf_file);
1138 	btf_file = NULL;
1139 	if (obj->efile.elf_class == ELFCLASS32) {
1140 		module_name_len = BTF_LINK_MODULE_NAME_MAX - 4;
1141 	} else if (obj->efile.elf_class == ELFCLASS64) {
1142 		module_name_len = BTF_LINK_MODULE_NAME_MAX - 8;
1143 	} else {
1144 		err = -EINVAL;
1145 		pr_err("FAILED: unsupported ELF class %u in %s\n",
1146 		       obj->efile.elf_class, obj->path);
1147 		goto out;
1148 	}
1149 	if (strlen(link->module) >= module_name_len) {
1150 		err = -EINVAL;
1151 		pr_err("FAILED: module name too long for BTF link: %s\n", link->module);
1152 		goto out;
1153 	}
1154 	len = snprintf(section, sizeof(section), "%s.link", link->section);
1155 	if (len < 0 || len >= sizeof(section)) {
1156 		err = -ENAMETOOLONG;
1157 		pr_err("FAILED: BTF link section name too long: %s.link\n", link->section);
1158 		goto out;
1159 	}
1160 
1161 	fd = open(obj->path, O_RDWR);
1162 	if (fd < 0) {
1163 		err = -errno;
1164 		pr_err("FAILED to open %s: %s\n", obj->path, strerror(errno));
1165 		goto out;
1166 	}
1167 	elf = elf_begin(fd, ELF_C_RDWR_MMAP, NULL);
1168 	if (!elf) {
1169 		err = -EINVAL;
1170 		pr_err("FAILED to create ELF descriptor for %s: %s\n",
1171 		       obj->path, elf_errmsg(-1));
1172 		goto out;
1173 	}
1174 	elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
1175 	if (elf_getshdrstrndx(elf, &shdrstrndx)) {
1176 		pr_err("FAILED to get section name index from %s: %s\n",
1177 		       obj->path, elf_errmsg(-1));
1178 		goto out;
1179 	}
1180 	while ((scn = elf_nextscn(elf, scn))) {
1181 		if (gelf_getshdr(scn, &sh) != &sh) {
1182 			pr_err("FAILED to get section header from %s: %s\n",
1183 			       obj->path, elf_errmsg(-1));
1184 			goto out;
1185 		}
1186 		name = elf_strptr(elf, shdrstrndx, sh.sh_name);
1187 		if (name && !strcmp(name, section))
1188 			break;
1189 	}
1190 	if (!scn) {
1191 		pr_err("FAILED: section %s not found in %s\n", section, obj->path);
1192 		goto out;
1193 	}
1194 	data = elf_getdata(scn, NULL);
1195 	if (sh.sh_type != SHT_PROGBITS || !data || !data->d_buf ||
1196 	    data->d_size != module_name_len +
1197 		BTF_SHA256_DIGEST_LENGTH + sizeof(u32)) {
1198 		pr_err("FAILED: section %s is not a writable BTF link\n", section);
1199 		goto out;
1200 	}
1201 	memset(data->d_buf, 0, data->d_size);
1202 	memcpy(data->d_buf, link->module, strlen(link->module) + 1);
1203 	btf_sha256(raw_btf_data, raw_btf_size,
1204 		   (u8 *)data->d_buf + module_name_len);
1205 	size = (u8 *)data->d_buf + module_name_len + BTF_SHA256_DIGEST_LENGTH;
1206 	if (obj->efile.encoding == ELFDATA2LSB) {
1207 		size[0] = raw_btf_size;
1208 		size[1] = raw_btf_size >> 8;
1209 		size[2] = raw_btf_size >> 16;
1210 		size[3] = raw_btf_size >> 24;
1211 	} else if (obj->efile.encoding == ELFDATA2MSB) {
1212 		size[0] = raw_btf_size >> 24;
1213 		size[1] = raw_btf_size >> 16;
1214 		size[2] = raw_btf_size >> 8;
1215 		size[3] = raw_btf_size;
1216 	} else {
1217 		pr_err("FAILED: unsupported ELF data encoding %u in %s\n",
1218 		       obj->efile.encoding, obj->path);
1219 		goto out;
1220 	}
1221 	elf_flagdata(data, ELF_C_SET, ELF_F_DIRTY);
1222 	if (elf_update(elf, ELF_C_WRITE) < 0) {
1223 		pr_err("FAILED to update ELF file %s: %s\n",
1224 		       obj->path, elf_errmsg(-1));
1225 		goto out;
1226 	}
1227 	err = 0;
1228 out:
1229 	if (elf)
1230 		elf_end(elf);
1231 	if (fd >= 0)
1232 		close(fd);
1233 	if (btf_file)
1234 		fclose(btf_file);
1235 	free(raw_btf_data);
1236 	return err;
1237 }
1238 
1239 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf, s32 type_id)
1240 {
1241 	const struct btf_type *t = btf__type_by_id(btf, type_id);
1242 
1243 	while (btf_is_mod(t))
1244 		t = btf__type_by_id(btf, t->type);
1245 
1246 	return t;
1247 }
1248 
1249 static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
1250 {
1251 	if (ensure_mem(&ctx->decl_tags, &ctx->max_decl_tags, ctx->nr_decl_tags + 1))
1252 		return -ENOMEM;
1253 
1254 	ctx->decl_tags[ctx->nr_decl_tags++] = decl_tag_id;
1255 
1256 	return 0;
1257 }
1258 
1259 static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
1260 {
1261 	struct rb_node **p = &ctx->kfuncs.rb_node;
1262 	struct rb_node *parent = NULL;
1263 	struct kfunc *k;
1264 
1265 	/*
1266 	 * Dedup by BTF ID: collecting the same kfunc twice is a no-op,
1267 	 * UNLESS the kfunc flags are inconsistent, in which case we
1268 	 * fail hard because it indicates a bug in a kfunc set declaration.
1269 	 */
1270 	while (*p) {
1271 		parent = *p;
1272 		k = rb_entry(parent, struct kfunc, rb_node);
1273 
1274 		if (kfunc->btf_id < k->btf_id) {
1275 			p = &(*p)->rb_left;
1276 		} else if (kfunc->btf_id > k->btf_id) {
1277 			p = &(*p)->rb_right;
1278 		} else if (k->flags == kfunc->flags) {
1279 			return 0;
1280 		} else {
1281 			pr_err("ERROR: resolve_btfids: kfunc %s has inconsistent flags across BTF ID sets: 0x%x != 0x%x\n",
1282 			       kfunc->name, k->flags, kfunc->flags);
1283 			return -EINVAL;
1284 		}
1285 	}
1286 
1287 	k = zalloc(sizeof(*k));
1288 	if (!k)
1289 		return -ENOMEM;
1290 
1291 	*k = *kfunc;
1292 	rb_link_node(&k->rb_node, parent, p);
1293 	rb_insert_color(&k->rb_node, &ctx->kfuncs);
1294 
1295 	return 0;
1296 }
1297 
1298 static void free_kfuncs(struct rb_root *root)
1299 {
1300 	struct rb_node *next;
1301 	struct kfunc *kfunc;
1302 
1303 	next = rb_first(root);
1304 	while (next) {
1305 		kfunc = rb_entry(next, struct kfunc, rb_node);
1306 		next = rb_next(&kfunc->rb_node);
1307 		rb_erase(&kfunc->rb_node, root);
1308 		free(kfunc);
1309 	}
1310 }
1311 
1312 static int collect_decl_tags(struct btf2btf_context *ctx)
1313 {
1314 	const u32 type_cnt = btf__type_cnt(ctx->btf);
1315 	struct btf *btf = ctx->btf;
1316 	const struct btf_type *t;
1317 	int err;
1318 
1319 	for (u32 id = 1; id < type_cnt; id++) {
1320 		t = btf__type_by_id(btf, id);
1321 		if (!btf_is_decl_tag(t))
1322 			continue;
1323 		err = push_decl_tag_id(ctx, id);
1324 		if (err)
1325 			return err;
1326 	}
1327 
1328 	return 0;
1329 }
1330 
1331 static bool param_name_has_suffix(const char *name, const char *suffix)
1332 {
1333 	size_t name_len = strlen(name);
1334 	size_t suffix_len = strlen(suffix);
1335 
1336 	return name_len >= suffix_len && !strcmp(name + name_len - suffix_len, suffix);
1337 }
1338 
1339 static bool is_arena_param(const struct btf *btf, const struct btf_param *param)
1340 {
1341 	const char *name = btf__name_by_offset(btf, param->name_off);
1342 
1343 	return param_name_has_suffix(name, PARAM_SUFFIX_ARENA) ||
1344 	       param_name_has_suffix(name, PARAM_SUFFIX_ARENA_NULLABLE);
1345 }
1346 
1347 static int collect_kfuncs(struct object *obj, struct btf2btf_context *ctx)
1348 {
1349 	Elf_Data *idlist = obj->efile.idlist;
1350 	struct btf *btf = ctx->btf;
1351 	struct rb_node *next;
1352 
1353 	if (!idlist || !idlist->d_buf)
1354 		return 0;
1355 
1356 	for (next = rb_first(&obj->sets); next; next = rb_next(next)) {
1357 		struct btf_id_set8 *set8;
1358 		struct btf_id *set_id;
1359 		u64 set_addr;
1360 
1361 		set_id = rb_entry(next, struct btf_id, rb_node);
1362 		if (set_id->kind != BTF_ID_KIND_SET8 || set_id->addr_cnt != 1)
1363 			continue;
1364 
1365 		set_addr = set_id->addr[0];
1366 		set8 = idlist->d_buf + (set_addr - obj->efile.idlist_addr);
1367 		if (!(set8->flags & BTF_SET8_KFUNCS))
1368 			continue;
1369 
1370 		for (u32 i = 0; i < set_id->cnt; i++) {
1371 			size_t off = (char *)&set8->pairs[i] - (char *)set8;
1372 			const char *name = find_name_by_addr(obj, set_addr + off);
1373 			struct kfunc kfunc;
1374 			s32 func_id;
1375 			int err;
1376 
1377 			if (!name) {
1378 				pr_err("WARN: resolve_btfids: no BTF ID symbol for %s entry %u\n",
1379 				       set_id->name, i);
1380 				warnings++;
1381 				continue;
1382 			}
1383 
1384 			func_id = btf__find_by_name_kind_own(btf, name, BTF_KIND_FUNC);
1385 			if (func_id < 0) {
1386 				pr_err("WARN: resolve_btfids: no BTF func for kfunc %s in %s\n",
1387 				       name, set_id->name);
1388 				warnings++;
1389 				continue;
1390 			}
1391 
1392 			pr_debug("found kfunc %s in %s\n", name, set_id->name);
1393 
1394 			kfunc.name = name;
1395 			kfunc.btf_id = func_id;
1396 			kfunc.flags = set8->pairs[i].flags;
1397 			err = push_kfunc(ctx, &kfunc);
1398 			if (err)
1399 				return err;
1400 		}
1401 	}
1402 
1403 	return 0;
1404 }
1405 
1406 static int build_btf2btf_context(struct object *obj, struct btf2btf_context *ctx)
1407 {
1408 	int err;
1409 
1410 	ctx->btf = obj->btf;
1411 
1412 	err = collect_decl_tags(ctx);
1413 	if (err) {
1414 		pr_err("ERROR: resolve_btfids: failed to collect decl tags from BTF\n");
1415 		return err;
1416 	}
1417 
1418 	err = collect_kfuncs(obj, ctx);
1419 	if (err) {
1420 		pr_err("ERROR: resolve_btfids: failed to collect kfuncs from BTF\n");
1421 		return err;
1422 	}
1423 
1424 	return 0;
1425 }
1426 
1427 
1428 /* Implicit BPF kfunc arguments can only be of particular types */
1429 static bool is_kf_implicit_arg(const struct btf *btf, const struct btf_param *p)
1430 {
1431 	static const char *const kf_implicit_arg_types[] = {
1432 		"bpf_prog_aux",
1433 		"btf_struct_meta",
1434 	};
1435 	const struct btf_type *t;
1436 	const char *name;
1437 
1438 	t = btf_type_skip_qualifiers(btf, p->type);
1439 	if (!btf_is_ptr(t))
1440 		return false;
1441 
1442 	t = btf_type_skip_qualifiers(btf, t->type);
1443 	if (!btf_is_struct(t))
1444 		return false;
1445 
1446 	name = btf__name_by_offset(btf, t->name_off);
1447 	if (!name)
1448 		return false;
1449 
1450 	for (int i = 0; i < ARRAY_SIZE(kf_implicit_arg_types); i++)
1451 		if (strcmp(name, kf_implicit_arg_types[i]) == 0)
1452 			return true;
1453 
1454 	return false;
1455 }
1456 
1457 /*
1458  * For a kfunc with KF_IMPLICIT_ARGS we do the following:
1459  *   1. Add a new function with _impl suffix in the name, with the prototype
1460  *      of the original kfunc.
1461  *   2. Add all decl tags except "bpf_kfunc" for the _impl func.
1462  *   3. Add a new function prototype with modified list of arguments:
1463  *      omitting implicit args.
1464  *   4. Change the prototype of the original kfunc to the new one.
1465  *
1466  * This way we transform the BTF associated with the kfunc from
1467  *	__bpf_kfunc bpf_foo(int arg1, void *implicit_arg);
1468  * into
1469  *	bpf_foo_impl(int arg1, void *implicit_arg);
1470  *	__bpf_kfunc bpf_foo(int arg1);
1471  *
1472  * If a kfunc with KF_IMPLICIT_ARGS already has an _impl counterpart
1473  * in BTF, then it's a legacy case: an _impl function is declared in the
1474  * source code. In this case, we can skip adding an _impl function, but we
1475  * still have to add a func prototype that omits implicit args.
1476  */
1477 static int process_kfunc_with_implicit_args(struct btf2btf_context *ctx, struct kfunc *kfunc)
1478 {
1479 	s32 idx, new_proto_id, new_func_id, proto_id;
1480 	const char *param_name, *tag_name;
1481 	const struct btf_param *params;
1482 	enum btf_func_linkage linkage;
1483 	char tmp_name[KSYM_NAME_LEN];
1484 	struct btf *btf = ctx->btf;
1485 	int err, len, nr_params;
1486 	struct btf_type *t;
1487 
1488 	t = (struct btf_type *)btf__type_by_id(btf, kfunc->btf_id);
1489 	if (!t || !btf_is_func(t)) {
1490 		pr_err("ERROR: resolve_btfids: btf id %d is not a function\n", kfunc->btf_id);
1491 		return -EINVAL;
1492 	}
1493 
1494 	linkage = btf_vlen(t);
1495 
1496 	proto_id = t->type;
1497 	t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1498 	if (!t || !btf_is_func_proto(t)) {
1499 		pr_err("ERROR: resolve_btfids: btf id %d is not a function prototype\n", proto_id);
1500 		return -EINVAL;
1501 	}
1502 
1503 	len = snprintf(tmp_name, sizeof(tmp_name), "%s%s", kfunc->name, KF_IMPL_SUFFIX);
1504 	if (len < 0 || len >= sizeof(tmp_name)) {
1505 		pr_err("ERROR: function name is too long: %s%s\n", kfunc->name, KF_IMPL_SUFFIX);
1506 		return -E2BIG;
1507 	}
1508 
1509 	if (btf__find_by_name_kind_own(btf, tmp_name, BTF_KIND_FUNC) > 0) {
1510 		pr_debug("resolve_btfids: function %s already exists in BTF\n", tmp_name);
1511 		goto add_new_proto;
1512 	}
1513 
1514 	/* Add a new function with _impl suffix and original prototype */
1515 	new_func_id = btf__add_func(btf, tmp_name, linkage, proto_id);
1516 	if (new_func_id < 0) {
1517 		pr_err("ERROR: resolve_btfids: failed to add func %s to BTF\n", tmp_name);
1518 		return new_func_id;
1519 	}
1520 
1521 	/* Copy all decl tags except "bpf_kfunc" from the original kfunc to the new one */
1522 	for (int i = 0; i < ctx->nr_decl_tags; i++) {
1523 		t = (struct btf_type *)btf__type_by_id(btf, ctx->decl_tags[i]);
1524 		if (t->type != kfunc->btf_id)
1525 			continue;
1526 
1527 		tag_name = btf__name_by_offset(btf, t->name_off);
1528 		if (strcmp(tag_name, DECL_TAG_KFUNC) == 0)
1529 			continue;
1530 
1531 		idx = btf_decl_tag(t)->component_idx;
1532 
1533 		if (btf_kflag(t))
1534 			err = btf__add_decl_attr(btf, tag_name, new_func_id, idx);
1535 		else
1536 			err = btf__add_decl_tag(btf, tag_name, new_func_id, idx);
1537 
1538 		if (err < 0) {
1539 			pr_err("ERROR: resolve_btfids: failed to add decl tag %s for %s\n",
1540 			       tag_name, tmp_name);
1541 			return -EINVAL;
1542 		}
1543 	}
1544 
1545 add_new_proto:
1546 	t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1547 	new_proto_id = btf__add_func_proto(btf, t->type);
1548 	if (new_proto_id < 0) {
1549 		pr_err("ERROR: resolve_btfids: failed to add func proto for %s\n", kfunc->name);
1550 		return new_proto_id;
1551 	}
1552 
1553 	/* Add non-implicit args to the new prototype */
1554 	t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1555 	nr_params = btf_vlen(t);
1556 	for (int i = 0; i < nr_params; i++) {
1557 		params = btf_params(t);
1558 		if (is_kf_implicit_arg(btf, &params[i]))
1559 			break;
1560 		param_name = btf__name_by_offset(btf, params[i].name_off);
1561 		err = btf__add_func_param(btf, param_name, params[i].type);
1562 		if (err < 0) {
1563 			pr_err("ERROR: resolve_btfids: failed to add param %s for %s\n",
1564 			       param_name, kfunc->name);
1565 			return err;
1566 		}
1567 		t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1568 	}
1569 
1570 	/* Finally change the prototype of the original kfunc to the new one */
1571 	t = (struct btf_type *)btf__type_by_id(btf, kfunc->btf_id);
1572 	t->type = new_proto_id;
1573 
1574 	pr_debug("resolve_btfids: updated BTF for kfunc with implicit args %s\n", kfunc->name);
1575 
1576 	return 0;
1577 }
1578 
1579 static bool is_arena_arg(const struct btf *btf, const struct kfunc *kfunc,
1580 			 const struct btf_param *param, u32 idx)
1581 {
1582 	if (is_arena_param(btf, param))
1583 		return true;
1584 
1585 	switch (idx) {
1586 	case 0:
1587 		return kfunc->flags & KF_ARENA_ARG1;
1588 	case 1:
1589 		return kfunc->flags & KF_ARENA_ARG2;
1590 	default:
1591 		return false;
1592 	}
1593 }
1594 
1595 static s32 arena_tag_ptr(struct btf *btf, u32 ptr_id, struct kfunc *kfunc)
1596 {
1597 	const struct btf_type *ptr = btf__type_by_id(btf, ptr_id);
1598 	s32 tag_id, new_ptr_id;
1599 
1600 	if (!btf_is_ptr(ptr)) {
1601 		pr_err("ERROR: resolve_btfids: kfunc %s: arena type is not a pointer\n",
1602 		       kfunc->name);
1603 		return -EINVAL;
1604 	}
1605 
1606 	tag_id = btf__add_type_attr(btf, TYPE_ATTR_ARENA, ptr->type);
1607 	if (tag_id < 0) {
1608 		pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a type attr to BTF: %d\n",
1609 		       kfunc->name, tag_id);
1610 		return tag_id;
1611 	}
1612 
1613 	new_ptr_id = btf__add_ptr(btf, tag_id);
1614 	if (new_ptr_id < 0) {
1615 		pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a pointer to BTF: %d\n",
1616 		       kfunc->name, new_ptr_id);
1617 	}
1618 
1619 	return new_ptr_id;
1620 }
1621 
1622 /*
1623  * Add a FUNC_PROTO for @kfunc with each arena pointer tagged with an
1624  * "address_space(1)" attribute. The original proto may be shared with
1625  * other FUNCs, so it is never modified in place. Returns the original
1626  * proto id when @kfunc has no arena return value or arguments.
1627  */
1628 static s32 add_arena_tagged_proto(struct btf *btf, struct kfunc *kfunc)
1629 {
1630 	const struct btf_type *func = btf__type_by_id(btf, kfunc->btf_id);
1631 	u32 proto_id = func->type;
1632 	const struct btf_type *proto = btf__type_by_id(btf, proto_id);
1633 	const struct btf_param *params = btf_params(proto);
1634 	u32 nr_params = btf_vlen(proto);
1635 	s32 ret_type_id = proto->type;
1636 	const struct btf_type *t;
1637 	struct btf_param *tag_params;
1638 	s32 new_proto_id, id;
1639 	const char *name;
1640 	bool has_arena_arg = false;
1641 	int err, i;
1642 
1643 	for (i = 0; i < nr_params; i++) {
1644 		if (is_arena_arg(btf, kfunc, &params[i], i)) {
1645 			has_arena_arg = true;
1646 			break;
1647 		}
1648 	}
1649 
1650 	if (!(kfunc->flags & KF_ARENA_RET) && !has_arena_arg)
1651 		return proto_id;
1652 
1653 	if (kfunc->flags & KF_ARENA_RET) {
1654 		ret_type_id = arena_tag_ptr(btf, ret_type_id, kfunc);
1655 		if (ret_type_id < 0)
1656 			return ret_type_id;
1657 	}
1658 
1659 	new_proto_id = btf__add_func_proto(btf, ret_type_id);
1660 	if (new_proto_id < 0) {
1661 		pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a func proto to BTF: %d\n",
1662 		       kfunc->name, new_proto_id);
1663 		return new_proto_id;
1664 	}
1665 
1666 	for (i = 0; i < nr_params; i++) {
1667 		/* btf__add_func_param() below may move the proto, re-fetch */
1668 		proto = btf__type_by_id(btf, proto_id);
1669 		name = btf__name_by_offset(btf, btf_params(proto)[i].name_off);
1670 
1671 		err = btf__add_func_param(btf, name ?: "", btf_params(proto)[i].type);
1672 		if (err < 0) {
1673 			pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a proto param to BTF: %d\n",
1674 			       kfunc->name, err);
1675 			return err;
1676 		}
1677 	}
1678 
1679 	for (i = 0; i < nr_params; i++) {
1680 		t = btf__type_by_id(btf, new_proto_id);
1681 		tag_params = btf_params(t);
1682 		if (!is_arena_arg(btf, kfunc, &tag_params[i], i))
1683 			continue;
1684 
1685 		id = arena_tag_ptr(btf, tag_params[i].type, kfunc);
1686 		if (id < 0)
1687 			return id;
1688 
1689 		t = btf__type_by_id(btf, new_proto_id);
1690 		tag_params = btf_params(t);
1691 		tag_params[i].type = id;
1692 	}
1693 
1694 	pr_debug("added arena-tagged proto for kfunc %s: %d\n", kfunc->name, new_proto_id);
1695 
1696 	return new_proto_id;
1697 }
1698 
1699 static int process_kfunc_with_arena_attrs(struct btf2btf_context *ctx,
1700 					  struct kfunc *kfunc)
1701 {
1702 	struct btf_type *t;
1703 	s32 proto_id;
1704 
1705 	proto_id = add_arena_tagged_proto(ctx->btf, kfunc);
1706 	if (proto_id < 0)
1707 		return proto_id;
1708 
1709 	t = (struct btf_type *)btf__type_by_id(ctx->btf, kfunc->btf_id);
1710 	t->type = proto_id;
1711 
1712 	return 0;
1713 }
1714 
1715 static int add_decl_tag(struct btf2btf_context *ctx, const char *tag_name,
1716 			u32 target_btf_id, int component_idx)
1717 {
1718 	s32 new_id;
1719 
1720 	new_id = btf__add_decl_tag(ctx->btf, tag_name, target_btf_id, component_idx);
1721 	if (new_id < 0) {
1722 		pr_err("ERROR: resolve_btfids: failed to add '%s' decl tag for BTF id %u: %d\n",
1723 		       tag_name, target_btf_id, new_id);
1724 		return new_id;
1725 	}
1726 
1727 	return push_decl_tag_id(ctx, new_id);
1728 }
1729 
1730 static int btf2btf(struct object *obj)
1731 {
1732 	struct btf2btf_context ctx = {};
1733 	struct rb_node *next;
1734 	int err;
1735 
1736 	err = build_btf2btf_context(obj, &ctx);
1737 	if (err)
1738 		goto out;
1739 
1740 	for (next = rb_first(&ctx.kfuncs); next; next = rb_next(next)) {
1741 		struct kfunc *kfunc = rb_entry(next, struct kfunc, rb_node);
1742 
1743 		err = add_decl_tag(&ctx, DECL_TAG_KFUNC, kfunc->btf_id, -1);
1744 		if (err)
1745 			goto out;
1746 
1747 		if (kfunc->flags & KF_FASTCALL) {
1748 			err = add_decl_tag(&ctx, DECL_TAG_FASTCALL, kfunc->btf_id, -1);
1749 			if (err)
1750 				goto out;
1751 		}
1752 
1753 		if (kfunc->flags & KF_IMPLICIT_ARGS) {
1754 			err = process_kfunc_with_implicit_args(&ctx, kfunc);
1755 			if (err)
1756 				goto out;
1757 		}
1758 
1759 		err = process_kfunc_with_arena_attrs(&ctx, kfunc);
1760 		if (err)
1761 			goto out;
1762 	}
1763 
1764 	err = 0;
1765 out:
1766 	free(ctx.decl_tags);
1767 	free_kfuncs(&ctx.kfuncs);
1768 
1769 	return err;
1770 }
1771 
1772 static bool keep_in_base_btf(struct object *obj, const struct btf_type *t)
1773 {
1774 	const char *name;
1775 
1776 	switch (btf_kind(t)) {
1777 	case BTF_KIND_FUNC:
1778 		name = btf__name_by_offset(obj->btf, t->name_off);
1779 		return !obj->efile.func_symbols_collected || has_func_symbol(obj, name) ||
1780 		       btf_id__find(&obj->funcs, name);
1781 	case BTF_KIND_FUNC_PROTO:
1782 	case BTF_KIND_LOC_PARAM:
1783 	case BTF_KIND_LOC_PROTO:
1784 	case BTF_KIND_LOCSEC:
1785 		return false;
1786 	default:
1787 		/*
1788 		 * Ordinary types stay in base btf even if only inline records use them.
1789 		 * Should we relax this?
1790 		 */
1791 		return true;
1792 	}
1793 }
1794 
1795 /* Mark which types should go to .BTF.inline */
1796 static int color_btf(struct object *obj, __u8 *colors)
1797 {
1798 	struct btf *btf = obj->btf;
1799 	const struct btf *base = btf__base_btf(btf);
1800 	__u32 start_id = base ? btf__type_cnt(base) : 1;
1801 	__u32 type_cnt = btf__type_cnt(btf), i;
1802 	__u32 *worklist;
1803 
1804 	worklist = malloc((type_cnt - start_id ?: 1) * sizeof(*worklist));
1805 	if (!worklist)
1806 		return -ENOMEM;
1807 	/* First, mark all types reachable from LOC BTF entries. */
1808 	for (i = start_id; i < type_cnt; i++) {
1809 		const struct btf_type *t = btf__type_by_id(btf, i);
1810 
1811 		if (!btf_is_locsec(t) && !btf_is_loc_proto(t) && !btf_is_loc_param(t))
1812 			continue;
1813 		btf_mark_reachable(btf, i, BTF_COLOR_LOC, colors, worklist);
1814 	}
1815 	/* Next, traverse non-marked types converting some LOC markings to SHARED. */
1816 	for (i = start_id; i < type_cnt; i++) {
1817 		const struct btf_type *t = btf__type_by_id(btf, i);
1818 
1819 		if (colors[i] == BTF_COLOR_LOC && !keep_in_base_btf(obj, t))
1820 			continue;
1821 		btf_mark_reachable(btf, i, BTF_COLOR_MAIN, colors, worklist);
1822 	}
1823 	free(worklist);
1824 	return 0;
1825 }
1826 
1827 static int extract_inline_btf(struct object *obj)
1828 {
1829 	struct btf *btf = obj->btf, *main_btf, *inline_btf;
1830 	__u8 *colors;
1831 	int err;
1832 
1833 	colors = calloc(btf__type_cnt(btf), sizeof(*colors));
1834 	if (!colors)
1835 		return -ENOMEM;
1836 	err = color_btf(obj, colors);
1837 	if (err)
1838 		goto out;
1839 	err = btf_split_by_color(btf, colors, &main_btf, &inline_btf);
1840 	if (!err) {
1841 		obj->orig_btf = btf;
1842 		obj->btf = main_btf;
1843 		obj->inline_btf = inline_btf;
1844 	}
1845 out:
1846 	free(colors);
1847 	return err;
1848 }
1849 
1850 /*
1851  * Sort types by name in ascending order resulting in all
1852  * anonymous types being placed before named types.
1853  */
1854 static int cmp_type_names(const void *a, const void *b, void *priv)
1855 {
1856 	struct btf *btf = (struct btf *)priv;
1857 	const struct btf_type *ta = btf__type_by_id(btf, *(__u32 *)a);
1858 	const struct btf_type *tb = btf__type_by_id(btf, *(__u32 *)b);
1859 	const char *na, *nb;
1860 	int r;
1861 
1862 	na = btf__str_by_offset(btf, ta->name_off);
1863 	nb = btf__str_by_offset(btf, tb->name_off);
1864 	r = strcmp(na, nb);
1865 	if (r != 0)
1866 		return r;
1867 
1868 	/* preserve original relative order of anonymous or same-named types */
1869 	return *(__u32 *)a < *(__u32 *)b ? -1 : 1;
1870 }
1871 
1872 static int sort_btf_by_name(struct btf *btf)
1873 {
1874 	__u32 *permute_ids = NULL, *id_map = NULL;
1875 	int nr_types, i, err = 0;
1876 	__u32 start_id = 0, id;
1877 
1878 	if (btf__base_btf(btf))
1879 		start_id = btf__type_cnt(btf__base_btf(btf));
1880 	nr_types = btf__type_cnt(btf) - start_id;
1881 
1882 	permute_ids = calloc(nr_types, sizeof(*permute_ids));
1883 	if (!permute_ids) {
1884 		err = -ENOMEM;
1885 		goto out;
1886 	}
1887 
1888 	id_map = calloc(nr_types, sizeof(*id_map));
1889 	if (!id_map) {
1890 		err = -ENOMEM;
1891 		goto out;
1892 	}
1893 
1894 	for (i = 0, id = start_id; i < nr_types; i++, id++)
1895 		permute_ids[i] = id;
1896 
1897 	qsort_r(permute_ids, nr_types, sizeof(*permute_ids), cmp_type_names,
1898 		btf);
1899 
1900 	for (i = 0; i < nr_types; i++) {
1901 		id = permute_ids[i] - start_id;
1902 		id_map[id] = i + start_id;
1903 	}
1904 
1905 	err = btf__permute(btf, id_map, nr_types, NULL);
1906 	if (err)
1907 		pr_err("FAILED: btf permute: %s\n", strerror(-err));
1908 
1909 out:
1910 	free(permute_ids);
1911 	free(id_map);
1912 	return err;
1913 }
1914 
1915 static int finalize_btf(struct object *obj)
1916 {
1917 	struct btf *base_btf = obj->base_btf, *btf = obj->btf;
1918 	int err;
1919 
1920 	err = btf__dedup(obj->btf, NULL);
1921 	if (err) {
1922 		pr_err("FAILED to dedup BTF: %s\n", strerror(errno));
1923 		return err;
1924 	}
1925 
1926 	if (obj->base_btf && obj->distill_base) {
1927 		err = btf__distill_base(obj->btf, &base_btf, &btf);
1928 		if (err) {
1929 			pr_err("FAILED to distill base BTF: %s\n", strerror(errno));
1930 			return err;
1931 		}
1932 
1933 		btf__free(obj->base_btf);
1934 		btf__free(obj->btf);
1935 		obj->base_btf = base_btf;
1936 		obj->btf = btf;
1937 	}
1938 
1939 	err = sort_btf_by_name(obj->btf);
1940 	if (err) {
1941 		pr_err("FAILED to sort BTF: %s\n", strerror(errno));
1942 		return err;
1943 	}
1944 
1945 	if (obj->extract_inline) {
1946 		err = extract_inline_btf(obj);
1947 		if (err) {
1948 			pr_err("FAILED to extract inline BTF: %s\n", strerror(-err));
1949 			return err;
1950 		}
1951 	}
1952 
1953 	return 0;
1954 }
1955 
1956 static inline int make_out_path(char *buf, u32 buf_sz, const char *in_path, const char *suffix)
1957 {
1958 	int len = snprintf(buf, buf_sz, "%s%s", in_path, suffix);
1959 
1960 	if (len < 0 || len >= buf_sz) {
1961 		pr_err("Output path is too long: %s%s\n", in_path, suffix);
1962 		return -E2BIG;
1963 	}
1964 
1965 	return 0;
1966 }
1967 
1968 /*
1969  * Patch the .BTF_ids section of an ELF file with data from provided file.
1970  * Equivalent to: objcopy --update-section .BTF_ids=<btfids> <elf>
1971  *
1972  * 1. Find .BTF_ids section in the ELF
1973  * 2. Verify that blob file size matches section size
1974  * 3. Update section data buffer with blob data
1975  * 4. Write the ELF file
1976  */
1977 static int patch_btfids(const char *btfids_path, const char *elf_path)
1978 {
1979 	Elf_Scn *scn = NULL;
1980 	FILE *btfids_file;
1981 	size_t shdrstrndx;
1982 	int fd, err = -1;
1983 	Elf_Data *data;
1984 	struct stat st;
1985 	GElf_Shdr sh;
1986 	char *name;
1987 	Elf *elf;
1988 
1989 	elf_version(EV_CURRENT);
1990 
1991 	fd = open(elf_path, O_RDWR, 0666);
1992 	if (fd < 0) {
1993 		pr_err("FAILED to open %s: %s\n", elf_path, strerror(errno));
1994 		return -1;
1995 	}
1996 
1997 	elf = elf_begin(fd, ELF_C_RDWR_MMAP, NULL);
1998 	if (!elf) {
1999 		close(fd);
2000 		pr_err("FAILED cannot create ELF descriptor: %s\n", elf_errmsg(-1));
2001 		return -1;
2002 	}
2003 
2004 	elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
2005 
2006 	if (elf_getshdrstrndx(elf, &shdrstrndx) != 0) {
2007 		pr_err("FAILED cannot get shdr str ndx\n");
2008 		goto out;
2009 	}
2010 
2011 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
2012 
2013 		if (gelf_getshdr(scn, &sh) != &sh) {
2014 			pr_err("FAILED to get section header\n");
2015 			goto out;
2016 		}
2017 
2018 		name = elf_strptr(elf, shdrstrndx, sh.sh_name);
2019 		if (!name)
2020 			continue;
2021 
2022 		if (strcmp(name, BTF_IDS_SECTION) == 0)
2023 			break;
2024 	}
2025 
2026 	if (!scn) {
2027 		pr_err("FAILED: section %s not found in %s\n", BTF_IDS_SECTION, elf_path);
2028 		goto out;
2029 	}
2030 
2031 	data = elf_getdata(scn, NULL);
2032 	if (!data) {
2033 		pr_err("FAILED to get %s section data from %s\n", BTF_IDS_SECTION, elf_path);
2034 		goto out;
2035 	}
2036 
2037 	if (stat(btfids_path, &st) < 0) {
2038 		pr_err("FAILED to stat %s: %s\n", btfids_path, strerror(errno));
2039 		goto out;
2040 	}
2041 
2042 	if ((size_t)st.st_size != data->d_size) {
2043 		pr_err("FAILED: size mismatch - %s section in %s is %zu bytes, %s is %zu bytes\n",
2044 		       BTF_IDS_SECTION, elf_path, data->d_size, btfids_path, (size_t)st.st_size);
2045 		goto out;
2046 	}
2047 
2048 	btfids_file = fopen(btfids_path, "rb");
2049 	if (!btfids_file) {
2050 		pr_err("FAILED to open %s: %s\n", btfids_path, strerror(errno));
2051 		goto out;
2052 	}
2053 
2054 	pr_debug("Copying data from %s to %s section of %s (%zu bytes)\n",
2055 		 btfids_path, BTF_IDS_SECTION, elf_path, data->d_size);
2056 
2057 	if (fread(data->d_buf, data->d_size, 1, btfids_file) != 1) {
2058 		pr_err("FAILED to read %s\n", btfids_path);
2059 		fclose(btfids_file);
2060 		goto out;
2061 	}
2062 	fclose(btfids_file);
2063 
2064 	elf_flagdata(data, ELF_C_SET, ELF_F_DIRTY);
2065 	if (elf_update(elf, ELF_C_WRITE) < 0) {
2066 		pr_err("FAILED to update ELF file %s\n", elf_path);
2067 		goto out;
2068 	}
2069 
2070 	err = 0;
2071 out:
2072 	elf_end(elf);
2073 	close(fd);
2074 
2075 	return err;
2076 }
2077 
2078 static const char * const resolve_btfids_usage[] = {
2079 	"resolve_btfids [<options>] <ELF object>",
2080 	"resolve_btfids --patch_btfids <.BTF_ids file> [--btf_link <section:module:btf-file>] <ELF object>",
2081 	NULL
2082 };
2083 
2084 int main(int argc, const char **argv)
2085 {
2086 	struct object obj = {
2087 		.efile = {
2088 			.idlist_shndx  = -1,
2089 			.symbols_shndx = -1,
2090 		},
2091 		.structs  = RB_ROOT,
2092 		.unions   = RB_ROOT,
2093 		.typedefs = RB_ROOT,
2094 		.funcs    = RB_ROOT,
2095 		.sets     = RB_ROOT,
2096 	};
2097 	const char *btfids_path = NULL;
2098 	struct btf_links btf_links = {};
2099 	bool fatal_warnings = false;
2100 	bool resolve_btfids = true;
2101 	char out_path[PATH_MAX];
2102 
2103 	struct option btfid_options[] = {
2104 		OPT_INCR('v', "verbose", &verbose,
2105 			 "be more verbose (show errors, etc)"),
2106 		OPT_STRING(0, "btf", &obj.btf_path, "file",
2107 			   "path to a file with input BTF data"),
2108 		OPT_STRING('b', "btf_base", &obj.base_btf_path, "file",
2109 			   "path of file providing base BTF"),
2110 		OPT_BOOLEAN(0, "fatal_warnings", &fatal_warnings,
2111 			    "turn warnings into errors"),
2112 		OPT_BOOLEAN(0, "distill_base", &obj.distill_base,
2113 			    "distill --btf_base and emit .BTF.base section data"),
2114 		OPT_BOOLEAN(0, "inline", &obj.extract_inline,
2115 			    "extract location BTF into a .BTF.inline file"),
2116 		OPT_CALLBACK(0, "btf_link", &btf_links, "section:module:btf-file",
2117 			     "patch a BTF link with --patch_btfids", parse_btf_link),
2118 		OPT_STRING(0, "patch_btfids", &btfids_path, "file",
2119 			   "path to .BTF_ids section data blob to patch into ELF file"),
2120 		OPT_END()
2121 	};
2122 	int err = -1;
2123 
2124 	argc = parse_options(argc, argv, btfid_options, resolve_btfids_usage,
2125 			     PARSE_OPT_STOP_AT_NON_OPTION);
2126 	if (argc != 1)
2127 		usage_with_options(resolve_btfids_usage, btfid_options);
2128 	if (btf_links.cnt && !btfids_path) {
2129 		pr_err("--btf_link requires --patch_btfids\n");
2130 		goto out;
2131 	}
2132 
2133 	obj.path = argv[0];
2134 
2135 	if (btfids_path) {
2136 		err = patch_btfids(btfids_path, obj.path);
2137 		if (err || !btf_links.cnt)
2138 			goto out;
2139 		if (elf_collect(&obj)) {
2140 			err = -EINVAL;
2141 			goto out;
2142 		}
2143 		for (u32 i = 0; i < btf_links.cnt; i++) {
2144 			struct btf_link *link = &btf_links.links[i];
2145 
2146 			err = patch_btf_link(&obj, link);
2147 			if (err)
2148 				break;
2149 		}
2150 		goto out;
2151 	}
2152 	if (elf_collect(&obj))
2153 		goto out;
2154 	if (obj.extract_inline && collect_func_symbols(&obj))
2155 		goto out;
2156 
2157 	/*
2158 	 * We did not find .BTF_ids section or symbols section,
2159 	 * nothing to do..
2160 	 */
2161 	if (obj.efile.idlist_shndx == -1 ||
2162 	    obj.efile.symbols_shndx == -1) {
2163 		pr_debug("Cannot find .BTF_ids or symbols sections, skip symbols resolution\n");
2164 		resolve_btfids = false;
2165 	}
2166 
2167 	if (resolve_btfids)
2168 		if (symbols_collect(&obj))
2169 			goto out;
2170 
2171 	if (load_btf(&obj))
2172 		goto out;
2173 
2174 	if (btf2btf(&obj))
2175 		goto out;
2176 
2177 	if (finalize_btf(&obj))
2178 		goto out;
2179 
2180 	if (!resolve_btfids)
2181 		goto dump_btf;
2182 
2183 	if (symbols_resolve(&obj))
2184 		goto out;
2185 
2186 	if (symbols_patch(&obj))
2187 		goto out;
2188 
2189 	err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_IDS_SECTION);
2190 	err = err ?: dump_raw_btf_ids(&obj, out_path);
2191 	if (err)
2192 		goto out;
2193 
2194 dump_btf:
2195 	err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_ELF_SEC);
2196 	err = err ?: dump_raw_btf(obj.btf, out_path);
2197 	if (err)
2198 		goto out;
2199 
2200 	if (obj.base_btf && obj.distill_base) {
2201 		err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_BASE_ELF_SEC);
2202 		err = err ?: dump_raw_btf(obj.base_btf, out_path);
2203 		if (err)
2204 			goto out;
2205 	}
2206 	if (obj.inline_btf) {
2207 		err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_ELF_SEC ".inline");
2208 		err = err ?: dump_raw_btf(obj.inline_btf, out_path);
2209 		if (err)
2210 			goto out;
2211 	}
2212 
2213 	err = fatal_warnings && warnings ? -1 : 0;
2214 out:
2215 	free_btf_links(&btf_links);
2216 	/*
2217 	 * Free BTFs in reverse dependency order.  inline_btf borrows obj.btf;
2218 	 * obj.btf can borrow a base owned by orig_btf or obj.base_btf, and
2219 	 * orig_btf can also borrow obj.base_btf.
2220 	 */
2221 	btf__free(obj.inline_btf);
2222 	btf__free(obj.btf);
2223 	btf__free(obj.orig_btf);
2224 	btf__free(obj.base_btf);
2225 	btf_id__free_all(&obj.structs);
2226 	btf_id__free_all(&obj.unions);
2227 	btf_id__free_all(&obj.typedefs);
2228 	btf_id__free_all(&obj.funcs);
2229 	btf_id__free_all(&obj.sets);
2230 	free(obj.addr_syms);
2231 	free(obj.efile.func_symbols);
2232 	if (obj.efile.elf) {
2233 		elf_end(obj.efile.elf);
2234 		close(obj.efile.fd);
2235 	}
2236 	return err;
2237 }
2238