1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 /* Copyright (c) 2018 Facebook */
12 #include <sys/utsname.h>
13 #include <sys/param.h>
15 #include <linux/kernel.h>
16 #include <linux/err.h>
17 #include <linux/btf.h>
22 #include "libbpf_internal.h"
25 #define BTF_MAX_NR_TYPES 0x7fffffffU
26 #define BTF_MAX_STR_OFFSET 0x7fffffffU
28 static struct btf_type btf_void;
31 /* raw BTF data in native endianness */
33 /* raw BTF data in non-native endianness */
34 void *raw_data_swapped;
36 /* whether target endianness differs from the native one */
40 * When BTF is loaded from an ELF or raw memory it is stored
41 * in a contiguous memory block. The hdr, type_data, and, strs_data
42 * point inside that memory region to their respective parts of BTF
45 * +--------------------------------+
46 * | Header | Types | Strings |
47 * +--------------------------------+
52 * strs_data------------+
54 * If BTF data is later modified, e.g., due to types added or
55 * removed, BTF deduplication performed, etc, this contiguous
56 * representation is broken up into three independently allocated
57 * memory regions to be able to modify them independently.
58 * raw_data is nulled out at that point, but can be later allocated
59 * and cached again if user calls btf__get_raw_data(), at which point
60 * raw_data will contain a contiguous copy of header, types, and
63 * +----------+ +---------+ +-----------+
64 * | Header | | Types | | Strings |
65 * +----------+ +---------+ +-----------+
70 * strs_data------------------+
72 * +----------+---------+-----------+
73 * | Header | Types | Strings |
74 * raw_data----->+----------+---------+-----------+
76 struct btf_header *hdr;
79 size_t types_data_cap; /* used size stored in hdr->type_len */
81 /* type ID to `struct btf_type *` lookup index
82 * type_offs[0] corresponds to the first non-VOID type:
83 * - for base BTF it's type [1];
84 * - for split BTF it's the first non-base BTF type.
88 /* number of types in this BTF instance:
89 * - doesn't include special [0] void type;
90 * - for split BTF counts number of types added on top of base BTF.
93 /* if not NULL, points to the base BTF on top of which the current
97 /* BTF type ID of the first type in this BTF instance:
98 * - for base BTF it's equal to 1;
99 * - for split BTF it's equal to biggest type ID of base BTF plus 1.
102 /* logical string offset of this BTF instance:
103 * - for base BTF it's equal to 0;
104 * - for split BTF it's equal to total size of base BTF's string section size.
109 size_t strs_data_cap; /* used size stored in hdr->str_len */
111 /* lookup index for each unique string in strings section */
112 struct hashmap *strs_hash;
113 /* whether strings are already deduplicated */
115 /* extra indirection layer to make strings hashmap work with stable
116 * string offsets and ability to transparently choose between
117 * btf->strs_data or btf_dedup->strs_data as a source of strings.
118 * This is used for BTF strings dedup to transfer deduplicated strings
119 * data back to struct btf without re-building strings index.
121 void **strs_data_ptr;
123 /* BTF object FD, if loaded into kernel */
126 /* Pointer size (in bytes) for a target architecture of this BTF */
130 static inline __u64 ptr_to_u64(const void *ptr)
132 return (__u64) (unsigned long) ptr;
135 /* Ensure given dynamically allocated memory region pointed to by *data* with
136 * capacity of *cap_cnt* elements each taking *elem_sz* bytes has enough
137 * memory to accomodate *add_cnt* new elements, assuming *cur_cnt* elements
138 * are already used. At most *max_cnt* elements can be ever allocated.
139 * If necessary, memory is reallocated and all existing data is copied over,
140 * new pointer to the memory region is stored at *data, new memory region
141 * capacity (in number of elements) is stored in *cap.
142 * On success, memory pointer to the beginning of unused memory is returned.
143 * On error, NULL is returned.
145 void *btf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
146 size_t cur_cnt, size_t max_cnt, size_t add_cnt)
151 if (cur_cnt + add_cnt <= *cap_cnt)
152 return *data + cur_cnt * elem_sz;
154 /* requested more than the set limit */
155 if (cur_cnt + add_cnt > max_cnt)
159 new_cnt += new_cnt / 4; /* expand by 25% */
160 if (new_cnt < 16) /* but at least 16 elements */
162 if (new_cnt > max_cnt) /* but not exceeding a set limit */
164 if (new_cnt < cur_cnt + add_cnt) /* also ensure we have enough memory */
165 new_cnt = cur_cnt + add_cnt;
167 new_data = libbpf_reallocarray(*data, new_cnt, elem_sz);
171 /* zero out newly allocated portion of memory */
172 memset(new_data + (*cap_cnt) * elem_sz, 0, (new_cnt - *cap_cnt) * elem_sz);
176 return new_data + cur_cnt * elem_sz;
179 /* Ensure given dynamically allocated memory region has enough allocated space
180 * to accommodate *need_cnt* elements of size *elem_sz* bytes each
182 int btf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt)
186 if (need_cnt <= *cap_cnt)
189 p = btf_add_mem(data, cap_cnt, elem_sz, *cap_cnt, SIZE_MAX, need_cnt - *cap_cnt);
196 static int btf_add_type_idx_entry(struct btf *btf, __u32 type_off)
200 p = btf_add_mem((void **)&btf->type_offs, &btf->type_offs_cap, sizeof(__u32),
201 btf->nr_types, BTF_MAX_NR_TYPES, 1);
209 static void btf_bswap_hdr(struct btf_header *h)
211 h->magic = bswap_16(h->magic);
212 h->hdr_len = bswap_32(h->hdr_len);
213 h->type_off = bswap_32(h->type_off);
214 h->type_len = bswap_32(h->type_len);
215 h->str_off = bswap_32(h->str_off);
216 h->str_len = bswap_32(h->str_len);
219 static int btf_parse_hdr(struct btf *btf)
221 struct btf_header *hdr = btf->hdr;
224 if (btf->raw_size < sizeof(struct btf_header)) {
225 pr_debug("BTF header not found\n");
229 if (hdr->magic == bswap_16(BTF_MAGIC)) {
230 btf->swapped_endian = true;
231 if (bswap_32(hdr->hdr_len) != sizeof(struct btf_header)) {
232 pr_warn("Can't load BTF with non-native endianness due to unsupported header length %u\n",
233 bswap_32(hdr->hdr_len));
237 } else if (hdr->magic != BTF_MAGIC) {
238 pr_debug("Invalid BTF magic:%x\n", hdr->magic);
242 meta_left = btf->raw_size - sizeof(*hdr);
244 pr_debug("BTF has no data\n");
248 if (meta_left < hdr->str_off + hdr->str_len) {
249 pr_debug("Invalid BTF total size:%u\n", btf->raw_size);
253 if (hdr->type_off + hdr->type_len > hdr->str_off) {
254 pr_debug("Invalid BTF data sections layout: type data at %u + %u, strings data at %u + %u\n",
255 hdr->type_off, hdr->type_len, hdr->str_off, hdr->str_len);
259 if (hdr->type_off % 4) {
260 pr_debug("BTF type section is not aligned to 4 bytes\n");
267 static int btf_parse_str_sec(struct btf *btf)
269 const struct btf_header *hdr = btf->hdr;
270 const char *start = btf->strs_data;
271 const char *end = start + btf->hdr->str_len;
273 if (btf->base_btf && hdr->str_len == 0)
275 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_STR_OFFSET || end[-1]) {
276 pr_debug("Invalid BTF string section\n");
279 if (!btf->base_btf && start[0]) {
280 pr_debug("Invalid BTF string section\n");
286 static int btf_type_size(const struct btf_type *t)
288 const int base_size = sizeof(struct btf_type);
289 __u16 vlen = btf_vlen(t);
291 switch (btf_kind(t)) {
294 case BTF_KIND_VOLATILE:
295 case BTF_KIND_RESTRICT:
297 case BTF_KIND_TYPEDEF:
301 return base_size + sizeof(__u32);
303 return base_size + vlen * sizeof(struct btf_enum);
305 return base_size + sizeof(struct btf_array);
306 case BTF_KIND_STRUCT:
308 return base_size + vlen * sizeof(struct btf_member);
309 case BTF_KIND_FUNC_PROTO:
310 return base_size + vlen * sizeof(struct btf_param);
312 return base_size + sizeof(struct btf_var);
313 case BTF_KIND_DATASEC:
314 return base_size + vlen * sizeof(struct btf_var_secinfo);
316 pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
321 static void btf_bswap_type_base(struct btf_type *t)
323 t->name_off = bswap_32(t->name_off);
324 t->info = bswap_32(t->info);
325 t->type = bswap_32(t->type);
328 static int btf_bswap_type_rest(struct btf_type *t)
330 struct btf_var_secinfo *v;
331 struct btf_member *m;
335 __u16 vlen = btf_vlen(t);
338 switch (btf_kind(t)) {
341 case BTF_KIND_VOLATILE:
342 case BTF_KIND_RESTRICT:
344 case BTF_KIND_TYPEDEF:
348 *(__u32 *)(t + 1) = bswap_32(*(__u32 *)(t + 1));
351 for (i = 0, e = btf_enum(t); i < vlen; i++, e++) {
352 e->name_off = bswap_32(e->name_off);
353 e->val = bswap_32(e->val);
358 a->type = bswap_32(a->type);
359 a->index_type = bswap_32(a->index_type);
360 a->nelems = bswap_32(a->nelems);
362 case BTF_KIND_STRUCT:
364 for (i = 0, m = btf_members(t); i < vlen; i++, m++) {
365 m->name_off = bswap_32(m->name_off);
366 m->type = bswap_32(m->type);
367 m->offset = bswap_32(m->offset);
370 case BTF_KIND_FUNC_PROTO:
371 for (i = 0, p = btf_params(t); i < vlen; i++, p++) {
372 p->name_off = bswap_32(p->name_off);
373 p->type = bswap_32(p->type);
377 btf_var(t)->linkage = bswap_32(btf_var(t)->linkage);
379 case BTF_KIND_DATASEC:
380 for (i = 0, v = btf_var_secinfos(t); i < vlen; i++, v++) {
381 v->type = bswap_32(v->type);
382 v->offset = bswap_32(v->offset);
383 v->size = bswap_32(v->size);
387 pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
392 static int btf_parse_type_sec(struct btf *btf)
394 struct btf_header *hdr = btf->hdr;
395 void *next_type = btf->types_data;
396 void *end_type = next_type + hdr->type_len;
399 while (next_type + sizeof(struct btf_type) <= end_type) {
400 if (btf->swapped_endian)
401 btf_bswap_type_base(next_type);
403 type_size = btf_type_size(next_type);
406 if (next_type + type_size > end_type) {
407 pr_warn("BTF type [%d] is malformed\n", btf->start_id + btf->nr_types);
411 if (btf->swapped_endian && btf_bswap_type_rest(next_type))
414 err = btf_add_type_idx_entry(btf, next_type - btf->types_data);
418 next_type += type_size;
422 if (next_type != end_type) {
423 pr_warn("BTF types data is malformed\n");
430 __u32 btf__get_nr_types(const struct btf *btf)
432 return btf->start_id + btf->nr_types - 1;
435 const struct btf *btf__base_btf(const struct btf *btf)
437 return btf->base_btf;
440 /* internal helper returning non-const pointer to a type */
441 static struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id)
445 if (type_id < btf->start_id)
446 return btf_type_by_id(btf->base_btf, type_id);
447 return btf->types_data + btf->type_offs[type_id - btf->start_id];
450 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id)
452 if (type_id >= btf->start_id + btf->nr_types)
454 return btf_type_by_id((struct btf *)btf, type_id);
457 static int determine_ptr_size(const struct btf *btf)
459 const struct btf_type *t;
463 if (btf->base_btf && btf->base_btf->ptr_sz > 0)
464 return btf->base_btf->ptr_sz;
466 n = btf__get_nr_types(btf);
467 for (i = 1; i <= n; i++) {
468 t = btf__type_by_id(btf, i);
472 name = btf__name_by_offset(btf, t->name_off);
476 if (strcmp(name, "long int") == 0 ||
477 strcmp(name, "long unsigned int") == 0) {
478 if (t->size != 4 && t->size != 8)
487 static size_t btf_ptr_sz(const struct btf *btf)
490 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
491 return btf->ptr_sz < 0 ? sizeof(void *) : btf->ptr_sz;
494 /* Return pointer size this BTF instance assumes. The size is heuristically
495 * determined by looking for 'long' or 'unsigned long' integer type and
496 * recording its size in bytes. If BTF type information doesn't have any such
497 * type, this function returns 0. In the latter case, native architecture's
498 * pointer size is assumed, so will be either 4 or 8, depending on
499 * architecture that libbpf was compiled for. It's possible to override
500 * guessed value by using btf__set_pointer_size() API.
502 size_t btf__pointer_size(const struct btf *btf)
505 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
508 /* not enough BTF type info to guess */
514 /* Override or set pointer size in bytes. Only values of 4 and 8 are
517 int btf__set_pointer_size(struct btf *btf, size_t ptr_sz)
519 if (ptr_sz != 4 && ptr_sz != 8)
521 btf->ptr_sz = ptr_sz;
525 static bool is_host_big_endian(void)
527 #if __BYTE_ORDER == __LITTLE_ENDIAN
529 #elif __BYTE_ORDER == __BIG_ENDIAN
532 # error "Unrecognized __BYTE_ORDER__"
536 enum btf_endianness btf__endianness(const struct btf *btf)
538 if (is_host_big_endian())
539 return btf->swapped_endian ? BTF_LITTLE_ENDIAN : BTF_BIG_ENDIAN;
541 return btf->swapped_endian ? BTF_BIG_ENDIAN : BTF_LITTLE_ENDIAN;
544 int btf__set_endianness(struct btf *btf, enum btf_endianness endian)
546 if (endian != BTF_LITTLE_ENDIAN && endian != BTF_BIG_ENDIAN)
549 btf->swapped_endian = is_host_big_endian() != (endian == BTF_BIG_ENDIAN);
550 if (!btf->swapped_endian) {
551 free(btf->raw_data_swapped);
552 btf->raw_data_swapped = NULL;
557 static bool btf_type_is_void(const struct btf_type *t)
559 return t == &btf_void || btf_is_fwd(t);
562 static bool btf_type_is_void_or_null(const struct btf_type *t)
564 return !t || btf_type_is_void(t);
567 #define MAX_RESOLVE_DEPTH 32
569 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id)
571 const struct btf_array *array;
572 const struct btf_type *t;
577 t = btf__type_by_id(btf, type_id);
578 for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t);
580 switch (btf_kind(t)) {
582 case BTF_KIND_STRUCT:
585 case BTF_KIND_DATASEC:
589 size = btf_ptr_sz(btf);
591 case BTF_KIND_TYPEDEF:
592 case BTF_KIND_VOLATILE:
594 case BTF_KIND_RESTRICT:
599 array = btf_array(t);
600 if (nelems && array->nelems > UINT32_MAX / nelems)
602 nelems *= array->nelems;
603 type_id = array->type;
609 t = btf__type_by_id(btf, type_id);
615 if (nelems && size > UINT32_MAX / nelems)
618 return nelems * size;
621 int btf__align_of(const struct btf *btf, __u32 id)
623 const struct btf_type *t = btf__type_by_id(btf, id);
624 __u16 kind = btf_kind(t);
629 return min(btf_ptr_sz(btf), (size_t)t->size);
631 return btf_ptr_sz(btf);
632 case BTF_KIND_TYPEDEF:
633 case BTF_KIND_VOLATILE:
635 case BTF_KIND_RESTRICT:
636 return btf__align_of(btf, t->type);
638 return btf__align_of(btf, btf_array(t)->type);
639 case BTF_KIND_STRUCT:
640 case BTF_KIND_UNION: {
641 const struct btf_member *m = btf_members(t);
642 __u16 vlen = btf_vlen(t);
643 int i, max_align = 1, align;
645 for (i = 0; i < vlen; i++, m++) {
646 align = btf__align_of(btf, m->type);
649 max_align = max(max_align, align);
655 pr_warn("unsupported BTF_KIND:%u\n", btf_kind(t));
660 int btf__resolve_type(const struct btf *btf, __u32 type_id)
662 const struct btf_type *t;
665 t = btf__type_by_id(btf, type_id);
666 while (depth < MAX_RESOLVE_DEPTH &&
667 !btf_type_is_void_or_null(t) &&
668 (btf_is_mod(t) || btf_is_typedef(t) || btf_is_var(t))) {
670 t = btf__type_by_id(btf, type_id);
674 if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t))
680 __s32 btf__find_by_name(const struct btf *btf, const char *type_name)
682 __u32 i, nr_types = btf__get_nr_types(btf);
684 if (!strcmp(type_name, "void"))
687 for (i = 1; i <= nr_types; i++) {
688 const struct btf_type *t = btf__type_by_id(btf, i);
689 const char *name = btf__name_by_offset(btf, t->name_off);
691 if (name && !strcmp(type_name, name))
698 __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,
701 __u32 i, nr_types = btf__get_nr_types(btf);
703 if (kind == BTF_KIND_UNKN || !strcmp(type_name, "void"))
706 for (i = 1; i <= nr_types; i++) {
707 const struct btf_type *t = btf__type_by_id(btf, i);
710 if (btf_kind(t) != kind)
712 name = btf__name_by_offset(btf, t->name_off);
713 if (name && !strcmp(type_name, name))
720 static bool btf_is_modifiable(const struct btf *btf)
722 return (void *)btf->hdr != btf->raw_data;
725 void btf__free(struct btf *btf)
727 if (IS_ERR_OR_NULL(btf))
733 if (btf_is_modifiable(btf)) {
734 /* if BTF was modified after loading, it will have a split
735 * in-memory representation for header, types, and strings
736 * sections, so we need to free all of them individually. It
737 * might still have a cached contiguous raw data present,
738 * which will be unconditionally freed below.
741 free(btf->types_data);
742 free(btf->strs_data);
745 free(btf->raw_data_swapped);
746 free(btf->type_offs);
750 static struct btf *btf_new_empty(struct btf *base_btf)
754 btf = calloc(1, sizeof(*btf));
756 return ERR_PTR(-ENOMEM);
760 btf->start_str_off = 0;
762 btf->ptr_sz = sizeof(void *);
763 btf->swapped_endian = false;
766 btf->base_btf = base_btf;
767 btf->start_id = btf__get_nr_types(base_btf) + 1;
768 btf->start_str_off = base_btf->hdr->str_len;
771 /* +1 for empty string at offset 0 */
772 btf->raw_size = sizeof(struct btf_header) + (base_btf ? 0 : 1);
773 btf->raw_data = calloc(1, btf->raw_size);
774 if (!btf->raw_data) {
776 return ERR_PTR(-ENOMEM);
779 btf->hdr = btf->raw_data;
780 btf->hdr->hdr_len = sizeof(struct btf_header);
781 btf->hdr->magic = BTF_MAGIC;
782 btf->hdr->version = BTF_VERSION;
784 btf->types_data = btf->raw_data + btf->hdr->hdr_len;
785 btf->strs_data = btf->raw_data + btf->hdr->hdr_len;
786 btf->hdr->str_len = base_btf ? 0 : 1; /* empty string at offset 0 */
791 struct btf *btf__new_empty(void)
793 return btf_new_empty(NULL);
796 struct btf *btf__new_empty_split(struct btf *base_btf)
798 return btf_new_empty(base_btf);
801 static struct btf *btf_new(const void *data, __u32 size, struct btf *base_btf)
806 btf = calloc(1, sizeof(struct btf));
808 return ERR_PTR(-ENOMEM);
812 btf->start_str_off = 0;
815 btf->base_btf = base_btf;
816 btf->start_id = btf__get_nr_types(base_btf) + 1;
817 btf->start_str_off = base_btf->hdr->str_len;
820 btf->raw_data = malloc(size);
821 if (!btf->raw_data) {
825 memcpy(btf->raw_data, data, size);
826 btf->raw_size = size;
828 btf->hdr = btf->raw_data;
829 err = btf_parse_hdr(btf);
833 btf->strs_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->str_off;
834 btf->types_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->type_off;
836 err = btf_parse_str_sec(btf);
837 err = err ?: btf_parse_type_sec(btf);
852 struct btf *btf__new(const void *data, __u32 size)
854 return btf_new(data, size, NULL);
857 static struct btf *btf_parse_elf(const char *path, struct btf *base_btf,
858 struct btf_ext **btf_ext)
860 Elf_Data *btf_data = NULL, *btf_ext_data = NULL;
861 int err = 0, fd = -1, idx = 0;
862 struct btf *btf = NULL;
867 if (elf_version(EV_CURRENT) == EV_NONE) {
868 pr_warn("failed to init libelf for %s\n", path);
869 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
872 fd = open(path, O_RDONLY);
875 pr_warn("failed to open %s: %s\n", path, strerror(errno));
879 err = -LIBBPF_ERRNO__FORMAT;
881 elf = elf_begin(fd, ELF_C_READ, NULL);
883 pr_warn("failed to open %s as ELF file\n", path);
886 if (!gelf_getehdr(elf, &ehdr)) {
887 pr_warn("failed to get EHDR from %s\n", path);
890 if (!elf_rawdata(elf_getscn(elf, ehdr.e_shstrndx), NULL)) {
891 pr_warn("failed to get e_shstrndx from %s\n", path);
895 while ((scn = elf_nextscn(elf, scn)) != NULL) {
900 if (gelf_getshdr(scn, &sh) != &sh) {
901 pr_warn("failed to get section(%d) header from %s\n",
905 name = elf_strptr(elf, ehdr.e_shstrndx, sh.sh_name);
907 pr_warn("failed to get section(%d) name from %s\n",
911 if (strcmp(name, BTF_ELF_SEC) == 0) {
912 btf_data = elf_getdata(scn, 0);
914 pr_warn("failed to get section(%d, %s) data from %s\n",
919 } else if (btf_ext && strcmp(name, BTF_EXT_ELF_SEC) == 0) {
920 btf_ext_data = elf_getdata(scn, 0);
922 pr_warn("failed to get section(%d, %s) data from %s\n",
936 btf = btf_new(btf_data->d_buf, btf_data->d_size, base_btf);
940 switch (gelf_getclass(elf)) {
942 btf__set_pointer_size(btf, 4);
945 btf__set_pointer_size(btf, 8);
948 pr_warn("failed to get ELF class (bitness) for %s\n", path);
952 if (btf_ext && btf_ext_data) {
953 *btf_ext = btf_ext__new(btf_ext_data->d_buf,
954 btf_ext_data->d_size);
955 if (IS_ERR(*btf_ext))
957 } else if (btf_ext) {
968 * btf is always parsed before btf_ext, so no need to clean up
969 * btf_ext, if btf loading failed
973 if (btf_ext && IS_ERR(*btf_ext)) {
975 err = PTR_ERR(*btf_ext);
981 struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext)
983 return btf_parse_elf(path, NULL, btf_ext);
986 struct btf *btf__parse_elf_split(const char *path, struct btf *base_btf)
988 return btf_parse_elf(path, base_btf, NULL);
991 static struct btf *btf_parse_raw(const char *path, struct btf *base_btf)
993 struct btf *btf = NULL;
1000 f = fopen(path, "rb");
1006 /* check BTF magic */
1007 if (fread(&magic, 1, sizeof(magic), f) < sizeof(magic)) {
1011 if (magic != BTF_MAGIC && magic != bswap_16(BTF_MAGIC)) {
1012 /* definitely not a raw BTF */
1018 if (fseek(f, 0, SEEK_END)) {
1027 /* rewind to the start */
1028 if (fseek(f, 0, SEEK_SET)) {
1033 /* pre-alloc memory and read all of BTF data */
1039 if (fread(data, 1, sz, f) < sz) {
1044 /* finally parse BTF data */
1045 btf = btf_new(data, sz, base_btf);
1051 return err ? ERR_PTR(err) : btf;
1054 struct btf *btf__parse_raw(const char *path)
1056 return btf_parse_raw(path, NULL);
1059 struct btf *btf__parse_raw_split(const char *path, struct btf *base_btf)
1061 return btf_parse_raw(path, base_btf);
1064 static struct btf *btf_parse(const char *path, struct btf *base_btf, struct btf_ext **btf_ext)
1071 btf = btf_parse_raw(path, base_btf);
1072 if (!IS_ERR(btf) || PTR_ERR(btf) != -EPROTO)
1075 return btf_parse_elf(path, base_btf, btf_ext);
1078 struct btf *btf__parse(const char *path, struct btf_ext **btf_ext)
1080 return btf_parse(path, NULL, btf_ext);
1083 struct btf *btf__parse_split(const char *path, struct btf *base_btf)
1085 return btf_parse(path, base_btf, NULL);
1088 static int compare_vsi_off(const void *_a, const void *_b)
1090 const struct btf_var_secinfo *a = _a;
1091 const struct btf_var_secinfo *b = _b;
1093 return a->offset - b->offset;
1096 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
1099 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
1100 const char *name = btf__name_by_offset(btf, t->name_off);
1101 const struct btf_type *t_var;
1102 struct btf_var_secinfo *vsi;
1103 const struct btf_var *var;
1107 pr_debug("No name found in string section for DATASEC kind.\n");
1111 /* .extern datasec size and var offsets were set correctly during
1112 * extern collection step, so just skip straight to sorting variables
1117 ret = bpf_object__section_size(obj, name, &size);
1118 if (ret || !size || (t->size && t->size != size)) {
1119 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
1125 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
1126 t_var = btf__type_by_id(btf, vsi->type);
1127 var = btf_var(t_var);
1129 if (!btf_is_var(t_var)) {
1130 pr_debug("Non-VAR type seen in section %s\n", name);
1134 if (var->linkage == BTF_VAR_STATIC)
1137 name = btf__name_by_offset(btf, t_var->name_off);
1139 pr_debug("No name found in string section for VAR kind\n");
1143 ret = bpf_object__variable_offset(obj, name, &off);
1145 pr_debug("No offset found in symbol table for VAR %s\n",
1154 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
1158 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
1163 for (i = 1; i <= btf->nr_types; i++) {
1164 struct btf_type *t = btf_type_by_id(btf, i);
1166 /* Loader needs to fix up some of the things compiler
1167 * couldn't get its hands on while emitting BTF. This
1168 * is section size and global variable offset. We use
1169 * the info from the ELF itself for this purpose.
1171 if (btf_is_datasec(t)) {
1172 err = btf_fixup_datasec(obj, btf, t);
1181 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian);
1183 int btf__load(struct btf *btf)
1185 __u32 log_buf_size = 0, raw_size;
1186 char *log_buf = NULL;
1195 log_buf = malloc(log_buf_size);
1202 raw_data = btf_get_raw_data(btf, &raw_size, false);
1207 /* cache native raw data representation */
1208 btf->raw_size = raw_size;
1209 btf->raw_data = raw_data;
1211 btf->fd = bpf_load_btf(raw_data, raw_size, log_buf, log_buf_size, false);
1213 if (!log_buf || errno == ENOSPC) {
1214 log_buf_size = max((__u32)BPF_LOG_BUF_SIZE,
1221 pr_warn("Error loading BTF: %s(%d)\n", strerror(errno), errno);
1223 pr_warn("%s\n", log_buf);
1232 int btf__fd(const struct btf *btf)
1237 void btf__set_fd(struct btf *btf, int fd)
1242 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian)
1244 struct btf_header *hdr = btf->hdr;
1250 data = swap_endian ? btf->raw_data_swapped : btf->raw_data;
1252 *size = btf->raw_size;
1256 data_sz = hdr->hdr_len + hdr->type_len + hdr->str_len;
1257 data = calloc(1, data_sz);
1262 memcpy(p, hdr, hdr->hdr_len);
1267 memcpy(p, btf->types_data, hdr->type_len);
1269 for (i = 0; i < btf->nr_types; i++) {
1270 t = p + btf->type_offs[i];
1271 /* btf_bswap_type_rest() relies on native t->info, so
1272 * we swap base type info after we swapped all the
1273 * additional information
1275 if (btf_bswap_type_rest(t))
1277 btf_bswap_type_base(t);
1282 memcpy(p, btf->strs_data, hdr->str_len);
1292 const void *btf__get_raw_data(const struct btf *btf_ro, __u32 *size)
1294 struct btf *btf = (struct btf *)btf_ro;
1298 data = btf_get_raw_data(btf, &data_sz, btf->swapped_endian);
1302 btf->raw_size = data_sz;
1303 if (btf->swapped_endian)
1304 btf->raw_data_swapped = data;
1306 btf->raw_data = data;
1311 const char *btf__str_by_offset(const struct btf *btf, __u32 offset)
1313 if (offset < btf->start_str_off)
1314 return btf__str_by_offset(btf->base_btf, offset);
1315 else if (offset - btf->start_str_off < btf->hdr->str_len)
1316 return btf->strs_data + (offset - btf->start_str_off);
1321 const char *btf__name_by_offset(const struct btf *btf, __u32 offset)
1323 return btf__str_by_offset(btf, offset);
1326 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf)
1328 struct bpf_btf_info btf_info;
1329 __u32 len = sizeof(btf_info);
1335 /* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so
1336 * let's start with a sane default - 4KiB here - and resize it only if
1337 * bpf_obj_get_info_by_fd() needs a bigger buffer.
1340 ptr = malloc(last_size);
1342 return ERR_PTR(-ENOMEM);
1344 memset(&btf_info, 0, sizeof(btf_info));
1345 btf_info.btf = ptr_to_u64(ptr);
1346 btf_info.btf_size = last_size;
1347 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1349 if (!err && btf_info.btf_size > last_size) {
1352 last_size = btf_info.btf_size;
1353 temp_ptr = realloc(ptr, last_size);
1355 btf = ERR_PTR(-ENOMEM);
1360 len = sizeof(btf_info);
1361 memset(&btf_info, 0, sizeof(btf_info));
1362 btf_info.btf = ptr_to_u64(ptr);
1363 btf_info.btf_size = last_size;
1365 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1368 if (err || btf_info.btf_size > last_size) {
1369 btf = err ? ERR_PTR(-errno) : ERR_PTR(-E2BIG);
1373 btf = btf_new(ptr, btf_info.btf_size, base_btf);
1380 int btf__get_from_id(__u32 id, struct btf **btf)
1386 btf_fd = bpf_btf_get_fd_by_id(id);
1390 res = btf_get_from_fd(btf_fd, NULL);
1393 return PTR_ERR(res);
1399 int btf__get_map_kv_tids(const struct btf *btf, const char *map_name,
1400 __u32 expected_key_size, __u32 expected_value_size,
1401 __u32 *key_type_id, __u32 *value_type_id)
1403 const struct btf_type *container_type;
1404 const struct btf_member *key, *value;
1405 const size_t max_name = 256;
1406 char container_name[max_name];
1407 __s64 key_size, value_size;
1410 if (snprintf(container_name, max_name, "____btf_map_%s", map_name) ==
1412 pr_warn("map:%s length of '____btf_map_%s' is too long\n",
1413 map_name, map_name);
1417 container_id = btf__find_by_name(btf, container_name);
1418 if (container_id < 0) {
1419 pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n",
1420 map_name, container_name);
1421 return container_id;
1424 container_type = btf__type_by_id(btf, container_id);
1425 if (!container_type) {
1426 pr_warn("map:%s cannot find BTF type for container_id:%u\n",
1427 map_name, container_id);
1431 if (!btf_is_struct(container_type) || btf_vlen(container_type) < 2) {
1432 pr_warn("map:%s container_name:%s is an invalid container struct\n",
1433 map_name, container_name);
1437 key = btf_members(container_type);
1440 key_size = btf__resolve_size(btf, key->type);
1442 pr_warn("map:%s invalid BTF key_type_size\n", map_name);
1446 if (expected_key_size != key_size) {
1447 pr_warn("map:%s btf_key_type_size:%u != map_def_key_size:%u\n",
1448 map_name, (__u32)key_size, expected_key_size);
1452 value_size = btf__resolve_size(btf, value->type);
1453 if (value_size < 0) {
1454 pr_warn("map:%s invalid BTF value_type_size\n", map_name);
1458 if (expected_value_size != value_size) {
1459 pr_warn("map:%s btf_value_type_size:%u != map_def_value_size:%u\n",
1460 map_name, (__u32)value_size, expected_value_size);
1464 *key_type_id = key->type;
1465 *value_type_id = value->type;
1470 static size_t strs_hash_fn(const void *key, void *ctx)
1472 const struct btf *btf = ctx;
1473 const char *strs = *btf->strs_data_ptr;
1474 const char *str = strs + (long)key;
1476 return str_hash(str);
1479 static bool strs_hash_equal_fn(const void *key1, const void *key2, void *ctx)
1481 const struct btf *btf = ctx;
1482 const char *strs = *btf->strs_data_ptr;
1483 const char *str1 = strs + (long)key1;
1484 const char *str2 = strs + (long)key2;
1486 return strcmp(str1, str2) == 0;
1489 static void btf_invalidate_raw_data(struct btf *btf)
1491 if (btf->raw_data) {
1492 free(btf->raw_data);
1493 btf->raw_data = NULL;
1495 if (btf->raw_data_swapped) {
1496 free(btf->raw_data_swapped);
1497 btf->raw_data_swapped = NULL;
1501 /* Ensure BTF is ready to be modified (by splitting into a three memory
1502 * regions for header, types, and strings). Also invalidate cached
1505 static int btf_ensure_modifiable(struct btf *btf)
1507 void *hdr, *types, *strs, *strs_end, *s;
1508 struct hashmap *hash = NULL;
1512 if (btf_is_modifiable(btf)) {
1513 /* any BTF modification invalidates raw_data */
1514 btf_invalidate_raw_data(btf);
1518 /* split raw data into three memory regions */
1519 hdr = malloc(btf->hdr->hdr_len);
1520 types = malloc(btf->hdr->type_len);
1521 strs = malloc(btf->hdr->str_len);
1522 if (!hdr || !types || !strs)
1525 memcpy(hdr, btf->hdr, btf->hdr->hdr_len);
1526 memcpy(types, btf->types_data, btf->hdr->type_len);
1527 memcpy(strs, btf->strs_data, btf->hdr->str_len);
1529 /* make hashmap below use btf->strs_data as a source of strings */
1530 btf->strs_data_ptr = &btf->strs_data;
1532 /* build lookup index for all strings */
1533 hash = hashmap__new(strs_hash_fn, strs_hash_equal_fn, btf);
1535 err = PTR_ERR(hash);
1540 strs_end = strs + btf->hdr->str_len;
1541 for (off = 0, s = strs; s < strs_end; off += strlen(s) + 1, s = strs + off) {
1542 /* hashmap__add() returns EEXIST if string with the same
1543 * content already is in the hash map
1545 err = hashmap__add(hash, (void *)off, (void *)off);
1547 continue; /* duplicate */
1552 /* only when everything was successful, update internal state */
1554 btf->types_data = types;
1555 btf->types_data_cap = btf->hdr->type_len;
1556 btf->strs_data = strs;
1557 btf->strs_data_cap = btf->hdr->str_len;
1558 btf->strs_hash = hash;
1559 /* if BTF was created from scratch, all strings are guaranteed to be
1560 * unique and deduplicated
1562 if (btf->hdr->str_len == 0)
1563 btf->strs_deduped = true;
1564 if (!btf->base_btf && btf->hdr->str_len == 1)
1565 btf->strs_deduped = true;
1567 /* invalidate raw_data representation */
1568 btf_invalidate_raw_data(btf);
1573 hashmap__free(hash);
1580 static void *btf_add_str_mem(struct btf *btf, size_t add_sz)
1582 return btf_add_mem(&btf->strs_data, &btf->strs_data_cap, 1,
1583 btf->hdr->str_len, BTF_MAX_STR_OFFSET, add_sz);
1586 /* Find an offset in BTF string section that corresponds to a given string *s*.
1588 * - >0 offset into string section, if string is found;
1589 * - -ENOENT, if string is not in the string section;
1590 * - <0, on any other error.
1592 int btf__find_str(struct btf *btf, const char *s)
1594 long old_off, new_off, len;
1597 if (btf->base_btf) {
1600 ret = btf__find_str(btf->base_btf, s);
1605 /* BTF needs to be in a modifiable state to build string lookup index */
1606 if (btf_ensure_modifiable(btf))
1609 /* see btf__add_str() for why we do this */
1610 len = strlen(s) + 1;
1611 p = btf_add_str_mem(btf, len);
1615 new_off = btf->hdr->str_len;
1618 if (hashmap__find(btf->strs_hash, (void *)new_off, (void **)&old_off))
1619 return btf->start_str_off + old_off;
1624 /* Add a string s to the BTF string section.
1626 * - > 0 offset into string section, on success;
1629 int btf__add_str(struct btf *btf, const char *s)
1631 long old_off, new_off, len;
1635 if (btf->base_btf) {
1638 ret = btf__find_str(btf->base_btf, s);
1643 if (btf_ensure_modifiable(btf))
1646 /* Hashmap keys are always offsets within btf->strs_data, so to even
1647 * look up some string from the "outside", we need to first append it
1648 * at the end, so that it can be addressed with an offset. Luckily,
1649 * until btf->hdr->str_len is incremented, that string is just a piece
1650 * of garbage for the rest of BTF code, so no harm, no foul. On the
1651 * other hand, if the string is unique, it's already appended and
1652 * ready to be used, only a simple btf->hdr->str_len increment away.
1654 len = strlen(s) + 1;
1655 p = btf_add_str_mem(btf, len);
1659 new_off = btf->hdr->str_len;
1662 /* Now attempt to add the string, but only if the string with the same
1663 * contents doesn't exist already (HASHMAP_ADD strategy). If such
1664 * string exists, we'll get its offset in old_off (that's old_key).
1666 err = hashmap__insert(btf->strs_hash, (void *)new_off, (void *)new_off,
1667 HASHMAP_ADD, (const void **)&old_off, NULL);
1669 return btf->start_str_off + old_off; /* duplicated string, return existing offset */
1673 btf->hdr->str_len += len; /* new unique string, adjust data length */
1674 return btf->start_str_off + new_off;
1677 static void *btf_add_type_mem(struct btf *btf, size_t add_sz)
1679 return btf_add_mem(&btf->types_data, &btf->types_data_cap, 1,
1680 btf->hdr->type_len, UINT_MAX, add_sz);
1683 static __u32 btf_type_info(int kind, int vlen, int kflag)
1685 return (kflag << 31) | (kind << 24) | vlen;
1688 static void btf_type_inc_vlen(struct btf_type *t)
1690 t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, btf_kflag(t));
1693 static int btf_commit_type(struct btf *btf, int data_sz)
1697 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1701 btf->hdr->type_len += data_sz;
1702 btf->hdr->str_off += data_sz;
1704 return btf->start_id + btf->nr_types - 1;
1708 * Append new BTF_KIND_INT type with:
1709 * - *name* - non-empty, non-NULL type name;
1710 * - *sz* - power-of-2 (1, 2, 4, ..) size of the type, in bytes;
1711 * - encoding is a combination of BTF_INT_SIGNED, BTF_INT_CHAR, BTF_INT_BOOL.
1713 * - >0, type ID of newly added BTF type;
1716 int btf__add_int(struct btf *btf, const char *name, size_t byte_sz, int encoding)
1721 /* non-empty name */
1722 if (!name || !name[0])
1724 /* byte_sz must be power of 2 */
1725 if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 16)
1727 if (encoding & ~(BTF_INT_SIGNED | BTF_INT_CHAR | BTF_INT_BOOL))
1730 /* deconstruct BTF, if necessary, and invalidate raw_data */
1731 if (btf_ensure_modifiable(btf))
1734 sz = sizeof(struct btf_type) + sizeof(int);
1735 t = btf_add_type_mem(btf, sz);
1739 /* if something goes wrong later, we might end up with an extra string,
1740 * but that shouldn't be a problem, because BTF can't be constructed
1741 * completely anyway and will most probably be just discarded
1743 name_off = btf__add_str(btf, name);
1747 t->name_off = name_off;
1748 t->info = btf_type_info(BTF_KIND_INT, 0, 0);
1750 /* set INT info, we don't allow setting legacy bit offset/size */
1751 *(__u32 *)(t + 1) = (encoding << 24) | (byte_sz * 8);
1753 return btf_commit_type(btf, sz);
1756 /* it's completely legal to append BTF types with type IDs pointing forward to
1757 * types that haven't been appended yet, so we only make sure that id looks
1758 * sane, we can't guarantee that ID will always be valid
1760 static int validate_type_id(int id)
1762 if (id < 0 || id > BTF_MAX_NR_TYPES)
1767 /* generic append function for PTR, TYPEDEF, CONST/VOLATILE/RESTRICT */
1768 static int btf_add_ref_kind(struct btf *btf, int kind, const char *name, int ref_type_id)
1771 int sz, name_off = 0;
1773 if (validate_type_id(ref_type_id))
1776 if (btf_ensure_modifiable(btf))
1779 sz = sizeof(struct btf_type);
1780 t = btf_add_type_mem(btf, sz);
1784 if (name && name[0]) {
1785 name_off = btf__add_str(btf, name);
1790 t->name_off = name_off;
1791 t->info = btf_type_info(kind, 0, 0);
1792 t->type = ref_type_id;
1794 return btf_commit_type(btf, sz);
1798 * Append new BTF_KIND_PTR type with:
1799 * - *ref_type_id* - referenced type ID, it might not exist yet;
1801 * - >0, type ID of newly added BTF type;
1804 int btf__add_ptr(struct btf *btf, int ref_type_id)
1806 return btf_add_ref_kind(btf, BTF_KIND_PTR, NULL, ref_type_id);
1810 * Append new BTF_KIND_ARRAY type with:
1811 * - *index_type_id* - type ID of the type describing array index;
1812 * - *elem_type_id* - type ID of the type describing array element;
1813 * - *nr_elems* - the size of the array;
1815 * - >0, type ID of newly added BTF type;
1818 int btf__add_array(struct btf *btf, int index_type_id, int elem_type_id, __u32 nr_elems)
1821 struct btf_array *a;
1824 if (validate_type_id(index_type_id) || validate_type_id(elem_type_id))
1827 if (btf_ensure_modifiable(btf))
1830 sz = sizeof(struct btf_type) + sizeof(struct btf_array);
1831 t = btf_add_type_mem(btf, sz);
1836 t->info = btf_type_info(BTF_KIND_ARRAY, 0, 0);
1840 a->type = elem_type_id;
1841 a->index_type = index_type_id;
1842 a->nelems = nr_elems;
1844 return btf_commit_type(btf, sz);
1847 /* generic STRUCT/UNION append function */
1848 static int btf_add_composite(struct btf *btf, int kind, const char *name, __u32 bytes_sz)
1851 int sz, name_off = 0;
1853 if (btf_ensure_modifiable(btf))
1856 sz = sizeof(struct btf_type);
1857 t = btf_add_type_mem(btf, sz);
1861 if (name && name[0]) {
1862 name_off = btf__add_str(btf, name);
1867 /* start out with vlen=0 and no kflag; this will be adjusted when
1868 * adding each member
1870 t->name_off = name_off;
1871 t->info = btf_type_info(kind, 0, 0);
1874 return btf_commit_type(btf, sz);
1878 * Append new BTF_KIND_STRUCT type with:
1879 * - *name* - name of the struct, can be NULL or empty for anonymous structs;
1880 * - *byte_sz* - size of the struct, in bytes;
1882 * Struct initially has no fields in it. Fields can be added by
1883 * btf__add_field() right after btf__add_struct() succeeds.
1886 * - >0, type ID of newly added BTF type;
1889 int btf__add_struct(struct btf *btf, const char *name, __u32 byte_sz)
1891 return btf_add_composite(btf, BTF_KIND_STRUCT, name, byte_sz);
1895 * Append new BTF_KIND_UNION type with:
1896 * - *name* - name of the union, can be NULL or empty for anonymous union;
1897 * - *byte_sz* - size of the union, in bytes;
1899 * Union initially has no fields in it. Fields can be added by
1900 * btf__add_field() right after btf__add_union() succeeds. All fields
1901 * should have *bit_offset* of 0.
1904 * - >0, type ID of newly added BTF type;
1907 int btf__add_union(struct btf *btf, const char *name, __u32 byte_sz)
1909 return btf_add_composite(btf, BTF_KIND_UNION, name, byte_sz);
1912 static struct btf_type *btf_last_type(struct btf *btf)
1914 return btf_type_by_id(btf, btf__get_nr_types(btf));
1918 * Append new field for the current STRUCT/UNION type with:
1919 * - *name* - name of the field, can be NULL or empty for anonymous field;
1920 * - *type_id* - type ID for the type describing field type;
1921 * - *bit_offset* - bit offset of the start of the field within struct/union;
1922 * - *bit_size* - bit size of a bitfield, 0 for non-bitfield fields;
1927 int btf__add_field(struct btf *btf, const char *name, int type_id,
1928 __u32 bit_offset, __u32 bit_size)
1931 struct btf_member *m;
1933 int sz, name_off = 0;
1935 /* last type should be union/struct */
1936 if (btf->nr_types == 0)
1938 t = btf_last_type(btf);
1939 if (!btf_is_composite(t))
1942 if (validate_type_id(type_id))
1944 /* best-effort bit field offset/size enforcement */
1945 is_bitfield = bit_size || (bit_offset % 8 != 0);
1946 if (is_bitfield && (bit_size == 0 || bit_size > 255 || bit_offset > 0xffffff))
1949 /* only offset 0 is allowed for unions */
1950 if (btf_is_union(t) && bit_offset)
1953 /* decompose and invalidate raw data */
1954 if (btf_ensure_modifiable(btf))
1957 sz = sizeof(struct btf_member);
1958 m = btf_add_type_mem(btf, sz);
1962 if (name && name[0]) {
1963 name_off = btf__add_str(btf, name);
1968 m->name_off = name_off;
1970 m->offset = bit_offset | (bit_size << 24);
1972 /* btf_add_type_mem can invalidate t pointer */
1973 t = btf_last_type(btf);
1974 /* update parent type's vlen and kflag */
1975 t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, is_bitfield || btf_kflag(t));
1977 btf->hdr->type_len += sz;
1978 btf->hdr->str_off += sz;
1983 * Append new BTF_KIND_ENUM type with:
1984 * - *name* - name of the enum, can be NULL or empty for anonymous enums;
1985 * - *byte_sz* - size of the enum, in bytes.
1987 * Enum initially has no enum values in it (and corresponds to enum forward
1988 * declaration). Enumerator values can be added by btf__add_enum_value()
1989 * immediately after btf__add_enum() succeeds.
1992 * - >0, type ID of newly added BTF type;
1995 int btf__add_enum(struct btf *btf, const char *name, __u32 byte_sz)
1998 int sz, name_off = 0;
2000 /* byte_sz must be power of 2 */
2001 if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 8)
2004 if (btf_ensure_modifiable(btf))
2007 sz = sizeof(struct btf_type);
2008 t = btf_add_type_mem(btf, sz);
2012 if (name && name[0]) {
2013 name_off = btf__add_str(btf, name);
2018 /* start out with vlen=0; it will be adjusted when adding enum values */
2019 t->name_off = name_off;
2020 t->info = btf_type_info(BTF_KIND_ENUM, 0, 0);
2023 return btf_commit_type(btf, sz);
2027 * Append new enum value for the current ENUM type with:
2028 * - *name* - name of the enumerator value, can't be NULL or empty;
2029 * - *value* - integer value corresponding to enum value *name*;
2034 int btf__add_enum_value(struct btf *btf, const char *name, __s64 value)
2040 /* last type should be BTF_KIND_ENUM */
2041 if (btf->nr_types == 0)
2043 t = btf_last_type(btf);
2044 if (!btf_is_enum(t))
2047 /* non-empty name */
2048 if (!name || !name[0])
2050 if (value < INT_MIN || value > UINT_MAX)
2053 /* decompose and invalidate raw data */
2054 if (btf_ensure_modifiable(btf))
2057 sz = sizeof(struct btf_enum);
2058 v = btf_add_type_mem(btf, sz);
2062 name_off = btf__add_str(btf, name);
2066 v->name_off = name_off;
2069 /* update parent type's vlen */
2070 t = btf_last_type(btf);
2071 btf_type_inc_vlen(t);
2073 btf->hdr->type_len += sz;
2074 btf->hdr->str_off += sz;
2079 * Append new BTF_KIND_FWD type with:
2080 * - *name*, non-empty/non-NULL name;
2081 * - *fwd_kind*, kind of forward declaration, one of BTF_FWD_STRUCT,
2082 * BTF_FWD_UNION, or BTF_FWD_ENUM;
2084 * - >0, type ID of newly added BTF type;
2087 int btf__add_fwd(struct btf *btf, const char *name, enum btf_fwd_kind fwd_kind)
2089 if (!name || !name[0])
2093 case BTF_FWD_STRUCT:
2094 case BTF_FWD_UNION: {
2098 id = btf_add_ref_kind(btf, BTF_KIND_FWD, name, 0);
2101 t = btf_type_by_id(btf, id);
2102 t->info = btf_type_info(BTF_KIND_FWD, 0, fwd_kind == BTF_FWD_UNION);
2106 /* enum forward in BTF currently is just an enum with no enum
2107 * values; we also assume a standard 4-byte size for it
2109 return btf__add_enum(btf, name, sizeof(int));
2116 * Append new BTF_KING_TYPEDEF type with:
2117 * - *name*, non-empty/non-NULL name;
2118 * - *ref_type_id* - referenced type ID, it might not exist yet;
2120 * - >0, type ID of newly added BTF type;
2123 int btf__add_typedef(struct btf *btf, const char *name, int ref_type_id)
2125 if (!name || !name[0])
2128 return btf_add_ref_kind(btf, BTF_KIND_TYPEDEF, name, ref_type_id);
2132 * Append new BTF_KIND_VOLATILE type with:
2133 * - *ref_type_id* - referenced type ID, it might not exist yet;
2135 * - >0, type ID of newly added BTF type;
2138 int btf__add_volatile(struct btf *btf, int ref_type_id)
2140 return btf_add_ref_kind(btf, BTF_KIND_VOLATILE, NULL, ref_type_id);
2144 * Append new BTF_KIND_CONST type with:
2145 * - *ref_type_id* - referenced type ID, it might not exist yet;
2147 * - >0, type ID of newly added BTF type;
2150 int btf__add_const(struct btf *btf, int ref_type_id)
2152 return btf_add_ref_kind(btf, BTF_KIND_CONST, NULL, ref_type_id);
2156 * Append new BTF_KIND_RESTRICT type with:
2157 * - *ref_type_id* - referenced type ID, it might not exist yet;
2159 * - >0, type ID of newly added BTF type;
2162 int btf__add_restrict(struct btf *btf, int ref_type_id)
2164 return btf_add_ref_kind(btf, BTF_KIND_RESTRICT, NULL, ref_type_id);
2168 * Append new BTF_KIND_FUNC type with:
2169 * - *name*, non-empty/non-NULL name;
2170 * - *proto_type_id* - FUNC_PROTO's type ID, it might not exist yet;
2172 * - >0, type ID of newly added BTF type;
2175 int btf__add_func(struct btf *btf, const char *name,
2176 enum btf_func_linkage linkage, int proto_type_id)
2180 if (!name || !name[0])
2182 if (linkage != BTF_FUNC_STATIC && linkage != BTF_FUNC_GLOBAL &&
2183 linkage != BTF_FUNC_EXTERN)
2186 id = btf_add_ref_kind(btf, BTF_KIND_FUNC, name, proto_type_id);
2188 struct btf_type *t = btf_type_by_id(btf, id);
2190 t->info = btf_type_info(BTF_KIND_FUNC, linkage, 0);
2196 * Append new BTF_KIND_FUNC_PROTO with:
2197 * - *ret_type_id* - type ID for return result of a function.
2199 * Function prototype initially has no arguments, but they can be added by
2200 * btf__add_func_param() one by one, immediately after
2201 * btf__add_func_proto() succeeded.
2204 * - >0, type ID of newly added BTF type;
2207 int btf__add_func_proto(struct btf *btf, int ret_type_id)
2212 if (validate_type_id(ret_type_id))
2215 if (btf_ensure_modifiable(btf))
2218 sz = sizeof(struct btf_type);
2219 t = btf_add_type_mem(btf, sz);
2223 /* start out with vlen=0; this will be adjusted when adding enum
2224 * values, if necessary
2227 t->info = btf_type_info(BTF_KIND_FUNC_PROTO, 0, 0);
2228 t->type = ret_type_id;
2230 return btf_commit_type(btf, sz);
2234 * Append new function parameter for current FUNC_PROTO type with:
2235 * - *name* - parameter name, can be NULL or empty;
2236 * - *type_id* - type ID describing the type of the parameter.
2241 int btf__add_func_param(struct btf *btf, const char *name, int type_id)
2244 struct btf_param *p;
2245 int sz, name_off = 0;
2247 if (validate_type_id(type_id))
2250 /* last type should be BTF_KIND_FUNC_PROTO */
2251 if (btf->nr_types == 0)
2253 t = btf_last_type(btf);
2254 if (!btf_is_func_proto(t))
2257 /* decompose and invalidate raw data */
2258 if (btf_ensure_modifiable(btf))
2261 sz = sizeof(struct btf_param);
2262 p = btf_add_type_mem(btf, sz);
2266 if (name && name[0]) {
2267 name_off = btf__add_str(btf, name);
2272 p->name_off = name_off;
2275 /* update parent type's vlen */
2276 t = btf_last_type(btf);
2277 btf_type_inc_vlen(t);
2279 btf->hdr->type_len += sz;
2280 btf->hdr->str_off += sz;
2285 * Append new BTF_KIND_VAR type with:
2286 * - *name* - non-empty/non-NULL name;
2287 * - *linkage* - variable linkage, one of BTF_VAR_STATIC,
2288 * BTF_VAR_GLOBAL_ALLOCATED, or BTF_VAR_GLOBAL_EXTERN;
2289 * - *type_id* - type ID of the type describing the type of the variable.
2291 * - >0, type ID of newly added BTF type;
2294 int btf__add_var(struct btf *btf, const char *name, int linkage, int type_id)
2300 /* non-empty name */
2301 if (!name || !name[0])
2303 if (linkage != BTF_VAR_STATIC && linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2304 linkage != BTF_VAR_GLOBAL_EXTERN)
2306 if (validate_type_id(type_id))
2309 /* deconstruct BTF, if necessary, and invalidate raw_data */
2310 if (btf_ensure_modifiable(btf))
2313 sz = sizeof(struct btf_type) + sizeof(struct btf_var);
2314 t = btf_add_type_mem(btf, sz);
2318 name_off = btf__add_str(btf, name);
2322 t->name_off = name_off;
2323 t->info = btf_type_info(BTF_KIND_VAR, 0, 0);
2327 v->linkage = linkage;
2329 return btf_commit_type(btf, sz);
2333 * Append new BTF_KIND_DATASEC type with:
2334 * - *name* - non-empty/non-NULL name;
2335 * - *byte_sz* - data section size, in bytes.
2337 * Data section is initially empty. Variables info can be added with
2338 * btf__add_datasec_var_info() calls, after btf__add_datasec() succeeds.
2341 * - >0, type ID of newly added BTF type;
2344 int btf__add_datasec(struct btf *btf, const char *name, __u32 byte_sz)
2349 /* non-empty name */
2350 if (!name || !name[0])
2353 if (btf_ensure_modifiable(btf))
2356 sz = sizeof(struct btf_type);
2357 t = btf_add_type_mem(btf, sz);
2361 name_off = btf__add_str(btf, name);
2365 /* start with vlen=0, which will be update as var_secinfos are added */
2366 t->name_off = name_off;
2367 t->info = btf_type_info(BTF_KIND_DATASEC, 0, 0);
2370 return btf_commit_type(btf, sz);
2374 * Append new data section variable information entry for current DATASEC type:
2375 * - *var_type_id* - type ID, describing type of the variable;
2376 * - *offset* - variable offset within data section, in bytes;
2377 * - *byte_sz* - variable size, in bytes.
2383 int btf__add_datasec_var_info(struct btf *btf, int var_type_id, __u32 offset, __u32 byte_sz)
2386 struct btf_var_secinfo *v;
2389 /* last type should be BTF_KIND_DATASEC */
2390 if (btf->nr_types == 0)
2392 t = btf_last_type(btf);
2393 if (!btf_is_datasec(t))
2396 if (validate_type_id(var_type_id))
2399 /* decompose and invalidate raw data */
2400 if (btf_ensure_modifiable(btf))
2403 sz = sizeof(struct btf_var_secinfo);
2404 v = btf_add_type_mem(btf, sz);
2408 v->type = var_type_id;
2412 /* update parent type's vlen */
2413 t = btf_last_type(btf);
2414 btf_type_inc_vlen(t);
2416 btf->hdr->type_len += sz;
2417 btf->hdr->str_off += sz;
2421 struct btf_ext_sec_setup_param {
2425 struct btf_ext_info *ext_info;
2429 static int btf_ext_setup_info(struct btf_ext *btf_ext,
2430 struct btf_ext_sec_setup_param *ext_sec)
2432 const struct btf_ext_info_sec *sinfo;
2433 struct btf_ext_info *ext_info;
2434 __u32 info_left, record_size;
2435 /* The start of the info sec (including the __u32 record_size). */
2438 if (ext_sec->len == 0)
2441 if (ext_sec->off & 0x03) {
2442 pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n",
2447 info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off;
2448 info_left = ext_sec->len;
2450 if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) {
2451 pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n",
2452 ext_sec->desc, ext_sec->off, ext_sec->len);
2456 /* At least a record size */
2457 if (info_left < sizeof(__u32)) {
2458 pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc);
2462 /* The record size needs to meet the minimum standard */
2463 record_size = *(__u32 *)info;
2464 if (record_size < ext_sec->min_rec_size ||
2465 record_size & 0x03) {
2466 pr_debug("%s section in .BTF.ext has invalid record size %u\n",
2467 ext_sec->desc, record_size);
2471 sinfo = info + sizeof(__u32);
2472 info_left -= sizeof(__u32);
2474 /* If no records, return failure now so .BTF.ext won't be used. */
2476 pr_debug("%s section in .BTF.ext has no records", ext_sec->desc);
2481 unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec);
2482 __u64 total_record_size;
2485 if (info_left < sec_hdrlen) {
2486 pr_debug("%s section header is not found in .BTF.ext\n",
2491 num_records = sinfo->num_info;
2492 if (num_records == 0) {
2493 pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2498 total_record_size = sec_hdrlen +
2499 (__u64)num_records * record_size;
2500 if (info_left < total_record_size) {
2501 pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2506 info_left -= total_record_size;
2507 sinfo = (void *)sinfo + total_record_size;
2510 ext_info = ext_sec->ext_info;
2511 ext_info->len = ext_sec->len - sizeof(__u32);
2512 ext_info->rec_size = record_size;
2513 ext_info->info = info + sizeof(__u32);
2518 static int btf_ext_setup_func_info(struct btf_ext *btf_ext)
2520 struct btf_ext_sec_setup_param param = {
2521 .off = btf_ext->hdr->func_info_off,
2522 .len = btf_ext->hdr->func_info_len,
2523 .min_rec_size = sizeof(struct bpf_func_info_min),
2524 .ext_info = &btf_ext->func_info,
2528 return btf_ext_setup_info(btf_ext, ¶m);
2531 static int btf_ext_setup_line_info(struct btf_ext *btf_ext)
2533 struct btf_ext_sec_setup_param param = {
2534 .off = btf_ext->hdr->line_info_off,
2535 .len = btf_ext->hdr->line_info_len,
2536 .min_rec_size = sizeof(struct bpf_line_info_min),
2537 .ext_info = &btf_ext->line_info,
2538 .desc = "line_info",
2541 return btf_ext_setup_info(btf_ext, ¶m);
2544 static int btf_ext_setup_core_relos(struct btf_ext *btf_ext)
2546 struct btf_ext_sec_setup_param param = {
2547 .off = btf_ext->hdr->core_relo_off,
2548 .len = btf_ext->hdr->core_relo_len,
2549 .min_rec_size = sizeof(struct bpf_core_relo),
2550 .ext_info = &btf_ext->core_relo_info,
2551 .desc = "core_relo",
2554 return btf_ext_setup_info(btf_ext, ¶m);
2557 static int btf_ext_parse_hdr(__u8 *data, __u32 data_size)
2559 const struct btf_ext_header *hdr = (struct btf_ext_header *)data;
2561 if (data_size < offsetofend(struct btf_ext_header, hdr_len) ||
2562 data_size < hdr->hdr_len) {
2563 pr_debug("BTF.ext header not found");
2567 if (hdr->magic == bswap_16(BTF_MAGIC)) {
2568 pr_warn("BTF.ext in non-native endianness is not supported\n");
2570 } else if (hdr->magic != BTF_MAGIC) {
2571 pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic);
2575 if (hdr->version != BTF_VERSION) {
2576 pr_debug("Unsupported BTF.ext version:%u\n", hdr->version);
2581 pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags);
2585 if (data_size == hdr->hdr_len) {
2586 pr_debug("BTF.ext has no data\n");
2593 void btf_ext__free(struct btf_ext *btf_ext)
2595 if (IS_ERR_OR_NULL(btf_ext))
2597 free(btf_ext->data);
2601 struct btf_ext *btf_ext__new(__u8 *data, __u32 size)
2603 struct btf_ext *btf_ext;
2606 err = btf_ext_parse_hdr(data, size);
2608 return ERR_PTR(err);
2610 btf_ext = calloc(1, sizeof(struct btf_ext));
2612 return ERR_PTR(-ENOMEM);
2614 btf_ext->data_size = size;
2615 btf_ext->data = malloc(size);
2616 if (!btf_ext->data) {
2620 memcpy(btf_ext->data, data, size);
2622 if (btf_ext->hdr->hdr_len <
2623 offsetofend(struct btf_ext_header, line_info_len))
2625 err = btf_ext_setup_func_info(btf_ext);
2629 err = btf_ext_setup_line_info(btf_ext);
2633 if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len))
2635 err = btf_ext_setup_core_relos(btf_ext);
2641 btf_ext__free(btf_ext);
2642 return ERR_PTR(err);
2648 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size)
2650 *size = btf_ext->data_size;
2651 return btf_ext->data;
2654 static int btf_ext_reloc_info(const struct btf *btf,
2655 const struct btf_ext_info *ext_info,
2656 const char *sec_name, __u32 insns_cnt,
2657 void **info, __u32 *cnt)
2659 __u32 sec_hdrlen = sizeof(struct btf_ext_info_sec);
2660 __u32 i, record_size, existing_len, records_len;
2661 struct btf_ext_info_sec *sinfo;
2662 const char *info_sec_name;
2666 record_size = ext_info->rec_size;
2667 sinfo = ext_info->info;
2668 remain_len = ext_info->len;
2669 while (remain_len > 0) {
2670 records_len = sinfo->num_info * record_size;
2671 info_sec_name = btf__name_by_offset(btf, sinfo->sec_name_off);
2672 if (strcmp(info_sec_name, sec_name)) {
2673 remain_len -= sec_hdrlen + records_len;
2674 sinfo = (void *)sinfo + sec_hdrlen + records_len;
2678 existing_len = (*cnt) * record_size;
2679 data = realloc(*info, existing_len + records_len);
2683 memcpy(data + existing_len, sinfo->data, records_len);
2684 /* adjust insn_off only, the rest data will be passed
2687 for (i = 0; i < sinfo->num_info; i++) {
2690 insn_off = data + existing_len + (i * record_size);
2691 *insn_off = *insn_off / sizeof(struct bpf_insn) +
2695 *cnt += sinfo->num_info;
2702 int btf_ext__reloc_func_info(const struct btf *btf,
2703 const struct btf_ext *btf_ext,
2704 const char *sec_name, __u32 insns_cnt,
2705 void **func_info, __u32 *cnt)
2707 return btf_ext_reloc_info(btf, &btf_ext->func_info, sec_name,
2708 insns_cnt, func_info, cnt);
2711 int btf_ext__reloc_line_info(const struct btf *btf,
2712 const struct btf_ext *btf_ext,
2713 const char *sec_name, __u32 insns_cnt,
2714 void **line_info, __u32 *cnt)
2716 return btf_ext_reloc_info(btf, &btf_ext->line_info, sec_name,
2717 insns_cnt, line_info, cnt);
2720 __u32 btf_ext__func_info_rec_size(const struct btf_ext *btf_ext)
2722 return btf_ext->func_info.rec_size;
2725 __u32 btf_ext__line_info_rec_size(const struct btf_ext *btf_ext)
2727 return btf_ext->line_info.rec_size;
2732 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
2733 const struct btf_dedup_opts *opts);
2734 static void btf_dedup_free(struct btf_dedup *d);
2735 static int btf_dedup_prep(struct btf_dedup *d);
2736 static int btf_dedup_strings(struct btf_dedup *d);
2737 static int btf_dedup_prim_types(struct btf_dedup *d);
2738 static int btf_dedup_struct_types(struct btf_dedup *d);
2739 static int btf_dedup_ref_types(struct btf_dedup *d);
2740 static int btf_dedup_compact_types(struct btf_dedup *d);
2741 static int btf_dedup_remap_types(struct btf_dedup *d);
2744 * Deduplicate BTF types and strings.
2746 * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF
2747 * section with all BTF type descriptors and string data. It overwrites that
2748 * memory in-place with deduplicated types and strings without any loss of
2749 * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section
2750 * is provided, all the strings referenced from .BTF.ext section are honored
2751 * and updated to point to the right offsets after deduplication.
2753 * If function returns with error, type/string data might be garbled and should
2756 * More verbose and detailed description of both problem btf_dedup is solving,
2757 * as well as solution could be found at:
2758 * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html
2760 * Problem description and justification
2761 * =====================================
2763 * BTF type information is typically emitted either as a result of conversion
2764 * from DWARF to BTF or directly by compiler. In both cases, each compilation
2765 * unit contains information about a subset of all the types that are used
2766 * in an application. These subsets are frequently overlapping and contain a lot
2767 * of duplicated information when later concatenated together into a single
2768 * binary. This algorithm ensures that each unique type is represented by single
2769 * BTF type descriptor, greatly reducing resulting size of BTF data.
2771 * Compilation unit isolation and subsequent duplication of data is not the only
2772 * problem. The same type hierarchy (e.g., struct and all the type that struct
2773 * references) in different compilation units can be represented in BTF to
2774 * various degrees of completeness (or, rather, incompleteness) due to
2775 * struct/union forward declarations.
2777 * Let's take a look at an example, that we'll use to better understand the
2778 * problem (and solution). Suppose we have two compilation units, each using
2779 * same `struct S`, but each of them having incomplete type information about
2808 * In case of CU #1, BTF data will know only that `struct B` exist (but no
2809 * more), but will know the complete type information about `struct A`. While
2810 * for CU #2, it will know full type information about `struct B`, but will
2811 * only know about forward declaration of `struct A` (in BTF terms, it will
2812 * have `BTF_KIND_FWD` type descriptor with name `B`).
2814 * This compilation unit isolation means that it's possible that there is no
2815 * single CU with complete type information describing structs `S`, `A`, and
2816 * `B`. Also, we might get tons of duplicated and redundant type information.
2818 * Additional complication we need to keep in mind comes from the fact that
2819 * types, in general, can form graphs containing cycles, not just DAGs.
2821 * While algorithm does deduplication, it also merges and resolves type
2822 * information (unless disabled throught `struct btf_opts`), whenever possible.
2823 * E.g., in the example above with two compilation units having partial type
2824 * information for structs `A` and `B`, the output of algorithm will emit
2825 * a single copy of each BTF type that describes structs `A`, `B`, and `S`
2826 * (as well as type information for `int` and pointers), as if they were defined
2827 * in a single compilation unit as:
2847 * Algorithm completes its work in 6 separate passes:
2849 * 1. Strings deduplication.
2850 * 2. Primitive types deduplication (int, enum, fwd).
2851 * 3. Struct/union types deduplication.
2852 * 4. Reference types deduplication (pointers, typedefs, arrays, funcs, func
2853 * protos, and const/volatile/restrict modifiers).
2854 * 5. Types compaction.
2855 * 6. Types remapping.
2857 * Algorithm determines canonical type descriptor, which is a single
2858 * representative type for each truly unique type. This canonical type is the
2859 * one that will go into final deduplicated BTF type information. For
2860 * struct/unions, it is also the type that algorithm will merge additional type
2861 * information into (while resolving FWDs), as it discovers it from data in
2862 * other CUs. Each input BTF type eventually gets either mapped to itself, if
2863 * that type is canonical, or to some other type, if that type is equivalent
2864 * and was chosen as canonical representative. This mapping is stored in
2865 * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that
2866 * FWD type got resolved to.
2868 * To facilitate fast discovery of canonical types, we also maintain canonical
2869 * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash
2870 * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types
2871 * that match that signature. With sufficiently good choice of type signature
2872 * hashing function, we can limit number of canonical types for each unique type
2873 * signature to a very small number, allowing to find canonical type for any
2874 * duplicated type very quickly.
2876 * Struct/union deduplication is the most critical part and algorithm for
2877 * deduplicating structs/unions is described in greater details in comments for
2878 * `btf_dedup_is_equiv` function.
2880 int btf__dedup(struct btf *btf, struct btf_ext *btf_ext,
2881 const struct btf_dedup_opts *opts)
2883 struct btf_dedup *d = btf_dedup_new(btf, btf_ext, opts);
2887 pr_debug("btf_dedup_new failed: %ld", PTR_ERR(d));
2891 if (btf_ensure_modifiable(btf))
2894 err = btf_dedup_prep(d);
2896 pr_debug("btf_dedup_prep failed:%d\n", err);
2899 err = btf_dedup_strings(d);
2901 pr_debug("btf_dedup_strings failed:%d\n", err);
2904 err = btf_dedup_prim_types(d);
2906 pr_debug("btf_dedup_prim_types failed:%d\n", err);
2909 err = btf_dedup_struct_types(d);
2911 pr_debug("btf_dedup_struct_types failed:%d\n", err);
2914 err = btf_dedup_ref_types(d);
2916 pr_debug("btf_dedup_ref_types failed:%d\n", err);
2919 err = btf_dedup_compact_types(d);
2921 pr_debug("btf_dedup_compact_types failed:%d\n", err);
2924 err = btf_dedup_remap_types(d);
2926 pr_debug("btf_dedup_remap_types failed:%d\n", err);
2935 #define BTF_UNPROCESSED_ID ((__u32)-1)
2936 #define BTF_IN_PROGRESS_ID ((__u32)-2)
2939 /* .BTF section to be deduped in-place */
2942 * Optional .BTF.ext section. When provided, any strings referenced
2943 * from it will be taken into account when deduping strings
2945 struct btf_ext *btf_ext;
2947 * This is a map from any type's signature hash to a list of possible
2948 * canonical representative type candidates. Hash collisions are
2949 * ignored, so even types of various kinds can share same list of
2950 * candidates, which is fine because we rely on subsequent
2951 * btf_xxx_equal() checks to authoritatively verify type equality.
2953 struct hashmap *dedup_table;
2954 /* Canonical types map */
2956 /* Hypothetical mapping, used during type graph equivalence checks */
2961 /* Whether hypothetical mapping, if successful, would need to adjust
2962 * already canonicalized types (due to a new forward declaration to
2963 * concrete type resolution). In such case, during split BTF dedup
2964 * candidate type would still be considered as different, because base
2965 * BTF is considered to be immutable.
2967 bool hypot_adjust_canon;
2968 /* Various option modifying behavior of algorithm */
2969 struct btf_dedup_opts opts;
2970 /* temporary strings deduplication state */
2974 struct hashmap* strs_hash;
2977 static long hash_combine(long h, long value)
2979 return h * 31 + value;
2982 #define for_each_dedup_cand(d, node, hash) \
2983 hashmap__for_each_key_entry(d->dedup_table, node, (void *)hash)
2985 static int btf_dedup_table_add(struct btf_dedup *d, long hash, __u32 type_id)
2987 return hashmap__append(d->dedup_table,
2988 (void *)hash, (void *)(long)type_id);
2991 static int btf_dedup_hypot_map_add(struct btf_dedup *d,
2992 __u32 from_id, __u32 to_id)
2994 if (d->hypot_cnt == d->hypot_cap) {
2997 d->hypot_cap += max((size_t)16, d->hypot_cap / 2);
2998 new_list = libbpf_reallocarray(d->hypot_list, d->hypot_cap, sizeof(__u32));
3001 d->hypot_list = new_list;
3003 d->hypot_list[d->hypot_cnt++] = from_id;
3004 d->hypot_map[from_id] = to_id;
3008 static void btf_dedup_clear_hypot_map(struct btf_dedup *d)
3012 for (i = 0; i < d->hypot_cnt; i++)
3013 d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID;
3015 d->hypot_adjust_canon = false;
3018 static void btf_dedup_free(struct btf_dedup *d)
3020 hashmap__free(d->dedup_table);
3021 d->dedup_table = NULL;
3027 d->hypot_map = NULL;
3029 free(d->hypot_list);
3030 d->hypot_list = NULL;
3035 static size_t btf_dedup_identity_hash_fn(const void *key, void *ctx)
3040 static size_t btf_dedup_collision_hash_fn(const void *key, void *ctx)
3045 static bool btf_dedup_equal_fn(const void *k1, const void *k2, void *ctx)
3050 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
3051 const struct btf_dedup_opts *opts)
3053 struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup));
3054 hashmap_hash_fn hash_fn = btf_dedup_identity_hash_fn;
3055 int i, err = 0, type_cnt;
3058 return ERR_PTR(-ENOMEM);
3060 d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds;
3061 /* dedup_table_size is now used only to force collisions in tests */
3062 if (opts && opts->dedup_table_size == 1)
3063 hash_fn = btf_dedup_collision_hash_fn;
3066 d->btf_ext = btf_ext;
3068 d->dedup_table = hashmap__new(hash_fn, btf_dedup_equal_fn, NULL);
3069 if (IS_ERR(d->dedup_table)) {
3070 err = PTR_ERR(d->dedup_table);
3071 d->dedup_table = NULL;
3075 type_cnt = btf__get_nr_types(btf) + 1;
3076 d->map = malloc(sizeof(__u32) * type_cnt);
3081 /* special BTF "void" type is made canonical immediately */
3083 for (i = 1; i < type_cnt; i++) {
3084 struct btf_type *t = btf_type_by_id(d->btf, i);
3086 /* VAR and DATASEC are never deduped and are self-canonical */
3087 if (btf_is_var(t) || btf_is_datasec(t))
3090 d->map[i] = BTF_UNPROCESSED_ID;
3093 d->hypot_map = malloc(sizeof(__u32) * type_cnt);
3094 if (!d->hypot_map) {
3098 for (i = 0; i < type_cnt; i++)
3099 d->hypot_map[i] = BTF_UNPROCESSED_ID;
3104 return ERR_PTR(err);
3110 typedef int (*str_off_fn_t)(__u32 *str_off_ptr, void *ctx);
3113 * Iterate over all possible places in .BTF and .BTF.ext that can reference
3114 * string and pass pointer to it to a provided callback `fn`.
3116 static int btf_for_each_str_off(struct btf_dedup *d, str_off_fn_t fn, void *ctx)
3118 void *line_data_cur, *line_data_end;
3119 int i, j, r, rec_size;
3122 for (i = 0; i < d->btf->nr_types; i++) {
3123 t = btf_type_by_id(d->btf, d->btf->start_id + i);
3124 r = fn(&t->name_off, ctx);
3128 switch (btf_kind(t)) {
3129 case BTF_KIND_STRUCT:
3130 case BTF_KIND_UNION: {
3131 struct btf_member *m = btf_members(t);
3132 __u16 vlen = btf_vlen(t);
3134 for (j = 0; j < vlen; j++) {
3135 r = fn(&m->name_off, ctx);
3142 case BTF_KIND_ENUM: {
3143 struct btf_enum *m = btf_enum(t);
3144 __u16 vlen = btf_vlen(t);
3146 for (j = 0; j < vlen; j++) {
3147 r = fn(&m->name_off, ctx);
3154 case BTF_KIND_FUNC_PROTO: {
3155 struct btf_param *m = btf_params(t);
3156 __u16 vlen = btf_vlen(t);
3158 for (j = 0; j < vlen; j++) {
3159 r = fn(&m->name_off, ctx);
3174 line_data_cur = d->btf_ext->line_info.info;
3175 line_data_end = d->btf_ext->line_info.info + d->btf_ext->line_info.len;
3176 rec_size = d->btf_ext->line_info.rec_size;
3178 while (line_data_cur < line_data_end) {
3179 struct btf_ext_info_sec *sec = line_data_cur;
3180 struct bpf_line_info_min *line_info;
3181 __u32 num_info = sec->num_info;
3183 r = fn(&sec->sec_name_off, ctx);
3187 line_data_cur += sizeof(struct btf_ext_info_sec);
3188 for (i = 0; i < num_info; i++) {
3189 line_info = line_data_cur;
3190 r = fn(&line_info->file_name_off, ctx);
3193 r = fn(&line_info->line_off, ctx);
3196 line_data_cur += rec_size;
3203 static int strs_dedup_remap_str_off(__u32 *str_off_ptr, void *ctx)
3205 struct btf_dedup *d = ctx;
3206 __u32 str_off = *str_off_ptr;
3207 long old_off, new_off, len;
3212 /* don't touch empty string or string in main BTF */
3213 if (str_off == 0 || str_off < d->btf->start_str_off)
3216 s = btf__str_by_offset(d->btf, str_off);
3217 if (d->btf->base_btf) {
3218 err = btf__find_str(d->btf->base_btf, s);
3227 len = strlen(s) + 1;
3229 new_off = d->strs_len;
3230 p = btf_add_mem(&d->strs_data, &d->strs_cap, 1, new_off, BTF_MAX_STR_OFFSET, len);
3236 /* Now attempt to add the string, but only if the string with the same
3237 * contents doesn't exist already (HASHMAP_ADD strategy). If such
3238 * string exists, we'll get its offset in old_off (that's old_key).
3240 err = hashmap__insert(d->strs_hash, (void *)new_off, (void *)new_off,
3241 HASHMAP_ADD, (const void **)&old_off, NULL);
3242 if (err == -EEXIST) {
3243 *str_off_ptr = d->btf->start_str_off + old_off;
3247 *str_off_ptr = d->btf->start_str_off + new_off;
3254 * Dedup string and filter out those that are not referenced from either .BTF
3255 * or .BTF.ext (if provided) sections.
3257 * This is done by building index of all strings in BTF's string section,
3258 * then iterating over all entities that can reference strings (e.g., type
3259 * names, struct field names, .BTF.ext line info, etc) and marking corresponding
3260 * strings as used. After that all used strings are deduped and compacted into
3261 * sequential blob of memory and new offsets are calculated. Then all the string
3262 * references are iterated again and rewritten using new offsets.
3264 static int btf_dedup_strings(struct btf_dedup *d)
3269 if (d->btf->strs_deduped)
3272 /* temporarily switch to use btf_dedup's strs_data for strings for hash
3273 * functions; later we'll just transfer hashmap to struct btf as is,
3274 * along the strs_data
3276 d->btf->strs_data_ptr = &d->strs_data;
3278 d->strs_hash = hashmap__new(strs_hash_fn, strs_hash_equal_fn, d->btf);
3279 if (IS_ERR(d->strs_hash)) {
3280 err = PTR_ERR(d->strs_hash);
3281 d->strs_hash = NULL;
3285 if (!d->btf->base_btf) {
3286 s = btf_add_mem(&d->strs_data, &d->strs_cap, 1, d->strs_len, BTF_MAX_STR_OFFSET, 1);
3289 /* initial empty string */
3293 /* insert empty string; we won't be looking it up during strings
3294 * dedup, but it's good to have it for generic BTF string lookups
3296 err = hashmap__insert(d->strs_hash, (void *)0, (void *)0,
3297 HASHMAP_ADD, NULL, NULL);
3302 /* remap string offsets */
3303 err = btf_for_each_str_off(d, strs_dedup_remap_str_off, d);
3307 /* replace BTF string data and hash with deduped ones */
3308 free(d->btf->strs_data);
3309 hashmap__free(d->btf->strs_hash);
3310 d->btf->strs_data = d->strs_data;
3311 d->btf->strs_data_cap = d->strs_cap;
3312 d->btf->hdr->str_len = d->strs_len;
3313 d->btf->strs_hash = d->strs_hash;
3314 /* now point strs_data_ptr back to btf->strs_data */
3315 d->btf->strs_data_ptr = &d->btf->strs_data;
3317 d->strs_data = d->strs_hash = NULL;
3318 d->strs_len = d->strs_cap = 0;
3319 d->btf->strs_deduped = true;
3324 hashmap__free(d->strs_hash);
3325 d->strs_data = d->strs_hash = NULL;
3326 d->strs_len = d->strs_cap = 0;
3328 /* restore strings pointer for existing d->btf->strs_hash back */
3329 d->btf->strs_data_ptr = &d->strs_data;
3334 static long btf_hash_common(struct btf_type *t)
3338 h = hash_combine(0, t->name_off);
3339 h = hash_combine(h, t->info);
3340 h = hash_combine(h, t->size);
3344 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2)
3346 return t1->name_off == t2->name_off &&
3347 t1->info == t2->info &&
3348 t1->size == t2->size;
3351 /* Calculate type signature hash of INT. */
3352 static long btf_hash_int(struct btf_type *t)
3354 __u32 info = *(__u32 *)(t + 1);
3357 h = btf_hash_common(t);
3358 h = hash_combine(h, info);
3362 /* Check structural equality of two INTs. */
3363 static bool btf_equal_int(struct btf_type *t1, struct btf_type *t2)
3367 if (!btf_equal_common(t1, t2))
3369 info1 = *(__u32 *)(t1 + 1);
3370 info2 = *(__u32 *)(t2 + 1);
3371 return info1 == info2;
3374 /* Calculate type signature hash of ENUM. */
3375 static long btf_hash_enum(struct btf_type *t)
3379 /* don't hash vlen and enum members to support enum fwd resolving */
3380 h = hash_combine(0, t->name_off);
3381 h = hash_combine(h, t->info & ~0xffff);
3382 h = hash_combine(h, t->size);
3386 /* Check structural equality of two ENUMs. */
3387 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2)
3389 const struct btf_enum *m1, *m2;
3393 if (!btf_equal_common(t1, t2))
3396 vlen = btf_vlen(t1);
3399 for (i = 0; i < vlen; i++) {
3400 if (m1->name_off != m2->name_off || m1->val != m2->val)
3408 static inline bool btf_is_enum_fwd(struct btf_type *t)
3410 return btf_is_enum(t) && btf_vlen(t) == 0;
3413 static bool btf_compat_enum(struct btf_type *t1, struct btf_type *t2)
3415 if (!btf_is_enum_fwd(t1) && !btf_is_enum_fwd(t2))
3416 return btf_equal_enum(t1, t2);
3417 /* ignore vlen when comparing */
3418 return t1->name_off == t2->name_off &&
3419 (t1->info & ~0xffff) == (t2->info & ~0xffff) &&
3420 t1->size == t2->size;
3424 * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs,
3425 * as referenced type IDs equivalence is established separately during type
3426 * graph equivalence check algorithm.
3428 static long btf_hash_struct(struct btf_type *t)
3430 const struct btf_member *member = btf_members(t);
3431 __u32 vlen = btf_vlen(t);
3432 long h = btf_hash_common(t);
3435 for (i = 0; i < vlen; i++) {
3436 h = hash_combine(h, member->name_off);
3437 h = hash_combine(h, member->offset);
3438 /* no hashing of referenced type ID, it can be unresolved yet */
3445 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
3446 * IDs. This check is performed during type graph equivalence check and
3447 * referenced types equivalence is checked separately.
3449 static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2)
3451 const struct btf_member *m1, *m2;
3455 if (!btf_equal_common(t1, t2))
3458 vlen = btf_vlen(t1);
3459 m1 = btf_members(t1);
3460 m2 = btf_members(t2);
3461 for (i = 0; i < vlen; i++) {
3462 if (m1->name_off != m2->name_off || m1->offset != m2->offset)
3471 * Calculate type signature hash of ARRAY, including referenced type IDs,
3472 * under assumption that they were already resolved to canonical type IDs and
3473 * are not going to change.
3475 static long btf_hash_array(struct btf_type *t)
3477 const struct btf_array *info = btf_array(t);
3478 long h = btf_hash_common(t);
3480 h = hash_combine(h, info->type);
3481 h = hash_combine(h, info->index_type);
3482 h = hash_combine(h, info->nelems);
3487 * Check exact equality of two ARRAYs, taking into account referenced
3488 * type IDs, under assumption that they were already resolved to canonical
3489 * type IDs and are not going to change.
3490 * This function is called during reference types deduplication to compare
3491 * ARRAY to potential canonical representative.
3493 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2)
3495 const struct btf_array *info1, *info2;
3497 if (!btf_equal_common(t1, t2))
3500 info1 = btf_array(t1);
3501 info2 = btf_array(t2);
3502 return info1->type == info2->type &&
3503 info1->index_type == info2->index_type &&
3504 info1->nelems == info2->nelems;
3508 * Check structural compatibility of two ARRAYs, ignoring referenced type
3509 * IDs. This check is performed during type graph equivalence check and
3510 * referenced types equivalence is checked separately.
3512 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2)
3514 if (!btf_equal_common(t1, t2))
3517 return btf_array(t1)->nelems == btf_array(t2)->nelems;
3521 * Calculate type signature hash of FUNC_PROTO, including referenced type IDs,
3522 * under assumption that they were already resolved to canonical type IDs and
3523 * are not going to change.
3525 static long btf_hash_fnproto(struct btf_type *t)
3527 const struct btf_param *member = btf_params(t);
3528 __u16 vlen = btf_vlen(t);
3529 long h = btf_hash_common(t);
3532 for (i = 0; i < vlen; i++) {
3533 h = hash_combine(h, member->name_off);
3534 h = hash_combine(h, member->type);
3541 * Check exact equality of two FUNC_PROTOs, taking into account referenced
3542 * type IDs, under assumption that they were already resolved to canonical
3543 * type IDs and are not going to change.
3544 * This function is called during reference types deduplication to compare
3545 * FUNC_PROTO to potential canonical representative.
3547 static bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2)
3549 const struct btf_param *m1, *m2;
3553 if (!btf_equal_common(t1, t2))
3556 vlen = btf_vlen(t1);
3557 m1 = btf_params(t1);
3558 m2 = btf_params(t2);
3559 for (i = 0; i < vlen; i++) {
3560 if (m1->name_off != m2->name_off || m1->type != m2->type)
3569 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
3570 * IDs. This check is performed during type graph equivalence check and
3571 * referenced types equivalence is checked separately.
3573 static bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2)
3575 const struct btf_param *m1, *m2;
3579 /* skip return type ID */
3580 if (t1->name_off != t2->name_off || t1->info != t2->info)
3583 vlen = btf_vlen(t1);
3584 m1 = btf_params(t1);
3585 m2 = btf_params(t2);
3586 for (i = 0; i < vlen; i++) {
3587 if (m1->name_off != m2->name_off)
3595 /* Prepare split BTF for deduplication by calculating hashes of base BTF's
3596 * types and initializing the rest of the state (canonical type mapping) for
3597 * the fixed base BTF part.
3599 static int btf_dedup_prep(struct btf_dedup *d)
3605 if (!d->btf->base_btf)
3608 for (type_id = 1; type_id < d->btf->start_id; type_id++) {
3609 t = btf_type_by_id(d->btf, type_id);
3611 /* all base BTF types are self-canonical by definition */
3612 d->map[type_id] = type_id;
3614 switch (btf_kind(t)) {
3616 case BTF_KIND_DATASEC:
3617 /* VAR and DATASEC are never hash/deduplicated */
3619 case BTF_KIND_CONST:
3620 case BTF_KIND_VOLATILE:
3621 case BTF_KIND_RESTRICT:
3624 case BTF_KIND_TYPEDEF:
3626 h = btf_hash_common(t);
3629 h = btf_hash_int(t);
3632 h = btf_hash_enum(t);
3634 case BTF_KIND_STRUCT:
3635 case BTF_KIND_UNION:
3636 h = btf_hash_struct(t);
3638 case BTF_KIND_ARRAY:
3639 h = btf_hash_array(t);
3641 case BTF_KIND_FUNC_PROTO:
3642 h = btf_hash_fnproto(t);
3645 pr_debug("unknown kind %d for type [%d]\n", btf_kind(t), type_id);
3648 if (btf_dedup_table_add(d, h, type_id))
3656 * Deduplicate primitive types, that can't reference other types, by calculating
3657 * their type signature hash and comparing them with any possible canonical
3658 * candidate. If no canonical candidate matches, type itself is marked as
3659 * canonical and is added into `btf_dedup->dedup_table` as another candidate.
3661 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id)
3663 struct btf_type *t = btf_type_by_id(d->btf, type_id);
3664 struct hashmap_entry *hash_entry;
3665 struct btf_type *cand;
3666 /* if we don't find equivalent type, then we are canonical */
3667 __u32 new_id = type_id;
3671 switch (btf_kind(t)) {
3672 case BTF_KIND_CONST:
3673 case BTF_KIND_VOLATILE:
3674 case BTF_KIND_RESTRICT:
3676 case BTF_KIND_TYPEDEF:
3677 case BTF_KIND_ARRAY:
3678 case BTF_KIND_STRUCT:
3679 case BTF_KIND_UNION:
3681 case BTF_KIND_FUNC_PROTO:
3683 case BTF_KIND_DATASEC:
3687 h = btf_hash_int(t);
3688 for_each_dedup_cand(d, hash_entry, h) {
3689 cand_id = (__u32)(long)hash_entry->value;
3690 cand = btf_type_by_id(d->btf, cand_id);
3691 if (btf_equal_int(t, cand)) {
3699 h = btf_hash_enum(t);
3700 for_each_dedup_cand(d, hash_entry, h) {
3701 cand_id = (__u32)(long)hash_entry->value;
3702 cand = btf_type_by_id(d->btf, cand_id);
3703 if (btf_equal_enum(t, cand)) {
3707 if (d->opts.dont_resolve_fwds)
3709 if (btf_compat_enum(t, cand)) {
3710 if (btf_is_enum_fwd(t)) {
3711 /* resolve fwd to full enum */
3715 /* resolve canonical enum fwd to full enum */
3716 d->map[cand_id] = type_id;
3722 h = btf_hash_common(t);
3723 for_each_dedup_cand(d, hash_entry, h) {
3724 cand_id = (__u32)(long)hash_entry->value;
3725 cand = btf_type_by_id(d->btf, cand_id);
3726 if (btf_equal_common(t, cand)) {
3737 d->map[type_id] = new_id;
3738 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
3744 static int btf_dedup_prim_types(struct btf_dedup *d)
3748 for (i = 0; i < d->btf->nr_types; i++) {
3749 err = btf_dedup_prim_type(d, d->btf->start_id + i);
3757 * Check whether type is already mapped into canonical one (could be to itself).
3759 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id)
3761 return d->map[type_id] <= BTF_MAX_NR_TYPES;
3765 * Resolve type ID into its canonical type ID, if any; otherwise return original
3766 * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow
3767 * STRUCT/UNION link and resolve it into canonical type ID as well.
3769 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id)
3771 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3772 type_id = d->map[type_id];
3777 * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original
3780 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id)
3782 __u32 orig_type_id = type_id;
3784 if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3787 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3788 type_id = d->map[type_id];
3790 if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3793 return orig_type_id;
3797 static inline __u16 btf_fwd_kind(struct btf_type *t)
3799 return btf_kflag(t) ? BTF_KIND_UNION : BTF_KIND_STRUCT;
3802 /* Check if given two types are identical ARRAY definitions */
3803 static int btf_dedup_identical_arrays(struct btf_dedup *d, __u32 id1, __u32 id2)
3805 struct btf_type *t1, *t2;
3807 t1 = btf_type_by_id(d->btf, id1);
3808 t2 = btf_type_by_id(d->btf, id2);
3809 if (!btf_is_array(t1) || !btf_is_array(t2))
3812 return btf_equal_array(t1, t2);
3816 * Check equivalence of BTF type graph formed by candidate struct/union (we'll
3817 * call it "candidate graph" in this description for brevity) to a type graph
3818 * formed by (potential) canonical struct/union ("canonical graph" for brevity
3819 * here, though keep in mind that not all types in canonical graph are
3820 * necessarily canonical representatives themselves, some of them might be
3821 * duplicates or its uniqueness might not have been established yet).
3823 * - >0, if type graphs are equivalent;
3824 * - 0, if not equivalent;
3827 * Algorithm performs side-by-side DFS traversal of both type graphs and checks
3828 * equivalence of BTF types at each step. If at any point BTF types in candidate
3829 * and canonical graphs are not compatible structurally, whole graphs are
3830 * incompatible. If types are structurally equivalent (i.e., all information
3831 * except referenced type IDs is exactly the same), a mapping from `canon_id` to
3832 * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`).
3833 * If a type references other types, then those referenced types are checked
3834 * for equivalence recursively.
3836 * During DFS traversal, if we find that for current `canon_id` type we
3837 * already have some mapping in hypothetical map, we check for two possible
3839 * - `canon_id` is mapped to exactly the same type as `cand_id`. This will
3840 * happen when type graphs have cycles. In this case we assume those two
3841 * types are equivalent.
3842 * - `canon_id` is mapped to different type. This is contradiction in our
3843 * hypothetical mapping, because same graph in canonical graph corresponds
3844 * to two different types in candidate graph, which for equivalent type
3845 * graphs shouldn't happen. This condition terminates equivalence check
3846 * with negative result.
3848 * If type graphs traversal exhausts types to check and find no contradiction,
3849 * then type graphs are equivalent.
3851 * When checking types for equivalence, there is one special case: FWD types.
3852 * If FWD type resolution is allowed and one of the types (either from canonical
3853 * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind
3854 * flag) and their names match, hypothetical mapping is updated to point from
3855 * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully,
3856 * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently.
3858 * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution,
3859 * if there are two exactly named (or anonymous) structs/unions that are
3860 * compatible structurally, one of which has FWD field, while other is concrete
3861 * STRUCT/UNION, but according to C sources they are different structs/unions
3862 * that are referencing different types with the same name. This is extremely
3863 * unlikely to happen, but btf_dedup API allows to disable FWD resolution if
3864 * this logic is causing problems.
3866 * Doing FWD resolution means that both candidate and/or canonical graphs can
3867 * consists of portions of the graph that come from multiple compilation units.
3868 * This is due to the fact that types within single compilation unit are always
3869 * deduplicated and FWDs are already resolved, if referenced struct/union
3870 * definiton is available. So, if we had unresolved FWD and found corresponding
3871 * STRUCT/UNION, they will be from different compilation units. This
3872 * consequently means that when we "link" FWD to corresponding STRUCT/UNION,
3873 * type graph will likely have at least two different BTF types that describe
3874 * same type (e.g., most probably there will be two different BTF types for the
3875 * same 'int' primitive type) and could even have "overlapping" parts of type
3876 * graph that describe same subset of types.
3878 * This in turn means that our assumption that each type in canonical graph
3879 * must correspond to exactly one type in candidate graph might not hold
3880 * anymore and will make it harder to detect contradictions using hypothetical
3881 * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION
3882 * resolution only in canonical graph. FWDs in candidate graphs are never
3883 * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs
3885 * - Both types in canonical and candidate graphs are FWDs. If they are
3886 * structurally equivalent, then they can either be both resolved to the
3887 * same STRUCT/UNION or not resolved at all. In both cases they are
3888 * equivalent and there is no need to resolve FWD on candidate side.
3889 * - Both types in canonical and candidate graphs are concrete STRUCT/UNION,
3890 * so nothing to resolve as well, algorithm will check equivalence anyway.
3891 * - Type in canonical graph is FWD, while type in candidate is concrete
3892 * STRUCT/UNION. In this case candidate graph comes from single compilation
3893 * unit, so there is exactly one BTF type for each unique C type. After
3894 * resolving FWD into STRUCT/UNION, there might be more than one BTF type
3895 * in canonical graph mapping to single BTF type in candidate graph, but
3896 * because hypothetical mapping maps from canonical to candidate types, it's
3897 * alright, and we still maintain the property of having single `canon_id`
3898 * mapping to single `cand_id` (there could be two different `canon_id`
3899 * mapped to the same `cand_id`, but it's not contradictory).
3900 * - Type in canonical graph is concrete STRUCT/UNION, while type in candidate
3901 * graph is FWD. In this case we are just going to check compatibility of
3902 * STRUCT/UNION and corresponding FWD, and if they are compatible, we'll
3903 * assume that whatever STRUCT/UNION FWD resolves to must be equivalent to
3904 * a concrete STRUCT/UNION from canonical graph. If the rest of type graphs
3905 * turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from
3908 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id,
3911 struct btf_type *cand_type;
3912 struct btf_type *canon_type;
3913 __u32 hypot_type_id;
3918 /* if both resolve to the same canonical, they must be equivalent */
3919 if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id))
3922 canon_id = resolve_fwd_id(d, canon_id);
3924 hypot_type_id = d->hypot_map[canon_id];
3925 if (hypot_type_id <= BTF_MAX_NR_TYPES) {
3926 /* In some cases compiler will generate different DWARF types
3927 * for *identical* array type definitions and use them for
3928 * different fields within the *same* struct. This breaks type
3929 * equivalence check, which makes an assumption that candidate
3930 * types sub-graph has a consistent and deduped-by-compiler
3931 * types within a single CU. So work around that by explicitly
3932 * allowing identical array types here.
3934 return hypot_type_id == cand_id ||
3935 btf_dedup_identical_arrays(d, hypot_type_id, cand_id);
3938 if (btf_dedup_hypot_map_add(d, canon_id, cand_id))
3941 cand_type = btf_type_by_id(d->btf, cand_id);
3942 canon_type = btf_type_by_id(d->btf, canon_id);
3943 cand_kind = btf_kind(cand_type);
3944 canon_kind = btf_kind(canon_type);
3946 if (cand_type->name_off != canon_type->name_off)
3949 /* FWD <--> STRUCT/UNION equivalence check, if enabled */
3950 if (!d->opts.dont_resolve_fwds
3951 && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD)
3952 && cand_kind != canon_kind) {
3956 if (cand_kind == BTF_KIND_FWD) {
3957 real_kind = canon_kind;
3958 fwd_kind = btf_fwd_kind(cand_type);
3960 real_kind = cand_kind;
3961 fwd_kind = btf_fwd_kind(canon_type);
3962 /* we'd need to resolve base FWD to STRUCT/UNION */
3963 if (fwd_kind == real_kind && canon_id < d->btf->start_id)
3964 d->hypot_adjust_canon = true;
3966 return fwd_kind == real_kind;
3969 if (cand_kind != canon_kind)
3972 switch (cand_kind) {
3974 return btf_equal_int(cand_type, canon_type);
3977 if (d->opts.dont_resolve_fwds)
3978 return btf_equal_enum(cand_type, canon_type);
3980 return btf_compat_enum(cand_type, canon_type);
3983 return btf_equal_common(cand_type, canon_type);
3985 case BTF_KIND_CONST:
3986 case BTF_KIND_VOLATILE:
3987 case BTF_KIND_RESTRICT:
3989 case BTF_KIND_TYPEDEF:
3991 if (cand_type->info != canon_type->info)
3993 return btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
3995 case BTF_KIND_ARRAY: {
3996 const struct btf_array *cand_arr, *canon_arr;
3998 if (!btf_compat_array(cand_type, canon_type))
4000 cand_arr = btf_array(cand_type);
4001 canon_arr = btf_array(canon_type);
4002 eq = btf_dedup_is_equiv(d, cand_arr->index_type, canon_arr->index_type);
4005 return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type);
4008 case BTF_KIND_STRUCT:
4009 case BTF_KIND_UNION: {
4010 const struct btf_member *cand_m, *canon_m;
4013 if (!btf_shallow_equal_struct(cand_type, canon_type))
4015 vlen = btf_vlen(cand_type);
4016 cand_m = btf_members(cand_type);
4017 canon_m = btf_members(canon_type);
4018 for (i = 0; i < vlen; i++) {
4019 eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type);
4029 case BTF_KIND_FUNC_PROTO: {
4030 const struct btf_param *cand_p, *canon_p;
4033 if (!btf_compat_fnproto(cand_type, canon_type))
4035 eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
4038 vlen = btf_vlen(cand_type);
4039 cand_p = btf_params(cand_type);
4040 canon_p = btf_params(canon_type);
4041 for (i = 0; i < vlen; i++) {
4042 eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type);
4058 * Use hypothetical mapping, produced by successful type graph equivalence
4059 * check, to augment existing struct/union canonical mapping, where possible.
4061 * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record
4062 * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional:
4063 * it doesn't matter if FWD type was part of canonical graph or candidate one,
4064 * we are recording the mapping anyway. As opposed to carefulness required
4065 * for struct/union correspondence mapping (described below), for FWD resolution
4066 * it's not important, as by the time that FWD type (reference type) will be
4067 * deduplicated all structs/unions will be deduped already anyway.
4069 * Recording STRUCT/UNION mapping is purely a performance optimization and is
4070 * not required for correctness. It needs to be done carefully to ensure that
4071 * struct/union from candidate's type graph is not mapped into corresponding
4072 * struct/union from canonical type graph that itself hasn't been resolved into
4073 * canonical representative. The only guarantee we have is that canonical
4074 * struct/union was determined as canonical and that won't change. But any
4075 * types referenced through that struct/union fields could have been not yet
4076 * resolved, so in case like that it's too early to establish any kind of
4077 * correspondence between structs/unions.
4079 * No canonical correspondence is derived for primitive types (they are already
4080 * deduplicated completely already anyway) or reference types (they rely on
4081 * stability of struct/union canonical relationship for equivalence checks).
4083 static void btf_dedup_merge_hypot_map(struct btf_dedup *d)
4085 __u32 canon_type_id, targ_type_id;
4086 __u16 t_kind, c_kind;
4090 for (i = 0; i < d->hypot_cnt; i++) {
4091 canon_type_id = d->hypot_list[i];
4092 targ_type_id = d->hypot_map[canon_type_id];
4093 t_id = resolve_type_id(d, targ_type_id);
4094 c_id = resolve_type_id(d, canon_type_id);
4095 t_kind = btf_kind(btf__type_by_id(d->btf, t_id));
4096 c_kind = btf_kind(btf__type_by_id(d->btf, c_id));
4098 * Resolve FWD into STRUCT/UNION.
4099 * It's ok to resolve FWD into STRUCT/UNION that's not yet
4100 * mapped to canonical representative (as opposed to
4101 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because
4102 * eventually that struct is going to be mapped and all resolved
4103 * FWDs will automatically resolve to correct canonical
4104 * representative. This will happen before ref type deduping,
4105 * which critically depends on stability of these mapping. This
4106 * stability is not a requirement for STRUCT/UNION equivalence
4110 /* if it's the split BTF case, we still need to point base FWD
4111 * to STRUCT/UNION in a split BTF, because FWDs from split BTF
4112 * will be resolved against base FWD. If we don't point base
4113 * canonical FWD to the resolved STRUCT/UNION, then all the
4114 * FWDs in split BTF won't be correctly resolved to a proper
4117 if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD)
4118 d->map[c_id] = t_id;
4120 /* if graph equivalence determined that we'd need to adjust
4121 * base canonical types, then we need to only point base FWDs
4122 * to STRUCTs/UNIONs and do no more modifications. For all
4123 * other purposes the type graphs were not equivalent.
4125 if (d->hypot_adjust_canon)
4128 if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD)
4129 d->map[t_id] = c_id;
4131 if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) &&
4132 c_kind != BTF_KIND_FWD &&
4133 is_type_mapped(d, c_id) &&
4134 !is_type_mapped(d, t_id)) {
4136 * as a perf optimization, we can map struct/union
4137 * that's part of type graph we just verified for
4138 * equivalence. We can do that for struct/union that has
4139 * canonical representative only, though.
4141 d->map[t_id] = c_id;
4147 * Deduplicate struct/union types.
4149 * For each struct/union type its type signature hash is calculated, taking
4150 * into account type's name, size, number, order and names of fields, but
4151 * ignoring type ID's referenced from fields, because they might not be deduped
4152 * completely until after reference types deduplication phase. This type hash
4153 * is used to iterate over all potential canonical types, sharing same hash.
4154 * For each canonical candidate we check whether type graphs that they form
4155 * (through referenced types in fields and so on) are equivalent using algorithm
4156 * implemented in `btf_dedup_is_equiv`. If such equivalence is found and
4157 * BTF_KIND_FWD resolution is allowed, then hypothetical mapping
4158 * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence
4159 * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to
4160 * potentially map other structs/unions to their canonical representatives,
4161 * if such relationship hasn't yet been established. This speeds up algorithm
4162 * by eliminating some of the duplicate work.
4164 * If no matching canonical representative was found, struct/union is marked
4165 * as canonical for itself and is added into btf_dedup->dedup_table hash map
4166 * for further look ups.
4168 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id)
4170 struct btf_type *cand_type, *t;
4171 struct hashmap_entry *hash_entry;
4172 /* if we don't find equivalent type, then we are canonical */
4173 __u32 new_id = type_id;
4177 /* already deduped or is in process of deduping (loop detected) */
4178 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4181 t = btf_type_by_id(d->btf, type_id);
4184 if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION)
4187 h = btf_hash_struct(t);
4188 for_each_dedup_cand(d, hash_entry, h) {
4189 __u32 cand_id = (__u32)(long)hash_entry->value;
4193 * Even though btf_dedup_is_equiv() checks for
4194 * btf_shallow_equal_struct() internally when checking two
4195 * structs (unions) for equivalence, we need to guard here
4196 * from picking matching FWD type as a dedup candidate.
4197 * This can happen due to hash collision. In such case just
4198 * relying on btf_dedup_is_equiv() would lead to potentially
4199 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because
4200 * FWD and compatible STRUCT/UNION are considered equivalent.
4202 cand_type = btf_type_by_id(d->btf, cand_id);
4203 if (!btf_shallow_equal_struct(t, cand_type))
4206 btf_dedup_clear_hypot_map(d);
4207 eq = btf_dedup_is_equiv(d, type_id, cand_id);
4212 btf_dedup_merge_hypot_map(d);
4213 if (d->hypot_adjust_canon) /* not really equivalent */
4219 d->map[type_id] = new_id;
4220 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4226 static int btf_dedup_struct_types(struct btf_dedup *d)
4230 for (i = 0; i < d->btf->nr_types; i++) {
4231 err = btf_dedup_struct_type(d, d->btf->start_id + i);
4239 * Deduplicate reference type.
4241 * Once all primitive and struct/union types got deduplicated, we can easily
4242 * deduplicate all other (reference) BTF types. This is done in two steps:
4244 * 1. Resolve all referenced type IDs into their canonical type IDs. This
4245 * resolution can be done either immediately for primitive or struct/union types
4246 * (because they were deduped in previous two phases) or recursively for
4247 * reference types. Recursion will always terminate at either primitive or
4248 * struct/union type, at which point we can "unwind" chain of reference types
4249 * one by one. There is no danger of encountering cycles because in C type
4250 * system the only way to form type cycle is through struct/union, so any chain
4251 * of reference types, even those taking part in a type cycle, will inevitably
4252 * reach struct/union at some point.
4254 * 2. Once all referenced type IDs are resolved into canonical ones, BTF type
4255 * becomes "stable", in the sense that no further deduplication will cause
4256 * any changes to it. With that, it's now possible to calculate type's signature
4257 * hash (this time taking into account referenced type IDs) and loop over all
4258 * potential canonical representatives. If no match was found, current type
4259 * will become canonical representative of itself and will be added into
4260 * btf_dedup->dedup_table as another possible canonical representative.
4262 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id)
4264 struct hashmap_entry *hash_entry;
4265 __u32 new_id = type_id, cand_id;
4266 struct btf_type *t, *cand;
4267 /* if we don't find equivalent type, then we are representative type */
4271 if (d->map[type_id] == BTF_IN_PROGRESS_ID)
4273 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4274 return resolve_type_id(d, type_id);
4276 t = btf_type_by_id(d->btf, type_id);
4277 d->map[type_id] = BTF_IN_PROGRESS_ID;
4279 switch (btf_kind(t)) {
4280 case BTF_KIND_CONST:
4281 case BTF_KIND_VOLATILE:
4282 case BTF_KIND_RESTRICT:
4284 case BTF_KIND_TYPEDEF:
4286 ref_type_id = btf_dedup_ref_type(d, t->type);
4287 if (ref_type_id < 0)
4289 t->type = ref_type_id;
4291 h = btf_hash_common(t);
4292 for_each_dedup_cand(d, hash_entry, h) {
4293 cand_id = (__u32)(long)hash_entry->value;
4294 cand = btf_type_by_id(d->btf, cand_id);
4295 if (btf_equal_common(t, cand)) {
4302 case BTF_KIND_ARRAY: {
4303 struct btf_array *info = btf_array(t);
4305 ref_type_id = btf_dedup_ref_type(d, info->type);
4306 if (ref_type_id < 0)
4308 info->type = ref_type_id;
4310 ref_type_id = btf_dedup_ref_type(d, info->index_type);
4311 if (ref_type_id < 0)
4313 info->index_type = ref_type_id;
4315 h = btf_hash_array(t);
4316 for_each_dedup_cand(d, hash_entry, h) {
4317 cand_id = (__u32)(long)hash_entry->value;
4318 cand = btf_type_by_id(d->btf, cand_id);
4319 if (btf_equal_array(t, cand)) {
4327 case BTF_KIND_FUNC_PROTO: {
4328 struct btf_param *param;
4332 ref_type_id = btf_dedup_ref_type(d, t->type);
4333 if (ref_type_id < 0)
4335 t->type = ref_type_id;
4338 param = btf_params(t);
4339 for (i = 0; i < vlen; i++) {
4340 ref_type_id = btf_dedup_ref_type(d, param->type);
4341 if (ref_type_id < 0)
4343 param->type = ref_type_id;
4347 h = btf_hash_fnproto(t);
4348 for_each_dedup_cand(d, hash_entry, h) {
4349 cand_id = (__u32)(long)hash_entry->value;
4350 cand = btf_type_by_id(d->btf, cand_id);
4351 if (btf_equal_fnproto(t, cand)) {
4363 d->map[type_id] = new_id;
4364 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4370 static int btf_dedup_ref_types(struct btf_dedup *d)
4374 for (i = 0; i < d->btf->nr_types; i++) {
4375 err = btf_dedup_ref_type(d, d->btf->start_id + i);
4379 /* we won't need d->dedup_table anymore */
4380 hashmap__free(d->dedup_table);
4381 d->dedup_table = NULL;
4388 * After we established for each type its corresponding canonical representative
4389 * type, we now can eliminate types that are not canonical and leave only
4390 * canonical ones layed out sequentially in memory by copying them over
4391 * duplicates. During compaction btf_dedup->hypot_map array is reused to store
4392 * a map from original type ID to a new compacted type ID, which will be used
4393 * during next phase to "fix up" type IDs, referenced from struct/union and
4396 static int btf_dedup_compact_types(struct btf_dedup *d)
4399 __u32 next_type_id = d->btf->start_id;
4400 const struct btf_type *t;
4404 /* we are going to reuse hypot_map to store compaction remapping */
4405 d->hypot_map[0] = 0;
4406 /* base BTF types are not renumbered */
4407 for (id = 1; id < d->btf->start_id; id++)
4408 d->hypot_map[id] = id;
4409 for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++)
4410 d->hypot_map[id] = BTF_UNPROCESSED_ID;
4412 p = d->btf->types_data;
4414 for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++) {
4415 if (d->map[id] != id)
4418 t = btf__type_by_id(d->btf, id);
4419 len = btf_type_size(t);
4424 d->hypot_map[id] = next_type_id;
4425 d->btf->type_offs[next_type_id - d->btf->start_id] = p - d->btf->types_data;
4430 /* shrink struct btf's internal types index and update btf_header */
4431 d->btf->nr_types = next_type_id - d->btf->start_id;
4432 d->btf->type_offs_cap = d->btf->nr_types;
4433 d->btf->hdr->type_len = p - d->btf->types_data;
4434 new_offs = libbpf_reallocarray(d->btf->type_offs, d->btf->type_offs_cap,
4436 if (d->btf->type_offs_cap && !new_offs)
4438 d->btf->type_offs = new_offs;
4439 d->btf->hdr->str_off = d->btf->hdr->type_len;
4440 d->btf->raw_size = d->btf->hdr->hdr_len + d->btf->hdr->type_len + d->btf->hdr->str_len;
4445 * Figure out final (deduplicated and compacted) type ID for provided original
4446 * `type_id` by first resolving it into corresponding canonical type ID and
4447 * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map,
4448 * which is populated during compaction phase.
4450 static int btf_dedup_remap_type_id(struct btf_dedup *d, __u32 type_id)
4452 __u32 resolved_type_id, new_type_id;
4454 resolved_type_id = resolve_type_id(d, type_id);
4455 new_type_id = d->hypot_map[resolved_type_id];
4456 if (new_type_id > BTF_MAX_NR_TYPES)
4462 * Remap referenced type IDs into deduped type IDs.
4464 * After BTF types are deduplicated and compacted, their final type IDs may
4465 * differ from original ones. The map from original to a corresponding
4466 * deduped type ID is stored in btf_dedup->hypot_map and is populated during
4467 * compaction phase. During remapping phase we are rewriting all type IDs
4468 * referenced from any BTF type (e.g., struct fields, func proto args, etc) to
4469 * their final deduped type IDs.
4471 static int btf_dedup_remap_type(struct btf_dedup *d, __u32 type_id)
4473 struct btf_type *t = btf_type_by_id(d->btf, type_id);
4476 switch (btf_kind(t)) {
4482 case BTF_KIND_CONST:
4483 case BTF_KIND_VOLATILE:
4484 case BTF_KIND_RESTRICT:
4486 case BTF_KIND_TYPEDEF:
4489 r = btf_dedup_remap_type_id(d, t->type);
4495 case BTF_KIND_ARRAY: {
4496 struct btf_array *arr_info = btf_array(t);
4498 r = btf_dedup_remap_type_id(d, arr_info->type);
4502 r = btf_dedup_remap_type_id(d, arr_info->index_type);
4505 arr_info->index_type = r;
4509 case BTF_KIND_STRUCT:
4510 case BTF_KIND_UNION: {
4511 struct btf_member *member = btf_members(t);
4512 __u16 vlen = btf_vlen(t);
4514 for (i = 0; i < vlen; i++) {
4515 r = btf_dedup_remap_type_id(d, member->type);
4524 case BTF_KIND_FUNC_PROTO: {
4525 struct btf_param *param = btf_params(t);
4526 __u16 vlen = btf_vlen(t);
4528 r = btf_dedup_remap_type_id(d, t->type);
4533 for (i = 0; i < vlen; i++) {
4534 r = btf_dedup_remap_type_id(d, param->type);
4543 case BTF_KIND_DATASEC: {
4544 struct btf_var_secinfo *var = btf_var_secinfos(t);
4545 __u16 vlen = btf_vlen(t);
4547 for (i = 0; i < vlen; i++) {
4548 r = btf_dedup_remap_type_id(d, var->type);
4564 static int btf_dedup_remap_types(struct btf_dedup *d)
4568 for (i = 0; i < d->btf->nr_types; i++) {
4569 r = btf_dedup_remap_type(d, d->btf->start_id + i);
4577 * Probe few well-known locations for vmlinux kernel image and try to load BTF
4578 * data out of it to use for target BTF.
4580 struct btf *libbpf_find_kernel_btf(void)
4583 const char *path_fmt;
4586 /* try canonical vmlinux BTF through sysfs first */
4587 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
4588 /* fall back to trying to find vmlinux ELF on disk otherwise */
4589 { "/boot/vmlinux-%1$s" },
4590 { "/lib/modules/%1$s/vmlinux-%1$s" },
4591 { "/lib/modules/%1$s/build/vmlinux" },
4592 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
4593 { "/usr/lib/debug/boot/vmlinux-%1$s" },
4594 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
4595 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
4597 char path[PATH_MAX + 1];
4604 for (i = 0; i < ARRAY_SIZE(locations); i++) {
4605 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
4607 if (access(path, R_OK))
4610 if (locations[i].raw_btf)
4611 btf = btf__parse_raw(path);
4613 btf = btf__parse_elf(path, NULL);
4615 pr_debug("loading kernel BTF '%s': %ld\n",
4616 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
4623 pr_warn("failed to find valid kernel BTF\n");
4624 return ERR_PTR(-ESRCH);