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 */
87 size_t strs_data_cap; /* used size stored in hdr->str_len */
89 /* lookup index for each unique string in strings section */
90 struct hashmap *strs_hash;
91 /* whether strings are already deduplicated */
93 /* BTF object FD, if loaded into kernel */
96 /* Pointer size (in bytes) for a target architecture of this BTF */
100 static inline __u64 ptr_to_u64(const void *ptr)
102 return (__u64) (unsigned long) ptr;
105 /* Ensure given dynamically allocated memory region pointed to by *data* with
106 * capacity of *cap_cnt* elements each taking *elem_sz* bytes has enough
107 * memory to accomodate *add_cnt* new elements, assuming *cur_cnt* elements
108 * are already used. At most *max_cnt* elements can be ever allocated.
109 * If necessary, memory is reallocated and all existing data is copied over,
110 * new pointer to the memory region is stored at *data, new memory region
111 * capacity (in number of elements) is stored in *cap.
112 * On success, memory pointer to the beginning of unused memory is returned.
113 * On error, NULL is returned.
115 void *btf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
116 size_t cur_cnt, size_t max_cnt, size_t add_cnt)
121 if (cur_cnt + add_cnt <= *cap_cnt)
122 return *data + cur_cnt * elem_sz;
124 /* requested more than the set limit */
125 if (cur_cnt + add_cnt > max_cnt)
129 new_cnt += new_cnt / 4; /* expand by 25% */
130 if (new_cnt < 16) /* but at least 16 elements */
132 if (new_cnt > max_cnt) /* but not exceeding a set limit */
134 if (new_cnt < cur_cnt + add_cnt) /* also ensure we have enough memory */
135 new_cnt = cur_cnt + add_cnt;
137 new_data = libbpf_reallocarray(*data, new_cnt, elem_sz);
141 /* zero out newly allocated portion of memory */
142 memset(new_data + (*cap_cnt) * elem_sz, 0, (new_cnt - *cap_cnt) * elem_sz);
146 return new_data + cur_cnt * elem_sz;
149 /* Ensure given dynamically allocated memory region has enough allocated space
150 * to accommodate *need_cnt* elements of size *elem_sz* bytes each
152 int btf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt)
156 if (need_cnt <= *cap_cnt)
159 p = btf_add_mem(data, cap_cnt, elem_sz, *cap_cnt, SIZE_MAX, need_cnt - *cap_cnt);
166 static int btf_add_type_idx_entry(struct btf *btf, __u32 type_off)
170 p = btf_add_mem((void **)&btf->type_offs, &btf->type_offs_cap, sizeof(__u32),
171 btf->nr_types + 1, BTF_MAX_NR_TYPES, 1);
179 static void btf_bswap_hdr(struct btf_header *h)
181 h->magic = bswap_16(h->magic);
182 h->hdr_len = bswap_32(h->hdr_len);
183 h->type_off = bswap_32(h->type_off);
184 h->type_len = bswap_32(h->type_len);
185 h->str_off = bswap_32(h->str_off);
186 h->str_len = bswap_32(h->str_len);
189 static int btf_parse_hdr(struct btf *btf)
191 struct btf_header *hdr = btf->hdr;
194 if (btf->raw_size < sizeof(struct btf_header)) {
195 pr_debug("BTF header not found\n");
199 if (hdr->magic == bswap_16(BTF_MAGIC)) {
200 btf->swapped_endian = true;
201 if (bswap_32(hdr->hdr_len) != sizeof(struct btf_header)) {
202 pr_warn("Can't load BTF with non-native endianness due to unsupported header length %u\n",
203 bswap_32(hdr->hdr_len));
207 } else if (hdr->magic != BTF_MAGIC) {
208 pr_debug("Invalid BTF magic:%x\n", hdr->magic);
212 meta_left = btf->raw_size - sizeof(*hdr);
214 pr_debug("BTF has no data\n");
218 if (meta_left < hdr->type_off) {
219 pr_debug("Invalid BTF type section offset:%u\n", hdr->type_off);
223 if (meta_left < hdr->str_off) {
224 pr_debug("Invalid BTF string section offset:%u\n", hdr->str_off);
228 if (hdr->type_off >= hdr->str_off) {
229 pr_debug("BTF type section offset >= string section offset. No type?\n");
233 if (hdr->type_off & 0x02) {
234 pr_debug("BTF type section is not aligned to 4 bytes\n");
241 static int btf_parse_str_sec(struct btf *btf)
243 const struct btf_header *hdr = btf->hdr;
244 const char *start = btf->strs_data;
245 const char *end = start + btf->hdr->str_len;
247 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_STR_OFFSET ||
248 start[0] || end[-1]) {
249 pr_debug("Invalid BTF string section\n");
256 static int btf_type_size(const struct btf_type *t)
258 const int base_size = sizeof(struct btf_type);
259 __u16 vlen = btf_vlen(t);
261 switch (btf_kind(t)) {
264 case BTF_KIND_VOLATILE:
265 case BTF_KIND_RESTRICT:
267 case BTF_KIND_TYPEDEF:
271 return base_size + sizeof(__u32);
273 return base_size + vlen * sizeof(struct btf_enum);
275 return base_size + sizeof(struct btf_array);
276 case BTF_KIND_STRUCT:
278 return base_size + vlen * sizeof(struct btf_member);
279 case BTF_KIND_FUNC_PROTO:
280 return base_size + vlen * sizeof(struct btf_param);
282 return base_size + sizeof(struct btf_var);
283 case BTF_KIND_DATASEC:
284 return base_size + vlen * sizeof(struct btf_var_secinfo);
286 pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
291 static void btf_bswap_type_base(struct btf_type *t)
293 t->name_off = bswap_32(t->name_off);
294 t->info = bswap_32(t->info);
295 t->type = bswap_32(t->type);
298 static int btf_bswap_type_rest(struct btf_type *t)
300 struct btf_var_secinfo *v;
301 struct btf_member *m;
305 __u16 vlen = btf_vlen(t);
308 switch (btf_kind(t)) {
311 case BTF_KIND_VOLATILE:
312 case BTF_KIND_RESTRICT:
314 case BTF_KIND_TYPEDEF:
318 *(__u32 *)(t + 1) = bswap_32(*(__u32 *)(t + 1));
321 for (i = 0, e = btf_enum(t); i < vlen; i++, e++) {
322 e->name_off = bswap_32(e->name_off);
323 e->val = bswap_32(e->val);
328 a->type = bswap_32(a->type);
329 a->index_type = bswap_32(a->index_type);
330 a->nelems = bswap_32(a->nelems);
332 case BTF_KIND_STRUCT:
334 for (i = 0, m = btf_members(t); i < vlen; i++, m++) {
335 m->name_off = bswap_32(m->name_off);
336 m->type = bswap_32(m->type);
337 m->offset = bswap_32(m->offset);
340 case BTF_KIND_FUNC_PROTO:
341 for (i = 0, p = btf_params(t); i < vlen; i++, p++) {
342 p->name_off = bswap_32(p->name_off);
343 p->type = bswap_32(p->type);
347 btf_var(t)->linkage = bswap_32(btf_var(t)->linkage);
349 case BTF_KIND_DATASEC:
350 for (i = 0, v = btf_var_secinfos(t); i < vlen; i++, v++) {
351 v->type = bswap_32(v->type);
352 v->offset = bswap_32(v->offset);
353 v->size = bswap_32(v->size);
357 pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
362 static int btf_parse_type_sec(struct btf *btf)
364 struct btf_header *hdr = btf->hdr;
365 void *next_type = btf->types_data;
366 void *end_type = next_type + hdr->type_len;
367 int err, i = 0, type_size;
369 /* VOID (type_id == 0) is specially handled by btf__get_type_by_id(),
370 * so ensure we can never properly use its offset from index by
371 * setting it to a large value
373 err = btf_add_type_idx_entry(btf, UINT_MAX);
377 while (next_type + sizeof(struct btf_type) <= end_type) {
380 if (btf->swapped_endian)
381 btf_bswap_type_base(next_type);
383 type_size = btf_type_size(next_type);
386 if (next_type + type_size > end_type) {
387 pr_warn("BTF type [%d] is malformed\n", i);
391 if (btf->swapped_endian && btf_bswap_type_rest(next_type))
394 err = btf_add_type_idx_entry(btf, next_type - btf->types_data);
398 next_type += type_size;
402 if (next_type != end_type) {
403 pr_warn("BTF types data is malformed\n");
410 __u32 btf__get_nr_types(const struct btf *btf)
412 return btf->nr_types;
415 /* internal helper returning non-const pointer to a type */
416 static struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id)
421 return btf->types_data + btf->type_offs[type_id];
424 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id)
426 if (type_id > btf->nr_types)
428 return btf_type_by_id((struct btf *)btf, type_id);
431 static int determine_ptr_size(const struct btf *btf)
433 const struct btf_type *t;
437 for (i = 1; i <= btf->nr_types; i++) {
438 t = btf__type_by_id(btf, i);
442 name = btf__name_by_offset(btf, t->name_off);
446 if (strcmp(name, "long int") == 0 ||
447 strcmp(name, "long unsigned int") == 0) {
448 if (t->size != 4 && t->size != 8)
457 static size_t btf_ptr_sz(const struct btf *btf)
460 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
461 return btf->ptr_sz < 0 ? sizeof(void *) : btf->ptr_sz;
464 /* Return pointer size this BTF instance assumes. The size is heuristically
465 * determined by looking for 'long' or 'unsigned long' integer type and
466 * recording its size in bytes. If BTF type information doesn't have any such
467 * type, this function returns 0. In the latter case, native architecture's
468 * pointer size is assumed, so will be either 4 or 8, depending on
469 * architecture that libbpf was compiled for. It's possible to override
470 * guessed value by using btf__set_pointer_size() API.
472 size_t btf__pointer_size(const struct btf *btf)
475 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
478 /* not enough BTF type info to guess */
484 /* Override or set pointer size in bytes. Only values of 4 and 8 are
487 int btf__set_pointer_size(struct btf *btf, size_t ptr_sz)
489 if (ptr_sz != 4 && ptr_sz != 8)
491 btf->ptr_sz = ptr_sz;
495 static bool is_host_big_endian(void)
497 #if __BYTE_ORDER == __LITTLE_ENDIAN
499 #elif __BYTE_ORDER == __BIG_ENDIAN
502 # error "Unrecognized __BYTE_ORDER__"
506 enum btf_endianness btf__endianness(const struct btf *btf)
508 if (is_host_big_endian())
509 return btf->swapped_endian ? BTF_LITTLE_ENDIAN : BTF_BIG_ENDIAN;
511 return btf->swapped_endian ? BTF_BIG_ENDIAN : BTF_LITTLE_ENDIAN;
514 int btf__set_endianness(struct btf *btf, enum btf_endianness endian)
516 if (endian != BTF_LITTLE_ENDIAN && endian != BTF_BIG_ENDIAN)
519 btf->swapped_endian = is_host_big_endian() != (endian == BTF_BIG_ENDIAN);
520 if (!btf->swapped_endian) {
521 free(btf->raw_data_swapped);
522 btf->raw_data_swapped = NULL;
527 static bool btf_type_is_void(const struct btf_type *t)
529 return t == &btf_void || btf_is_fwd(t);
532 static bool btf_type_is_void_or_null(const struct btf_type *t)
534 return !t || btf_type_is_void(t);
537 #define MAX_RESOLVE_DEPTH 32
539 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id)
541 const struct btf_array *array;
542 const struct btf_type *t;
547 t = btf__type_by_id(btf, type_id);
548 for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t);
550 switch (btf_kind(t)) {
552 case BTF_KIND_STRUCT:
555 case BTF_KIND_DATASEC:
559 size = btf_ptr_sz(btf);
561 case BTF_KIND_TYPEDEF:
562 case BTF_KIND_VOLATILE:
564 case BTF_KIND_RESTRICT:
569 array = btf_array(t);
570 if (nelems && array->nelems > UINT32_MAX / nelems)
572 nelems *= array->nelems;
573 type_id = array->type;
579 t = btf__type_by_id(btf, type_id);
585 if (nelems && size > UINT32_MAX / nelems)
588 return nelems * size;
591 int btf__align_of(const struct btf *btf, __u32 id)
593 const struct btf_type *t = btf__type_by_id(btf, id);
594 __u16 kind = btf_kind(t);
599 return min(btf_ptr_sz(btf), (size_t)t->size);
601 return btf_ptr_sz(btf);
602 case BTF_KIND_TYPEDEF:
603 case BTF_KIND_VOLATILE:
605 case BTF_KIND_RESTRICT:
606 return btf__align_of(btf, t->type);
608 return btf__align_of(btf, btf_array(t)->type);
609 case BTF_KIND_STRUCT:
610 case BTF_KIND_UNION: {
611 const struct btf_member *m = btf_members(t);
612 __u16 vlen = btf_vlen(t);
613 int i, max_align = 1, align;
615 for (i = 0; i < vlen; i++, m++) {
616 align = btf__align_of(btf, m->type);
619 max_align = max(max_align, align);
625 pr_warn("unsupported BTF_KIND:%u\n", btf_kind(t));
630 int btf__resolve_type(const struct btf *btf, __u32 type_id)
632 const struct btf_type *t;
635 t = btf__type_by_id(btf, type_id);
636 while (depth < MAX_RESOLVE_DEPTH &&
637 !btf_type_is_void_or_null(t) &&
638 (btf_is_mod(t) || btf_is_typedef(t) || btf_is_var(t))) {
640 t = btf__type_by_id(btf, type_id);
644 if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t))
650 __s32 btf__find_by_name(const struct btf *btf, const char *type_name)
654 if (!strcmp(type_name, "void"))
657 for (i = 1; i <= btf->nr_types; i++) {
658 const struct btf_type *t = btf__type_by_id(btf, i);
659 const char *name = btf__name_by_offset(btf, t->name_off);
661 if (name && !strcmp(type_name, name))
668 __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,
673 if (kind == BTF_KIND_UNKN || !strcmp(type_name, "void"))
676 for (i = 1; i <= btf->nr_types; i++) {
677 const struct btf_type *t = btf__type_by_id(btf, i);
680 if (btf_kind(t) != kind)
682 name = btf__name_by_offset(btf, t->name_off);
683 if (name && !strcmp(type_name, name))
690 static bool btf_is_modifiable(const struct btf *btf)
692 return (void *)btf->hdr != btf->raw_data;
695 void btf__free(struct btf *btf)
697 if (IS_ERR_OR_NULL(btf))
703 if (btf_is_modifiable(btf)) {
704 /* if BTF was modified after loading, it will have a split
705 * in-memory representation for header, types, and strings
706 * sections, so we need to free all of them individually. It
707 * might still have a cached contiguous raw data present,
708 * which will be unconditionally freed below.
711 free(btf->types_data);
712 free(btf->strs_data);
715 free(btf->raw_data_swapped);
716 free(btf->type_offs);
720 struct btf *btf__new_empty(void)
724 btf = calloc(1, sizeof(*btf));
726 return ERR_PTR(-ENOMEM);
729 btf->ptr_sz = sizeof(void *);
730 btf->swapped_endian = false;
732 /* +1 for empty string at offset 0 */
733 btf->raw_size = sizeof(struct btf_header) + 1;
734 btf->raw_data = calloc(1, btf->raw_size);
735 if (!btf->raw_data) {
737 return ERR_PTR(-ENOMEM);
740 btf->hdr = btf->raw_data;
741 btf->hdr->hdr_len = sizeof(struct btf_header);
742 btf->hdr->magic = BTF_MAGIC;
743 btf->hdr->version = BTF_VERSION;
745 btf->types_data = btf->raw_data + btf->hdr->hdr_len;
746 btf->strs_data = btf->raw_data + btf->hdr->hdr_len;
747 btf->hdr->str_len = 1; /* empty string at offset 0 */
752 struct btf *btf__new(const void *data, __u32 size)
757 btf = calloc(1, sizeof(struct btf));
759 return ERR_PTR(-ENOMEM);
761 btf->raw_data = malloc(size);
762 if (!btf->raw_data) {
766 memcpy(btf->raw_data, data, size);
767 btf->raw_size = size;
769 btf->hdr = btf->raw_data;
770 err = btf_parse_hdr(btf);
774 btf->strs_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->str_off;
775 btf->types_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->type_off;
777 err = btf_parse_str_sec(btf);
778 err = err ?: btf_parse_type_sec(btf);
793 struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext)
795 Elf_Data *btf_data = NULL, *btf_ext_data = NULL;
796 int err = 0, fd = -1, idx = 0;
797 struct btf *btf = NULL;
802 if (elf_version(EV_CURRENT) == EV_NONE) {
803 pr_warn("failed to init libelf for %s\n", path);
804 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
807 fd = open(path, O_RDONLY);
810 pr_warn("failed to open %s: %s\n", path, strerror(errno));
814 err = -LIBBPF_ERRNO__FORMAT;
816 elf = elf_begin(fd, ELF_C_READ, NULL);
818 pr_warn("failed to open %s as ELF file\n", path);
821 if (!gelf_getehdr(elf, &ehdr)) {
822 pr_warn("failed to get EHDR from %s\n", path);
825 if (!elf_rawdata(elf_getscn(elf, ehdr.e_shstrndx), NULL)) {
826 pr_warn("failed to get e_shstrndx from %s\n", path);
830 while ((scn = elf_nextscn(elf, scn)) != NULL) {
835 if (gelf_getshdr(scn, &sh) != &sh) {
836 pr_warn("failed to get section(%d) header from %s\n",
840 name = elf_strptr(elf, ehdr.e_shstrndx, sh.sh_name);
842 pr_warn("failed to get section(%d) name from %s\n",
846 if (strcmp(name, BTF_ELF_SEC) == 0) {
847 btf_data = elf_getdata(scn, 0);
849 pr_warn("failed to get section(%d, %s) data from %s\n",
854 } else if (btf_ext && strcmp(name, BTF_EXT_ELF_SEC) == 0) {
855 btf_ext_data = elf_getdata(scn, 0);
857 pr_warn("failed to get section(%d, %s) data from %s\n",
871 btf = btf__new(btf_data->d_buf, btf_data->d_size);
875 switch (gelf_getclass(elf)) {
877 btf__set_pointer_size(btf, 4);
880 btf__set_pointer_size(btf, 8);
883 pr_warn("failed to get ELF class (bitness) for %s\n", path);
887 if (btf_ext && btf_ext_data) {
888 *btf_ext = btf_ext__new(btf_ext_data->d_buf,
889 btf_ext_data->d_size);
890 if (IS_ERR(*btf_ext))
892 } else if (btf_ext) {
903 * btf is always parsed before btf_ext, so no need to clean up
904 * btf_ext, if btf loading failed
908 if (btf_ext && IS_ERR(*btf_ext)) {
910 err = PTR_ERR(*btf_ext);
916 struct btf *btf__parse_raw(const char *path)
918 struct btf *btf = NULL;
925 f = fopen(path, "rb");
931 /* check BTF magic */
932 if (fread(&magic, 1, sizeof(magic), f) < sizeof(magic)) {
936 if (magic != BTF_MAGIC && magic != bswap_16(BTF_MAGIC)) {
937 /* definitely not a raw BTF */
943 if (fseek(f, 0, SEEK_END)) {
952 /* rewind to the start */
953 if (fseek(f, 0, SEEK_SET)) {
958 /* pre-alloc memory and read all of BTF data */
964 if (fread(data, 1, sz, f) < sz) {
969 /* finally parse BTF data */
970 btf = btf__new(data, sz);
976 return err ? ERR_PTR(err) : btf;
979 struct btf *btf__parse(const char *path, struct btf_ext **btf_ext)
986 btf = btf__parse_raw(path);
987 if (!IS_ERR(btf) || PTR_ERR(btf) != -EPROTO)
990 return btf__parse_elf(path, btf_ext);
993 static int compare_vsi_off(const void *_a, const void *_b)
995 const struct btf_var_secinfo *a = _a;
996 const struct btf_var_secinfo *b = _b;
998 return a->offset - b->offset;
1001 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
1004 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
1005 const char *name = btf__name_by_offset(btf, t->name_off);
1006 const struct btf_type *t_var;
1007 struct btf_var_secinfo *vsi;
1008 const struct btf_var *var;
1012 pr_debug("No name found in string section for DATASEC kind.\n");
1016 /* .extern datasec size and var offsets were set correctly during
1017 * extern collection step, so just skip straight to sorting variables
1022 ret = bpf_object__section_size(obj, name, &size);
1023 if (ret || !size || (t->size && t->size != size)) {
1024 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
1030 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
1031 t_var = btf__type_by_id(btf, vsi->type);
1032 var = btf_var(t_var);
1034 if (!btf_is_var(t_var)) {
1035 pr_debug("Non-VAR type seen in section %s\n", name);
1039 if (var->linkage == BTF_VAR_STATIC)
1042 name = btf__name_by_offset(btf, t_var->name_off);
1044 pr_debug("No name found in string section for VAR kind\n");
1048 ret = bpf_object__variable_offset(obj, name, &off);
1050 pr_debug("No offset found in symbol table for VAR %s\n",
1059 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
1063 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
1068 for (i = 1; i <= btf->nr_types; i++) {
1069 struct btf_type *t = btf_type_by_id(btf, i);
1071 /* Loader needs to fix up some of the things compiler
1072 * couldn't get its hands on while emitting BTF. This
1073 * is section size and global variable offset. We use
1074 * the info from the ELF itself for this purpose.
1076 if (btf_is_datasec(t)) {
1077 err = btf_fixup_datasec(obj, btf, t);
1086 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian);
1088 int btf__load(struct btf *btf)
1090 __u32 log_buf_size = 0, raw_size;
1091 char *log_buf = NULL;
1100 log_buf = malloc(log_buf_size);
1107 raw_data = btf_get_raw_data(btf, &raw_size, false);
1112 /* cache native raw data representation */
1113 btf->raw_size = raw_size;
1114 btf->raw_data = raw_data;
1116 btf->fd = bpf_load_btf(raw_data, raw_size, log_buf, log_buf_size, false);
1118 if (!log_buf || errno == ENOSPC) {
1119 log_buf_size = max((__u32)BPF_LOG_BUF_SIZE,
1126 pr_warn("Error loading BTF: %s(%d)\n", strerror(errno), errno);
1128 pr_warn("%s\n", log_buf);
1137 int btf__fd(const struct btf *btf)
1142 void btf__set_fd(struct btf *btf, int fd)
1147 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian)
1149 struct btf_header *hdr = btf->hdr;
1155 data = swap_endian ? btf->raw_data_swapped : btf->raw_data;
1157 *size = btf->raw_size;
1161 data_sz = hdr->hdr_len + hdr->type_len + hdr->str_len;
1162 data = calloc(1, data_sz);
1167 memcpy(p, hdr, hdr->hdr_len);
1172 memcpy(p, btf->types_data, hdr->type_len);
1174 for (i = 1; i <= btf->nr_types; i++) {
1175 t = p + btf->type_offs[i];
1176 /* btf_bswap_type_rest() relies on native t->info, so
1177 * we swap base type info after we swapped all the
1178 * additional information
1180 if (btf_bswap_type_rest(t))
1182 btf_bswap_type_base(t);
1187 memcpy(p, btf->strs_data, hdr->str_len);
1197 const void *btf__get_raw_data(const struct btf *btf_ro, __u32 *size)
1199 struct btf *btf = (struct btf *)btf_ro;
1203 data = btf_get_raw_data(btf, &data_sz, btf->swapped_endian);
1207 btf->raw_size = data_sz;
1208 if (btf->swapped_endian)
1209 btf->raw_data_swapped = data;
1211 btf->raw_data = data;
1216 const char *btf__str_by_offset(const struct btf *btf, __u32 offset)
1218 if (offset < btf->hdr->str_len)
1219 return btf->strs_data + offset;
1224 const char *btf__name_by_offset(const struct btf *btf, __u32 offset)
1226 return btf__str_by_offset(btf, offset);
1229 int btf__get_from_id(__u32 id, struct btf **btf)
1231 struct bpf_btf_info btf_info = { 0 };
1232 __u32 len = sizeof(btf_info);
1240 btf_fd = bpf_btf_get_fd_by_id(id);
1244 /* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so
1245 * let's start with a sane default - 4KiB here - and resize it only if
1246 * bpf_obj_get_info_by_fd() needs a bigger buffer.
1248 btf_info.btf_size = 4096;
1249 last_size = btf_info.btf_size;
1250 ptr = malloc(last_size);
1256 memset(ptr, 0, last_size);
1257 btf_info.btf = ptr_to_u64(ptr);
1258 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1260 if (!err && btf_info.btf_size > last_size) {
1263 last_size = btf_info.btf_size;
1264 temp_ptr = realloc(ptr, last_size);
1270 memset(ptr, 0, last_size);
1271 btf_info.btf = ptr_to_u64(ptr);
1272 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1275 if (err || btf_info.btf_size > last_size) {
1280 *btf = btf__new((__u8 *)(long)btf_info.btf, btf_info.btf_size);
1282 err = PTR_ERR(*btf);
1293 int btf__get_map_kv_tids(const struct btf *btf, const char *map_name,
1294 __u32 expected_key_size, __u32 expected_value_size,
1295 __u32 *key_type_id, __u32 *value_type_id)
1297 const struct btf_type *container_type;
1298 const struct btf_member *key, *value;
1299 const size_t max_name = 256;
1300 char container_name[max_name];
1301 __s64 key_size, value_size;
1304 if (snprintf(container_name, max_name, "____btf_map_%s", map_name) ==
1306 pr_warn("map:%s length of '____btf_map_%s' is too long\n",
1307 map_name, map_name);
1311 container_id = btf__find_by_name(btf, container_name);
1312 if (container_id < 0) {
1313 pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n",
1314 map_name, container_name);
1315 return container_id;
1318 container_type = btf__type_by_id(btf, container_id);
1319 if (!container_type) {
1320 pr_warn("map:%s cannot find BTF type for container_id:%u\n",
1321 map_name, container_id);
1325 if (!btf_is_struct(container_type) || btf_vlen(container_type) < 2) {
1326 pr_warn("map:%s container_name:%s is an invalid container struct\n",
1327 map_name, container_name);
1331 key = btf_members(container_type);
1334 key_size = btf__resolve_size(btf, key->type);
1336 pr_warn("map:%s invalid BTF key_type_size\n", map_name);
1340 if (expected_key_size != key_size) {
1341 pr_warn("map:%s btf_key_type_size:%u != map_def_key_size:%u\n",
1342 map_name, (__u32)key_size, expected_key_size);
1346 value_size = btf__resolve_size(btf, value->type);
1347 if (value_size < 0) {
1348 pr_warn("map:%s invalid BTF value_type_size\n", map_name);
1352 if (expected_value_size != value_size) {
1353 pr_warn("map:%s btf_value_type_size:%u != map_def_value_size:%u\n",
1354 map_name, (__u32)value_size, expected_value_size);
1358 *key_type_id = key->type;
1359 *value_type_id = value->type;
1364 static size_t strs_hash_fn(const void *key, void *ctx)
1366 struct btf *btf = ctx;
1367 const char *str = btf->strs_data + (long)key;
1369 return str_hash(str);
1372 static bool strs_hash_equal_fn(const void *key1, const void *key2, void *ctx)
1374 struct btf *btf = ctx;
1375 const char *str1 = btf->strs_data + (long)key1;
1376 const char *str2 = btf->strs_data + (long)key2;
1378 return strcmp(str1, str2) == 0;
1381 static void btf_invalidate_raw_data(struct btf *btf)
1383 if (btf->raw_data) {
1384 free(btf->raw_data);
1385 btf->raw_data = NULL;
1387 if (btf->raw_data_swapped) {
1388 free(btf->raw_data_swapped);
1389 btf->raw_data_swapped = NULL;
1393 /* Ensure BTF is ready to be modified (by splitting into a three memory
1394 * regions for header, types, and strings). Also invalidate cached
1397 static int btf_ensure_modifiable(struct btf *btf)
1399 void *hdr, *types, *strs, *strs_end, *s;
1400 struct hashmap *hash = NULL;
1404 if (btf_is_modifiable(btf)) {
1405 /* any BTF modification invalidates raw_data */
1406 btf_invalidate_raw_data(btf);
1410 /* split raw data into three memory regions */
1411 hdr = malloc(btf->hdr->hdr_len);
1412 types = malloc(btf->hdr->type_len);
1413 strs = malloc(btf->hdr->str_len);
1414 if (!hdr || !types || !strs)
1417 memcpy(hdr, btf->hdr, btf->hdr->hdr_len);
1418 memcpy(types, btf->types_data, btf->hdr->type_len);
1419 memcpy(strs, btf->strs_data, btf->hdr->str_len);
1421 /* build lookup index for all strings */
1422 hash = hashmap__new(strs_hash_fn, strs_hash_equal_fn, btf);
1424 err = PTR_ERR(hash);
1429 strs_end = strs + btf->hdr->str_len;
1430 for (off = 0, s = strs; s < strs_end; off += strlen(s) + 1, s = strs + off) {
1431 /* hashmap__add() returns EEXIST if string with the same
1432 * content already is in the hash map
1434 err = hashmap__add(hash, (void *)off, (void *)off);
1436 continue; /* duplicate */
1441 /* only when everything was successful, update internal state */
1443 btf->types_data = types;
1444 btf->types_data_cap = btf->hdr->type_len;
1445 btf->strs_data = strs;
1446 btf->strs_data_cap = btf->hdr->str_len;
1447 btf->strs_hash = hash;
1448 /* if BTF was created from scratch, all strings are guaranteed to be
1449 * unique and deduplicated
1451 btf->strs_deduped = btf->hdr->str_len <= 1;
1453 /* invalidate raw_data representation */
1454 btf_invalidate_raw_data(btf);
1459 hashmap__free(hash);
1466 static void *btf_add_str_mem(struct btf *btf, size_t add_sz)
1468 return btf_add_mem(&btf->strs_data, &btf->strs_data_cap, 1,
1469 btf->hdr->str_len, BTF_MAX_STR_OFFSET, add_sz);
1472 /* Find an offset in BTF string section that corresponds to a given string *s*.
1474 * - >0 offset into string section, if string is found;
1475 * - -ENOENT, if string is not in the string section;
1476 * - <0, on any other error.
1478 int btf__find_str(struct btf *btf, const char *s)
1480 long old_off, new_off, len;
1483 /* BTF needs to be in a modifiable state to build string lookup index */
1484 if (btf_ensure_modifiable(btf))
1487 /* see btf__add_str() for why we do this */
1488 len = strlen(s) + 1;
1489 p = btf_add_str_mem(btf, len);
1493 new_off = btf->hdr->str_len;
1496 if (hashmap__find(btf->strs_hash, (void *)new_off, (void **)&old_off))
1502 /* Add a string s to the BTF string section.
1504 * - > 0 offset into string section, on success;
1507 int btf__add_str(struct btf *btf, const char *s)
1509 long old_off, new_off, len;
1513 if (btf_ensure_modifiable(btf))
1516 /* Hashmap keys are always offsets within btf->strs_data, so to even
1517 * look up some string from the "outside", we need to first append it
1518 * at the end, so that it can be addressed with an offset. Luckily,
1519 * until btf->hdr->str_len is incremented, that string is just a piece
1520 * of garbage for the rest of BTF code, so no harm, no foul. On the
1521 * other hand, if the string is unique, it's already appended and
1522 * ready to be used, only a simple btf->hdr->str_len increment away.
1524 len = strlen(s) + 1;
1525 p = btf_add_str_mem(btf, len);
1529 new_off = btf->hdr->str_len;
1532 /* Now attempt to add the string, but only if the string with the same
1533 * contents doesn't exist already (HASHMAP_ADD strategy). If such
1534 * string exists, we'll get its offset in old_off (that's old_key).
1536 err = hashmap__insert(btf->strs_hash, (void *)new_off, (void *)new_off,
1537 HASHMAP_ADD, (const void **)&old_off, NULL);
1539 return old_off; /* duplicated string, return existing offset */
1543 btf->hdr->str_len += len; /* new unique string, adjust data length */
1547 static void *btf_add_type_mem(struct btf *btf, size_t add_sz)
1549 return btf_add_mem(&btf->types_data, &btf->types_data_cap, 1,
1550 btf->hdr->type_len, UINT_MAX, add_sz);
1553 static __u32 btf_type_info(int kind, int vlen, int kflag)
1555 return (kflag << 31) | (kind << 24) | vlen;
1558 static void btf_type_inc_vlen(struct btf_type *t)
1560 t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, btf_kflag(t));
1564 * Append new BTF_KIND_INT type with:
1565 * - *name* - non-empty, non-NULL type name;
1566 * - *sz* - power-of-2 (1, 2, 4, ..) size of the type, in bytes;
1567 * - encoding is a combination of BTF_INT_SIGNED, BTF_INT_CHAR, BTF_INT_BOOL.
1569 * - >0, type ID of newly added BTF type;
1572 int btf__add_int(struct btf *btf, const char *name, size_t byte_sz, int encoding)
1575 int sz, err, name_off;
1577 /* non-empty name */
1578 if (!name || !name[0])
1580 /* byte_sz must be power of 2 */
1581 if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 16)
1583 if (encoding & ~(BTF_INT_SIGNED | BTF_INT_CHAR | BTF_INT_BOOL))
1586 /* deconstruct BTF, if necessary, and invalidate raw_data */
1587 if (btf_ensure_modifiable(btf))
1590 sz = sizeof(struct btf_type) + sizeof(int);
1591 t = btf_add_type_mem(btf, sz);
1595 /* if something goes wrong later, we might end up with an extra string,
1596 * but that shouldn't be a problem, because BTF can't be constructed
1597 * completely anyway and will most probably be just discarded
1599 name_off = btf__add_str(btf, name);
1603 t->name_off = name_off;
1604 t->info = btf_type_info(BTF_KIND_INT, 0, 0);
1606 /* set INT info, we don't allow setting legacy bit offset/size */
1607 *(__u32 *)(t + 1) = (encoding << 24) | (byte_sz * 8);
1609 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1613 btf->hdr->type_len += sz;
1614 btf->hdr->str_off += sz;
1616 return btf->nr_types;
1619 /* it's completely legal to append BTF types with type IDs pointing forward to
1620 * types that haven't been appended yet, so we only make sure that id looks
1621 * sane, we can't guarantee that ID will always be valid
1623 static int validate_type_id(int id)
1625 if (id < 0 || id > BTF_MAX_NR_TYPES)
1630 /* generic append function for PTR, TYPEDEF, CONST/VOLATILE/RESTRICT */
1631 static int btf_add_ref_kind(struct btf *btf, int kind, const char *name, int ref_type_id)
1634 int sz, name_off = 0, err;
1636 if (validate_type_id(ref_type_id))
1639 if (btf_ensure_modifiable(btf))
1642 sz = sizeof(struct btf_type);
1643 t = btf_add_type_mem(btf, sz);
1647 if (name && name[0]) {
1648 name_off = btf__add_str(btf, name);
1653 t->name_off = name_off;
1654 t->info = btf_type_info(kind, 0, 0);
1655 t->type = ref_type_id;
1657 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1661 btf->hdr->type_len += sz;
1662 btf->hdr->str_off += sz;
1664 return btf->nr_types;
1668 * Append new BTF_KIND_PTR type with:
1669 * - *ref_type_id* - referenced type ID, it might not exist yet;
1671 * - >0, type ID of newly added BTF type;
1674 int btf__add_ptr(struct btf *btf, int ref_type_id)
1676 return btf_add_ref_kind(btf, BTF_KIND_PTR, NULL, ref_type_id);
1680 * Append new BTF_KIND_ARRAY type with:
1681 * - *index_type_id* - type ID of the type describing array index;
1682 * - *elem_type_id* - type ID of the type describing array element;
1683 * - *nr_elems* - the size of the array;
1685 * - >0, type ID of newly added BTF type;
1688 int btf__add_array(struct btf *btf, int index_type_id, int elem_type_id, __u32 nr_elems)
1691 struct btf_array *a;
1694 if (validate_type_id(index_type_id) || validate_type_id(elem_type_id))
1697 if (btf_ensure_modifiable(btf))
1700 sz = sizeof(struct btf_type) + sizeof(struct btf_array);
1701 t = btf_add_type_mem(btf, sz);
1706 t->info = btf_type_info(BTF_KIND_ARRAY, 0, 0);
1710 a->type = elem_type_id;
1711 a->index_type = index_type_id;
1712 a->nelems = nr_elems;
1714 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1718 btf->hdr->type_len += sz;
1719 btf->hdr->str_off += sz;
1721 return btf->nr_types;
1724 /* generic STRUCT/UNION append function */
1725 static int btf_add_composite(struct btf *btf, int kind, const char *name, __u32 bytes_sz)
1728 int sz, err, name_off = 0;
1730 if (btf_ensure_modifiable(btf))
1733 sz = sizeof(struct btf_type);
1734 t = btf_add_type_mem(btf, sz);
1738 if (name && name[0]) {
1739 name_off = btf__add_str(btf, name);
1744 /* start out with vlen=0 and no kflag; this will be adjusted when
1745 * adding each member
1747 t->name_off = name_off;
1748 t->info = btf_type_info(kind, 0, 0);
1751 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1755 btf->hdr->type_len += sz;
1756 btf->hdr->str_off += sz;
1758 return btf->nr_types;
1762 * Append new BTF_KIND_STRUCT type with:
1763 * - *name* - name of the struct, can be NULL or empty for anonymous structs;
1764 * - *byte_sz* - size of the struct, in bytes;
1766 * Struct initially has no fields in it. Fields can be added by
1767 * btf__add_field() right after btf__add_struct() succeeds.
1770 * - >0, type ID of newly added BTF type;
1773 int btf__add_struct(struct btf *btf, const char *name, __u32 byte_sz)
1775 return btf_add_composite(btf, BTF_KIND_STRUCT, name, byte_sz);
1779 * Append new BTF_KIND_UNION type with:
1780 * - *name* - name of the union, can be NULL or empty for anonymous union;
1781 * - *byte_sz* - size of the union, in bytes;
1783 * Union initially has no fields in it. Fields can be added by
1784 * btf__add_field() right after btf__add_union() succeeds. All fields
1785 * should have *bit_offset* of 0.
1788 * - >0, type ID of newly added BTF type;
1791 int btf__add_union(struct btf *btf, const char *name, __u32 byte_sz)
1793 return btf_add_composite(btf, BTF_KIND_UNION, name, byte_sz);
1797 * Append new field for the current STRUCT/UNION type with:
1798 * - *name* - name of the field, can be NULL or empty for anonymous field;
1799 * - *type_id* - type ID for the type describing field type;
1800 * - *bit_offset* - bit offset of the start of the field within struct/union;
1801 * - *bit_size* - bit size of a bitfield, 0 for non-bitfield fields;
1806 int btf__add_field(struct btf *btf, const char *name, int type_id,
1807 __u32 bit_offset, __u32 bit_size)
1810 struct btf_member *m;
1812 int sz, name_off = 0;
1814 /* last type should be union/struct */
1815 if (btf->nr_types == 0)
1817 t = btf_type_by_id(btf, btf->nr_types);
1818 if (!btf_is_composite(t))
1821 if (validate_type_id(type_id))
1823 /* best-effort bit field offset/size enforcement */
1824 is_bitfield = bit_size || (bit_offset % 8 != 0);
1825 if (is_bitfield && (bit_size == 0 || bit_size > 255 || bit_offset > 0xffffff))
1828 /* only offset 0 is allowed for unions */
1829 if (btf_is_union(t) && bit_offset)
1832 /* decompose and invalidate raw data */
1833 if (btf_ensure_modifiable(btf))
1836 sz = sizeof(struct btf_member);
1837 m = btf_add_type_mem(btf, sz);
1841 if (name && name[0]) {
1842 name_off = btf__add_str(btf, name);
1847 m->name_off = name_off;
1849 m->offset = bit_offset | (bit_size << 24);
1851 /* btf_add_type_mem can invalidate t pointer */
1852 t = btf_type_by_id(btf, btf->nr_types);
1853 /* update parent type's vlen and kflag */
1854 t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, is_bitfield || btf_kflag(t));
1856 btf->hdr->type_len += sz;
1857 btf->hdr->str_off += sz;
1862 * Append new BTF_KIND_ENUM type with:
1863 * - *name* - name of the enum, can be NULL or empty for anonymous enums;
1864 * - *byte_sz* - size of the enum, in bytes.
1866 * Enum initially has no enum values in it (and corresponds to enum forward
1867 * declaration). Enumerator values can be added by btf__add_enum_value()
1868 * immediately after btf__add_enum() succeeds.
1871 * - >0, type ID of newly added BTF type;
1874 int btf__add_enum(struct btf *btf, const char *name, __u32 byte_sz)
1877 int sz, err, name_off = 0;
1879 /* byte_sz must be power of 2 */
1880 if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 8)
1883 if (btf_ensure_modifiable(btf))
1886 sz = sizeof(struct btf_type);
1887 t = btf_add_type_mem(btf, sz);
1891 if (name && name[0]) {
1892 name_off = btf__add_str(btf, name);
1897 /* start out with vlen=0; it will be adjusted when adding enum values */
1898 t->name_off = name_off;
1899 t->info = btf_type_info(BTF_KIND_ENUM, 0, 0);
1902 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1906 btf->hdr->type_len += sz;
1907 btf->hdr->str_off += sz;
1909 return btf->nr_types;
1913 * Append new enum value for the current ENUM type with:
1914 * - *name* - name of the enumerator value, can't be NULL or empty;
1915 * - *value* - integer value corresponding to enum value *name*;
1920 int btf__add_enum_value(struct btf *btf, const char *name, __s64 value)
1926 /* last type should be BTF_KIND_ENUM */
1927 if (btf->nr_types == 0)
1929 t = btf_type_by_id(btf, btf->nr_types);
1930 if (!btf_is_enum(t))
1933 /* non-empty name */
1934 if (!name || !name[0])
1936 if (value < INT_MIN || value > UINT_MAX)
1939 /* decompose and invalidate raw data */
1940 if (btf_ensure_modifiable(btf))
1943 sz = sizeof(struct btf_enum);
1944 v = btf_add_type_mem(btf, sz);
1948 name_off = btf__add_str(btf, name);
1952 v->name_off = name_off;
1955 /* update parent type's vlen */
1956 t = btf_type_by_id(btf, btf->nr_types);
1957 btf_type_inc_vlen(t);
1959 btf->hdr->type_len += sz;
1960 btf->hdr->str_off += sz;
1965 * Append new BTF_KIND_FWD type with:
1966 * - *name*, non-empty/non-NULL name;
1967 * - *fwd_kind*, kind of forward declaration, one of BTF_FWD_STRUCT,
1968 * BTF_FWD_UNION, or BTF_FWD_ENUM;
1970 * - >0, type ID of newly added BTF type;
1973 int btf__add_fwd(struct btf *btf, const char *name, enum btf_fwd_kind fwd_kind)
1975 if (!name || !name[0])
1979 case BTF_FWD_STRUCT:
1980 case BTF_FWD_UNION: {
1984 id = btf_add_ref_kind(btf, BTF_KIND_FWD, name, 0);
1987 t = btf_type_by_id(btf, id);
1988 t->info = btf_type_info(BTF_KIND_FWD, 0, fwd_kind == BTF_FWD_UNION);
1992 /* enum forward in BTF currently is just an enum with no enum
1993 * values; we also assume a standard 4-byte size for it
1995 return btf__add_enum(btf, name, sizeof(int));
2002 * Append new BTF_KING_TYPEDEF type with:
2003 * - *name*, non-empty/non-NULL name;
2004 * - *ref_type_id* - referenced type ID, it might not exist yet;
2006 * - >0, type ID of newly added BTF type;
2009 int btf__add_typedef(struct btf *btf, const char *name, int ref_type_id)
2011 if (!name || !name[0])
2014 return btf_add_ref_kind(btf, BTF_KIND_TYPEDEF, name, ref_type_id);
2018 * Append new BTF_KIND_VOLATILE type with:
2019 * - *ref_type_id* - referenced type ID, it might not exist yet;
2021 * - >0, type ID of newly added BTF type;
2024 int btf__add_volatile(struct btf *btf, int ref_type_id)
2026 return btf_add_ref_kind(btf, BTF_KIND_VOLATILE, NULL, ref_type_id);
2030 * Append new BTF_KIND_CONST type with:
2031 * - *ref_type_id* - referenced type ID, it might not exist yet;
2033 * - >0, type ID of newly added BTF type;
2036 int btf__add_const(struct btf *btf, int ref_type_id)
2038 return btf_add_ref_kind(btf, BTF_KIND_CONST, NULL, ref_type_id);
2042 * Append new BTF_KIND_RESTRICT type with:
2043 * - *ref_type_id* - referenced type ID, it might not exist yet;
2045 * - >0, type ID of newly added BTF type;
2048 int btf__add_restrict(struct btf *btf, int ref_type_id)
2050 return btf_add_ref_kind(btf, BTF_KIND_RESTRICT, NULL, ref_type_id);
2054 * Append new BTF_KIND_FUNC type with:
2055 * - *name*, non-empty/non-NULL name;
2056 * - *proto_type_id* - FUNC_PROTO's type ID, it might not exist yet;
2058 * - >0, type ID of newly added BTF type;
2061 int btf__add_func(struct btf *btf, const char *name,
2062 enum btf_func_linkage linkage, int proto_type_id)
2066 if (!name || !name[0])
2068 if (linkage != BTF_FUNC_STATIC && linkage != BTF_FUNC_GLOBAL &&
2069 linkage != BTF_FUNC_EXTERN)
2072 id = btf_add_ref_kind(btf, BTF_KIND_FUNC, name, proto_type_id);
2074 struct btf_type *t = btf_type_by_id(btf, id);
2076 t->info = btf_type_info(BTF_KIND_FUNC, linkage, 0);
2082 * Append new BTF_KIND_FUNC_PROTO with:
2083 * - *ret_type_id* - type ID for return result of a function.
2085 * Function prototype initially has no arguments, but they can be added by
2086 * btf__add_func_param() one by one, immediately after
2087 * btf__add_func_proto() succeeded.
2090 * - >0, type ID of newly added BTF type;
2093 int btf__add_func_proto(struct btf *btf, int ret_type_id)
2098 if (validate_type_id(ret_type_id))
2101 if (btf_ensure_modifiable(btf))
2104 sz = sizeof(struct btf_type);
2105 t = btf_add_type_mem(btf, sz);
2109 /* start out with vlen=0; this will be adjusted when adding enum
2110 * values, if necessary
2113 t->info = btf_type_info(BTF_KIND_FUNC_PROTO, 0, 0);
2114 t->type = ret_type_id;
2116 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
2120 btf->hdr->type_len += sz;
2121 btf->hdr->str_off += sz;
2123 return btf->nr_types;
2127 * Append new function parameter for current FUNC_PROTO type with:
2128 * - *name* - parameter name, can be NULL or empty;
2129 * - *type_id* - type ID describing the type of the parameter.
2134 int btf__add_func_param(struct btf *btf, const char *name, int type_id)
2137 struct btf_param *p;
2138 int sz, name_off = 0;
2140 if (validate_type_id(type_id))
2143 /* last type should be BTF_KIND_FUNC_PROTO */
2144 if (btf->nr_types == 0)
2146 t = btf_type_by_id(btf, btf->nr_types);
2147 if (!btf_is_func_proto(t))
2150 /* decompose and invalidate raw data */
2151 if (btf_ensure_modifiable(btf))
2154 sz = sizeof(struct btf_param);
2155 p = btf_add_type_mem(btf, sz);
2159 if (name && name[0]) {
2160 name_off = btf__add_str(btf, name);
2165 p->name_off = name_off;
2168 /* update parent type's vlen */
2169 t = btf_type_by_id(btf, btf->nr_types);
2170 btf_type_inc_vlen(t);
2172 btf->hdr->type_len += sz;
2173 btf->hdr->str_off += sz;
2178 * Append new BTF_KIND_VAR type with:
2179 * - *name* - non-empty/non-NULL name;
2180 * - *linkage* - variable linkage, one of BTF_VAR_STATIC,
2181 * BTF_VAR_GLOBAL_ALLOCATED, or BTF_VAR_GLOBAL_EXTERN;
2182 * - *type_id* - type ID of the type describing the type of the variable.
2184 * - >0, type ID of newly added BTF type;
2187 int btf__add_var(struct btf *btf, const char *name, int linkage, int type_id)
2191 int sz, err, name_off;
2193 /* non-empty name */
2194 if (!name || !name[0])
2196 if (linkage != BTF_VAR_STATIC && linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2197 linkage != BTF_VAR_GLOBAL_EXTERN)
2199 if (validate_type_id(type_id))
2202 /* deconstruct BTF, if necessary, and invalidate raw_data */
2203 if (btf_ensure_modifiable(btf))
2206 sz = sizeof(struct btf_type) + sizeof(struct btf_var);
2207 t = btf_add_type_mem(btf, sz);
2211 name_off = btf__add_str(btf, name);
2215 t->name_off = name_off;
2216 t->info = btf_type_info(BTF_KIND_VAR, 0, 0);
2220 v->linkage = linkage;
2222 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
2226 btf->hdr->type_len += sz;
2227 btf->hdr->str_off += sz;
2229 return btf->nr_types;
2233 * Append new BTF_KIND_DATASEC type with:
2234 * - *name* - non-empty/non-NULL name;
2235 * - *byte_sz* - data section size, in bytes.
2237 * Data section is initially empty. Variables info can be added with
2238 * btf__add_datasec_var_info() calls, after btf__add_datasec() succeeds.
2241 * - >0, type ID of newly added BTF type;
2244 int btf__add_datasec(struct btf *btf, const char *name, __u32 byte_sz)
2247 int sz, err, name_off;
2249 /* non-empty name */
2250 if (!name || !name[0])
2253 if (btf_ensure_modifiable(btf))
2256 sz = sizeof(struct btf_type);
2257 t = btf_add_type_mem(btf, sz);
2261 name_off = btf__add_str(btf, name);
2265 /* start with vlen=0, which will be update as var_secinfos are added */
2266 t->name_off = name_off;
2267 t->info = btf_type_info(BTF_KIND_DATASEC, 0, 0);
2270 err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
2274 btf->hdr->type_len += sz;
2275 btf->hdr->str_off += sz;
2277 return btf->nr_types;
2281 * Append new data section variable information entry for current DATASEC type:
2282 * - *var_type_id* - type ID, describing type of the variable;
2283 * - *offset* - variable offset within data section, in bytes;
2284 * - *byte_sz* - variable size, in bytes.
2290 int btf__add_datasec_var_info(struct btf *btf, int var_type_id, __u32 offset, __u32 byte_sz)
2293 struct btf_var_secinfo *v;
2296 /* last type should be BTF_KIND_DATASEC */
2297 if (btf->nr_types == 0)
2299 t = btf_type_by_id(btf, btf->nr_types);
2300 if (!btf_is_datasec(t))
2303 if (validate_type_id(var_type_id))
2306 /* decompose and invalidate raw data */
2307 if (btf_ensure_modifiable(btf))
2310 sz = sizeof(struct btf_var_secinfo);
2311 v = btf_add_type_mem(btf, sz);
2315 v->type = var_type_id;
2319 /* update parent type's vlen */
2320 t = btf_type_by_id(btf, btf->nr_types);
2321 btf_type_inc_vlen(t);
2323 btf->hdr->type_len += sz;
2324 btf->hdr->str_off += sz;
2328 struct btf_ext_sec_setup_param {
2332 struct btf_ext_info *ext_info;
2336 static int btf_ext_setup_info(struct btf_ext *btf_ext,
2337 struct btf_ext_sec_setup_param *ext_sec)
2339 const struct btf_ext_info_sec *sinfo;
2340 struct btf_ext_info *ext_info;
2341 __u32 info_left, record_size;
2342 /* The start of the info sec (including the __u32 record_size). */
2345 if (ext_sec->len == 0)
2348 if (ext_sec->off & 0x03) {
2349 pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n",
2354 info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off;
2355 info_left = ext_sec->len;
2357 if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) {
2358 pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n",
2359 ext_sec->desc, ext_sec->off, ext_sec->len);
2363 /* At least a record size */
2364 if (info_left < sizeof(__u32)) {
2365 pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc);
2369 /* The record size needs to meet the minimum standard */
2370 record_size = *(__u32 *)info;
2371 if (record_size < ext_sec->min_rec_size ||
2372 record_size & 0x03) {
2373 pr_debug("%s section in .BTF.ext has invalid record size %u\n",
2374 ext_sec->desc, record_size);
2378 sinfo = info + sizeof(__u32);
2379 info_left -= sizeof(__u32);
2381 /* If no records, return failure now so .BTF.ext won't be used. */
2383 pr_debug("%s section in .BTF.ext has no records", ext_sec->desc);
2388 unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec);
2389 __u64 total_record_size;
2392 if (info_left < sec_hdrlen) {
2393 pr_debug("%s section header is not found in .BTF.ext\n",
2398 num_records = sinfo->num_info;
2399 if (num_records == 0) {
2400 pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2405 total_record_size = sec_hdrlen +
2406 (__u64)num_records * record_size;
2407 if (info_left < total_record_size) {
2408 pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2413 info_left -= total_record_size;
2414 sinfo = (void *)sinfo + total_record_size;
2417 ext_info = ext_sec->ext_info;
2418 ext_info->len = ext_sec->len - sizeof(__u32);
2419 ext_info->rec_size = record_size;
2420 ext_info->info = info + sizeof(__u32);
2425 static int btf_ext_setup_func_info(struct btf_ext *btf_ext)
2427 struct btf_ext_sec_setup_param param = {
2428 .off = btf_ext->hdr->func_info_off,
2429 .len = btf_ext->hdr->func_info_len,
2430 .min_rec_size = sizeof(struct bpf_func_info_min),
2431 .ext_info = &btf_ext->func_info,
2435 return btf_ext_setup_info(btf_ext, ¶m);
2438 static int btf_ext_setup_line_info(struct btf_ext *btf_ext)
2440 struct btf_ext_sec_setup_param param = {
2441 .off = btf_ext->hdr->line_info_off,
2442 .len = btf_ext->hdr->line_info_len,
2443 .min_rec_size = sizeof(struct bpf_line_info_min),
2444 .ext_info = &btf_ext->line_info,
2445 .desc = "line_info",
2448 return btf_ext_setup_info(btf_ext, ¶m);
2451 static int btf_ext_setup_core_relos(struct btf_ext *btf_ext)
2453 struct btf_ext_sec_setup_param param = {
2454 .off = btf_ext->hdr->core_relo_off,
2455 .len = btf_ext->hdr->core_relo_len,
2456 .min_rec_size = sizeof(struct bpf_core_relo),
2457 .ext_info = &btf_ext->core_relo_info,
2458 .desc = "core_relo",
2461 return btf_ext_setup_info(btf_ext, ¶m);
2464 static int btf_ext_parse_hdr(__u8 *data, __u32 data_size)
2466 const struct btf_ext_header *hdr = (struct btf_ext_header *)data;
2468 if (data_size < offsetofend(struct btf_ext_header, hdr_len) ||
2469 data_size < hdr->hdr_len) {
2470 pr_debug("BTF.ext header not found");
2474 if (hdr->magic == bswap_16(BTF_MAGIC)) {
2475 pr_warn("BTF.ext in non-native endianness is not supported\n");
2477 } else if (hdr->magic != BTF_MAGIC) {
2478 pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic);
2482 if (hdr->version != BTF_VERSION) {
2483 pr_debug("Unsupported BTF.ext version:%u\n", hdr->version);
2488 pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags);
2492 if (data_size == hdr->hdr_len) {
2493 pr_debug("BTF.ext has no data\n");
2500 void btf_ext__free(struct btf_ext *btf_ext)
2502 if (IS_ERR_OR_NULL(btf_ext))
2504 free(btf_ext->data);
2508 struct btf_ext *btf_ext__new(__u8 *data, __u32 size)
2510 struct btf_ext *btf_ext;
2513 err = btf_ext_parse_hdr(data, size);
2515 return ERR_PTR(err);
2517 btf_ext = calloc(1, sizeof(struct btf_ext));
2519 return ERR_PTR(-ENOMEM);
2521 btf_ext->data_size = size;
2522 btf_ext->data = malloc(size);
2523 if (!btf_ext->data) {
2527 memcpy(btf_ext->data, data, size);
2529 if (btf_ext->hdr->hdr_len <
2530 offsetofend(struct btf_ext_header, line_info_len))
2532 err = btf_ext_setup_func_info(btf_ext);
2536 err = btf_ext_setup_line_info(btf_ext);
2540 if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len))
2542 err = btf_ext_setup_core_relos(btf_ext);
2548 btf_ext__free(btf_ext);
2549 return ERR_PTR(err);
2555 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size)
2557 *size = btf_ext->data_size;
2558 return btf_ext->data;
2561 static int btf_ext_reloc_info(const struct btf *btf,
2562 const struct btf_ext_info *ext_info,
2563 const char *sec_name, __u32 insns_cnt,
2564 void **info, __u32 *cnt)
2566 __u32 sec_hdrlen = sizeof(struct btf_ext_info_sec);
2567 __u32 i, record_size, existing_len, records_len;
2568 struct btf_ext_info_sec *sinfo;
2569 const char *info_sec_name;
2573 record_size = ext_info->rec_size;
2574 sinfo = ext_info->info;
2575 remain_len = ext_info->len;
2576 while (remain_len > 0) {
2577 records_len = sinfo->num_info * record_size;
2578 info_sec_name = btf__name_by_offset(btf, sinfo->sec_name_off);
2579 if (strcmp(info_sec_name, sec_name)) {
2580 remain_len -= sec_hdrlen + records_len;
2581 sinfo = (void *)sinfo + sec_hdrlen + records_len;
2585 existing_len = (*cnt) * record_size;
2586 data = realloc(*info, existing_len + records_len);
2590 memcpy(data + existing_len, sinfo->data, records_len);
2591 /* adjust insn_off only, the rest data will be passed
2594 for (i = 0; i < sinfo->num_info; i++) {
2597 insn_off = data + existing_len + (i * record_size);
2598 *insn_off = *insn_off / sizeof(struct bpf_insn) +
2602 *cnt += sinfo->num_info;
2609 int btf_ext__reloc_func_info(const struct btf *btf,
2610 const struct btf_ext *btf_ext,
2611 const char *sec_name, __u32 insns_cnt,
2612 void **func_info, __u32 *cnt)
2614 return btf_ext_reloc_info(btf, &btf_ext->func_info, sec_name,
2615 insns_cnt, func_info, cnt);
2618 int btf_ext__reloc_line_info(const struct btf *btf,
2619 const struct btf_ext *btf_ext,
2620 const char *sec_name, __u32 insns_cnt,
2621 void **line_info, __u32 *cnt)
2623 return btf_ext_reloc_info(btf, &btf_ext->line_info, sec_name,
2624 insns_cnt, line_info, cnt);
2627 __u32 btf_ext__func_info_rec_size(const struct btf_ext *btf_ext)
2629 return btf_ext->func_info.rec_size;
2632 __u32 btf_ext__line_info_rec_size(const struct btf_ext *btf_ext)
2634 return btf_ext->line_info.rec_size;
2639 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
2640 const struct btf_dedup_opts *opts);
2641 static void btf_dedup_free(struct btf_dedup *d);
2642 static int btf_dedup_strings(struct btf_dedup *d);
2643 static int btf_dedup_prim_types(struct btf_dedup *d);
2644 static int btf_dedup_struct_types(struct btf_dedup *d);
2645 static int btf_dedup_ref_types(struct btf_dedup *d);
2646 static int btf_dedup_compact_types(struct btf_dedup *d);
2647 static int btf_dedup_remap_types(struct btf_dedup *d);
2650 * Deduplicate BTF types and strings.
2652 * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF
2653 * section with all BTF type descriptors and string data. It overwrites that
2654 * memory in-place with deduplicated types and strings without any loss of
2655 * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section
2656 * is provided, all the strings referenced from .BTF.ext section are honored
2657 * and updated to point to the right offsets after deduplication.
2659 * If function returns with error, type/string data might be garbled and should
2662 * More verbose and detailed description of both problem btf_dedup is solving,
2663 * as well as solution could be found at:
2664 * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html
2666 * Problem description and justification
2667 * =====================================
2669 * BTF type information is typically emitted either as a result of conversion
2670 * from DWARF to BTF or directly by compiler. In both cases, each compilation
2671 * unit contains information about a subset of all the types that are used
2672 * in an application. These subsets are frequently overlapping and contain a lot
2673 * of duplicated information when later concatenated together into a single
2674 * binary. This algorithm ensures that each unique type is represented by single
2675 * BTF type descriptor, greatly reducing resulting size of BTF data.
2677 * Compilation unit isolation and subsequent duplication of data is not the only
2678 * problem. The same type hierarchy (e.g., struct and all the type that struct
2679 * references) in different compilation units can be represented in BTF to
2680 * various degrees of completeness (or, rather, incompleteness) due to
2681 * struct/union forward declarations.
2683 * Let's take a look at an example, that we'll use to better understand the
2684 * problem (and solution). Suppose we have two compilation units, each using
2685 * same `struct S`, but each of them having incomplete type information about
2714 * In case of CU #1, BTF data will know only that `struct B` exist (but no
2715 * more), but will know the complete type information about `struct A`. While
2716 * for CU #2, it will know full type information about `struct B`, but will
2717 * only know about forward declaration of `struct A` (in BTF terms, it will
2718 * have `BTF_KIND_FWD` type descriptor with name `B`).
2720 * This compilation unit isolation means that it's possible that there is no
2721 * single CU with complete type information describing structs `S`, `A`, and
2722 * `B`. Also, we might get tons of duplicated and redundant type information.
2724 * Additional complication we need to keep in mind comes from the fact that
2725 * types, in general, can form graphs containing cycles, not just DAGs.
2727 * While algorithm does deduplication, it also merges and resolves type
2728 * information (unless disabled throught `struct btf_opts`), whenever possible.
2729 * E.g., in the example above with two compilation units having partial type
2730 * information for structs `A` and `B`, the output of algorithm will emit
2731 * a single copy of each BTF type that describes structs `A`, `B`, and `S`
2732 * (as well as type information for `int` and pointers), as if they were defined
2733 * in a single compilation unit as:
2753 * Algorithm completes its work in 6 separate passes:
2755 * 1. Strings deduplication.
2756 * 2. Primitive types deduplication (int, enum, fwd).
2757 * 3. Struct/union types deduplication.
2758 * 4. Reference types deduplication (pointers, typedefs, arrays, funcs, func
2759 * protos, and const/volatile/restrict modifiers).
2760 * 5. Types compaction.
2761 * 6. Types remapping.
2763 * Algorithm determines canonical type descriptor, which is a single
2764 * representative type for each truly unique type. This canonical type is the
2765 * one that will go into final deduplicated BTF type information. For
2766 * struct/unions, it is also the type that algorithm will merge additional type
2767 * information into (while resolving FWDs), as it discovers it from data in
2768 * other CUs. Each input BTF type eventually gets either mapped to itself, if
2769 * that type is canonical, or to some other type, if that type is equivalent
2770 * and was chosen as canonical representative. This mapping is stored in
2771 * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that
2772 * FWD type got resolved to.
2774 * To facilitate fast discovery of canonical types, we also maintain canonical
2775 * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash
2776 * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types
2777 * that match that signature. With sufficiently good choice of type signature
2778 * hashing function, we can limit number of canonical types for each unique type
2779 * signature to a very small number, allowing to find canonical type for any
2780 * duplicated type very quickly.
2782 * Struct/union deduplication is the most critical part and algorithm for
2783 * deduplicating structs/unions is described in greater details in comments for
2784 * `btf_dedup_is_equiv` function.
2786 int btf__dedup(struct btf *btf, struct btf_ext *btf_ext,
2787 const struct btf_dedup_opts *opts)
2789 struct btf_dedup *d = btf_dedup_new(btf, btf_ext, opts);
2793 pr_debug("btf_dedup_new failed: %ld", PTR_ERR(d));
2797 if (btf_ensure_modifiable(btf))
2800 err = btf_dedup_strings(d);
2802 pr_debug("btf_dedup_strings failed:%d\n", err);
2805 err = btf_dedup_prim_types(d);
2807 pr_debug("btf_dedup_prim_types failed:%d\n", err);
2810 err = btf_dedup_struct_types(d);
2812 pr_debug("btf_dedup_struct_types failed:%d\n", err);
2815 err = btf_dedup_ref_types(d);
2817 pr_debug("btf_dedup_ref_types failed:%d\n", err);
2820 err = btf_dedup_compact_types(d);
2822 pr_debug("btf_dedup_compact_types failed:%d\n", err);
2825 err = btf_dedup_remap_types(d);
2827 pr_debug("btf_dedup_remap_types failed:%d\n", err);
2836 #define BTF_UNPROCESSED_ID ((__u32)-1)
2837 #define BTF_IN_PROGRESS_ID ((__u32)-2)
2840 /* .BTF section to be deduped in-place */
2843 * Optional .BTF.ext section. When provided, any strings referenced
2844 * from it will be taken into account when deduping strings
2846 struct btf_ext *btf_ext;
2848 * This is a map from any type's signature hash to a list of possible
2849 * canonical representative type candidates. Hash collisions are
2850 * ignored, so even types of various kinds can share same list of
2851 * candidates, which is fine because we rely on subsequent
2852 * btf_xxx_equal() checks to authoritatively verify type equality.
2854 struct hashmap *dedup_table;
2855 /* Canonical types map */
2857 /* Hypothetical mapping, used during type graph equivalence checks */
2862 /* Various option modifying behavior of algorithm */
2863 struct btf_dedup_opts opts;
2866 struct btf_str_ptr {
2872 struct btf_str_ptrs {
2873 struct btf_str_ptr *ptrs;
2879 static long hash_combine(long h, long value)
2881 return h * 31 + value;
2884 #define for_each_dedup_cand(d, node, hash) \
2885 hashmap__for_each_key_entry(d->dedup_table, node, (void *)hash)
2887 static int btf_dedup_table_add(struct btf_dedup *d, long hash, __u32 type_id)
2889 return hashmap__append(d->dedup_table,
2890 (void *)hash, (void *)(long)type_id);
2893 static int btf_dedup_hypot_map_add(struct btf_dedup *d,
2894 __u32 from_id, __u32 to_id)
2896 if (d->hypot_cnt == d->hypot_cap) {
2899 d->hypot_cap += max((size_t)16, d->hypot_cap / 2);
2900 new_list = libbpf_reallocarray(d->hypot_list, d->hypot_cap, sizeof(__u32));
2903 d->hypot_list = new_list;
2905 d->hypot_list[d->hypot_cnt++] = from_id;
2906 d->hypot_map[from_id] = to_id;
2910 static void btf_dedup_clear_hypot_map(struct btf_dedup *d)
2914 for (i = 0; i < d->hypot_cnt; i++)
2915 d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID;
2919 static void btf_dedup_free(struct btf_dedup *d)
2921 hashmap__free(d->dedup_table);
2922 d->dedup_table = NULL;
2928 d->hypot_map = NULL;
2930 free(d->hypot_list);
2931 d->hypot_list = NULL;
2936 static size_t btf_dedup_identity_hash_fn(const void *key, void *ctx)
2941 static size_t btf_dedup_collision_hash_fn(const void *key, void *ctx)
2946 static bool btf_dedup_equal_fn(const void *k1, const void *k2, void *ctx)
2951 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
2952 const struct btf_dedup_opts *opts)
2954 struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup));
2955 hashmap_hash_fn hash_fn = btf_dedup_identity_hash_fn;
2959 return ERR_PTR(-ENOMEM);
2961 d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds;
2962 /* dedup_table_size is now used only to force collisions in tests */
2963 if (opts && opts->dedup_table_size == 1)
2964 hash_fn = btf_dedup_collision_hash_fn;
2967 d->btf_ext = btf_ext;
2969 d->dedup_table = hashmap__new(hash_fn, btf_dedup_equal_fn, NULL);
2970 if (IS_ERR(d->dedup_table)) {
2971 err = PTR_ERR(d->dedup_table);
2972 d->dedup_table = NULL;
2976 d->map = malloc(sizeof(__u32) * (1 + btf->nr_types));
2981 /* special BTF "void" type is made canonical immediately */
2983 for (i = 1; i <= btf->nr_types; i++) {
2984 struct btf_type *t = btf_type_by_id(d->btf, i);
2986 /* VAR and DATASEC are never deduped and are self-canonical */
2987 if (btf_is_var(t) || btf_is_datasec(t))
2990 d->map[i] = BTF_UNPROCESSED_ID;
2993 d->hypot_map = malloc(sizeof(__u32) * (1 + btf->nr_types));
2994 if (!d->hypot_map) {
2998 for (i = 0; i <= btf->nr_types; i++)
2999 d->hypot_map[i] = BTF_UNPROCESSED_ID;
3004 return ERR_PTR(err);
3010 typedef int (*str_off_fn_t)(__u32 *str_off_ptr, void *ctx);
3013 * Iterate over all possible places in .BTF and .BTF.ext that can reference
3014 * string and pass pointer to it to a provided callback `fn`.
3016 static int btf_for_each_str_off(struct btf_dedup *d, str_off_fn_t fn, void *ctx)
3018 void *line_data_cur, *line_data_end;
3019 int i, j, r, rec_size;
3022 for (i = 1; i <= d->btf->nr_types; i++) {
3023 t = btf_type_by_id(d->btf, i);
3024 r = fn(&t->name_off, ctx);
3028 switch (btf_kind(t)) {
3029 case BTF_KIND_STRUCT:
3030 case BTF_KIND_UNION: {
3031 struct btf_member *m = btf_members(t);
3032 __u16 vlen = btf_vlen(t);
3034 for (j = 0; j < vlen; j++) {
3035 r = fn(&m->name_off, ctx);
3042 case BTF_KIND_ENUM: {
3043 struct btf_enum *m = btf_enum(t);
3044 __u16 vlen = btf_vlen(t);
3046 for (j = 0; j < vlen; j++) {
3047 r = fn(&m->name_off, ctx);
3054 case BTF_KIND_FUNC_PROTO: {
3055 struct btf_param *m = btf_params(t);
3056 __u16 vlen = btf_vlen(t);
3058 for (j = 0; j < vlen; j++) {
3059 r = fn(&m->name_off, ctx);
3074 line_data_cur = d->btf_ext->line_info.info;
3075 line_data_end = d->btf_ext->line_info.info + d->btf_ext->line_info.len;
3076 rec_size = d->btf_ext->line_info.rec_size;
3078 while (line_data_cur < line_data_end) {
3079 struct btf_ext_info_sec *sec = line_data_cur;
3080 struct bpf_line_info_min *line_info;
3081 __u32 num_info = sec->num_info;
3083 r = fn(&sec->sec_name_off, ctx);
3087 line_data_cur += sizeof(struct btf_ext_info_sec);
3088 for (i = 0; i < num_info; i++) {
3089 line_info = line_data_cur;
3090 r = fn(&line_info->file_name_off, ctx);
3093 r = fn(&line_info->line_off, ctx);
3096 line_data_cur += rec_size;
3103 static int str_sort_by_content(const void *a1, const void *a2)
3105 const struct btf_str_ptr *p1 = a1;
3106 const struct btf_str_ptr *p2 = a2;
3108 return strcmp(p1->str, p2->str);
3111 static int str_sort_by_offset(const void *a1, const void *a2)
3113 const struct btf_str_ptr *p1 = a1;
3114 const struct btf_str_ptr *p2 = a2;
3116 if (p1->str != p2->str)
3117 return p1->str < p2->str ? -1 : 1;
3121 static int btf_dedup_str_ptr_cmp(const void *str_ptr, const void *pelem)
3123 const struct btf_str_ptr *p = pelem;
3125 if (str_ptr != p->str)
3126 return (const char *)str_ptr < p->str ? -1 : 1;
3130 static int btf_str_mark_as_used(__u32 *str_off_ptr, void *ctx)
3132 struct btf_str_ptrs *strs;
3133 struct btf_str_ptr *s;
3135 if (*str_off_ptr == 0)
3139 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt,
3140 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp);
3147 static int btf_str_remap_offset(__u32 *str_off_ptr, void *ctx)
3149 struct btf_str_ptrs *strs;
3150 struct btf_str_ptr *s;
3152 if (*str_off_ptr == 0)
3156 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt,
3157 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp);
3160 *str_off_ptr = s->new_off;
3165 * Dedup string and filter out those that are not referenced from either .BTF
3166 * or .BTF.ext (if provided) sections.
3168 * This is done by building index of all strings in BTF's string section,
3169 * then iterating over all entities that can reference strings (e.g., type
3170 * names, struct field names, .BTF.ext line info, etc) and marking corresponding
3171 * strings as used. After that all used strings are deduped and compacted into
3172 * sequential blob of memory and new offsets are calculated. Then all the string
3173 * references are iterated again and rewritten using new offsets.
3175 static int btf_dedup_strings(struct btf_dedup *d)
3177 char *start = d->btf->strs_data;
3178 char *end = start + d->btf->hdr->str_len;
3179 char *p = start, *tmp_strs = NULL;
3180 struct btf_str_ptrs strs = {
3186 int i, j, err = 0, grp_idx;
3189 if (d->btf->strs_deduped)
3192 /* build index of all strings */
3194 if (strs.cnt + 1 > strs.cap) {
3195 struct btf_str_ptr *new_ptrs;
3197 strs.cap += max(strs.cnt / 2, 16U);
3198 new_ptrs = libbpf_reallocarray(strs.ptrs, strs.cap, sizeof(strs.ptrs[0]));
3203 strs.ptrs = new_ptrs;
3206 strs.ptrs[strs.cnt].str = p;
3207 strs.ptrs[strs.cnt].used = false;
3213 /* temporary storage for deduplicated strings */
3214 tmp_strs = malloc(d->btf->hdr->str_len);
3220 /* mark all used strings */
3221 strs.ptrs[0].used = true;
3222 err = btf_for_each_str_off(d, btf_str_mark_as_used, &strs);
3226 /* sort strings by context, so that we can identify duplicates */
3227 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_content);
3230 * iterate groups of equal strings and if any instance in a group was
3231 * referenced, emit single instance and remember new offset
3235 grp_used = strs.ptrs[0].used;
3236 /* iterate past end to avoid code duplication after loop */
3237 for (i = 1; i <= strs.cnt; i++) {
3239 * when i == strs.cnt, we want to skip string comparison and go
3240 * straight to handling last group of strings (otherwise we'd
3241 * need to handle last group after the loop w/ duplicated code)
3244 !strcmp(strs.ptrs[i].str, strs.ptrs[grp_idx].str)) {
3245 grp_used = grp_used || strs.ptrs[i].used;
3250 * this check would have been required after the loop to handle
3251 * last group of strings, but due to <= condition in a loop
3252 * we avoid that duplication
3255 int new_off = p - tmp_strs;
3256 __u32 len = strlen(strs.ptrs[grp_idx].str);
3258 memmove(p, strs.ptrs[grp_idx].str, len + 1);
3259 for (j = grp_idx; j < i; j++)
3260 strs.ptrs[j].new_off = new_off;
3266 grp_used = strs.ptrs[i].used;
3270 /* replace original strings with deduped ones */
3271 d->btf->hdr->str_len = p - tmp_strs;
3272 memmove(start, tmp_strs, d->btf->hdr->str_len);
3273 end = start + d->btf->hdr->str_len;
3275 /* restore original order for further binary search lookups */
3276 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_offset);
3278 /* remap string offsets */
3279 err = btf_for_each_str_off(d, btf_str_remap_offset, &strs);
3283 d->btf->hdr->str_len = end - start;
3284 d->btf->strs_deduped = true;
3292 static long btf_hash_common(struct btf_type *t)
3296 h = hash_combine(0, t->name_off);
3297 h = hash_combine(h, t->info);
3298 h = hash_combine(h, t->size);
3302 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2)
3304 return t1->name_off == t2->name_off &&
3305 t1->info == t2->info &&
3306 t1->size == t2->size;
3309 /* Calculate type signature hash of INT. */
3310 static long btf_hash_int(struct btf_type *t)
3312 __u32 info = *(__u32 *)(t + 1);
3315 h = btf_hash_common(t);
3316 h = hash_combine(h, info);
3320 /* Check structural equality of two INTs. */
3321 static bool btf_equal_int(struct btf_type *t1, struct btf_type *t2)
3325 if (!btf_equal_common(t1, t2))
3327 info1 = *(__u32 *)(t1 + 1);
3328 info2 = *(__u32 *)(t2 + 1);
3329 return info1 == info2;
3332 /* Calculate type signature hash of ENUM. */
3333 static long btf_hash_enum(struct btf_type *t)
3337 /* don't hash vlen and enum members to support enum fwd resolving */
3338 h = hash_combine(0, t->name_off);
3339 h = hash_combine(h, t->info & ~0xffff);
3340 h = hash_combine(h, t->size);
3344 /* Check structural equality of two ENUMs. */
3345 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2)
3347 const struct btf_enum *m1, *m2;
3351 if (!btf_equal_common(t1, t2))
3354 vlen = btf_vlen(t1);
3357 for (i = 0; i < vlen; i++) {
3358 if (m1->name_off != m2->name_off || m1->val != m2->val)
3366 static inline bool btf_is_enum_fwd(struct btf_type *t)
3368 return btf_is_enum(t) && btf_vlen(t) == 0;
3371 static bool btf_compat_enum(struct btf_type *t1, struct btf_type *t2)
3373 if (!btf_is_enum_fwd(t1) && !btf_is_enum_fwd(t2))
3374 return btf_equal_enum(t1, t2);
3375 /* ignore vlen when comparing */
3376 return t1->name_off == t2->name_off &&
3377 (t1->info & ~0xffff) == (t2->info & ~0xffff) &&
3378 t1->size == t2->size;
3382 * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs,
3383 * as referenced type IDs equivalence is established separately during type
3384 * graph equivalence check algorithm.
3386 static long btf_hash_struct(struct btf_type *t)
3388 const struct btf_member *member = btf_members(t);
3389 __u32 vlen = btf_vlen(t);
3390 long h = btf_hash_common(t);
3393 for (i = 0; i < vlen; i++) {
3394 h = hash_combine(h, member->name_off);
3395 h = hash_combine(h, member->offset);
3396 /* no hashing of referenced type ID, it can be unresolved yet */
3403 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
3404 * IDs. This check is performed during type graph equivalence check and
3405 * referenced types equivalence is checked separately.
3407 static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2)
3409 const struct btf_member *m1, *m2;
3413 if (!btf_equal_common(t1, t2))
3416 vlen = btf_vlen(t1);
3417 m1 = btf_members(t1);
3418 m2 = btf_members(t2);
3419 for (i = 0; i < vlen; i++) {
3420 if (m1->name_off != m2->name_off || m1->offset != m2->offset)
3429 * Calculate type signature hash of ARRAY, including referenced type IDs,
3430 * under assumption that they were already resolved to canonical type IDs and
3431 * are not going to change.
3433 static long btf_hash_array(struct btf_type *t)
3435 const struct btf_array *info = btf_array(t);
3436 long h = btf_hash_common(t);
3438 h = hash_combine(h, info->type);
3439 h = hash_combine(h, info->index_type);
3440 h = hash_combine(h, info->nelems);
3445 * Check exact equality of two ARRAYs, taking into account referenced
3446 * type IDs, under assumption that they were already resolved to canonical
3447 * type IDs and are not going to change.
3448 * This function is called during reference types deduplication to compare
3449 * ARRAY to potential canonical representative.
3451 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2)
3453 const struct btf_array *info1, *info2;
3455 if (!btf_equal_common(t1, t2))
3458 info1 = btf_array(t1);
3459 info2 = btf_array(t2);
3460 return info1->type == info2->type &&
3461 info1->index_type == info2->index_type &&
3462 info1->nelems == info2->nelems;
3466 * Check structural compatibility of two ARRAYs, ignoring referenced type
3467 * IDs. This check is performed during type graph equivalence check and
3468 * referenced types equivalence is checked separately.
3470 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2)
3472 if (!btf_equal_common(t1, t2))
3475 return btf_array(t1)->nelems == btf_array(t2)->nelems;
3479 * Calculate type signature hash of FUNC_PROTO, including referenced type IDs,
3480 * under assumption that they were already resolved to canonical type IDs and
3481 * are not going to change.
3483 static long btf_hash_fnproto(struct btf_type *t)
3485 const struct btf_param *member = btf_params(t);
3486 __u16 vlen = btf_vlen(t);
3487 long h = btf_hash_common(t);
3490 for (i = 0; i < vlen; i++) {
3491 h = hash_combine(h, member->name_off);
3492 h = hash_combine(h, member->type);
3499 * Check exact equality of two FUNC_PROTOs, taking into account referenced
3500 * type IDs, under assumption that they were already resolved to canonical
3501 * type IDs and are not going to change.
3502 * This function is called during reference types deduplication to compare
3503 * FUNC_PROTO to potential canonical representative.
3505 static bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2)
3507 const struct btf_param *m1, *m2;
3511 if (!btf_equal_common(t1, t2))
3514 vlen = btf_vlen(t1);
3515 m1 = btf_params(t1);
3516 m2 = btf_params(t2);
3517 for (i = 0; i < vlen; i++) {
3518 if (m1->name_off != m2->name_off || m1->type != m2->type)
3527 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
3528 * IDs. This check is performed during type graph equivalence check and
3529 * referenced types equivalence is checked separately.
3531 static bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2)
3533 const struct btf_param *m1, *m2;
3537 /* skip return type ID */
3538 if (t1->name_off != t2->name_off || t1->info != t2->info)
3541 vlen = btf_vlen(t1);
3542 m1 = btf_params(t1);
3543 m2 = btf_params(t2);
3544 for (i = 0; i < vlen; i++) {
3545 if (m1->name_off != m2->name_off)
3554 * Deduplicate primitive types, that can't reference other types, by calculating
3555 * their type signature hash and comparing them with any possible canonical
3556 * candidate. If no canonical candidate matches, type itself is marked as
3557 * canonical and is added into `btf_dedup->dedup_table` as another candidate.
3559 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id)
3561 struct btf_type *t = btf_type_by_id(d->btf, type_id);
3562 struct hashmap_entry *hash_entry;
3563 struct btf_type *cand;
3564 /* if we don't find equivalent type, then we are canonical */
3565 __u32 new_id = type_id;
3569 switch (btf_kind(t)) {
3570 case BTF_KIND_CONST:
3571 case BTF_KIND_VOLATILE:
3572 case BTF_KIND_RESTRICT:
3574 case BTF_KIND_TYPEDEF:
3575 case BTF_KIND_ARRAY:
3576 case BTF_KIND_STRUCT:
3577 case BTF_KIND_UNION:
3579 case BTF_KIND_FUNC_PROTO:
3581 case BTF_KIND_DATASEC:
3585 h = btf_hash_int(t);
3586 for_each_dedup_cand(d, hash_entry, h) {
3587 cand_id = (__u32)(long)hash_entry->value;
3588 cand = btf_type_by_id(d->btf, cand_id);
3589 if (btf_equal_int(t, cand)) {
3597 h = btf_hash_enum(t);
3598 for_each_dedup_cand(d, hash_entry, h) {
3599 cand_id = (__u32)(long)hash_entry->value;
3600 cand = btf_type_by_id(d->btf, cand_id);
3601 if (btf_equal_enum(t, cand)) {
3605 if (d->opts.dont_resolve_fwds)
3607 if (btf_compat_enum(t, cand)) {
3608 if (btf_is_enum_fwd(t)) {
3609 /* resolve fwd to full enum */
3613 /* resolve canonical enum fwd to full enum */
3614 d->map[cand_id] = type_id;
3620 h = btf_hash_common(t);
3621 for_each_dedup_cand(d, hash_entry, h) {
3622 cand_id = (__u32)(long)hash_entry->value;
3623 cand = btf_type_by_id(d->btf, cand_id);
3624 if (btf_equal_common(t, cand)) {
3635 d->map[type_id] = new_id;
3636 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
3642 static int btf_dedup_prim_types(struct btf_dedup *d)
3646 for (i = 1; i <= d->btf->nr_types; i++) {
3647 err = btf_dedup_prim_type(d, i);
3655 * Check whether type is already mapped into canonical one (could be to itself).
3657 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id)
3659 return d->map[type_id] <= BTF_MAX_NR_TYPES;
3663 * Resolve type ID into its canonical type ID, if any; otherwise return original
3664 * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow
3665 * STRUCT/UNION link and resolve it into canonical type ID as well.
3667 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id)
3669 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3670 type_id = d->map[type_id];
3675 * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original
3678 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id)
3680 __u32 orig_type_id = type_id;
3682 if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3685 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3686 type_id = d->map[type_id];
3688 if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3691 return orig_type_id;
3695 static inline __u16 btf_fwd_kind(struct btf_type *t)
3697 return btf_kflag(t) ? BTF_KIND_UNION : BTF_KIND_STRUCT;
3701 * Check equivalence of BTF type graph formed by candidate struct/union (we'll
3702 * call it "candidate graph" in this description for brevity) to a type graph
3703 * formed by (potential) canonical struct/union ("canonical graph" for brevity
3704 * here, though keep in mind that not all types in canonical graph are
3705 * necessarily canonical representatives themselves, some of them might be
3706 * duplicates or its uniqueness might not have been established yet).
3708 * - >0, if type graphs are equivalent;
3709 * - 0, if not equivalent;
3712 * Algorithm performs side-by-side DFS traversal of both type graphs and checks
3713 * equivalence of BTF types at each step. If at any point BTF types in candidate
3714 * and canonical graphs are not compatible structurally, whole graphs are
3715 * incompatible. If types are structurally equivalent (i.e., all information
3716 * except referenced type IDs is exactly the same), a mapping from `canon_id` to
3717 * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`).
3718 * If a type references other types, then those referenced types are checked
3719 * for equivalence recursively.
3721 * During DFS traversal, if we find that for current `canon_id` type we
3722 * already have some mapping in hypothetical map, we check for two possible
3724 * - `canon_id` is mapped to exactly the same type as `cand_id`. This will
3725 * happen when type graphs have cycles. In this case we assume those two
3726 * types are equivalent.
3727 * - `canon_id` is mapped to different type. This is contradiction in our
3728 * hypothetical mapping, because same graph in canonical graph corresponds
3729 * to two different types in candidate graph, which for equivalent type
3730 * graphs shouldn't happen. This condition terminates equivalence check
3731 * with negative result.
3733 * If type graphs traversal exhausts types to check and find no contradiction,
3734 * then type graphs are equivalent.
3736 * When checking types for equivalence, there is one special case: FWD types.
3737 * If FWD type resolution is allowed and one of the types (either from canonical
3738 * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind
3739 * flag) and their names match, hypothetical mapping is updated to point from
3740 * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully,
3741 * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently.
3743 * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution,
3744 * if there are two exactly named (or anonymous) structs/unions that are
3745 * compatible structurally, one of which has FWD field, while other is concrete
3746 * STRUCT/UNION, but according to C sources they are different structs/unions
3747 * that are referencing different types with the same name. This is extremely
3748 * unlikely to happen, but btf_dedup API allows to disable FWD resolution if
3749 * this logic is causing problems.
3751 * Doing FWD resolution means that both candidate and/or canonical graphs can
3752 * consists of portions of the graph that come from multiple compilation units.
3753 * This is due to the fact that types within single compilation unit are always
3754 * deduplicated and FWDs are already resolved, if referenced struct/union
3755 * definiton is available. So, if we had unresolved FWD and found corresponding
3756 * STRUCT/UNION, they will be from different compilation units. This
3757 * consequently means that when we "link" FWD to corresponding STRUCT/UNION,
3758 * type graph will likely have at least two different BTF types that describe
3759 * same type (e.g., most probably there will be two different BTF types for the
3760 * same 'int' primitive type) and could even have "overlapping" parts of type
3761 * graph that describe same subset of types.
3763 * This in turn means that our assumption that each type in canonical graph
3764 * must correspond to exactly one type in candidate graph might not hold
3765 * anymore and will make it harder to detect contradictions using hypothetical
3766 * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION
3767 * resolution only in canonical graph. FWDs in candidate graphs are never
3768 * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs
3770 * - Both types in canonical and candidate graphs are FWDs. If they are
3771 * structurally equivalent, then they can either be both resolved to the
3772 * same STRUCT/UNION or not resolved at all. In both cases they are
3773 * equivalent and there is no need to resolve FWD on candidate side.
3774 * - Both types in canonical and candidate graphs are concrete STRUCT/UNION,
3775 * so nothing to resolve as well, algorithm will check equivalence anyway.
3776 * - Type in canonical graph is FWD, while type in candidate is concrete
3777 * STRUCT/UNION. In this case candidate graph comes from single compilation
3778 * unit, so there is exactly one BTF type for each unique C type. After
3779 * resolving FWD into STRUCT/UNION, there might be more than one BTF type
3780 * in canonical graph mapping to single BTF type in candidate graph, but
3781 * because hypothetical mapping maps from canonical to candidate types, it's
3782 * alright, and we still maintain the property of having single `canon_id`
3783 * mapping to single `cand_id` (there could be two different `canon_id`
3784 * mapped to the same `cand_id`, but it's not contradictory).
3785 * - Type in canonical graph is concrete STRUCT/UNION, while type in candidate
3786 * graph is FWD. In this case we are just going to check compatibility of
3787 * STRUCT/UNION and corresponding FWD, and if they are compatible, we'll
3788 * assume that whatever STRUCT/UNION FWD resolves to must be equivalent to
3789 * a concrete STRUCT/UNION from canonical graph. If the rest of type graphs
3790 * turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from
3793 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id,
3796 struct btf_type *cand_type;
3797 struct btf_type *canon_type;
3798 __u32 hypot_type_id;
3803 /* if both resolve to the same canonical, they must be equivalent */
3804 if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id))
3807 canon_id = resolve_fwd_id(d, canon_id);
3809 hypot_type_id = d->hypot_map[canon_id];
3810 if (hypot_type_id <= BTF_MAX_NR_TYPES)
3811 return hypot_type_id == cand_id;
3813 if (btf_dedup_hypot_map_add(d, canon_id, cand_id))
3816 cand_type = btf_type_by_id(d->btf, cand_id);
3817 canon_type = btf_type_by_id(d->btf, canon_id);
3818 cand_kind = btf_kind(cand_type);
3819 canon_kind = btf_kind(canon_type);
3821 if (cand_type->name_off != canon_type->name_off)
3824 /* FWD <--> STRUCT/UNION equivalence check, if enabled */
3825 if (!d->opts.dont_resolve_fwds
3826 && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD)
3827 && cand_kind != canon_kind) {
3831 if (cand_kind == BTF_KIND_FWD) {
3832 real_kind = canon_kind;
3833 fwd_kind = btf_fwd_kind(cand_type);
3835 real_kind = cand_kind;
3836 fwd_kind = btf_fwd_kind(canon_type);
3838 return fwd_kind == real_kind;
3841 if (cand_kind != canon_kind)
3844 switch (cand_kind) {
3846 return btf_equal_int(cand_type, canon_type);
3849 if (d->opts.dont_resolve_fwds)
3850 return btf_equal_enum(cand_type, canon_type);
3852 return btf_compat_enum(cand_type, canon_type);
3855 return btf_equal_common(cand_type, canon_type);
3857 case BTF_KIND_CONST:
3858 case BTF_KIND_VOLATILE:
3859 case BTF_KIND_RESTRICT:
3861 case BTF_KIND_TYPEDEF:
3863 if (cand_type->info != canon_type->info)
3865 return btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
3867 case BTF_KIND_ARRAY: {
3868 const struct btf_array *cand_arr, *canon_arr;
3870 if (!btf_compat_array(cand_type, canon_type))
3872 cand_arr = btf_array(cand_type);
3873 canon_arr = btf_array(canon_type);
3874 eq = btf_dedup_is_equiv(d,
3875 cand_arr->index_type, canon_arr->index_type);
3878 return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type);
3881 case BTF_KIND_STRUCT:
3882 case BTF_KIND_UNION: {
3883 const struct btf_member *cand_m, *canon_m;
3886 if (!btf_shallow_equal_struct(cand_type, canon_type))
3888 vlen = btf_vlen(cand_type);
3889 cand_m = btf_members(cand_type);
3890 canon_m = btf_members(canon_type);
3891 for (i = 0; i < vlen; i++) {
3892 eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type);
3902 case BTF_KIND_FUNC_PROTO: {
3903 const struct btf_param *cand_p, *canon_p;
3906 if (!btf_compat_fnproto(cand_type, canon_type))
3908 eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
3911 vlen = btf_vlen(cand_type);
3912 cand_p = btf_params(cand_type);
3913 canon_p = btf_params(canon_type);
3914 for (i = 0; i < vlen; i++) {
3915 eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type);
3931 * Use hypothetical mapping, produced by successful type graph equivalence
3932 * check, to augment existing struct/union canonical mapping, where possible.
3934 * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record
3935 * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional:
3936 * it doesn't matter if FWD type was part of canonical graph or candidate one,
3937 * we are recording the mapping anyway. As opposed to carefulness required
3938 * for struct/union correspondence mapping (described below), for FWD resolution
3939 * it's not important, as by the time that FWD type (reference type) will be
3940 * deduplicated all structs/unions will be deduped already anyway.
3942 * Recording STRUCT/UNION mapping is purely a performance optimization and is
3943 * not required for correctness. It needs to be done carefully to ensure that
3944 * struct/union from candidate's type graph is not mapped into corresponding
3945 * struct/union from canonical type graph that itself hasn't been resolved into
3946 * canonical representative. The only guarantee we have is that canonical
3947 * struct/union was determined as canonical and that won't change. But any
3948 * types referenced through that struct/union fields could have been not yet
3949 * resolved, so in case like that it's too early to establish any kind of
3950 * correspondence between structs/unions.
3952 * No canonical correspondence is derived for primitive types (they are already
3953 * deduplicated completely already anyway) or reference types (they rely on
3954 * stability of struct/union canonical relationship for equivalence checks).
3956 static void btf_dedup_merge_hypot_map(struct btf_dedup *d)
3958 __u32 cand_type_id, targ_type_id;
3959 __u16 t_kind, c_kind;
3963 for (i = 0; i < d->hypot_cnt; i++) {
3964 cand_type_id = d->hypot_list[i];
3965 targ_type_id = d->hypot_map[cand_type_id];
3966 t_id = resolve_type_id(d, targ_type_id);
3967 c_id = resolve_type_id(d, cand_type_id);
3968 t_kind = btf_kind(btf__type_by_id(d->btf, t_id));
3969 c_kind = btf_kind(btf__type_by_id(d->btf, c_id));
3971 * Resolve FWD into STRUCT/UNION.
3972 * It's ok to resolve FWD into STRUCT/UNION that's not yet
3973 * mapped to canonical representative (as opposed to
3974 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because
3975 * eventually that struct is going to be mapped and all resolved
3976 * FWDs will automatically resolve to correct canonical
3977 * representative. This will happen before ref type deduping,
3978 * which critically depends on stability of these mapping. This
3979 * stability is not a requirement for STRUCT/UNION equivalence
3982 if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD)
3983 d->map[c_id] = t_id;
3984 else if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD)
3985 d->map[t_id] = c_id;
3987 if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) &&
3988 c_kind != BTF_KIND_FWD &&
3989 is_type_mapped(d, c_id) &&
3990 !is_type_mapped(d, t_id)) {
3992 * as a perf optimization, we can map struct/union
3993 * that's part of type graph we just verified for
3994 * equivalence. We can do that for struct/union that has
3995 * canonical representative only, though.
3997 d->map[t_id] = c_id;
4003 * Deduplicate struct/union types.
4005 * For each struct/union type its type signature hash is calculated, taking
4006 * into account type's name, size, number, order and names of fields, but
4007 * ignoring type ID's referenced from fields, because they might not be deduped
4008 * completely until after reference types deduplication phase. This type hash
4009 * is used to iterate over all potential canonical types, sharing same hash.
4010 * For each canonical candidate we check whether type graphs that they form
4011 * (through referenced types in fields and so on) are equivalent using algorithm
4012 * implemented in `btf_dedup_is_equiv`. If such equivalence is found and
4013 * BTF_KIND_FWD resolution is allowed, then hypothetical mapping
4014 * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence
4015 * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to
4016 * potentially map other structs/unions to their canonical representatives,
4017 * if such relationship hasn't yet been established. This speeds up algorithm
4018 * by eliminating some of the duplicate work.
4020 * If no matching canonical representative was found, struct/union is marked
4021 * as canonical for itself and is added into btf_dedup->dedup_table hash map
4022 * for further look ups.
4024 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id)
4026 struct btf_type *cand_type, *t;
4027 struct hashmap_entry *hash_entry;
4028 /* if we don't find equivalent type, then we are canonical */
4029 __u32 new_id = type_id;
4033 /* already deduped or is in process of deduping (loop detected) */
4034 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4037 t = btf_type_by_id(d->btf, type_id);
4040 if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION)
4043 h = btf_hash_struct(t);
4044 for_each_dedup_cand(d, hash_entry, h) {
4045 __u32 cand_id = (__u32)(long)hash_entry->value;
4049 * Even though btf_dedup_is_equiv() checks for
4050 * btf_shallow_equal_struct() internally when checking two
4051 * structs (unions) for equivalence, we need to guard here
4052 * from picking matching FWD type as a dedup candidate.
4053 * This can happen due to hash collision. In such case just
4054 * relying on btf_dedup_is_equiv() would lead to potentially
4055 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because
4056 * FWD and compatible STRUCT/UNION are considered equivalent.
4058 cand_type = btf_type_by_id(d->btf, cand_id);
4059 if (!btf_shallow_equal_struct(t, cand_type))
4062 btf_dedup_clear_hypot_map(d);
4063 eq = btf_dedup_is_equiv(d, type_id, cand_id);
4069 btf_dedup_merge_hypot_map(d);
4073 d->map[type_id] = new_id;
4074 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4080 static int btf_dedup_struct_types(struct btf_dedup *d)
4084 for (i = 1; i <= d->btf->nr_types; i++) {
4085 err = btf_dedup_struct_type(d, i);
4093 * Deduplicate reference type.
4095 * Once all primitive and struct/union types got deduplicated, we can easily
4096 * deduplicate all other (reference) BTF types. This is done in two steps:
4098 * 1. Resolve all referenced type IDs into their canonical type IDs. This
4099 * resolution can be done either immediately for primitive or struct/union types
4100 * (because they were deduped in previous two phases) or recursively for
4101 * reference types. Recursion will always terminate at either primitive or
4102 * struct/union type, at which point we can "unwind" chain of reference types
4103 * one by one. There is no danger of encountering cycles because in C type
4104 * system the only way to form type cycle is through struct/union, so any chain
4105 * of reference types, even those taking part in a type cycle, will inevitably
4106 * reach struct/union at some point.
4108 * 2. Once all referenced type IDs are resolved into canonical ones, BTF type
4109 * becomes "stable", in the sense that no further deduplication will cause
4110 * any changes to it. With that, it's now possible to calculate type's signature
4111 * hash (this time taking into account referenced type IDs) and loop over all
4112 * potential canonical representatives. If no match was found, current type
4113 * will become canonical representative of itself and will be added into
4114 * btf_dedup->dedup_table as another possible canonical representative.
4116 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id)
4118 struct hashmap_entry *hash_entry;
4119 __u32 new_id = type_id, cand_id;
4120 struct btf_type *t, *cand;
4121 /* if we don't find equivalent type, then we are representative type */
4125 if (d->map[type_id] == BTF_IN_PROGRESS_ID)
4127 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4128 return resolve_type_id(d, type_id);
4130 t = btf_type_by_id(d->btf, type_id);
4131 d->map[type_id] = BTF_IN_PROGRESS_ID;
4133 switch (btf_kind(t)) {
4134 case BTF_KIND_CONST:
4135 case BTF_KIND_VOLATILE:
4136 case BTF_KIND_RESTRICT:
4138 case BTF_KIND_TYPEDEF:
4140 ref_type_id = btf_dedup_ref_type(d, t->type);
4141 if (ref_type_id < 0)
4143 t->type = ref_type_id;
4145 h = btf_hash_common(t);
4146 for_each_dedup_cand(d, hash_entry, h) {
4147 cand_id = (__u32)(long)hash_entry->value;
4148 cand = btf_type_by_id(d->btf, cand_id);
4149 if (btf_equal_common(t, cand)) {
4156 case BTF_KIND_ARRAY: {
4157 struct btf_array *info = btf_array(t);
4159 ref_type_id = btf_dedup_ref_type(d, info->type);
4160 if (ref_type_id < 0)
4162 info->type = ref_type_id;
4164 ref_type_id = btf_dedup_ref_type(d, info->index_type);
4165 if (ref_type_id < 0)
4167 info->index_type = ref_type_id;
4169 h = btf_hash_array(t);
4170 for_each_dedup_cand(d, hash_entry, h) {
4171 cand_id = (__u32)(long)hash_entry->value;
4172 cand = btf_type_by_id(d->btf, cand_id);
4173 if (btf_equal_array(t, cand)) {
4181 case BTF_KIND_FUNC_PROTO: {
4182 struct btf_param *param;
4186 ref_type_id = btf_dedup_ref_type(d, t->type);
4187 if (ref_type_id < 0)
4189 t->type = ref_type_id;
4192 param = btf_params(t);
4193 for (i = 0; i < vlen; i++) {
4194 ref_type_id = btf_dedup_ref_type(d, param->type);
4195 if (ref_type_id < 0)
4197 param->type = ref_type_id;
4201 h = btf_hash_fnproto(t);
4202 for_each_dedup_cand(d, hash_entry, h) {
4203 cand_id = (__u32)(long)hash_entry->value;
4204 cand = btf_type_by_id(d->btf, cand_id);
4205 if (btf_equal_fnproto(t, cand)) {
4217 d->map[type_id] = new_id;
4218 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4224 static int btf_dedup_ref_types(struct btf_dedup *d)
4228 for (i = 1; i <= d->btf->nr_types; i++) {
4229 err = btf_dedup_ref_type(d, i);
4233 /* we won't need d->dedup_table anymore */
4234 hashmap__free(d->dedup_table);
4235 d->dedup_table = NULL;
4242 * After we established for each type its corresponding canonical representative
4243 * type, we now can eliminate types that are not canonical and leave only
4244 * canonical ones layed out sequentially in memory by copying them over
4245 * duplicates. During compaction btf_dedup->hypot_map array is reused to store
4246 * a map from original type ID to a new compacted type ID, which will be used
4247 * during next phase to "fix up" type IDs, referenced from struct/union and
4250 static int btf_dedup_compact_types(struct btf_dedup *d)
4253 __u32 next_type_id = 1;
4257 /* we are going to reuse hypot_map to store compaction remapping */
4258 d->hypot_map[0] = 0;
4259 for (i = 1; i <= d->btf->nr_types; i++)
4260 d->hypot_map[i] = BTF_UNPROCESSED_ID;
4262 p = d->btf->types_data;
4264 for (i = 1; i <= d->btf->nr_types; i++) {
4268 len = btf_type_size(btf__type_by_id(d->btf, i));
4272 memmove(p, btf__type_by_id(d->btf, i), len);
4273 d->hypot_map[i] = next_type_id;
4274 d->btf->type_offs[next_type_id] = p - d->btf->types_data;
4279 /* shrink struct btf's internal types index and update btf_header */
4280 d->btf->nr_types = next_type_id - 1;
4281 d->btf->type_offs_cap = d->btf->nr_types + 1;
4282 d->btf->hdr->type_len = p - d->btf->types_data;
4283 new_offs = libbpf_reallocarray(d->btf->type_offs, d->btf->type_offs_cap,
4287 d->btf->type_offs = new_offs;
4288 d->btf->hdr->str_off = d->btf->hdr->type_len;
4289 d->btf->raw_size = d->btf->hdr->hdr_len + d->btf->hdr->type_len + d->btf->hdr->str_len;
4294 * Figure out final (deduplicated and compacted) type ID for provided original
4295 * `type_id` by first resolving it into corresponding canonical type ID and
4296 * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map,
4297 * which is populated during compaction phase.
4299 static int btf_dedup_remap_type_id(struct btf_dedup *d, __u32 type_id)
4301 __u32 resolved_type_id, new_type_id;
4303 resolved_type_id = resolve_type_id(d, type_id);
4304 new_type_id = d->hypot_map[resolved_type_id];
4305 if (new_type_id > BTF_MAX_NR_TYPES)
4311 * Remap referenced type IDs into deduped type IDs.
4313 * After BTF types are deduplicated and compacted, their final type IDs may
4314 * differ from original ones. The map from original to a corresponding
4315 * deduped type ID is stored in btf_dedup->hypot_map and is populated during
4316 * compaction phase. During remapping phase we are rewriting all type IDs
4317 * referenced from any BTF type (e.g., struct fields, func proto args, etc) to
4318 * their final deduped type IDs.
4320 static int btf_dedup_remap_type(struct btf_dedup *d, __u32 type_id)
4322 struct btf_type *t = btf_type_by_id(d->btf, type_id);
4325 switch (btf_kind(t)) {
4331 case BTF_KIND_CONST:
4332 case BTF_KIND_VOLATILE:
4333 case BTF_KIND_RESTRICT:
4335 case BTF_KIND_TYPEDEF:
4338 r = btf_dedup_remap_type_id(d, t->type);
4344 case BTF_KIND_ARRAY: {
4345 struct btf_array *arr_info = btf_array(t);
4347 r = btf_dedup_remap_type_id(d, arr_info->type);
4351 r = btf_dedup_remap_type_id(d, arr_info->index_type);
4354 arr_info->index_type = r;
4358 case BTF_KIND_STRUCT:
4359 case BTF_KIND_UNION: {
4360 struct btf_member *member = btf_members(t);
4361 __u16 vlen = btf_vlen(t);
4363 for (i = 0; i < vlen; i++) {
4364 r = btf_dedup_remap_type_id(d, member->type);
4373 case BTF_KIND_FUNC_PROTO: {
4374 struct btf_param *param = btf_params(t);
4375 __u16 vlen = btf_vlen(t);
4377 r = btf_dedup_remap_type_id(d, t->type);
4382 for (i = 0; i < vlen; i++) {
4383 r = btf_dedup_remap_type_id(d, param->type);
4392 case BTF_KIND_DATASEC: {
4393 struct btf_var_secinfo *var = btf_var_secinfos(t);
4394 __u16 vlen = btf_vlen(t);
4396 for (i = 0; i < vlen; i++) {
4397 r = btf_dedup_remap_type_id(d, var->type);
4413 static int btf_dedup_remap_types(struct btf_dedup *d)
4417 for (i = 1; i <= d->btf->nr_types; i++) {
4418 r = btf_dedup_remap_type(d, i);
4426 * Probe few well-known locations for vmlinux kernel image and try to load BTF
4427 * data out of it to use for target BTF.
4429 struct btf *libbpf_find_kernel_btf(void)
4432 const char *path_fmt;
4435 /* try canonical vmlinux BTF through sysfs first */
4436 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
4437 /* fall back to trying to find vmlinux ELF on disk otherwise */
4438 { "/boot/vmlinux-%1$s" },
4439 { "/lib/modules/%1$s/vmlinux-%1$s" },
4440 { "/lib/modules/%1$s/build/vmlinux" },
4441 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
4442 { "/usr/lib/debug/boot/vmlinux-%1$s" },
4443 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
4444 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
4446 char path[PATH_MAX + 1];
4453 for (i = 0; i < ARRAY_SIZE(locations); i++) {
4454 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
4456 if (access(path, R_OK))
4459 if (locations[i].raw_btf)
4460 btf = btf__parse_raw(path);
4462 btf = btf__parse_elf(path, NULL);
4464 pr_debug("loading kernel BTF '%s': %ld\n",
4465 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
4472 pr_warn("failed to find valid kernel BTF\n");
4473 return ERR_PTR(-ESRCH);