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 <subcmd/parse-options.h>
93
94 #define BTF_IDS_SECTION ".BTF_ids"
95 #define BTF_ID_PREFIX "__BTF_ID__"
96
97 #define BTF_STRUCT "struct"
98 #define BTF_UNION "union"
99 #define BTF_TYPEDEF "typedef"
100 #define BTF_FUNC "func"
101 #define BTF_SET "set"
102 #define BTF_SET8 "set8"
103
104 #define ADDR_CNT 100
105
106 #if __BYTE_ORDER == __LITTLE_ENDIAN
107 # define ELFDATANATIVE ELFDATA2LSB
108 #elif __BYTE_ORDER == __BIG_ENDIAN
109 # define ELFDATANATIVE ELFDATA2MSB
110 #else
111 # error "Unknown machine endianness!"
112 #endif
113
114 enum btf_id_kind {
115 BTF_ID_KIND_NONE,
116 BTF_ID_KIND_SYM,
117 BTF_ID_KIND_SET,
118 BTF_ID_KIND_SET8
119 };
120
121 struct btf_id {
122 struct rb_node rb_node;
123 char *name;
124 union {
125 int id;
126 int cnt;
127 };
128 enum btf_id_kind kind;
129 int addr_cnt;
130 Elf64_Addr addr[ADDR_CNT];
131 };
132
133 struct addr_sym {
134 Elf64_Addr addr;
135 const char *name;
136 };
137
138 struct object {
139 const char *path;
140 const char *btf_path;
141 const char *base_btf_path;
142
143 struct btf *btf;
144 struct btf *base_btf;
145 bool distill_base;
146
147 struct {
148 int fd;
149 Elf *elf;
150 Elf_Data *symbols;
151 Elf_Data *idlist;
152 int symbols_shndx;
153 int idlist_shndx;
154 size_t strtabidx;
155 unsigned long idlist_addr;
156 int encoding;
157 } efile;
158
159 struct rb_root sets;
160 struct rb_root structs;
161 struct rb_root unions;
162 struct rb_root typedefs;
163 struct rb_root funcs;
164
165 int nr_funcs;
166 int nr_structs;
167 int nr_unions;
168 int nr_typedefs;
169
170 struct addr_sym *addr_syms;
171 u32 addr_syms_cnt;
172 u32 addr_syms_cap;
173 };
174
175 #define DECL_TAG_FASTCALL "bpf_fastcall"
176 #define DECL_TAG_KFUNC "bpf_kfunc"
177
178 #define KF_FASTCALL (1 << 12)
179 #define KF_ARENA_RET (1 << 13)
180 #define KF_ARENA_ARG1 (1 << 14)
181 #define KF_ARENA_ARG2 (1 << 15)
182 #define KF_IMPLICIT_ARGS (1 << 16)
183 #define KF_IMPL_SUFFIX "_impl"
184 #define TYPE_ATTR_ARENA "address_space(1)"
185 #define PARAM_SUFFIX_ARENA "__arena"
186 #define PARAM_SUFFIX_ARENA_NULLABLE "__arena__nullable"
187
188 struct kfunc {
189 struct rb_node rb_node;
190 const char *name;
191 u32 btf_id;
192 u32 flags;
193 };
194
195 struct btf2btf_context {
196 struct btf *btf;
197 u32 *decl_tags;
198 u32 nr_decl_tags;
199 u32 max_decl_tags;
200 struct rb_root kfuncs;
201 };
202
203 static int verbose;
204 static int warnings;
205
eprintf(int level,int var,const char * fmt,...)206 static int eprintf(int level, int var, const char *fmt, ...)
207 {
208 va_list args;
209 int ret = 0;
210
211 if (var >= level) {
212 va_start(args, fmt);
213 ret = vfprintf(stderr, fmt, args);
214 va_end(args);
215 }
216 return ret;
217 }
218
219 #ifndef pr_fmt
220 #define pr_fmt(fmt) fmt
221 #endif
222
223 #define pr_debug(fmt, ...) \
224 eprintf(1, verbose, pr_fmt(fmt), ##__VA_ARGS__)
225 #define pr_debugN(n, fmt, ...) \
226 eprintf(n, verbose, pr_fmt(fmt), ##__VA_ARGS__)
227 #define pr_debug2(fmt, ...) pr_debugN(2, pr_fmt(fmt), ##__VA_ARGS__)
228 #define pr_err(fmt, ...) \
229 eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
230 #define pr_info(fmt, ...) \
231 eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__)
232
233 /*
234 * Grow *data so it can hold at least cnt elements of elem_sz bytes each.
235 * *cap is the capacity in elements and is updated on growth.
236 */
__ensure_mem(void ** data,u32 * cap,u32 cnt,size_t elem_sz)237 static int __ensure_mem(void **data, u32 *cap, u32 cnt, size_t elem_sz)
238 {
239 u32 new_cap, old_cap = *cap;
240 void *arr;
241
242 if (cnt <= old_cap)
243 return 0;
244
245 new_cap = max(old_cap + 256, old_cap * 2);
246 if (new_cap < cnt)
247 new_cap = cnt;
248
249 arr = realloc(*data, elem_sz * new_cap);
250 if (!arr)
251 return -ENOMEM;
252
253 *data = arr;
254 *cap = new_cap;
255
256 return 0;
257 }
258
259 #define ensure_mem(arr_ptr, cap_ptr, cnt) \
260 __ensure_mem((void **)(arr_ptr), (cap_ptr), (cnt), sizeof(**(arr_ptr)))
261
is_btf_id(const char * name)262 static bool is_btf_id(const char *name)
263 {
264 return name && !strncmp(name, BTF_ID_PREFIX, sizeof(BTF_ID_PREFIX) - 1);
265 }
266
btf_id__find(struct rb_root * root,const char * name)267 static struct btf_id *btf_id__find(struct rb_root *root, const char *name)
268 {
269 struct rb_node *p = root->rb_node;
270 struct btf_id *id;
271 int cmp;
272
273 while (p) {
274 id = rb_entry(p, struct btf_id, rb_node);
275 cmp = strcmp(id->name, name);
276 if (cmp < 0)
277 p = p->rb_left;
278 else if (cmp > 0)
279 p = p->rb_right;
280 else
281 return id;
282 }
283 return NULL;
284 }
285
__btf_id__add(struct rb_root * root,const char * name,enum btf_id_kind kind,bool unique)286 static struct btf_id *__btf_id__add(struct rb_root *root,
287 const char *name,
288 enum btf_id_kind kind,
289 bool unique)
290 {
291 struct rb_node **p = &root->rb_node;
292 struct rb_node *parent = NULL;
293 struct btf_id *id;
294 int cmp;
295
296 while (*p != NULL) {
297 parent = *p;
298 id = rb_entry(parent, struct btf_id, rb_node);
299 cmp = strcmp(id->name, name);
300 if (cmp < 0)
301 p = &(*p)->rb_left;
302 else if (cmp > 0)
303 p = &(*p)->rb_right;
304 else
305 return unique ? NULL : id;
306 }
307
308 id = zalloc(sizeof(*id));
309 if (id) {
310 pr_debug("adding symbol %s\n", name);
311 id->name = strdup(name);
312 if (!id->name) {
313 free(id);
314 return NULL;
315 }
316 id->kind = kind;
317 rb_link_node(&id->rb_node, parent, p);
318 rb_insert_color(&id->rb_node, root);
319 }
320 return id;
321 }
322
btf_id__add(struct rb_root * root,const char * name,enum btf_id_kind kind)323 static inline struct btf_id *btf_id__add(struct rb_root *root,
324 const char *name,
325 enum btf_id_kind kind)
326 {
327 return __btf_id__add(root, name, kind, false);
328 }
329
btf_id__add_unique(struct rb_root * root,const char * name,enum btf_id_kind kind)330 static inline struct btf_id *btf_id__add_unique(struct rb_root *root,
331 const char *name,
332 enum btf_id_kind kind)
333 {
334 return __btf_id__add(root, name, kind, true);
335 }
336
get_id(const char * prefix_end,char * buf,size_t buf_sz)337 static int get_id(const char *prefix_end, char *buf, size_t buf_sz)
338 {
339 /*
340 * __BTF_ID__func__vfs_truncate__0
341 * prefix_end = ^
342 * pos = ^
343 */
344 int len = strlen(prefix_end);
345 int pos = sizeof("__") - 1;
346 char *p;
347
348 if (pos >= len)
349 return -1;
350
351 if (len - pos >= buf_sz)
352 return -1;
353
354 strcpy(buf, prefix_end + pos);
355 /*
356 * __BTF_ID__func__vfs_truncate__0
357 * buf = ^
358 *
359 * cut the unique id part
360 */
361 p = strrchr(buf, '_');
362 p--;
363 if (*p != '_')
364 return -1;
365 *p = '\0';
366
367 return 0;
368 }
369
add_set(struct object * obj,char * name,enum btf_id_kind kind)370 static struct btf_id *add_set(struct object *obj, char *name, enum btf_id_kind kind)
371 {
372 int len = strlen(name);
373 int prefixlen;
374 char *id;
375
376 /*
377 * __BTF_ID__set__name
378 * name = ^
379 * id = ^
380 */
381 switch (kind) {
382 case BTF_ID_KIND_SET:
383 prefixlen = sizeof(BTF_SET "__") - 1;
384 break;
385 case BTF_ID_KIND_SET8:
386 prefixlen = sizeof(BTF_SET8 "__") - 1;
387 break;
388 default:
389 pr_err("Unexpected kind %d passed to %s() for symbol %s\n", kind, __func__, name);
390 return NULL;
391 }
392
393 id = name + prefixlen;
394 if (id >= name + len) {
395 pr_err("FAILED to parse set name: %s\n", name);
396 return NULL;
397 }
398
399 return btf_id__add_unique(&obj->sets, id, kind);
400 }
401
add_symbol(struct rb_root * root,char * name,size_t size)402 static struct btf_id *add_symbol(struct rb_root *root, char *name, size_t size)
403 {
404 char id[KSYM_NAME_LEN];
405
406 if (get_id(name + size, id, sizeof(id))) {
407 pr_err("FAILED to parse symbol name: %s\n", name);
408 return NULL;
409 }
410
411 return btf_id__add(root, id, BTF_ID_KIND_SYM);
412 }
413
btf_id__free_all(struct rb_root * root)414 static void btf_id__free_all(struct rb_root *root)
415 {
416 struct rb_node *next;
417 struct btf_id *id;
418
419 next = rb_first(root);
420 while (next) {
421 id = rb_entry(next, struct btf_id, rb_node);
422 next = rb_next(&id->rb_node);
423 rb_erase(&id->rb_node, root);
424 free(id->name);
425 free(id);
426 }
427 }
428
bswap_32_data(void * data,u32 nr_bytes)429 static void bswap_32_data(void *data, u32 nr_bytes)
430 {
431 u32 cnt, i;
432 u32 *ptr;
433
434 cnt = nr_bytes / sizeof(u32);
435 ptr = data;
436
437 for (i = 0; i < cnt; i++)
438 ptr[i] = bswap_32(ptr[i]);
439 }
440
elf_collect(struct object * obj)441 static int elf_collect(struct object *obj)
442 {
443 Elf_Scn *scn = NULL;
444 size_t shdrstrndx;
445 GElf_Ehdr ehdr;
446 int idx = 0;
447 Elf *elf;
448 int fd;
449
450 fd = open(obj->path, O_RDWR, 0666);
451 if (fd == -1) {
452 pr_err("FAILED cannot open %s: %s\n",
453 obj->path, strerror(errno));
454 return -1;
455 }
456
457 elf_version(EV_CURRENT);
458
459 elf = elf_begin(fd, ELF_C_READ_MMAP_PRIVATE, NULL);
460 if (!elf) {
461 close(fd);
462 pr_err("FAILED cannot create ELF descriptor: %s\n",
463 elf_errmsg(-1));
464 return -1;
465 }
466
467 obj->efile.fd = fd;
468 obj->efile.elf = elf;
469
470 elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
471
472 if (elf_getshdrstrndx(elf, &shdrstrndx) != 0) {
473 pr_err("FAILED cannot get shdr str ndx\n");
474 return -1;
475 }
476
477 if (gelf_getehdr(obj->efile.elf, &ehdr) == NULL) {
478 pr_err("FAILED cannot get ELF header: %s\n",
479 elf_errmsg(-1));
480 return -1;
481 }
482 obj->efile.encoding = ehdr.e_ident[EI_DATA];
483
484 /*
485 * Scan all the elf sections and look for save data
486 * from .BTF_ids section and symbols.
487 */
488 while ((scn = elf_nextscn(elf, scn)) != NULL) {
489 Elf_Data *data;
490 GElf_Shdr sh;
491 char *name;
492
493 idx++;
494 if (gelf_getshdr(scn, &sh) != &sh) {
495 pr_err("FAILED get section(%d) header\n", idx);
496 return -1;
497 }
498
499 name = elf_strptr(elf, shdrstrndx, sh.sh_name);
500 if (!name) {
501 pr_err("FAILED get section(%d) name\n", idx);
502 return -1;
503 }
504
505 data = elf_getdata(scn, 0);
506 if (!data) {
507 pr_err("FAILED to get section(%d) data from %s\n",
508 idx, name);
509 return -1;
510 }
511
512 pr_debug2("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
513 idx, name, (unsigned long) data->d_size,
514 (int) sh.sh_link, (unsigned long) sh.sh_flags,
515 (int) sh.sh_type);
516
517 if (sh.sh_type == SHT_SYMTAB) {
518 obj->efile.symbols = data;
519 obj->efile.symbols_shndx = idx;
520 obj->efile.strtabidx = sh.sh_link;
521 } else if (!strcmp(name, BTF_IDS_SECTION)) {
522 /*
523 * If target endianness differs from host, we need to bswap32
524 * the .BTF_ids section data on load, because .BTF_ids has
525 * Elf_Type = ELF_T_BYTE, and so libelf returns data buffer in
526 * the target endianness. We repeat this on dump.
527 */
528 if (obj->efile.encoding != ELFDATANATIVE) {
529 pr_debug("bswap_32 .BTF_ids data from target to host endianness\n");
530 bswap_32_data(data->d_buf, data->d_size);
531 }
532 obj->efile.idlist = data;
533 obj->efile.idlist_shndx = idx;
534 obj->efile.idlist_addr = sh.sh_addr;
535 }
536 }
537
538 return 0;
539 }
540
push_addr_sym(struct object * obj,Elf64_Addr addr,const char * name)541 static int push_addr_sym(struct object *obj, Elf64_Addr addr, const char *name)
542 {
543 if (ensure_mem(&obj->addr_syms, &obj->addr_syms_cap, obj->addr_syms_cnt + 1))
544 return -ENOMEM;
545
546 obj->addr_syms[obj->addr_syms_cnt++] = (struct addr_sym){
547 .addr = addr,
548 .name = name,
549 };
550
551 return 0;
552 }
553
cmp_addr_sym(const void * a,const void * b)554 static int cmp_addr_sym(const void *a, const void *b)
555 {
556 Elf64_Addr aa = ((const struct addr_sym *)a)->addr;
557 Elf64_Addr ab = ((const struct addr_sym *)b)->addr;
558
559 return (aa > ab) - (aa < ab);
560 }
561
find_name_by_addr(struct object * obj,Elf64_Addr addr)562 static const char *find_name_by_addr(struct object *obj, Elf64_Addr addr)
563 {
564 struct addr_sym key = { .addr = addr };
565 struct addr_sym *res;
566
567 if (!obj->addr_syms_cnt)
568 return NULL;
569
570 res = bsearch(&key, obj->addr_syms, obj->addr_syms_cnt,
571 sizeof(*obj->addr_syms), cmp_addr_sym);
572 return res ? res->name : NULL;
573 }
574
symbols_collect(struct object * obj)575 static int symbols_collect(struct object *obj)
576 {
577 Elf_Scn *scn = NULL;
578 int n, i;
579 GElf_Shdr sh;
580 char *name;
581
582 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
583 if (!scn)
584 return -1;
585
586 if (gelf_getshdr(scn, &sh) != &sh)
587 return -1;
588
589 n = sh.sh_size / sh.sh_entsize;
590
591 /*
592 * Scan symbols and look for the ones starting with
593 * __BTF_ID__* over .BTF_ids section.
594 */
595 for (i = 0; i < n; i++) {
596 char *prefix;
597 struct btf_id *id;
598 GElf_Sym sym;
599
600 if (!gelf_getsym(obj->efile.symbols, i, &sym))
601 return -1;
602
603 if (sym.st_shndx != obj->efile.idlist_shndx)
604 continue;
605
606 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
607 sym.st_name);
608
609 if (!is_btf_id(name))
610 continue;
611
612 /*
613 * __BTF_ID__TYPE__vfs_truncate__0
614 * prefix = ^
615 */
616 prefix = name + sizeof(BTF_ID_PREFIX) - 1;
617
618 /* struct */
619 if (!strncmp(prefix, BTF_STRUCT, sizeof(BTF_STRUCT) - 1)) {
620 obj->nr_structs++;
621 id = add_symbol(&obj->structs, prefix, sizeof(BTF_STRUCT) - 1);
622 /* union */
623 } else if (!strncmp(prefix, BTF_UNION, sizeof(BTF_UNION) - 1)) {
624 obj->nr_unions++;
625 id = add_symbol(&obj->unions, prefix, sizeof(BTF_UNION) - 1);
626 /* typedef */
627 } else if (!strncmp(prefix, BTF_TYPEDEF, sizeof(BTF_TYPEDEF) - 1)) {
628 obj->nr_typedefs++;
629 id = add_symbol(&obj->typedefs, prefix, sizeof(BTF_TYPEDEF) - 1);
630 /* func */
631 } else if (!strncmp(prefix, BTF_FUNC, sizeof(BTF_FUNC) - 1)) {
632 obj->nr_funcs++;
633 id = add_symbol(&obj->funcs, prefix, sizeof(BTF_FUNC) - 1);
634 /* set8 */
635 } else if (!strncmp(prefix, BTF_SET8, sizeof(BTF_SET8) - 1)) {
636 id = add_set(obj, prefix, BTF_ID_KIND_SET8);
637 /*
638 * SET8 objects store list's count, which is encoded
639 * in symbol's size, together with 'cnt' field hence
640 * that - 1.
641 */
642 if (id)
643 id->cnt = sym.st_size / sizeof(uint64_t) - 1;
644 /* set */
645 } else if (!strncmp(prefix, BTF_SET, sizeof(BTF_SET) - 1)) {
646 id = add_set(obj, prefix, BTF_ID_KIND_SET);
647 /*
648 * SET objects store list's count, which is encoded
649 * in symbol's size, together with 'cnt' field hence
650 * that - 1.
651 */
652 if (id)
653 id->cnt = sym.st_size / sizeof(int) - 1;
654 } else {
655 pr_err("FAILED unsupported prefix %s\n", prefix);
656 return -1;
657 }
658
659 if (!id)
660 return -EINVAL;
661
662 if (id->addr_cnt >= ADDR_CNT) {
663 pr_err("FAILED symbol %s crossed the number of allowed lists\n",
664 id->name);
665 return -1;
666 }
667 id->addr[id->addr_cnt++] = sym.st_value;
668
669 if (push_addr_sym(obj, sym.st_value, id->name))
670 return -1;
671 }
672
673 if (obj->addr_syms_cnt)
674 qsort(obj->addr_syms, obj->addr_syms_cnt,
675 sizeof(*obj->addr_syms), cmp_addr_sym);
676
677 return 0;
678 }
679
load_btf(struct object * obj)680 static int load_btf(struct object *obj)
681 {
682 struct btf *base_btf = NULL, *btf = NULL;
683 int err;
684
685 if (obj->base_btf_path) {
686 base_btf = btf__parse(obj->base_btf_path, NULL);
687 err = libbpf_get_error(base_btf);
688 if (err) {
689 pr_err("FAILED: load base BTF from %s: %s\n",
690 obj->base_btf_path, strerror(-err));
691 goto out_err;
692 }
693 }
694
695 btf = btf__parse_split(obj->btf_path ?: obj->path, base_btf);
696 err = libbpf_get_error(btf);
697 if (err) {
698 pr_err("FAILED: load BTF from %s: %s\n",
699 obj->btf_path ?: obj->path, strerror(-err));
700 goto out_err;
701 }
702
703 obj->base_btf = base_btf;
704 obj->btf = btf;
705
706 return 0;
707
708 out_err:
709 btf__free(base_btf);
710 btf__free(btf);
711 obj->base_btf = NULL;
712 obj->btf = NULL;
713 return err;
714 }
715
symbols_resolve(struct object * obj)716 static int symbols_resolve(struct object *obj)
717 {
718 int nr_typedefs = obj->nr_typedefs;
719 int nr_structs = obj->nr_structs;
720 int nr_unions = obj->nr_unions;
721 int nr_funcs = obj->nr_funcs;
722 struct btf *btf = obj->btf;
723 int err, type_id;
724 __u32 nr_types;
725
726 err = -1;
727 nr_types = btf__type_cnt(btf);
728
729 /*
730 * Iterate all the BTF types and search for collected symbol IDs.
731 */
732 for (type_id = 1; type_id < nr_types; type_id++) {
733 const struct btf_type *type;
734 struct rb_root *root;
735 struct btf_id *id;
736 const char *str;
737 int *nr;
738
739 type = btf__type_by_id(btf, type_id);
740 if (!type) {
741 pr_err("FAILED: malformed BTF, can't resolve type for ID %d\n",
742 type_id);
743 goto out;
744 }
745
746 if (btf_is_func(type) && nr_funcs) {
747 nr = &nr_funcs;
748 root = &obj->funcs;
749 } else if (btf_is_struct(type) && nr_structs) {
750 nr = &nr_structs;
751 root = &obj->structs;
752 } else if (btf_is_union(type) && nr_unions) {
753 nr = &nr_unions;
754 root = &obj->unions;
755 } else if (btf_is_typedef(type) && nr_typedefs) {
756 nr = &nr_typedefs;
757 root = &obj->typedefs;
758 } else
759 continue;
760
761 str = btf__name_by_offset(btf, type->name_off);
762 if (!str) {
763 pr_err("FAILED: malformed BTF, can't resolve name for ID %d\n",
764 type_id);
765 goto out;
766 }
767
768 id = btf_id__find(root, str);
769 if (id) {
770 if (id->id) {
771 pr_info("WARN: multiple IDs found for '%s': %d, %d - using %d\n",
772 str, id->id, type_id, id->id);
773 warnings++;
774 } else {
775 id->id = type_id;
776 (*nr)--;
777 }
778 }
779 }
780
781 err = 0;
782 out:
783 return err;
784 }
785
id_patch(struct object * obj,struct btf_id * id)786 static int id_patch(struct object *obj, struct btf_id *id)
787 {
788 Elf_Data *data = obj->efile.idlist;
789 int *ptr = data->d_buf;
790 int i;
791
792 /* For set, set8, id->id may be 0 */
793 if (!id->id && id->kind != BTF_ID_KIND_SET && id->kind != BTF_ID_KIND_SET8) {
794 pr_err("WARN: resolve_btfids: unresolved symbol %s\n", id->name);
795 warnings++;
796 }
797
798 for (i = 0; i < id->addr_cnt; i++) {
799 unsigned long addr = id->addr[i];
800 unsigned long idx = addr - obj->efile.idlist_addr;
801
802 pr_debug("patching addr %5lu: ID %7d [%s]\n",
803 idx, id->id, id->name);
804
805 if (idx >= data->d_size) {
806 pr_err("FAILED patching index %lu out of bounds %lu\n",
807 idx, data->d_size);
808 return -1;
809 }
810
811 idx = idx / sizeof(int);
812 ptr[idx] = id->id;
813 }
814
815 return 0;
816 }
817
__symbols_patch(struct object * obj,struct rb_root * root)818 static int __symbols_patch(struct object *obj, struct rb_root *root)
819 {
820 struct rb_node *next;
821 struct btf_id *id;
822
823 next = rb_first(root);
824 while (next) {
825 id = rb_entry(next, struct btf_id, rb_node);
826
827 if (id_patch(obj, id))
828 return -1;
829
830 next = rb_next(next);
831 }
832 return 0;
833 }
834
cmp_id(const void * pa,const void * pb)835 static int cmp_id(const void *pa, const void *pb)
836 {
837 const int *a = pa, *b = pb;
838
839 return *a - *b;
840 }
841
sets_patch(struct object * obj)842 static int sets_patch(struct object *obj)
843 {
844 Elf_Data *data = obj->efile.idlist;
845 struct rb_node *next;
846 int cnt;
847
848 next = rb_first(&obj->sets);
849 while (next) {
850 struct btf_id_set8 *set8 = NULL;
851 struct btf_id_set *set = NULL;
852 unsigned long addr, off;
853 struct btf_id *id;
854
855 id = rb_entry(next, struct btf_id, rb_node);
856 addr = id->addr[0];
857 off = addr - obj->efile.idlist_addr;
858
859 /* sets are unique */
860 if (id->addr_cnt != 1) {
861 pr_err("FAILED malformed data for set '%s'\n",
862 id->name);
863 return -1;
864 }
865
866 switch (id->kind) {
867 case BTF_ID_KIND_SET:
868 set = data->d_buf + off;
869 cnt = set->cnt;
870 qsort(set->ids, set->cnt, sizeof(set->ids[0]), cmp_id);
871 break;
872 case BTF_ID_KIND_SET8:
873 set8 = data->d_buf + off;
874 cnt = set8->cnt;
875 /*
876 * Make sure id is at the beginning of the pairs
877 * struct, otherwise the below qsort would not work.
878 */
879 BUILD_BUG_ON((u32 *)set8->pairs != &set8->pairs[0].id);
880 qsort(set8->pairs, set8->cnt, sizeof(set8->pairs[0]), cmp_id);
881 break;
882 default:
883 pr_err("Unexpected btf_id_kind %d for set '%s'\n", id->kind, id->name);
884 return -1;
885 }
886
887 pr_debug("sorting addr %5lu: cnt %6d [%s]\n", off, cnt, id->name);
888
889 next = rb_next(next);
890 }
891 return 0;
892 }
893
symbols_patch(struct object * obj)894 static int symbols_patch(struct object *obj)
895 {
896 if (__symbols_patch(obj, &obj->structs) ||
897 __symbols_patch(obj, &obj->unions) ||
898 __symbols_patch(obj, &obj->typedefs) ||
899 __symbols_patch(obj, &obj->funcs) ||
900 __symbols_patch(obj, &obj->sets))
901 return -1;
902
903 if (sets_patch(obj))
904 return -1;
905
906 return 0;
907 }
908
dump_raw_data(const char * out_path,const void * data,u32 size)909 static int dump_raw_data(const char *out_path, const void *data, u32 size)
910 {
911 size_t written;
912 FILE *file;
913
914 file = fopen(out_path, "wb");
915 if (!file) {
916 pr_err("Couldn't open %s for writing\n", out_path);
917 return -1;
918 }
919
920 written = fwrite(data, 1, size, file);
921 if (written != size) {
922 pr_err("Failed to write data to %s\n", out_path);
923 fclose(file);
924 unlink(out_path);
925 return -1;
926 }
927
928 fclose(file);
929 pr_debug("Dumped %lu bytes of data to %s\n", size, out_path);
930
931 return 0;
932 }
933
dump_raw_btf_ids(struct object * obj,const char * out_path)934 static int dump_raw_btf_ids(struct object *obj, const char *out_path)
935 {
936 Elf_Data *data = obj->efile.idlist;
937 int err;
938
939 if (!data || !data->d_buf) {
940 pr_debug("%s has no BTF_ids data to dump\n", obj->path);
941 return 0;
942 }
943
944 /*
945 * If target endianness differs from host, we need to bswap32 the
946 * .BTF_ids section data before dumping so that the output is in
947 * target endianness.
948 */
949 if (obj->efile.encoding != ELFDATANATIVE) {
950 pr_debug("bswap_32 .BTF_ids data from host to target endianness\n");
951 bswap_32_data(data->d_buf, data->d_size);
952 }
953
954 err = dump_raw_data(out_path, data->d_buf, data->d_size);
955 if (err)
956 return -1;
957
958 return 0;
959 }
960
dump_raw_btf(struct btf * btf,const char * out_path)961 static int dump_raw_btf(struct btf *btf, const char *out_path)
962 {
963 const void *raw_btf_data;
964 u32 raw_btf_size;
965 int err;
966
967 raw_btf_data = btf__raw_data(btf, &raw_btf_size);
968 if (!raw_btf_data) {
969 pr_err("btf__raw_data() failed\n");
970 return -1;
971 }
972
973 err = dump_raw_data(out_path, raw_btf_data, raw_btf_size);
974 if (err)
975 return -1;
976
977 return 0;
978 }
979
btf_type_skip_qualifiers(const struct btf * btf,s32 type_id)980 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf, s32 type_id)
981 {
982 const struct btf_type *t = btf__type_by_id(btf, type_id);
983
984 while (btf_is_mod(t))
985 t = btf__type_by_id(btf, t->type);
986
987 return t;
988 }
989
push_decl_tag_id(struct btf2btf_context * ctx,u32 decl_tag_id)990 static int push_decl_tag_id(struct btf2btf_context *ctx, u32 decl_tag_id)
991 {
992 if (ensure_mem(&ctx->decl_tags, &ctx->max_decl_tags, ctx->nr_decl_tags + 1))
993 return -ENOMEM;
994
995 ctx->decl_tags[ctx->nr_decl_tags++] = decl_tag_id;
996
997 return 0;
998 }
999
push_kfunc(struct btf2btf_context * ctx,struct kfunc * kfunc)1000 static int push_kfunc(struct btf2btf_context *ctx, struct kfunc *kfunc)
1001 {
1002 struct rb_node **p = &ctx->kfuncs.rb_node;
1003 struct rb_node *parent = NULL;
1004 struct kfunc *k;
1005
1006 /*
1007 * Dedup by BTF ID: collecting the same kfunc twice is a no-op,
1008 * UNLESS the kfunc flags are inconsistent, in which case we
1009 * fail hard because it indicates a bug in a kfunc set declaration.
1010 */
1011 while (*p) {
1012 parent = *p;
1013 k = rb_entry(parent, struct kfunc, rb_node);
1014
1015 if (kfunc->btf_id < k->btf_id) {
1016 p = &(*p)->rb_left;
1017 } else if (kfunc->btf_id > k->btf_id) {
1018 p = &(*p)->rb_right;
1019 } else if (k->flags == kfunc->flags) {
1020 return 0;
1021 } else {
1022 pr_err("ERROR: resolve_btfids: kfunc %s has inconsistent flags across BTF ID sets: 0x%x != 0x%x\n",
1023 kfunc->name, k->flags, kfunc->flags);
1024 return -EINVAL;
1025 }
1026 }
1027
1028 k = zalloc(sizeof(*k));
1029 if (!k)
1030 return -ENOMEM;
1031
1032 *k = *kfunc;
1033 rb_link_node(&k->rb_node, parent, p);
1034 rb_insert_color(&k->rb_node, &ctx->kfuncs);
1035
1036 return 0;
1037 }
1038
free_kfuncs(struct rb_root * root)1039 static void free_kfuncs(struct rb_root *root)
1040 {
1041 struct rb_node *next;
1042 struct kfunc *kfunc;
1043
1044 next = rb_first(root);
1045 while (next) {
1046 kfunc = rb_entry(next, struct kfunc, rb_node);
1047 next = rb_next(&kfunc->rb_node);
1048 rb_erase(&kfunc->rb_node, root);
1049 free(kfunc);
1050 }
1051 }
1052
collect_decl_tags(struct btf2btf_context * ctx)1053 static int collect_decl_tags(struct btf2btf_context *ctx)
1054 {
1055 const u32 type_cnt = btf__type_cnt(ctx->btf);
1056 struct btf *btf = ctx->btf;
1057 const struct btf_type *t;
1058 int err;
1059
1060 for (u32 id = 1; id < type_cnt; id++) {
1061 t = btf__type_by_id(btf, id);
1062 if (!btf_is_decl_tag(t))
1063 continue;
1064 err = push_decl_tag_id(ctx, id);
1065 if (err)
1066 return err;
1067 }
1068
1069 return 0;
1070 }
1071
param_name_has_suffix(const char * name,const char * suffix)1072 static bool param_name_has_suffix(const char *name, const char *suffix)
1073 {
1074 size_t name_len = strlen(name);
1075 size_t suffix_len = strlen(suffix);
1076
1077 return name_len >= suffix_len && !strcmp(name + name_len - suffix_len, suffix);
1078 }
1079
is_arena_param(const struct btf * btf,const struct btf_param * param)1080 static bool is_arena_param(const struct btf *btf, const struct btf_param *param)
1081 {
1082 const char *name = btf__name_by_offset(btf, param->name_off);
1083
1084 return param_name_has_suffix(name, PARAM_SUFFIX_ARENA) ||
1085 param_name_has_suffix(name, PARAM_SUFFIX_ARENA_NULLABLE);
1086 }
1087
collect_kfuncs(struct object * obj,struct btf2btf_context * ctx)1088 static int collect_kfuncs(struct object *obj, struct btf2btf_context *ctx)
1089 {
1090 Elf_Data *idlist = obj->efile.idlist;
1091 struct btf *btf = ctx->btf;
1092 struct rb_node *next;
1093
1094 if (!idlist || !idlist->d_buf)
1095 return 0;
1096
1097 for (next = rb_first(&obj->sets); next; next = rb_next(next)) {
1098 struct btf_id_set8 *set8;
1099 struct btf_id *set_id;
1100 u64 set_addr;
1101
1102 set_id = rb_entry(next, struct btf_id, rb_node);
1103 if (set_id->kind != BTF_ID_KIND_SET8 || set_id->addr_cnt != 1)
1104 continue;
1105
1106 set_addr = set_id->addr[0];
1107 set8 = idlist->d_buf + (set_addr - obj->efile.idlist_addr);
1108 if (!(set8->flags & BTF_SET8_KFUNCS))
1109 continue;
1110
1111 for (u32 i = 0; i < set_id->cnt; i++) {
1112 size_t off = (char *)&set8->pairs[i] - (char *)set8;
1113 const char *name = find_name_by_addr(obj, set_addr + off);
1114 struct kfunc kfunc;
1115 s32 func_id;
1116 int err;
1117
1118 if (!name) {
1119 pr_err("WARN: resolve_btfids: no BTF ID symbol for %s entry %u\n",
1120 set_id->name, i);
1121 warnings++;
1122 continue;
1123 }
1124
1125 func_id = btf__find_by_name_kind_own(btf, name, BTF_KIND_FUNC);
1126 if (func_id < 0) {
1127 pr_err("WARN: resolve_btfids: no BTF func for kfunc %s in %s\n",
1128 name, set_id->name);
1129 warnings++;
1130 continue;
1131 }
1132
1133 pr_debug("found kfunc %s in %s\n", name, set_id->name);
1134
1135 kfunc.name = name;
1136 kfunc.btf_id = func_id;
1137 kfunc.flags = set8->pairs[i].flags;
1138 err = push_kfunc(ctx, &kfunc);
1139 if (err)
1140 return err;
1141 }
1142 }
1143
1144 return 0;
1145 }
1146
build_btf2btf_context(struct object * obj,struct btf2btf_context * ctx)1147 static int build_btf2btf_context(struct object *obj, struct btf2btf_context *ctx)
1148 {
1149 int err;
1150
1151 ctx->btf = obj->btf;
1152
1153 err = collect_decl_tags(ctx);
1154 if (err) {
1155 pr_err("ERROR: resolve_btfids: failed to collect decl tags from BTF\n");
1156 return err;
1157 }
1158
1159 err = collect_kfuncs(obj, ctx);
1160 if (err) {
1161 pr_err("ERROR: resolve_btfids: failed to collect kfuncs from BTF\n");
1162 return err;
1163 }
1164
1165 return 0;
1166 }
1167
1168
1169 /* Implicit BPF kfunc arguments can only be of particular types */
is_kf_implicit_arg(const struct btf * btf,const struct btf_param * p)1170 static bool is_kf_implicit_arg(const struct btf *btf, const struct btf_param *p)
1171 {
1172 static const char *const kf_implicit_arg_types[] = {
1173 "bpf_prog_aux",
1174 "btf_struct_meta",
1175 };
1176 const struct btf_type *t;
1177 const char *name;
1178
1179 t = btf_type_skip_qualifiers(btf, p->type);
1180 if (!btf_is_ptr(t))
1181 return false;
1182
1183 t = btf_type_skip_qualifiers(btf, t->type);
1184 if (!btf_is_struct(t))
1185 return false;
1186
1187 name = btf__name_by_offset(btf, t->name_off);
1188 if (!name)
1189 return false;
1190
1191 for (int i = 0; i < ARRAY_SIZE(kf_implicit_arg_types); i++)
1192 if (strcmp(name, kf_implicit_arg_types[i]) == 0)
1193 return true;
1194
1195 return false;
1196 }
1197
1198 /*
1199 * For a kfunc with KF_IMPLICIT_ARGS we do the following:
1200 * 1. Add a new function with _impl suffix in the name, with the prototype
1201 * of the original kfunc.
1202 * 2. Add all decl tags except "bpf_kfunc" for the _impl func.
1203 * 3. Add a new function prototype with modified list of arguments:
1204 * omitting implicit args.
1205 * 4. Change the prototype of the original kfunc to the new one.
1206 *
1207 * This way we transform the BTF associated with the kfunc from
1208 * __bpf_kfunc bpf_foo(int arg1, void *implicit_arg);
1209 * into
1210 * bpf_foo_impl(int arg1, void *implicit_arg);
1211 * __bpf_kfunc bpf_foo(int arg1);
1212 *
1213 * If a kfunc with KF_IMPLICIT_ARGS already has an _impl counterpart
1214 * in BTF, then it's a legacy case: an _impl function is declared in the
1215 * source code. In this case, we can skip adding an _impl function, but we
1216 * still have to add a func prototype that omits implicit args.
1217 */
process_kfunc_with_implicit_args(struct btf2btf_context * ctx,struct kfunc * kfunc)1218 static int process_kfunc_with_implicit_args(struct btf2btf_context *ctx, struct kfunc *kfunc)
1219 {
1220 s32 idx, new_proto_id, new_func_id, proto_id;
1221 const char *param_name, *tag_name;
1222 const struct btf_param *params;
1223 enum btf_func_linkage linkage;
1224 char tmp_name[KSYM_NAME_LEN];
1225 struct btf *btf = ctx->btf;
1226 int err, len, nr_params;
1227 struct btf_type *t;
1228
1229 t = (struct btf_type *)btf__type_by_id(btf, kfunc->btf_id);
1230 if (!t || !btf_is_func(t)) {
1231 pr_err("ERROR: resolve_btfids: btf id %d is not a function\n", kfunc->btf_id);
1232 return -EINVAL;
1233 }
1234
1235 linkage = btf_vlen(t);
1236
1237 proto_id = t->type;
1238 t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1239 if (!t || !btf_is_func_proto(t)) {
1240 pr_err("ERROR: resolve_btfids: btf id %d is not a function prototype\n", proto_id);
1241 return -EINVAL;
1242 }
1243
1244 len = snprintf(tmp_name, sizeof(tmp_name), "%s%s", kfunc->name, KF_IMPL_SUFFIX);
1245 if (len < 0 || len >= sizeof(tmp_name)) {
1246 pr_err("ERROR: function name is too long: %s%s\n", kfunc->name, KF_IMPL_SUFFIX);
1247 return -E2BIG;
1248 }
1249
1250 if (btf__find_by_name_kind_own(btf, tmp_name, BTF_KIND_FUNC) > 0) {
1251 pr_debug("resolve_btfids: function %s already exists in BTF\n", tmp_name);
1252 goto add_new_proto;
1253 }
1254
1255 /* Add a new function with _impl suffix and original prototype */
1256 new_func_id = btf__add_func(btf, tmp_name, linkage, proto_id);
1257 if (new_func_id < 0) {
1258 pr_err("ERROR: resolve_btfids: failed to add func %s to BTF\n", tmp_name);
1259 return new_func_id;
1260 }
1261
1262 /* Copy all decl tags except "bpf_kfunc" from the original kfunc to the new one */
1263 for (int i = 0; i < ctx->nr_decl_tags; i++) {
1264 t = (struct btf_type *)btf__type_by_id(btf, ctx->decl_tags[i]);
1265 if (t->type != kfunc->btf_id)
1266 continue;
1267
1268 tag_name = btf__name_by_offset(btf, t->name_off);
1269 if (strcmp(tag_name, DECL_TAG_KFUNC) == 0)
1270 continue;
1271
1272 idx = btf_decl_tag(t)->component_idx;
1273
1274 if (btf_kflag(t))
1275 err = btf__add_decl_attr(btf, tag_name, new_func_id, idx);
1276 else
1277 err = btf__add_decl_tag(btf, tag_name, new_func_id, idx);
1278
1279 if (err < 0) {
1280 pr_err("ERROR: resolve_btfids: failed to add decl tag %s for %s\n",
1281 tag_name, tmp_name);
1282 return -EINVAL;
1283 }
1284 }
1285
1286 add_new_proto:
1287 t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1288 new_proto_id = btf__add_func_proto(btf, t->type);
1289 if (new_proto_id < 0) {
1290 pr_err("ERROR: resolve_btfids: failed to add func proto for %s\n", kfunc->name);
1291 return new_proto_id;
1292 }
1293
1294 /* Add non-implicit args to the new prototype */
1295 t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1296 nr_params = btf_vlen(t);
1297 for (int i = 0; i < nr_params; i++) {
1298 params = btf_params(t);
1299 if (is_kf_implicit_arg(btf, ¶ms[i]))
1300 break;
1301 param_name = btf__name_by_offset(btf, params[i].name_off);
1302 err = btf__add_func_param(btf, param_name, params[i].type);
1303 if (err < 0) {
1304 pr_err("ERROR: resolve_btfids: failed to add param %s for %s\n",
1305 param_name, kfunc->name);
1306 return err;
1307 }
1308 t = (struct btf_type *)btf__type_by_id(btf, proto_id);
1309 }
1310
1311 /* Finally change the prototype of the original kfunc to the new one */
1312 t = (struct btf_type *)btf__type_by_id(btf, kfunc->btf_id);
1313 t->type = new_proto_id;
1314
1315 pr_debug("resolve_btfids: updated BTF for kfunc with implicit args %s\n", kfunc->name);
1316
1317 return 0;
1318 }
1319
is_arena_arg(const struct btf * btf,const struct kfunc * kfunc,const struct btf_param * param,u32 idx)1320 static bool is_arena_arg(const struct btf *btf, const struct kfunc *kfunc,
1321 const struct btf_param *param, u32 idx)
1322 {
1323 if (is_arena_param(btf, param))
1324 return true;
1325
1326 switch (idx) {
1327 case 0:
1328 return kfunc->flags & KF_ARENA_ARG1;
1329 case 1:
1330 return kfunc->flags & KF_ARENA_ARG2;
1331 default:
1332 return false;
1333 }
1334 }
1335
arena_tag_ptr(struct btf * btf,u32 ptr_id,struct kfunc * kfunc)1336 static s32 arena_tag_ptr(struct btf *btf, u32 ptr_id, struct kfunc *kfunc)
1337 {
1338 const struct btf_type *ptr = btf__type_by_id(btf, ptr_id);
1339 s32 tag_id, new_ptr_id;
1340
1341 if (!btf_is_ptr(ptr)) {
1342 pr_err("ERROR: resolve_btfids: kfunc %s: arena type is not a pointer\n",
1343 kfunc->name);
1344 return -EINVAL;
1345 }
1346
1347 tag_id = btf__add_type_attr(btf, TYPE_ATTR_ARENA, ptr->type);
1348 if (tag_id < 0) {
1349 pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a type attr to BTF: %d\n",
1350 kfunc->name, tag_id);
1351 return tag_id;
1352 }
1353
1354 new_ptr_id = btf__add_ptr(btf, tag_id);
1355 if (new_ptr_id < 0) {
1356 pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a pointer to BTF: %d\n",
1357 kfunc->name, new_ptr_id);
1358 }
1359
1360 return new_ptr_id;
1361 }
1362
1363 /*
1364 * Add a FUNC_PROTO for @kfunc with each arena pointer tagged with an
1365 * "address_space(1)" attribute. The original proto may be shared with
1366 * other FUNCs, so it is never modified in place. Returns the original
1367 * proto id when @kfunc has no arena return value or arguments.
1368 */
add_arena_tagged_proto(struct btf * btf,struct kfunc * kfunc)1369 static s32 add_arena_tagged_proto(struct btf *btf, struct kfunc *kfunc)
1370 {
1371 const struct btf_type *func = btf__type_by_id(btf, kfunc->btf_id);
1372 u32 proto_id = func->type;
1373 const struct btf_type *proto = btf__type_by_id(btf, proto_id);
1374 const struct btf_param *params = btf_params(proto);
1375 u32 nr_params = btf_vlen(proto);
1376 s32 ret_type_id = proto->type;
1377 const struct btf_type *t;
1378 struct btf_param *tag_params;
1379 s32 new_proto_id, id;
1380 const char *name;
1381 bool has_arena_arg = false;
1382 int err, i;
1383
1384 for (i = 0; i < nr_params; i++) {
1385 if (is_arena_arg(btf, kfunc, ¶ms[i], i)) {
1386 has_arena_arg = true;
1387 break;
1388 }
1389 }
1390
1391 if (!(kfunc->flags & KF_ARENA_RET) && !has_arena_arg)
1392 return proto_id;
1393
1394 if (kfunc->flags & KF_ARENA_RET) {
1395 ret_type_id = arena_tag_ptr(btf, ret_type_id, kfunc);
1396 if (ret_type_id < 0)
1397 return ret_type_id;
1398 }
1399
1400 new_proto_id = btf__add_func_proto(btf, ret_type_id);
1401 if (new_proto_id < 0) {
1402 pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a func proto to BTF: %d\n",
1403 kfunc->name, new_proto_id);
1404 return new_proto_id;
1405 }
1406
1407 for (i = 0; i < nr_params; i++) {
1408 /* btf__add_func_param() below may move the proto, re-fetch */
1409 proto = btf__type_by_id(btf, proto_id);
1410 name = btf__name_by_offset(btf, btf_params(proto)[i].name_off);
1411
1412 err = btf__add_func_param(btf, name ?: "", btf_params(proto)[i].type);
1413 if (err < 0) {
1414 pr_err("ERROR: resolve_btfids: kfunc %s: failed to add a proto param to BTF: %d\n",
1415 kfunc->name, err);
1416 return err;
1417 }
1418 }
1419
1420 for (i = 0; i < nr_params; i++) {
1421 t = btf__type_by_id(btf, new_proto_id);
1422 tag_params = btf_params(t);
1423 if (!is_arena_arg(btf, kfunc, &tag_params[i], i))
1424 continue;
1425
1426 id = arena_tag_ptr(btf, tag_params[i].type, kfunc);
1427 if (id < 0)
1428 return id;
1429
1430 t = btf__type_by_id(btf, new_proto_id);
1431 tag_params = btf_params(t);
1432 tag_params[i].type = id;
1433 }
1434
1435 pr_debug("added arena-tagged proto for kfunc %s: %d\n", kfunc->name, new_proto_id);
1436
1437 return new_proto_id;
1438 }
1439
process_kfunc_with_arena_attrs(struct btf2btf_context * ctx,struct kfunc * kfunc)1440 static int process_kfunc_with_arena_attrs(struct btf2btf_context *ctx,
1441 struct kfunc *kfunc)
1442 {
1443 struct btf_type *t;
1444 s32 proto_id;
1445
1446 proto_id = add_arena_tagged_proto(ctx->btf, kfunc);
1447 if (proto_id < 0)
1448 return proto_id;
1449
1450 t = (struct btf_type *)btf__type_by_id(ctx->btf, kfunc->btf_id);
1451 t->type = proto_id;
1452
1453 return 0;
1454 }
1455
add_decl_tag(struct btf2btf_context * ctx,const char * tag_name,u32 target_btf_id,int component_idx)1456 static int add_decl_tag(struct btf2btf_context *ctx, const char *tag_name,
1457 u32 target_btf_id, int component_idx)
1458 {
1459 s32 new_id;
1460
1461 new_id = btf__add_decl_tag(ctx->btf, tag_name, target_btf_id, component_idx);
1462 if (new_id < 0) {
1463 pr_err("ERROR: resolve_btfids: failed to add '%s' decl tag for BTF id %u: %d\n",
1464 tag_name, target_btf_id, new_id);
1465 return new_id;
1466 }
1467
1468 return push_decl_tag_id(ctx, new_id);
1469 }
1470
btf2btf(struct object * obj)1471 static int btf2btf(struct object *obj)
1472 {
1473 struct btf2btf_context ctx = {};
1474 struct rb_node *next;
1475 int err;
1476
1477 err = build_btf2btf_context(obj, &ctx);
1478 if (err)
1479 goto out;
1480
1481 for (next = rb_first(&ctx.kfuncs); next; next = rb_next(next)) {
1482 struct kfunc *kfunc = rb_entry(next, struct kfunc, rb_node);
1483
1484 err = add_decl_tag(&ctx, DECL_TAG_KFUNC, kfunc->btf_id, -1);
1485 if (err)
1486 goto out;
1487
1488 if (kfunc->flags & KF_FASTCALL) {
1489 err = add_decl_tag(&ctx, DECL_TAG_FASTCALL, kfunc->btf_id, -1);
1490 if (err)
1491 goto out;
1492 }
1493
1494 if (kfunc->flags & KF_IMPLICIT_ARGS) {
1495 err = process_kfunc_with_implicit_args(&ctx, kfunc);
1496 if (err)
1497 goto out;
1498 }
1499
1500 err = process_kfunc_with_arena_attrs(&ctx, kfunc);
1501 if (err)
1502 goto out;
1503 }
1504
1505 err = 0;
1506 out:
1507 free(ctx.decl_tags);
1508 free_kfuncs(&ctx.kfuncs);
1509
1510 return err;
1511 }
1512
1513 /*
1514 * Sort types by name in ascending order resulting in all
1515 * anonymous types being placed before named types.
1516 */
cmp_type_names(const void * a,const void * b,void * priv)1517 static int cmp_type_names(const void *a, const void *b, void *priv)
1518 {
1519 struct btf *btf = (struct btf *)priv;
1520 const struct btf_type *ta = btf__type_by_id(btf, *(__u32 *)a);
1521 const struct btf_type *tb = btf__type_by_id(btf, *(__u32 *)b);
1522 const char *na, *nb;
1523 int r;
1524
1525 na = btf__str_by_offset(btf, ta->name_off);
1526 nb = btf__str_by_offset(btf, tb->name_off);
1527 r = strcmp(na, nb);
1528 if (r != 0)
1529 return r;
1530
1531 /* preserve original relative order of anonymous or same-named types */
1532 return *(__u32 *)a < *(__u32 *)b ? -1 : 1;
1533 }
1534
sort_btf_by_name(struct btf * btf)1535 static int sort_btf_by_name(struct btf *btf)
1536 {
1537 __u32 *permute_ids = NULL, *id_map = NULL;
1538 int nr_types, i, err = 0;
1539 __u32 start_id = 0, id;
1540
1541 if (btf__base_btf(btf))
1542 start_id = btf__type_cnt(btf__base_btf(btf));
1543 nr_types = btf__type_cnt(btf) - start_id;
1544
1545 permute_ids = calloc(nr_types, sizeof(*permute_ids));
1546 if (!permute_ids) {
1547 err = -ENOMEM;
1548 goto out;
1549 }
1550
1551 id_map = calloc(nr_types, sizeof(*id_map));
1552 if (!id_map) {
1553 err = -ENOMEM;
1554 goto out;
1555 }
1556
1557 for (i = 0, id = start_id; i < nr_types; i++, id++)
1558 permute_ids[i] = id;
1559
1560 qsort_r(permute_ids, nr_types, sizeof(*permute_ids), cmp_type_names,
1561 btf);
1562
1563 for (i = 0; i < nr_types; i++) {
1564 id = permute_ids[i] - start_id;
1565 id_map[id] = i + start_id;
1566 }
1567
1568 err = btf__permute(btf, id_map, nr_types, NULL);
1569 if (err)
1570 pr_err("FAILED: btf permute: %s\n", strerror(-err));
1571
1572 out:
1573 free(permute_ids);
1574 free(id_map);
1575 return err;
1576 }
1577
finalize_btf(struct object * obj)1578 static int finalize_btf(struct object *obj)
1579 {
1580 struct btf *base_btf = obj->base_btf, *btf = obj->btf;
1581 int err;
1582
1583 err = btf__dedup(obj->btf, NULL);
1584 if (err) {
1585 pr_err("FAILED to dedup BTF: %s\n", strerror(errno));
1586 goto out_err;
1587 }
1588
1589 if (obj->base_btf && obj->distill_base) {
1590 err = btf__distill_base(obj->btf, &base_btf, &btf);
1591 if (err) {
1592 pr_err("FAILED to distill base BTF: %s\n", strerror(errno));
1593 goto out_err;
1594 }
1595
1596 btf__free(obj->base_btf);
1597 btf__free(obj->btf);
1598 obj->base_btf = base_btf;
1599 obj->btf = btf;
1600 }
1601
1602 err = sort_btf_by_name(obj->btf);
1603 if (err) {
1604 pr_err("FAILED to sort BTF: %s\n", strerror(errno));
1605 goto out_err;
1606 }
1607
1608 return 0;
1609
1610 out_err:
1611 btf__free(base_btf);
1612 btf__free(btf);
1613 obj->base_btf = NULL;
1614 obj->btf = NULL;
1615
1616 return err;
1617 }
1618
make_out_path(char * buf,u32 buf_sz,const char * in_path,const char * suffix)1619 static inline int make_out_path(char *buf, u32 buf_sz, const char *in_path, const char *suffix)
1620 {
1621 int len = snprintf(buf, buf_sz, "%s%s", in_path, suffix);
1622
1623 if (len < 0 || len >= buf_sz) {
1624 pr_err("Output path is too long: %s%s\n", in_path, suffix);
1625 return -E2BIG;
1626 }
1627
1628 return 0;
1629 }
1630
1631 /*
1632 * Patch the .BTF_ids section of an ELF file with data from provided file.
1633 * Equivalent to: objcopy --update-section .BTF_ids=<btfids> <elf>
1634 *
1635 * 1. Find .BTF_ids section in the ELF
1636 * 2. Verify that blob file size matches section size
1637 * 3. Update section data buffer with blob data
1638 * 4. Write the ELF file
1639 */
patch_btfids(const char * btfids_path,const char * elf_path)1640 static int patch_btfids(const char *btfids_path, const char *elf_path)
1641 {
1642 Elf_Scn *scn = NULL;
1643 FILE *btfids_file;
1644 size_t shdrstrndx;
1645 int fd, err = -1;
1646 Elf_Data *data;
1647 struct stat st;
1648 GElf_Shdr sh;
1649 char *name;
1650 Elf *elf;
1651
1652 elf_version(EV_CURRENT);
1653
1654 fd = open(elf_path, O_RDWR, 0666);
1655 if (fd < 0) {
1656 pr_err("FAILED to open %s: %s\n", elf_path, strerror(errno));
1657 return -1;
1658 }
1659
1660 elf = elf_begin(fd, ELF_C_RDWR_MMAP, NULL);
1661 if (!elf) {
1662 close(fd);
1663 pr_err("FAILED cannot create ELF descriptor: %s\n", elf_errmsg(-1));
1664 return -1;
1665 }
1666
1667 elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
1668
1669 if (elf_getshdrstrndx(elf, &shdrstrndx) != 0) {
1670 pr_err("FAILED cannot get shdr str ndx\n");
1671 goto out;
1672 }
1673
1674 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1675
1676 if (gelf_getshdr(scn, &sh) != &sh) {
1677 pr_err("FAILED to get section header\n");
1678 goto out;
1679 }
1680
1681 name = elf_strptr(elf, shdrstrndx, sh.sh_name);
1682 if (!name)
1683 continue;
1684
1685 if (strcmp(name, BTF_IDS_SECTION) == 0)
1686 break;
1687 }
1688
1689 if (!scn) {
1690 pr_err("FAILED: section %s not found in %s\n", BTF_IDS_SECTION, elf_path);
1691 goto out;
1692 }
1693
1694 data = elf_getdata(scn, NULL);
1695 if (!data) {
1696 pr_err("FAILED to get %s section data from %s\n", BTF_IDS_SECTION, elf_path);
1697 goto out;
1698 }
1699
1700 if (stat(btfids_path, &st) < 0) {
1701 pr_err("FAILED to stat %s: %s\n", btfids_path, strerror(errno));
1702 goto out;
1703 }
1704
1705 if ((size_t)st.st_size != data->d_size) {
1706 pr_err("FAILED: size mismatch - %s section in %s is %zu bytes, %s is %zu bytes\n",
1707 BTF_IDS_SECTION, elf_path, data->d_size, btfids_path, (size_t)st.st_size);
1708 goto out;
1709 }
1710
1711 btfids_file = fopen(btfids_path, "rb");
1712 if (!btfids_file) {
1713 pr_err("FAILED to open %s: %s\n", btfids_path, strerror(errno));
1714 goto out;
1715 }
1716
1717 pr_debug("Copying data from %s to %s section of %s (%zu bytes)\n",
1718 btfids_path, BTF_IDS_SECTION, elf_path, data->d_size);
1719
1720 if (fread(data->d_buf, data->d_size, 1, btfids_file) != 1) {
1721 pr_err("FAILED to read %s\n", btfids_path);
1722 fclose(btfids_file);
1723 goto out;
1724 }
1725 fclose(btfids_file);
1726
1727 elf_flagdata(data, ELF_C_SET, ELF_F_DIRTY);
1728 if (elf_update(elf, ELF_C_WRITE) < 0) {
1729 pr_err("FAILED to update ELF file %s\n", elf_path);
1730 goto out;
1731 }
1732
1733 err = 0;
1734 out:
1735 elf_end(elf);
1736 close(fd);
1737
1738 return err;
1739 }
1740
1741 static const char * const resolve_btfids_usage[] = {
1742 "resolve_btfids [<options>] <ELF object>",
1743 "resolve_btfids --patch_btfids <.BTF_ids file> <ELF object>",
1744 NULL
1745 };
1746
main(int argc,const char ** argv)1747 int main(int argc, const char **argv)
1748 {
1749 struct object obj = {
1750 .efile = {
1751 .idlist_shndx = -1,
1752 .symbols_shndx = -1,
1753 },
1754 .structs = RB_ROOT,
1755 .unions = RB_ROOT,
1756 .typedefs = RB_ROOT,
1757 .funcs = RB_ROOT,
1758 .sets = RB_ROOT,
1759 };
1760 const char *btfids_path = NULL;
1761 bool fatal_warnings = false;
1762 bool resolve_btfids = true;
1763 char out_path[PATH_MAX];
1764
1765 struct option btfid_options[] = {
1766 OPT_INCR('v', "verbose", &verbose,
1767 "be more verbose (show errors, etc)"),
1768 OPT_STRING(0, "btf", &obj.btf_path, "file",
1769 "path to a file with input BTF data"),
1770 OPT_STRING('b', "btf_base", &obj.base_btf_path, "file",
1771 "path of file providing base BTF"),
1772 OPT_BOOLEAN(0, "fatal_warnings", &fatal_warnings,
1773 "turn warnings into errors"),
1774 OPT_BOOLEAN(0, "distill_base", &obj.distill_base,
1775 "distill --btf_base and emit .BTF.base section data"),
1776 OPT_STRING(0, "patch_btfids", &btfids_path, "file",
1777 "path to .BTF_ids section data blob to patch into ELF file"),
1778 OPT_END()
1779 };
1780 int err = -1;
1781
1782 argc = parse_options(argc, argv, btfid_options, resolve_btfids_usage,
1783 PARSE_OPT_STOP_AT_NON_OPTION);
1784 if (argc != 1)
1785 usage_with_options(resolve_btfids_usage, btfid_options);
1786
1787 obj.path = argv[0];
1788
1789 if (btfids_path)
1790 return patch_btfids(btfids_path, obj.path);
1791
1792 if (elf_collect(&obj))
1793 goto out;
1794
1795 /*
1796 * We did not find .BTF_ids section or symbols section,
1797 * nothing to do..
1798 */
1799 if (obj.efile.idlist_shndx == -1 ||
1800 obj.efile.symbols_shndx == -1) {
1801 pr_debug("Cannot find .BTF_ids or symbols sections, skip symbols resolution\n");
1802 resolve_btfids = false;
1803 }
1804
1805 if (resolve_btfids)
1806 if (symbols_collect(&obj))
1807 goto out;
1808
1809 if (load_btf(&obj))
1810 goto out;
1811
1812 if (btf2btf(&obj))
1813 goto out;
1814
1815 if (finalize_btf(&obj))
1816 goto out;
1817
1818 if (!resolve_btfids)
1819 goto dump_btf;
1820
1821 if (symbols_resolve(&obj))
1822 goto out;
1823
1824 if (symbols_patch(&obj))
1825 goto out;
1826
1827 err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_IDS_SECTION);
1828 err = err ?: dump_raw_btf_ids(&obj, out_path);
1829 if (err)
1830 goto out;
1831
1832 dump_btf:
1833 err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_ELF_SEC);
1834 err = err ?: dump_raw_btf(obj.btf, out_path);
1835 if (err)
1836 goto out;
1837
1838 if (obj.base_btf && obj.distill_base) {
1839 err = make_out_path(out_path, sizeof(out_path), obj.path, BTF_BASE_ELF_SEC);
1840 err = err ?: dump_raw_btf(obj.base_btf, out_path);
1841 if (err)
1842 goto out;
1843 }
1844
1845 if (!(fatal_warnings && warnings))
1846 err = 0;
1847 out:
1848 btf__free(obj.base_btf);
1849 btf__free(obj.btf);
1850 btf_id__free_all(&obj.structs);
1851 btf_id__free_all(&obj.unions);
1852 btf_id__free_all(&obj.typedefs);
1853 btf_id__free_all(&obj.funcs);
1854 btf_id__free_all(&obj.sets);
1855 free(obj.addr_syms);
1856 if (obj.efile.elf) {
1857 elf_end(obj.efile.elf);
1858 close(obj.efile.fd);
1859 }
1860 return err;
1861 }
1862