1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 /* Copyright (c) 2018 Facebook */
11 #include <sys/utsname.h>
12 #include <sys/param.h>
14 #include <linux/kernel.h>
15 #include <linux/err.h>
16 #include <linux/btf.h>
21 #include "libbpf_internal.h"
24 /* make sure libbpf doesn't use kernel-only integer typedefs */
25 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
27 #define BTF_MAX_NR_TYPES 0x7fffffffU
28 #define BTF_MAX_STR_OFFSET 0x7fffffffU
30 static struct btf_type btf_void;
34 struct btf_header *hdr;
37 struct btf_type **types;
47 static inline __u64 ptr_to_u64(const void *ptr)
49 return (__u64) (unsigned long) ptr;
52 static int btf_add_type(struct btf *btf, struct btf_type *t)
54 if (btf->types_size - btf->nr_types < 2) {
55 struct btf_type **new_types;
56 __u32 expand_by, new_size;
58 if (btf->types_size == BTF_MAX_NR_TYPES)
61 expand_by = max(btf->types_size >> 2, 16U);
62 new_size = min(BTF_MAX_NR_TYPES, btf->types_size + expand_by);
64 new_types = realloc(btf->types, sizeof(*new_types) * new_size);
68 if (btf->nr_types == 0)
69 new_types[0] = &btf_void;
71 btf->types = new_types;
72 btf->types_size = new_size;
75 btf->types[++(btf->nr_types)] = t;
80 static int btf_parse_hdr(struct btf *btf)
82 const struct btf_header *hdr = btf->hdr;
85 if (btf->data_size < sizeof(struct btf_header)) {
86 pr_debug("BTF header not found\n");
90 if (hdr->magic != BTF_MAGIC) {
91 pr_debug("Invalid BTF magic:%x\n", hdr->magic);
95 if (hdr->version != BTF_VERSION) {
96 pr_debug("Unsupported BTF version:%u\n", hdr->version);
101 pr_debug("Unsupported BTF flags:%x\n", hdr->flags);
105 meta_left = btf->data_size - sizeof(*hdr);
107 pr_debug("BTF has no data\n");
111 if (meta_left < hdr->type_off) {
112 pr_debug("Invalid BTF type section offset:%u\n", hdr->type_off);
116 if (meta_left < hdr->str_off) {
117 pr_debug("Invalid BTF string section offset:%u\n", hdr->str_off);
121 if (hdr->type_off >= hdr->str_off) {
122 pr_debug("BTF type section offset >= string section offset. No type?\n");
126 if (hdr->type_off & 0x02) {
127 pr_debug("BTF type section is not aligned to 4 bytes\n");
131 btf->nohdr_data = btf->hdr + 1;
136 static int btf_parse_str_sec(struct btf *btf)
138 const struct btf_header *hdr = btf->hdr;
139 const char *start = btf->nohdr_data + hdr->str_off;
140 const char *end = start + btf->hdr->str_len;
142 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_STR_OFFSET ||
143 start[0] || end[-1]) {
144 pr_debug("Invalid BTF string section\n");
148 btf->strings = start;
153 static int btf_type_size(struct btf_type *t)
155 int base_size = sizeof(struct btf_type);
156 __u16 vlen = btf_vlen(t);
158 switch (btf_kind(t)) {
161 case BTF_KIND_VOLATILE:
162 case BTF_KIND_RESTRICT:
164 case BTF_KIND_TYPEDEF:
168 return base_size + sizeof(__u32);
170 return base_size + vlen * sizeof(struct btf_enum);
172 return base_size + sizeof(struct btf_array);
173 case BTF_KIND_STRUCT:
175 return base_size + vlen * sizeof(struct btf_member);
176 case BTF_KIND_FUNC_PROTO:
177 return base_size + vlen * sizeof(struct btf_param);
179 return base_size + sizeof(struct btf_var);
180 case BTF_KIND_DATASEC:
181 return base_size + vlen * sizeof(struct btf_var_secinfo);
183 pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
188 static int btf_parse_type_sec(struct btf *btf)
190 struct btf_header *hdr = btf->hdr;
191 void *nohdr_data = btf->nohdr_data;
192 void *next_type = nohdr_data + hdr->type_off;
193 void *end_type = nohdr_data + hdr->str_off;
195 while (next_type < end_type) {
196 struct btf_type *t = next_type;
200 type_size = btf_type_size(t);
203 next_type += type_size;
204 err = btf_add_type(btf, t);
212 __u32 btf__get_nr_types(const struct btf *btf)
214 return btf->nr_types;
217 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id)
219 if (type_id > btf->nr_types)
222 return btf->types[type_id];
225 static int determine_ptr_size(const struct btf *btf)
227 const struct btf_type *t;
231 for (i = 1; i <= btf->nr_types; i++) {
232 t = btf__type_by_id(btf, i);
236 name = btf__name_by_offset(btf, t->name_off);
240 if (strcmp(name, "long int") == 0 ||
241 strcmp(name, "long unsigned int") == 0) {
242 if (t->size != 4 && t->size != 8)
251 static size_t btf_ptr_sz(const struct btf *btf)
254 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
255 return btf->ptr_sz < 0 ? sizeof(void *) : btf->ptr_sz;
258 /* Return pointer size this BTF instance assumes. The size is heuristically
259 * determined by looking for 'long' or 'unsigned long' integer type and
260 * recording its size in bytes. If BTF type information doesn't have any such
261 * type, this function returns 0. In the latter case, native architecture's
262 * pointer size is assumed, so will be either 4 or 8, depending on
263 * architecture that libbpf was compiled for. It's possible to override
264 * guessed value by using btf__set_pointer_size() API.
266 size_t btf__pointer_size(const struct btf *btf)
269 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
272 /* not enough BTF type info to guess */
278 /* Override or set pointer size in bytes. Only values of 4 and 8 are
281 int btf__set_pointer_size(struct btf *btf, size_t ptr_sz)
283 if (ptr_sz != 4 && ptr_sz != 8)
285 btf->ptr_sz = ptr_sz;
289 static bool btf_type_is_void(const struct btf_type *t)
291 return t == &btf_void || btf_is_fwd(t);
294 static bool btf_type_is_void_or_null(const struct btf_type *t)
296 return !t || btf_type_is_void(t);
299 #define MAX_RESOLVE_DEPTH 32
301 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id)
303 const struct btf_array *array;
304 const struct btf_type *t;
309 t = btf__type_by_id(btf, type_id);
310 for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t);
312 switch (btf_kind(t)) {
314 case BTF_KIND_STRUCT:
317 case BTF_KIND_DATASEC:
321 size = btf_ptr_sz(btf);
323 case BTF_KIND_TYPEDEF:
324 case BTF_KIND_VOLATILE:
326 case BTF_KIND_RESTRICT:
331 array = btf_array(t);
332 if (nelems && array->nelems > UINT32_MAX / nelems)
334 nelems *= array->nelems;
335 type_id = array->type;
341 t = btf__type_by_id(btf, type_id);
347 if (nelems && size > UINT32_MAX / nelems)
350 return nelems * size;
353 int btf__align_of(const struct btf *btf, __u32 id)
355 const struct btf_type *t = btf__type_by_id(btf, id);
356 __u16 kind = btf_kind(t);
361 return min(btf_ptr_sz(btf), (size_t)t->size);
363 return btf_ptr_sz(btf);
364 case BTF_KIND_TYPEDEF:
365 case BTF_KIND_VOLATILE:
367 case BTF_KIND_RESTRICT:
368 return btf__align_of(btf, t->type);
370 return btf__align_of(btf, btf_array(t)->type);
371 case BTF_KIND_STRUCT:
372 case BTF_KIND_UNION: {
373 const struct btf_member *m = btf_members(t);
374 __u16 vlen = btf_vlen(t);
375 int i, max_align = 1, align;
377 for (i = 0; i < vlen; i++, m++) {
378 align = btf__align_of(btf, m->type);
381 max_align = max(max_align, align);
387 pr_warn("unsupported BTF_KIND:%u\n", btf_kind(t));
392 int btf__resolve_type(const struct btf *btf, __u32 type_id)
394 const struct btf_type *t;
397 t = btf__type_by_id(btf, type_id);
398 while (depth < MAX_RESOLVE_DEPTH &&
399 !btf_type_is_void_or_null(t) &&
400 (btf_is_mod(t) || btf_is_typedef(t) || btf_is_var(t))) {
402 t = btf__type_by_id(btf, type_id);
406 if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t))
412 __s32 btf__find_by_name(const struct btf *btf, const char *type_name)
416 if (!strcmp(type_name, "void"))
419 for (i = 1; i <= btf->nr_types; i++) {
420 const struct btf_type *t = btf->types[i];
421 const char *name = btf__name_by_offset(btf, t->name_off);
423 if (name && !strcmp(type_name, name))
430 __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,
435 if (kind == BTF_KIND_UNKN || !strcmp(type_name, "void"))
438 for (i = 1; i <= btf->nr_types; i++) {
439 const struct btf_type *t = btf->types[i];
442 if (btf_kind(t) != kind)
444 name = btf__name_by_offset(btf, t->name_off);
445 if (name && !strcmp(type_name, name))
452 void btf__free(struct btf *btf)
454 if (IS_ERR_OR_NULL(btf))
465 struct btf *btf__new(const void *data, __u32 size)
470 btf = calloc(1, sizeof(struct btf));
472 return ERR_PTR(-ENOMEM);
476 btf->data = malloc(size);
482 memcpy(btf->data, data, size);
483 btf->data_size = size;
485 err = btf_parse_hdr(btf);
489 err = btf_parse_str_sec(btf);
493 err = btf_parse_type_sec(btf);
504 static bool btf_check_endianness(const GElf_Ehdr *ehdr)
506 #if __BYTE_ORDER == __LITTLE_ENDIAN
507 return ehdr->e_ident[EI_DATA] == ELFDATA2LSB;
508 #elif __BYTE_ORDER == __BIG_ENDIAN
509 return ehdr->e_ident[EI_DATA] == ELFDATA2MSB;
511 # error "Unrecognized __BYTE_ORDER__"
515 struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext)
517 Elf_Data *btf_data = NULL, *btf_ext_data = NULL;
518 int err = 0, fd = -1, idx = 0;
519 struct btf *btf = NULL;
524 if (elf_version(EV_CURRENT) == EV_NONE) {
525 pr_warn("failed to init libelf for %s\n", path);
526 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
529 fd = open(path, O_RDONLY);
532 pr_warn("failed to open %s: %s\n", path, strerror(errno));
536 err = -LIBBPF_ERRNO__FORMAT;
538 elf = elf_begin(fd, ELF_C_READ, NULL);
540 pr_warn("failed to open %s as ELF file\n", path);
543 if (!gelf_getehdr(elf, &ehdr)) {
544 pr_warn("failed to get EHDR from %s\n", path);
547 if (!btf_check_endianness(&ehdr)) {
548 pr_warn("non-native ELF endianness is not supported\n");
551 if (!elf_rawdata(elf_getscn(elf, ehdr.e_shstrndx), NULL)) {
552 pr_warn("failed to get e_shstrndx from %s\n", path);
556 while ((scn = elf_nextscn(elf, scn)) != NULL) {
561 if (gelf_getshdr(scn, &sh) != &sh) {
562 pr_warn("failed to get section(%d) header from %s\n",
566 name = elf_strptr(elf, ehdr.e_shstrndx, sh.sh_name);
568 pr_warn("failed to get section(%d) name from %s\n",
572 if (strcmp(name, BTF_ELF_SEC) == 0) {
573 btf_data = elf_getdata(scn, 0);
575 pr_warn("failed to get section(%d, %s) data from %s\n",
580 } else if (btf_ext && strcmp(name, BTF_EXT_ELF_SEC) == 0) {
581 btf_ext_data = elf_getdata(scn, 0);
583 pr_warn("failed to get section(%d, %s) data from %s\n",
597 btf = btf__new(btf_data->d_buf, btf_data->d_size);
601 switch (gelf_getclass(elf)) {
603 btf__set_pointer_size(btf, 4);
606 btf__set_pointer_size(btf, 8);
609 pr_warn("failed to get ELF class (bitness) for %s\n", path);
613 if (btf_ext && btf_ext_data) {
614 *btf_ext = btf_ext__new(btf_ext_data->d_buf,
615 btf_ext_data->d_size);
616 if (IS_ERR(*btf_ext))
618 } else if (btf_ext) {
629 * btf is always parsed before btf_ext, so no need to clean up
630 * btf_ext, if btf loading failed
634 if (btf_ext && IS_ERR(*btf_ext)) {
636 err = PTR_ERR(*btf_ext);
642 struct btf *btf__parse_raw(const char *path)
644 struct btf *btf = NULL;
651 f = fopen(path, "rb");
657 /* check BTF magic */
658 if (fread(&magic, 1, sizeof(magic), f) < sizeof(magic)) {
662 if (magic != BTF_MAGIC) {
663 /* definitely not a raw BTF */
669 if (fseek(f, 0, SEEK_END)) {
678 /* rewind to the start */
679 if (fseek(f, 0, SEEK_SET)) {
684 /* pre-alloc memory and read all of BTF data */
690 if (fread(data, 1, sz, f) < sz) {
695 /* finally parse BTF data */
696 btf = btf__new(data, sz);
702 return err ? ERR_PTR(err) : btf;
705 struct btf *btf__parse(const char *path, struct btf_ext **btf_ext)
712 btf = btf__parse_raw(path);
713 if (!IS_ERR(btf) || PTR_ERR(btf) != -EPROTO)
716 return btf__parse_elf(path, btf_ext);
719 static int compare_vsi_off(const void *_a, const void *_b)
721 const struct btf_var_secinfo *a = _a;
722 const struct btf_var_secinfo *b = _b;
724 return a->offset - b->offset;
727 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
730 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
731 const char *name = btf__name_by_offset(btf, t->name_off);
732 const struct btf_type *t_var;
733 struct btf_var_secinfo *vsi;
734 const struct btf_var *var;
738 pr_debug("No name found in string section for DATASEC kind.\n");
742 /* .extern datasec size and var offsets were set correctly during
743 * extern collection step, so just skip straight to sorting variables
748 ret = bpf_object__section_size(obj, name, &size);
749 if (ret || !size || (t->size && t->size != size)) {
750 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
756 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
757 t_var = btf__type_by_id(btf, vsi->type);
758 var = btf_var(t_var);
760 if (!btf_is_var(t_var)) {
761 pr_debug("Non-VAR type seen in section %s\n", name);
765 if (var->linkage == BTF_VAR_STATIC)
768 name = btf__name_by_offset(btf, t_var->name_off);
770 pr_debug("No name found in string section for VAR kind\n");
774 ret = bpf_object__variable_offset(obj, name, &off);
776 pr_debug("No offset found in symbol table for VAR %s\n",
785 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
789 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
794 for (i = 1; i <= btf->nr_types; i++) {
795 struct btf_type *t = btf->types[i];
797 /* Loader needs to fix up some of the things compiler
798 * couldn't get its hands on while emitting BTF. This
799 * is section size and global variable offset. We use
800 * the info from the ELF itself for this purpose.
802 if (btf_is_datasec(t)) {
803 err = btf_fixup_datasec(obj, btf, t);
812 int btf__load(struct btf *btf)
814 __u32 log_buf_size = 0;
815 char *log_buf = NULL;
823 log_buf = malloc(log_buf_size);
830 btf->fd = bpf_load_btf(btf->data, btf->data_size,
831 log_buf, log_buf_size, false);
833 if (!log_buf || errno == ENOSPC) {
834 log_buf_size = max((__u32)BPF_LOG_BUF_SIZE,
841 pr_warn("Error loading BTF: %s(%d)\n", strerror(errno), errno);
843 pr_warn("%s\n", log_buf);
852 int btf__fd(const struct btf *btf)
857 void btf__set_fd(struct btf *btf, int fd)
862 const void *btf__get_raw_data(const struct btf *btf, __u32 *size)
864 *size = btf->data_size;
868 const char *btf__name_by_offset(const struct btf *btf, __u32 offset)
870 if (offset < btf->hdr->str_len)
871 return &btf->strings[offset];
876 int btf__get_from_id(__u32 id, struct btf **btf)
878 struct bpf_btf_info btf_info = { 0 };
879 __u32 len = sizeof(btf_info);
887 btf_fd = bpf_btf_get_fd_by_id(id);
891 /* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so
892 * let's start with a sane default - 4KiB here - and resize it only if
893 * bpf_obj_get_info_by_fd() needs a bigger buffer.
895 btf_info.btf_size = 4096;
896 last_size = btf_info.btf_size;
897 ptr = malloc(last_size);
903 memset(ptr, 0, last_size);
904 btf_info.btf = ptr_to_u64(ptr);
905 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
907 if (!err && btf_info.btf_size > last_size) {
910 last_size = btf_info.btf_size;
911 temp_ptr = realloc(ptr, last_size);
917 memset(ptr, 0, last_size);
918 btf_info.btf = ptr_to_u64(ptr);
919 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
922 if (err || btf_info.btf_size > last_size) {
927 *btf = btf__new((__u8 *)(long)btf_info.btf, btf_info.btf_size);
940 int btf__get_map_kv_tids(const struct btf *btf, const char *map_name,
941 __u32 expected_key_size, __u32 expected_value_size,
942 __u32 *key_type_id, __u32 *value_type_id)
944 const struct btf_type *container_type;
945 const struct btf_member *key, *value;
946 const size_t max_name = 256;
947 char container_name[max_name];
948 __s64 key_size, value_size;
951 if (snprintf(container_name, max_name, "____btf_map_%s", map_name) ==
953 pr_warn("map:%s length of '____btf_map_%s' is too long\n",
958 container_id = btf__find_by_name(btf, container_name);
959 if (container_id < 0) {
960 pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n",
961 map_name, container_name);
965 container_type = btf__type_by_id(btf, container_id);
966 if (!container_type) {
967 pr_warn("map:%s cannot find BTF type for container_id:%u\n",
968 map_name, container_id);
972 if (!btf_is_struct(container_type) || btf_vlen(container_type) < 2) {
973 pr_warn("map:%s container_name:%s is an invalid container struct\n",
974 map_name, container_name);
978 key = btf_members(container_type);
981 key_size = btf__resolve_size(btf, key->type);
983 pr_warn("map:%s invalid BTF key_type_size\n", map_name);
987 if (expected_key_size != key_size) {
988 pr_warn("map:%s btf_key_type_size:%u != map_def_key_size:%u\n",
989 map_name, (__u32)key_size, expected_key_size);
993 value_size = btf__resolve_size(btf, value->type);
994 if (value_size < 0) {
995 pr_warn("map:%s invalid BTF value_type_size\n", map_name);
999 if (expected_value_size != value_size) {
1000 pr_warn("map:%s btf_value_type_size:%u != map_def_value_size:%u\n",
1001 map_name, (__u32)value_size, expected_value_size);
1005 *key_type_id = key->type;
1006 *value_type_id = value->type;
1011 struct btf_ext_sec_setup_param {
1015 struct btf_ext_info *ext_info;
1019 static int btf_ext_setup_info(struct btf_ext *btf_ext,
1020 struct btf_ext_sec_setup_param *ext_sec)
1022 const struct btf_ext_info_sec *sinfo;
1023 struct btf_ext_info *ext_info;
1024 __u32 info_left, record_size;
1025 /* The start of the info sec (including the __u32 record_size). */
1028 if (ext_sec->len == 0)
1031 if (ext_sec->off & 0x03) {
1032 pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n",
1037 info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off;
1038 info_left = ext_sec->len;
1040 if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) {
1041 pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n",
1042 ext_sec->desc, ext_sec->off, ext_sec->len);
1046 /* At least a record size */
1047 if (info_left < sizeof(__u32)) {
1048 pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc);
1052 /* The record size needs to meet the minimum standard */
1053 record_size = *(__u32 *)info;
1054 if (record_size < ext_sec->min_rec_size ||
1055 record_size & 0x03) {
1056 pr_debug("%s section in .BTF.ext has invalid record size %u\n",
1057 ext_sec->desc, record_size);
1061 sinfo = info + sizeof(__u32);
1062 info_left -= sizeof(__u32);
1064 /* If no records, return failure now so .BTF.ext won't be used. */
1066 pr_debug("%s section in .BTF.ext has no records", ext_sec->desc);
1071 unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec);
1072 __u64 total_record_size;
1075 if (info_left < sec_hdrlen) {
1076 pr_debug("%s section header is not found in .BTF.ext\n",
1081 num_records = sinfo->num_info;
1082 if (num_records == 0) {
1083 pr_debug("%s section has incorrect num_records in .BTF.ext\n",
1088 total_record_size = sec_hdrlen +
1089 (__u64)num_records * record_size;
1090 if (info_left < total_record_size) {
1091 pr_debug("%s section has incorrect num_records in .BTF.ext\n",
1096 info_left -= total_record_size;
1097 sinfo = (void *)sinfo + total_record_size;
1100 ext_info = ext_sec->ext_info;
1101 ext_info->len = ext_sec->len - sizeof(__u32);
1102 ext_info->rec_size = record_size;
1103 ext_info->info = info + sizeof(__u32);
1108 static int btf_ext_setup_func_info(struct btf_ext *btf_ext)
1110 struct btf_ext_sec_setup_param param = {
1111 .off = btf_ext->hdr->func_info_off,
1112 .len = btf_ext->hdr->func_info_len,
1113 .min_rec_size = sizeof(struct bpf_func_info_min),
1114 .ext_info = &btf_ext->func_info,
1118 return btf_ext_setup_info(btf_ext, ¶m);
1121 static int btf_ext_setup_line_info(struct btf_ext *btf_ext)
1123 struct btf_ext_sec_setup_param param = {
1124 .off = btf_ext->hdr->line_info_off,
1125 .len = btf_ext->hdr->line_info_len,
1126 .min_rec_size = sizeof(struct bpf_line_info_min),
1127 .ext_info = &btf_ext->line_info,
1128 .desc = "line_info",
1131 return btf_ext_setup_info(btf_ext, ¶m);
1134 static int btf_ext_setup_field_reloc(struct btf_ext *btf_ext)
1136 struct btf_ext_sec_setup_param param = {
1137 .off = btf_ext->hdr->field_reloc_off,
1138 .len = btf_ext->hdr->field_reloc_len,
1139 .min_rec_size = sizeof(struct bpf_field_reloc),
1140 .ext_info = &btf_ext->field_reloc_info,
1141 .desc = "field_reloc",
1144 return btf_ext_setup_info(btf_ext, ¶m);
1147 static int btf_ext_parse_hdr(__u8 *data, __u32 data_size)
1149 const struct btf_ext_header *hdr = (struct btf_ext_header *)data;
1151 if (data_size < offsetofend(struct btf_ext_header, hdr_len) ||
1152 data_size < hdr->hdr_len) {
1153 pr_debug("BTF.ext header not found");
1157 if (hdr->magic != BTF_MAGIC) {
1158 pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic);
1162 if (hdr->version != BTF_VERSION) {
1163 pr_debug("Unsupported BTF.ext version:%u\n", hdr->version);
1168 pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags);
1172 if (data_size == hdr->hdr_len) {
1173 pr_debug("BTF.ext has no data\n");
1180 void btf_ext__free(struct btf_ext *btf_ext)
1182 if (IS_ERR_OR_NULL(btf_ext))
1184 free(btf_ext->data);
1188 struct btf_ext *btf_ext__new(__u8 *data, __u32 size)
1190 struct btf_ext *btf_ext;
1193 err = btf_ext_parse_hdr(data, size);
1195 return ERR_PTR(err);
1197 btf_ext = calloc(1, sizeof(struct btf_ext));
1199 return ERR_PTR(-ENOMEM);
1201 btf_ext->data_size = size;
1202 btf_ext->data = malloc(size);
1203 if (!btf_ext->data) {
1207 memcpy(btf_ext->data, data, size);
1209 if (btf_ext->hdr->hdr_len <
1210 offsetofend(struct btf_ext_header, line_info_len))
1212 err = btf_ext_setup_func_info(btf_ext);
1216 err = btf_ext_setup_line_info(btf_ext);
1220 if (btf_ext->hdr->hdr_len <
1221 offsetofend(struct btf_ext_header, field_reloc_len))
1223 err = btf_ext_setup_field_reloc(btf_ext);
1229 btf_ext__free(btf_ext);
1230 return ERR_PTR(err);
1236 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size)
1238 *size = btf_ext->data_size;
1239 return btf_ext->data;
1242 static int btf_ext_reloc_info(const struct btf *btf,
1243 const struct btf_ext_info *ext_info,
1244 const char *sec_name, __u32 insns_cnt,
1245 void **info, __u32 *cnt)
1247 __u32 sec_hdrlen = sizeof(struct btf_ext_info_sec);
1248 __u32 i, record_size, existing_len, records_len;
1249 struct btf_ext_info_sec *sinfo;
1250 const char *info_sec_name;
1254 record_size = ext_info->rec_size;
1255 sinfo = ext_info->info;
1256 remain_len = ext_info->len;
1257 while (remain_len > 0) {
1258 records_len = sinfo->num_info * record_size;
1259 info_sec_name = btf__name_by_offset(btf, sinfo->sec_name_off);
1260 if (strcmp(info_sec_name, sec_name)) {
1261 remain_len -= sec_hdrlen + records_len;
1262 sinfo = (void *)sinfo + sec_hdrlen + records_len;
1266 existing_len = (*cnt) * record_size;
1267 data = realloc(*info, existing_len + records_len);
1271 memcpy(data + existing_len, sinfo->data, records_len);
1272 /* adjust insn_off only, the rest data will be passed
1275 for (i = 0; i < sinfo->num_info; i++) {
1278 insn_off = data + existing_len + (i * record_size);
1279 *insn_off = *insn_off / sizeof(struct bpf_insn) +
1283 *cnt += sinfo->num_info;
1290 int btf_ext__reloc_func_info(const struct btf *btf,
1291 const struct btf_ext *btf_ext,
1292 const char *sec_name, __u32 insns_cnt,
1293 void **func_info, __u32 *cnt)
1295 return btf_ext_reloc_info(btf, &btf_ext->func_info, sec_name,
1296 insns_cnt, func_info, cnt);
1299 int btf_ext__reloc_line_info(const struct btf *btf,
1300 const struct btf_ext *btf_ext,
1301 const char *sec_name, __u32 insns_cnt,
1302 void **line_info, __u32 *cnt)
1304 return btf_ext_reloc_info(btf, &btf_ext->line_info, sec_name,
1305 insns_cnt, line_info, cnt);
1308 __u32 btf_ext__func_info_rec_size(const struct btf_ext *btf_ext)
1310 return btf_ext->func_info.rec_size;
1313 __u32 btf_ext__line_info_rec_size(const struct btf_ext *btf_ext)
1315 return btf_ext->line_info.rec_size;
1320 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
1321 const struct btf_dedup_opts *opts);
1322 static void btf_dedup_free(struct btf_dedup *d);
1323 static int btf_dedup_strings(struct btf_dedup *d);
1324 static int btf_dedup_prim_types(struct btf_dedup *d);
1325 static int btf_dedup_struct_types(struct btf_dedup *d);
1326 static int btf_dedup_ref_types(struct btf_dedup *d);
1327 static int btf_dedup_compact_types(struct btf_dedup *d);
1328 static int btf_dedup_remap_types(struct btf_dedup *d);
1331 * Deduplicate BTF types and strings.
1333 * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF
1334 * section with all BTF type descriptors and string data. It overwrites that
1335 * memory in-place with deduplicated types and strings without any loss of
1336 * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section
1337 * is provided, all the strings referenced from .BTF.ext section are honored
1338 * and updated to point to the right offsets after deduplication.
1340 * If function returns with error, type/string data might be garbled and should
1343 * More verbose and detailed description of both problem btf_dedup is solving,
1344 * as well as solution could be found at:
1345 * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html
1347 * Problem description and justification
1348 * =====================================
1350 * BTF type information is typically emitted either as a result of conversion
1351 * from DWARF to BTF or directly by compiler. In both cases, each compilation
1352 * unit contains information about a subset of all the types that are used
1353 * in an application. These subsets are frequently overlapping and contain a lot
1354 * of duplicated information when later concatenated together into a single
1355 * binary. This algorithm ensures that each unique type is represented by single
1356 * BTF type descriptor, greatly reducing resulting size of BTF data.
1358 * Compilation unit isolation and subsequent duplication of data is not the only
1359 * problem. The same type hierarchy (e.g., struct and all the type that struct
1360 * references) in different compilation units can be represented in BTF to
1361 * various degrees of completeness (or, rather, incompleteness) due to
1362 * struct/union forward declarations.
1364 * Let's take a look at an example, that we'll use to better understand the
1365 * problem (and solution). Suppose we have two compilation units, each using
1366 * same `struct S`, but each of them having incomplete type information about
1395 * In case of CU #1, BTF data will know only that `struct B` exist (but no
1396 * more), but will know the complete type information about `struct A`. While
1397 * for CU #2, it will know full type information about `struct B`, but will
1398 * only know about forward declaration of `struct A` (in BTF terms, it will
1399 * have `BTF_KIND_FWD` type descriptor with name `B`).
1401 * This compilation unit isolation means that it's possible that there is no
1402 * single CU with complete type information describing structs `S`, `A`, and
1403 * `B`. Also, we might get tons of duplicated and redundant type information.
1405 * Additional complication we need to keep in mind comes from the fact that
1406 * types, in general, can form graphs containing cycles, not just DAGs.
1408 * While algorithm does deduplication, it also merges and resolves type
1409 * information (unless disabled throught `struct btf_opts`), whenever possible.
1410 * E.g., in the example above with two compilation units having partial type
1411 * information for structs `A` and `B`, the output of algorithm will emit
1412 * a single copy of each BTF type that describes structs `A`, `B`, and `S`
1413 * (as well as type information for `int` and pointers), as if they were defined
1414 * in a single compilation unit as:
1434 * Algorithm completes its work in 6 separate passes:
1436 * 1. Strings deduplication.
1437 * 2. Primitive types deduplication (int, enum, fwd).
1438 * 3. Struct/union types deduplication.
1439 * 4. Reference types deduplication (pointers, typedefs, arrays, funcs, func
1440 * protos, and const/volatile/restrict modifiers).
1441 * 5. Types compaction.
1442 * 6. Types remapping.
1444 * Algorithm determines canonical type descriptor, which is a single
1445 * representative type for each truly unique type. This canonical type is the
1446 * one that will go into final deduplicated BTF type information. For
1447 * struct/unions, it is also the type that algorithm will merge additional type
1448 * information into (while resolving FWDs), as it discovers it from data in
1449 * other CUs. Each input BTF type eventually gets either mapped to itself, if
1450 * that type is canonical, or to some other type, if that type is equivalent
1451 * and was chosen as canonical representative. This mapping is stored in
1452 * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that
1453 * FWD type got resolved to.
1455 * To facilitate fast discovery of canonical types, we also maintain canonical
1456 * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash
1457 * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types
1458 * that match that signature. With sufficiently good choice of type signature
1459 * hashing function, we can limit number of canonical types for each unique type
1460 * signature to a very small number, allowing to find canonical type for any
1461 * duplicated type very quickly.
1463 * Struct/union deduplication is the most critical part and algorithm for
1464 * deduplicating structs/unions is described in greater details in comments for
1465 * `btf_dedup_is_equiv` function.
1467 int btf__dedup(struct btf *btf, struct btf_ext *btf_ext,
1468 const struct btf_dedup_opts *opts)
1470 struct btf_dedup *d = btf_dedup_new(btf, btf_ext, opts);
1474 pr_debug("btf_dedup_new failed: %ld", PTR_ERR(d));
1478 err = btf_dedup_strings(d);
1480 pr_debug("btf_dedup_strings failed:%d\n", err);
1483 err = btf_dedup_prim_types(d);
1485 pr_debug("btf_dedup_prim_types failed:%d\n", err);
1488 err = btf_dedup_struct_types(d);
1490 pr_debug("btf_dedup_struct_types failed:%d\n", err);
1493 err = btf_dedup_ref_types(d);
1495 pr_debug("btf_dedup_ref_types failed:%d\n", err);
1498 err = btf_dedup_compact_types(d);
1500 pr_debug("btf_dedup_compact_types failed:%d\n", err);
1503 err = btf_dedup_remap_types(d);
1505 pr_debug("btf_dedup_remap_types failed:%d\n", err);
1514 #define BTF_UNPROCESSED_ID ((__u32)-1)
1515 #define BTF_IN_PROGRESS_ID ((__u32)-2)
1518 /* .BTF section to be deduped in-place */
1521 * Optional .BTF.ext section. When provided, any strings referenced
1522 * from it will be taken into account when deduping strings
1524 struct btf_ext *btf_ext;
1526 * This is a map from any type's signature hash to a list of possible
1527 * canonical representative type candidates. Hash collisions are
1528 * ignored, so even types of various kinds can share same list of
1529 * candidates, which is fine because we rely on subsequent
1530 * btf_xxx_equal() checks to authoritatively verify type equality.
1532 struct hashmap *dedup_table;
1533 /* Canonical types map */
1535 /* Hypothetical mapping, used during type graph equivalence checks */
1540 /* Various option modifying behavior of algorithm */
1541 struct btf_dedup_opts opts;
1544 struct btf_str_ptr {
1550 struct btf_str_ptrs {
1551 struct btf_str_ptr *ptrs;
1557 static long hash_combine(long h, long value)
1559 return h * 31 + value;
1562 #define for_each_dedup_cand(d, node, hash) \
1563 hashmap__for_each_key_entry(d->dedup_table, node, (void *)hash)
1565 static int btf_dedup_table_add(struct btf_dedup *d, long hash, __u32 type_id)
1567 return hashmap__append(d->dedup_table,
1568 (void *)hash, (void *)(long)type_id);
1571 static int btf_dedup_hypot_map_add(struct btf_dedup *d,
1572 __u32 from_id, __u32 to_id)
1574 if (d->hypot_cnt == d->hypot_cap) {
1577 d->hypot_cap += max((size_t)16, d->hypot_cap / 2);
1578 new_list = realloc(d->hypot_list, sizeof(__u32) * d->hypot_cap);
1581 d->hypot_list = new_list;
1583 d->hypot_list[d->hypot_cnt++] = from_id;
1584 d->hypot_map[from_id] = to_id;
1588 static void btf_dedup_clear_hypot_map(struct btf_dedup *d)
1592 for (i = 0; i < d->hypot_cnt; i++)
1593 d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID;
1597 static void btf_dedup_free(struct btf_dedup *d)
1599 hashmap__free(d->dedup_table);
1600 d->dedup_table = NULL;
1606 d->hypot_map = NULL;
1608 free(d->hypot_list);
1609 d->hypot_list = NULL;
1614 static size_t btf_dedup_identity_hash_fn(const void *key, void *ctx)
1619 static size_t btf_dedup_collision_hash_fn(const void *key, void *ctx)
1624 static bool btf_dedup_equal_fn(const void *k1, const void *k2, void *ctx)
1629 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
1630 const struct btf_dedup_opts *opts)
1632 struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup));
1633 hashmap_hash_fn hash_fn = btf_dedup_identity_hash_fn;
1637 return ERR_PTR(-ENOMEM);
1639 d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds;
1640 /* dedup_table_size is now used only to force collisions in tests */
1641 if (opts && opts->dedup_table_size == 1)
1642 hash_fn = btf_dedup_collision_hash_fn;
1645 d->btf_ext = btf_ext;
1647 d->dedup_table = hashmap__new(hash_fn, btf_dedup_equal_fn, NULL);
1648 if (IS_ERR(d->dedup_table)) {
1649 err = PTR_ERR(d->dedup_table);
1650 d->dedup_table = NULL;
1654 d->map = malloc(sizeof(__u32) * (1 + btf->nr_types));
1659 /* special BTF "void" type is made canonical immediately */
1661 for (i = 1; i <= btf->nr_types; i++) {
1662 struct btf_type *t = d->btf->types[i];
1664 /* VAR and DATASEC are never deduped and are self-canonical */
1665 if (btf_is_var(t) || btf_is_datasec(t))
1668 d->map[i] = BTF_UNPROCESSED_ID;
1671 d->hypot_map = malloc(sizeof(__u32) * (1 + btf->nr_types));
1672 if (!d->hypot_map) {
1676 for (i = 0; i <= btf->nr_types; i++)
1677 d->hypot_map[i] = BTF_UNPROCESSED_ID;
1682 return ERR_PTR(err);
1688 typedef int (*str_off_fn_t)(__u32 *str_off_ptr, void *ctx);
1691 * Iterate over all possible places in .BTF and .BTF.ext that can reference
1692 * string and pass pointer to it to a provided callback `fn`.
1694 static int btf_for_each_str_off(struct btf_dedup *d, str_off_fn_t fn, void *ctx)
1696 void *line_data_cur, *line_data_end;
1697 int i, j, r, rec_size;
1700 for (i = 1; i <= d->btf->nr_types; i++) {
1701 t = d->btf->types[i];
1702 r = fn(&t->name_off, ctx);
1706 switch (btf_kind(t)) {
1707 case BTF_KIND_STRUCT:
1708 case BTF_KIND_UNION: {
1709 struct btf_member *m = btf_members(t);
1710 __u16 vlen = btf_vlen(t);
1712 for (j = 0; j < vlen; j++) {
1713 r = fn(&m->name_off, ctx);
1720 case BTF_KIND_ENUM: {
1721 struct btf_enum *m = btf_enum(t);
1722 __u16 vlen = btf_vlen(t);
1724 for (j = 0; j < vlen; j++) {
1725 r = fn(&m->name_off, ctx);
1732 case BTF_KIND_FUNC_PROTO: {
1733 struct btf_param *m = btf_params(t);
1734 __u16 vlen = btf_vlen(t);
1736 for (j = 0; j < vlen; j++) {
1737 r = fn(&m->name_off, ctx);
1752 line_data_cur = d->btf_ext->line_info.info;
1753 line_data_end = d->btf_ext->line_info.info + d->btf_ext->line_info.len;
1754 rec_size = d->btf_ext->line_info.rec_size;
1756 while (line_data_cur < line_data_end) {
1757 struct btf_ext_info_sec *sec = line_data_cur;
1758 struct bpf_line_info_min *line_info;
1759 __u32 num_info = sec->num_info;
1761 r = fn(&sec->sec_name_off, ctx);
1765 line_data_cur += sizeof(struct btf_ext_info_sec);
1766 for (i = 0; i < num_info; i++) {
1767 line_info = line_data_cur;
1768 r = fn(&line_info->file_name_off, ctx);
1771 r = fn(&line_info->line_off, ctx);
1774 line_data_cur += rec_size;
1781 static int str_sort_by_content(const void *a1, const void *a2)
1783 const struct btf_str_ptr *p1 = a1;
1784 const struct btf_str_ptr *p2 = a2;
1786 return strcmp(p1->str, p2->str);
1789 static int str_sort_by_offset(const void *a1, const void *a2)
1791 const struct btf_str_ptr *p1 = a1;
1792 const struct btf_str_ptr *p2 = a2;
1794 if (p1->str != p2->str)
1795 return p1->str < p2->str ? -1 : 1;
1799 static int btf_dedup_str_ptr_cmp(const void *str_ptr, const void *pelem)
1801 const struct btf_str_ptr *p = pelem;
1803 if (str_ptr != p->str)
1804 return (const char *)str_ptr < p->str ? -1 : 1;
1808 static int btf_str_mark_as_used(__u32 *str_off_ptr, void *ctx)
1810 struct btf_str_ptrs *strs;
1811 struct btf_str_ptr *s;
1813 if (*str_off_ptr == 0)
1817 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt,
1818 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp);
1825 static int btf_str_remap_offset(__u32 *str_off_ptr, void *ctx)
1827 struct btf_str_ptrs *strs;
1828 struct btf_str_ptr *s;
1830 if (*str_off_ptr == 0)
1834 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt,
1835 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp);
1838 *str_off_ptr = s->new_off;
1843 * Dedup string and filter out those that are not referenced from either .BTF
1844 * or .BTF.ext (if provided) sections.
1846 * This is done by building index of all strings in BTF's string section,
1847 * then iterating over all entities that can reference strings (e.g., type
1848 * names, struct field names, .BTF.ext line info, etc) and marking corresponding
1849 * strings as used. After that all used strings are deduped and compacted into
1850 * sequential blob of memory and new offsets are calculated. Then all the string
1851 * references are iterated again and rewritten using new offsets.
1853 static int btf_dedup_strings(struct btf_dedup *d)
1855 const struct btf_header *hdr = d->btf->hdr;
1856 char *start = (char *)d->btf->nohdr_data + hdr->str_off;
1857 char *end = start + d->btf->hdr->str_len;
1858 char *p = start, *tmp_strs = NULL;
1859 struct btf_str_ptrs strs = {
1865 int i, j, err = 0, grp_idx;
1868 /* build index of all strings */
1870 if (strs.cnt + 1 > strs.cap) {
1871 struct btf_str_ptr *new_ptrs;
1873 strs.cap += max(strs.cnt / 2, 16U);
1874 new_ptrs = realloc(strs.ptrs,
1875 sizeof(strs.ptrs[0]) * strs.cap);
1880 strs.ptrs = new_ptrs;
1883 strs.ptrs[strs.cnt].str = p;
1884 strs.ptrs[strs.cnt].used = false;
1890 /* temporary storage for deduplicated strings */
1891 tmp_strs = malloc(d->btf->hdr->str_len);
1897 /* mark all used strings */
1898 strs.ptrs[0].used = true;
1899 err = btf_for_each_str_off(d, btf_str_mark_as_used, &strs);
1903 /* sort strings by context, so that we can identify duplicates */
1904 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_content);
1907 * iterate groups of equal strings and if any instance in a group was
1908 * referenced, emit single instance and remember new offset
1912 grp_used = strs.ptrs[0].used;
1913 /* iterate past end to avoid code duplication after loop */
1914 for (i = 1; i <= strs.cnt; i++) {
1916 * when i == strs.cnt, we want to skip string comparison and go
1917 * straight to handling last group of strings (otherwise we'd
1918 * need to handle last group after the loop w/ duplicated code)
1921 !strcmp(strs.ptrs[i].str, strs.ptrs[grp_idx].str)) {
1922 grp_used = grp_used || strs.ptrs[i].used;
1927 * this check would have been required after the loop to handle
1928 * last group of strings, but due to <= condition in a loop
1929 * we avoid that duplication
1932 int new_off = p - tmp_strs;
1933 __u32 len = strlen(strs.ptrs[grp_idx].str);
1935 memmove(p, strs.ptrs[grp_idx].str, len + 1);
1936 for (j = grp_idx; j < i; j++)
1937 strs.ptrs[j].new_off = new_off;
1943 grp_used = strs.ptrs[i].used;
1947 /* replace original strings with deduped ones */
1948 d->btf->hdr->str_len = p - tmp_strs;
1949 memmove(start, tmp_strs, d->btf->hdr->str_len);
1950 end = start + d->btf->hdr->str_len;
1952 /* restore original order for further binary search lookups */
1953 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_offset);
1955 /* remap string offsets */
1956 err = btf_for_each_str_off(d, btf_str_remap_offset, &strs);
1960 d->btf->hdr->str_len = end - start;
1968 static long btf_hash_common(struct btf_type *t)
1972 h = hash_combine(0, t->name_off);
1973 h = hash_combine(h, t->info);
1974 h = hash_combine(h, t->size);
1978 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2)
1980 return t1->name_off == t2->name_off &&
1981 t1->info == t2->info &&
1982 t1->size == t2->size;
1985 /* Calculate type signature hash of INT. */
1986 static long btf_hash_int(struct btf_type *t)
1988 __u32 info = *(__u32 *)(t + 1);
1991 h = btf_hash_common(t);
1992 h = hash_combine(h, info);
1996 /* Check structural equality of two INTs. */
1997 static bool btf_equal_int(struct btf_type *t1, struct btf_type *t2)
2001 if (!btf_equal_common(t1, t2))
2003 info1 = *(__u32 *)(t1 + 1);
2004 info2 = *(__u32 *)(t2 + 1);
2005 return info1 == info2;
2008 /* Calculate type signature hash of ENUM. */
2009 static long btf_hash_enum(struct btf_type *t)
2013 /* don't hash vlen and enum members to support enum fwd resolving */
2014 h = hash_combine(0, t->name_off);
2015 h = hash_combine(h, t->info & ~0xffff);
2016 h = hash_combine(h, t->size);
2020 /* Check structural equality of two ENUMs. */
2021 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2)
2023 const struct btf_enum *m1, *m2;
2027 if (!btf_equal_common(t1, t2))
2030 vlen = btf_vlen(t1);
2033 for (i = 0; i < vlen; i++) {
2034 if (m1->name_off != m2->name_off || m1->val != m2->val)
2042 static inline bool btf_is_enum_fwd(struct btf_type *t)
2044 return btf_is_enum(t) && btf_vlen(t) == 0;
2047 static bool btf_compat_enum(struct btf_type *t1, struct btf_type *t2)
2049 if (!btf_is_enum_fwd(t1) && !btf_is_enum_fwd(t2))
2050 return btf_equal_enum(t1, t2);
2051 /* ignore vlen when comparing */
2052 return t1->name_off == t2->name_off &&
2053 (t1->info & ~0xffff) == (t2->info & ~0xffff) &&
2054 t1->size == t2->size;
2058 * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs,
2059 * as referenced type IDs equivalence is established separately during type
2060 * graph equivalence check algorithm.
2062 static long btf_hash_struct(struct btf_type *t)
2064 const struct btf_member *member = btf_members(t);
2065 __u32 vlen = btf_vlen(t);
2066 long h = btf_hash_common(t);
2069 for (i = 0; i < vlen; i++) {
2070 h = hash_combine(h, member->name_off);
2071 h = hash_combine(h, member->offset);
2072 /* no hashing of referenced type ID, it can be unresolved yet */
2079 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
2080 * IDs. This check is performed during type graph equivalence check and
2081 * referenced types equivalence is checked separately.
2083 static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2)
2085 const struct btf_member *m1, *m2;
2089 if (!btf_equal_common(t1, t2))
2092 vlen = btf_vlen(t1);
2093 m1 = btf_members(t1);
2094 m2 = btf_members(t2);
2095 for (i = 0; i < vlen; i++) {
2096 if (m1->name_off != m2->name_off || m1->offset != m2->offset)
2105 * Calculate type signature hash of ARRAY, including referenced type IDs,
2106 * under assumption that they were already resolved to canonical type IDs and
2107 * are not going to change.
2109 static long btf_hash_array(struct btf_type *t)
2111 const struct btf_array *info = btf_array(t);
2112 long h = btf_hash_common(t);
2114 h = hash_combine(h, info->type);
2115 h = hash_combine(h, info->index_type);
2116 h = hash_combine(h, info->nelems);
2121 * Check exact equality of two ARRAYs, taking into account referenced
2122 * type IDs, under assumption that they were already resolved to canonical
2123 * type IDs and are not going to change.
2124 * This function is called during reference types deduplication to compare
2125 * ARRAY to potential canonical representative.
2127 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2)
2129 const struct btf_array *info1, *info2;
2131 if (!btf_equal_common(t1, t2))
2134 info1 = btf_array(t1);
2135 info2 = btf_array(t2);
2136 return info1->type == info2->type &&
2137 info1->index_type == info2->index_type &&
2138 info1->nelems == info2->nelems;
2142 * Check structural compatibility of two ARRAYs, ignoring referenced type
2143 * IDs. This check is performed during type graph equivalence check and
2144 * referenced types equivalence is checked separately.
2146 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2)
2148 if (!btf_equal_common(t1, t2))
2151 return btf_array(t1)->nelems == btf_array(t2)->nelems;
2155 * Calculate type signature hash of FUNC_PROTO, including referenced type IDs,
2156 * under assumption that they were already resolved to canonical type IDs and
2157 * are not going to change.
2159 static long btf_hash_fnproto(struct btf_type *t)
2161 const struct btf_param *member = btf_params(t);
2162 __u16 vlen = btf_vlen(t);
2163 long h = btf_hash_common(t);
2166 for (i = 0; i < vlen; i++) {
2167 h = hash_combine(h, member->name_off);
2168 h = hash_combine(h, member->type);
2175 * Check exact equality of two FUNC_PROTOs, taking into account referenced
2176 * type IDs, under assumption that they were already resolved to canonical
2177 * type IDs and are not going to change.
2178 * This function is called during reference types deduplication to compare
2179 * FUNC_PROTO to potential canonical representative.
2181 static bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2)
2183 const struct btf_param *m1, *m2;
2187 if (!btf_equal_common(t1, t2))
2190 vlen = btf_vlen(t1);
2191 m1 = btf_params(t1);
2192 m2 = btf_params(t2);
2193 for (i = 0; i < vlen; i++) {
2194 if (m1->name_off != m2->name_off || m1->type != m2->type)
2203 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
2204 * IDs. This check is performed during type graph equivalence check and
2205 * referenced types equivalence is checked separately.
2207 static bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2)
2209 const struct btf_param *m1, *m2;
2213 /* skip return type ID */
2214 if (t1->name_off != t2->name_off || t1->info != t2->info)
2217 vlen = btf_vlen(t1);
2218 m1 = btf_params(t1);
2219 m2 = btf_params(t2);
2220 for (i = 0; i < vlen; i++) {
2221 if (m1->name_off != m2->name_off)
2230 * Deduplicate primitive types, that can't reference other types, by calculating
2231 * their type signature hash and comparing them with any possible canonical
2232 * candidate. If no canonical candidate matches, type itself is marked as
2233 * canonical and is added into `btf_dedup->dedup_table` as another candidate.
2235 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id)
2237 struct btf_type *t = d->btf->types[type_id];
2238 struct hashmap_entry *hash_entry;
2239 struct btf_type *cand;
2240 /* if we don't find equivalent type, then we are canonical */
2241 __u32 new_id = type_id;
2245 switch (btf_kind(t)) {
2246 case BTF_KIND_CONST:
2247 case BTF_KIND_VOLATILE:
2248 case BTF_KIND_RESTRICT:
2250 case BTF_KIND_TYPEDEF:
2251 case BTF_KIND_ARRAY:
2252 case BTF_KIND_STRUCT:
2253 case BTF_KIND_UNION:
2255 case BTF_KIND_FUNC_PROTO:
2257 case BTF_KIND_DATASEC:
2261 h = btf_hash_int(t);
2262 for_each_dedup_cand(d, hash_entry, h) {
2263 cand_id = (__u32)(long)hash_entry->value;
2264 cand = d->btf->types[cand_id];
2265 if (btf_equal_int(t, cand)) {
2273 h = btf_hash_enum(t);
2274 for_each_dedup_cand(d, hash_entry, h) {
2275 cand_id = (__u32)(long)hash_entry->value;
2276 cand = d->btf->types[cand_id];
2277 if (btf_equal_enum(t, cand)) {
2281 if (d->opts.dont_resolve_fwds)
2283 if (btf_compat_enum(t, cand)) {
2284 if (btf_is_enum_fwd(t)) {
2285 /* resolve fwd to full enum */
2289 /* resolve canonical enum fwd to full enum */
2290 d->map[cand_id] = type_id;
2296 h = btf_hash_common(t);
2297 for_each_dedup_cand(d, hash_entry, h) {
2298 cand_id = (__u32)(long)hash_entry->value;
2299 cand = d->btf->types[cand_id];
2300 if (btf_equal_common(t, cand)) {
2311 d->map[type_id] = new_id;
2312 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
2318 static int btf_dedup_prim_types(struct btf_dedup *d)
2322 for (i = 1; i <= d->btf->nr_types; i++) {
2323 err = btf_dedup_prim_type(d, i);
2331 * Check whether type is already mapped into canonical one (could be to itself).
2333 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id)
2335 return d->map[type_id] <= BTF_MAX_NR_TYPES;
2339 * Resolve type ID into its canonical type ID, if any; otherwise return original
2340 * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow
2341 * STRUCT/UNION link and resolve it into canonical type ID as well.
2343 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id)
2345 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
2346 type_id = d->map[type_id];
2351 * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original
2354 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id)
2356 __u32 orig_type_id = type_id;
2358 if (!btf_is_fwd(d->btf->types[type_id]))
2361 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
2362 type_id = d->map[type_id];
2364 if (!btf_is_fwd(d->btf->types[type_id]))
2367 return orig_type_id;
2371 static inline __u16 btf_fwd_kind(struct btf_type *t)
2373 return btf_kflag(t) ? BTF_KIND_UNION : BTF_KIND_STRUCT;
2377 * Check equivalence of BTF type graph formed by candidate struct/union (we'll
2378 * call it "candidate graph" in this description for brevity) to a type graph
2379 * formed by (potential) canonical struct/union ("canonical graph" for brevity
2380 * here, though keep in mind that not all types in canonical graph are
2381 * necessarily canonical representatives themselves, some of them might be
2382 * duplicates or its uniqueness might not have been established yet).
2384 * - >0, if type graphs are equivalent;
2385 * - 0, if not equivalent;
2388 * Algorithm performs side-by-side DFS traversal of both type graphs and checks
2389 * equivalence of BTF types at each step. If at any point BTF types in candidate
2390 * and canonical graphs are not compatible structurally, whole graphs are
2391 * incompatible. If types are structurally equivalent (i.e., all information
2392 * except referenced type IDs is exactly the same), a mapping from `canon_id` to
2393 * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`).
2394 * If a type references other types, then those referenced types are checked
2395 * for equivalence recursively.
2397 * During DFS traversal, if we find that for current `canon_id` type we
2398 * already have some mapping in hypothetical map, we check for two possible
2400 * - `canon_id` is mapped to exactly the same type as `cand_id`. This will
2401 * happen when type graphs have cycles. In this case we assume those two
2402 * types are equivalent.
2403 * - `canon_id` is mapped to different type. This is contradiction in our
2404 * hypothetical mapping, because same graph in canonical graph corresponds
2405 * to two different types in candidate graph, which for equivalent type
2406 * graphs shouldn't happen. This condition terminates equivalence check
2407 * with negative result.
2409 * If type graphs traversal exhausts types to check and find no contradiction,
2410 * then type graphs are equivalent.
2412 * When checking types for equivalence, there is one special case: FWD types.
2413 * If FWD type resolution is allowed and one of the types (either from canonical
2414 * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind
2415 * flag) and their names match, hypothetical mapping is updated to point from
2416 * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully,
2417 * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently.
2419 * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution,
2420 * if there are two exactly named (or anonymous) structs/unions that are
2421 * compatible structurally, one of which has FWD field, while other is concrete
2422 * STRUCT/UNION, but according to C sources they are different structs/unions
2423 * that are referencing different types with the same name. This is extremely
2424 * unlikely to happen, but btf_dedup API allows to disable FWD resolution if
2425 * this logic is causing problems.
2427 * Doing FWD resolution means that both candidate and/or canonical graphs can
2428 * consists of portions of the graph that come from multiple compilation units.
2429 * This is due to the fact that types within single compilation unit are always
2430 * deduplicated and FWDs are already resolved, if referenced struct/union
2431 * definiton is available. So, if we had unresolved FWD and found corresponding
2432 * STRUCT/UNION, they will be from different compilation units. This
2433 * consequently means that when we "link" FWD to corresponding STRUCT/UNION,
2434 * type graph will likely have at least two different BTF types that describe
2435 * same type (e.g., most probably there will be two different BTF types for the
2436 * same 'int' primitive type) and could even have "overlapping" parts of type
2437 * graph that describe same subset of types.
2439 * This in turn means that our assumption that each type in canonical graph
2440 * must correspond to exactly one type in candidate graph might not hold
2441 * anymore and will make it harder to detect contradictions using hypothetical
2442 * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION
2443 * resolution only in canonical graph. FWDs in candidate graphs are never
2444 * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs
2446 * - Both types in canonical and candidate graphs are FWDs. If they are
2447 * structurally equivalent, then they can either be both resolved to the
2448 * same STRUCT/UNION or not resolved at all. In both cases they are
2449 * equivalent and there is no need to resolve FWD on candidate side.
2450 * - Both types in canonical and candidate graphs are concrete STRUCT/UNION,
2451 * so nothing to resolve as well, algorithm will check equivalence anyway.
2452 * - Type in canonical graph is FWD, while type in candidate is concrete
2453 * STRUCT/UNION. In this case candidate graph comes from single compilation
2454 * unit, so there is exactly one BTF type for each unique C type. After
2455 * resolving FWD into STRUCT/UNION, there might be more than one BTF type
2456 * in canonical graph mapping to single BTF type in candidate graph, but
2457 * because hypothetical mapping maps from canonical to candidate types, it's
2458 * alright, and we still maintain the property of having single `canon_id`
2459 * mapping to single `cand_id` (there could be two different `canon_id`
2460 * mapped to the same `cand_id`, but it's not contradictory).
2461 * - Type in canonical graph is concrete STRUCT/UNION, while type in candidate
2462 * graph is FWD. In this case we are just going to check compatibility of
2463 * STRUCT/UNION and corresponding FWD, and if they are compatible, we'll
2464 * assume that whatever STRUCT/UNION FWD resolves to must be equivalent to
2465 * a concrete STRUCT/UNION from canonical graph. If the rest of type graphs
2466 * turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from
2469 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id,
2472 struct btf_type *cand_type;
2473 struct btf_type *canon_type;
2474 __u32 hypot_type_id;
2479 /* if both resolve to the same canonical, they must be equivalent */
2480 if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id))
2483 canon_id = resolve_fwd_id(d, canon_id);
2485 hypot_type_id = d->hypot_map[canon_id];
2486 if (hypot_type_id <= BTF_MAX_NR_TYPES)
2487 return hypot_type_id == cand_id;
2489 if (btf_dedup_hypot_map_add(d, canon_id, cand_id))
2492 cand_type = d->btf->types[cand_id];
2493 canon_type = d->btf->types[canon_id];
2494 cand_kind = btf_kind(cand_type);
2495 canon_kind = btf_kind(canon_type);
2497 if (cand_type->name_off != canon_type->name_off)
2500 /* FWD <--> STRUCT/UNION equivalence check, if enabled */
2501 if (!d->opts.dont_resolve_fwds
2502 && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD)
2503 && cand_kind != canon_kind) {
2507 if (cand_kind == BTF_KIND_FWD) {
2508 real_kind = canon_kind;
2509 fwd_kind = btf_fwd_kind(cand_type);
2511 real_kind = cand_kind;
2512 fwd_kind = btf_fwd_kind(canon_type);
2514 return fwd_kind == real_kind;
2517 if (cand_kind != canon_kind)
2520 switch (cand_kind) {
2522 return btf_equal_int(cand_type, canon_type);
2525 if (d->opts.dont_resolve_fwds)
2526 return btf_equal_enum(cand_type, canon_type);
2528 return btf_compat_enum(cand_type, canon_type);
2531 return btf_equal_common(cand_type, canon_type);
2533 case BTF_KIND_CONST:
2534 case BTF_KIND_VOLATILE:
2535 case BTF_KIND_RESTRICT:
2537 case BTF_KIND_TYPEDEF:
2539 if (cand_type->info != canon_type->info)
2541 return btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
2543 case BTF_KIND_ARRAY: {
2544 const struct btf_array *cand_arr, *canon_arr;
2546 if (!btf_compat_array(cand_type, canon_type))
2548 cand_arr = btf_array(cand_type);
2549 canon_arr = btf_array(canon_type);
2550 eq = btf_dedup_is_equiv(d,
2551 cand_arr->index_type, canon_arr->index_type);
2554 return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type);
2557 case BTF_KIND_STRUCT:
2558 case BTF_KIND_UNION: {
2559 const struct btf_member *cand_m, *canon_m;
2562 if (!btf_shallow_equal_struct(cand_type, canon_type))
2564 vlen = btf_vlen(cand_type);
2565 cand_m = btf_members(cand_type);
2566 canon_m = btf_members(canon_type);
2567 for (i = 0; i < vlen; i++) {
2568 eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type);
2578 case BTF_KIND_FUNC_PROTO: {
2579 const struct btf_param *cand_p, *canon_p;
2582 if (!btf_compat_fnproto(cand_type, canon_type))
2584 eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
2587 vlen = btf_vlen(cand_type);
2588 cand_p = btf_params(cand_type);
2589 canon_p = btf_params(canon_type);
2590 for (i = 0; i < vlen; i++) {
2591 eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type);
2607 * Use hypothetical mapping, produced by successful type graph equivalence
2608 * check, to augment existing struct/union canonical mapping, where possible.
2610 * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record
2611 * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional:
2612 * it doesn't matter if FWD type was part of canonical graph or candidate one,
2613 * we are recording the mapping anyway. As opposed to carefulness required
2614 * for struct/union correspondence mapping (described below), for FWD resolution
2615 * it's not important, as by the time that FWD type (reference type) will be
2616 * deduplicated all structs/unions will be deduped already anyway.
2618 * Recording STRUCT/UNION mapping is purely a performance optimization and is
2619 * not required for correctness. It needs to be done carefully to ensure that
2620 * struct/union from candidate's type graph is not mapped into corresponding
2621 * struct/union from canonical type graph that itself hasn't been resolved into
2622 * canonical representative. The only guarantee we have is that canonical
2623 * struct/union was determined as canonical and that won't change. But any
2624 * types referenced through that struct/union fields could have been not yet
2625 * resolved, so in case like that it's too early to establish any kind of
2626 * correspondence between structs/unions.
2628 * No canonical correspondence is derived for primitive types (they are already
2629 * deduplicated completely already anyway) or reference types (they rely on
2630 * stability of struct/union canonical relationship for equivalence checks).
2632 static void btf_dedup_merge_hypot_map(struct btf_dedup *d)
2634 __u32 cand_type_id, targ_type_id;
2635 __u16 t_kind, c_kind;
2639 for (i = 0; i < d->hypot_cnt; i++) {
2640 cand_type_id = d->hypot_list[i];
2641 targ_type_id = d->hypot_map[cand_type_id];
2642 t_id = resolve_type_id(d, targ_type_id);
2643 c_id = resolve_type_id(d, cand_type_id);
2644 t_kind = btf_kind(d->btf->types[t_id]);
2645 c_kind = btf_kind(d->btf->types[c_id]);
2647 * Resolve FWD into STRUCT/UNION.
2648 * It's ok to resolve FWD into STRUCT/UNION that's not yet
2649 * mapped to canonical representative (as opposed to
2650 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because
2651 * eventually that struct is going to be mapped and all resolved
2652 * FWDs will automatically resolve to correct canonical
2653 * representative. This will happen before ref type deduping,
2654 * which critically depends on stability of these mapping. This
2655 * stability is not a requirement for STRUCT/UNION equivalence
2658 if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD)
2659 d->map[c_id] = t_id;
2660 else if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD)
2661 d->map[t_id] = c_id;
2663 if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) &&
2664 c_kind != BTF_KIND_FWD &&
2665 is_type_mapped(d, c_id) &&
2666 !is_type_mapped(d, t_id)) {
2668 * as a perf optimization, we can map struct/union
2669 * that's part of type graph we just verified for
2670 * equivalence. We can do that for struct/union that has
2671 * canonical representative only, though.
2673 d->map[t_id] = c_id;
2679 * Deduplicate struct/union types.
2681 * For each struct/union type its type signature hash is calculated, taking
2682 * into account type's name, size, number, order and names of fields, but
2683 * ignoring type ID's referenced from fields, because they might not be deduped
2684 * completely until after reference types deduplication phase. This type hash
2685 * is used to iterate over all potential canonical types, sharing same hash.
2686 * For each canonical candidate we check whether type graphs that they form
2687 * (through referenced types in fields and so on) are equivalent using algorithm
2688 * implemented in `btf_dedup_is_equiv`. If such equivalence is found and
2689 * BTF_KIND_FWD resolution is allowed, then hypothetical mapping
2690 * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence
2691 * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to
2692 * potentially map other structs/unions to their canonical representatives,
2693 * if such relationship hasn't yet been established. This speeds up algorithm
2694 * by eliminating some of the duplicate work.
2696 * If no matching canonical representative was found, struct/union is marked
2697 * as canonical for itself and is added into btf_dedup->dedup_table hash map
2698 * for further look ups.
2700 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id)
2702 struct btf_type *cand_type, *t;
2703 struct hashmap_entry *hash_entry;
2704 /* if we don't find equivalent type, then we are canonical */
2705 __u32 new_id = type_id;
2709 /* already deduped or is in process of deduping (loop detected) */
2710 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
2713 t = d->btf->types[type_id];
2716 if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION)
2719 h = btf_hash_struct(t);
2720 for_each_dedup_cand(d, hash_entry, h) {
2721 __u32 cand_id = (__u32)(long)hash_entry->value;
2725 * Even though btf_dedup_is_equiv() checks for
2726 * btf_shallow_equal_struct() internally when checking two
2727 * structs (unions) for equivalence, we need to guard here
2728 * from picking matching FWD type as a dedup candidate.
2729 * This can happen due to hash collision. In such case just
2730 * relying on btf_dedup_is_equiv() would lead to potentially
2731 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because
2732 * FWD and compatible STRUCT/UNION are considered equivalent.
2734 cand_type = d->btf->types[cand_id];
2735 if (!btf_shallow_equal_struct(t, cand_type))
2738 btf_dedup_clear_hypot_map(d);
2739 eq = btf_dedup_is_equiv(d, type_id, cand_id);
2745 btf_dedup_merge_hypot_map(d);
2749 d->map[type_id] = new_id;
2750 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
2756 static int btf_dedup_struct_types(struct btf_dedup *d)
2760 for (i = 1; i <= d->btf->nr_types; i++) {
2761 err = btf_dedup_struct_type(d, i);
2769 * Deduplicate reference type.
2771 * Once all primitive and struct/union types got deduplicated, we can easily
2772 * deduplicate all other (reference) BTF types. This is done in two steps:
2774 * 1. Resolve all referenced type IDs into their canonical type IDs. This
2775 * resolution can be done either immediately for primitive or struct/union types
2776 * (because they were deduped in previous two phases) or recursively for
2777 * reference types. Recursion will always terminate at either primitive or
2778 * struct/union type, at which point we can "unwind" chain of reference types
2779 * one by one. There is no danger of encountering cycles because in C type
2780 * system the only way to form type cycle is through struct/union, so any chain
2781 * of reference types, even those taking part in a type cycle, will inevitably
2782 * reach struct/union at some point.
2784 * 2. Once all referenced type IDs are resolved into canonical ones, BTF type
2785 * becomes "stable", in the sense that no further deduplication will cause
2786 * any changes to it. With that, it's now possible to calculate type's signature
2787 * hash (this time taking into account referenced type IDs) and loop over all
2788 * potential canonical representatives. If no match was found, current type
2789 * will become canonical representative of itself and will be added into
2790 * btf_dedup->dedup_table as another possible canonical representative.
2792 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id)
2794 struct hashmap_entry *hash_entry;
2795 __u32 new_id = type_id, cand_id;
2796 struct btf_type *t, *cand;
2797 /* if we don't find equivalent type, then we are representative type */
2801 if (d->map[type_id] == BTF_IN_PROGRESS_ID)
2803 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
2804 return resolve_type_id(d, type_id);
2806 t = d->btf->types[type_id];
2807 d->map[type_id] = BTF_IN_PROGRESS_ID;
2809 switch (btf_kind(t)) {
2810 case BTF_KIND_CONST:
2811 case BTF_KIND_VOLATILE:
2812 case BTF_KIND_RESTRICT:
2814 case BTF_KIND_TYPEDEF:
2816 ref_type_id = btf_dedup_ref_type(d, t->type);
2817 if (ref_type_id < 0)
2819 t->type = ref_type_id;
2821 h = btf_hash_common(t);
2822 for_each_dedup_cand(d, hash_entry, h) {
2823 cand_id = (__u32)(long)hash_entry->value;
2824 cand = d->btf->types[cand_id];
2825 if (btf_equal_common(t, cand)) {
2832 case BTF_KIND_ARRAY: {
2833 struct btf_array *info = btf_array(t);
2835 ref_type_id = btf_dedup_ref_type(d, info->type);
2836 if (ref_type_id < 0)
2838 info->type = ref_type_id;
2840 ref_type_id = btf_dedup_ref_type(d, info->index_type);
2841 if (ref_type_id < 0)
2843 info->index_type = ref_type_id;
2845 h = btf_hash_array(t);
2846 for_each_dedup_cand(d, hash_entry, h) {
2847 cand_id = (__u32)(long)hash_entry->value;
2848 cand = d->btf->types[cand_id];
2849 if (btf_equal_array(t, cand)) {
2857 case BTF_KIND_FUNC_PROTO: {
2858 struct btf_param *param;
2862 ref_type_id = btf_dedup_ref_type(d, t->type);
2863 if (ref_type_id < 0)
2865 t->type = ref_type_id;
2868 param = btf_params(t);
2869 for (i = 0; i < vlen; i++) {
2870 ref_type_id = btf_dedup_ref_type(d, param->type);
2871 if (ref_type_id < 0)
2873 param->type = ref_type_id;
2877 h = btf_hash_fnproto(t);
2878 for_each_dedup_cand(d, hash_entry, h) {
2879 cand_id = (__u32)(long)hash_entry->value;
2880 cand = d->btf->types[cand_id];
2881 if (btf_equal_fnproto(t, cand)) {
2893 d->map[type_id] = new_id;
2894 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
2900 static int btf_dedup_ref_types(struct btf_dedup *d)
2904 for (i = 1; i <= d->btf->nr_types; i++) {
2905 err = btf_dedup_ref_type(d, i);
2909 /* we won't need d->dedup_table anymore */
2910 hashmap__free(d->dedup_table);
2911 d->dedup_table = NULL;
2918 * After we established for each type its corresponding canonical representative
2919 * type, we now can eliminate types that are not canonical and leave only
2920 * canonical ones layed out sequentially in memory by copying them over
2921 * duplicates. During compaction btf_dedup->hypot_map array is reused to store
2922 * a map from original type ID to a new compacted type ID, which will be used
2923 * during next phase to "fix up" type IDs, referenced from struct/union and
2926 static int btf_dedup_compact_types(struct btf_dedup *d)
2928 struct btf_type **new_types;
2929 __u32 next_type_id = 1;
2930 char *types_start, *p;
2933 /* we are going to reuse hypot_map to store compaction remapping */
2934 d->hypot_map[0] = 0;
2935 for (i = 1; i <= d->btf->nr_types; i++)
2936 d->hypot_map[i] = BTF_UNPROCESSED_ID;
2938 types_start = d->btf->nohdr_data + d->btf->hdr->type_off;
2941 for (i = 1; i <= d->btf->nr_types; i++) {
2945 len = btf_type_size(d->btf->types[i]);
2949 memmove(p, d->btf->types[i], len);
2950 d->hypot_map[i] = next_type_id;
2951 d->btf->types[next_type_id] = (struct btf_type *)p;
2956 /* shrink struct btf's internal types index and update btf_header */
2957 d->btf->nr_types = next_type_id - 1;
2958 d->btf->types_size = d->btf->nr_types;
2959 d->btf->hdr->type_len = p - types_start;
2960 new_types = realloc(d->btf->types,
2961 (1 + d->btf->nr_types) * sizeof(struct btf_type *));
2964 d->btf->types = new_types;
2966 /* make sure string section follows type information without gaps */
2967 d->btf->hdr->str_off = p - (char *)d->btf->nohdr_data;
2968 memmove(p, d->btf->strings, d->btf->hdr->str_len);
2969 d->btf->strings = p;
2970 p += d->btf->hdr->str_len;
2972 d->btf->data_size = p - (char *)d->btf->data;
2977 * Figure out final (deduplicated and compacted) type ID for provided original
2978 * `type_id` by first resolving it into corresponding canonical type ID and
2979 * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map,
2980 * which is populated during compaction phase.
2982 static int btf_dedup_remap_type_id(struct btf_dedup *d, __u32 type_id)
2984 __u32 resolved_type_id, new_type_id;
2986 resolved_type_id = resolve_type_id(d, type_id);
2987 new_type_id = d->hypot_map[resolved_type_id];
2988 if (new_type_id > BTF_MAX_NR_TYPES)
2994 * Remap referenced type IDs into deduped type IDs.
2996 * After BTF types are deduplicated and compacted, their final type IDs may
2997 * differ from original ones. The map from original to a corresponding
2998 * deduped type ID is stored in btf_dedup->hypot_map and is populated during
2999 * compaction phase. During remapping phase we are rewriting all type IDs
3000 * referenced from any BTF type (e.g., struct fields, func proto args, etc) to
3001 * their final deduped type IDs.
3003 static int btf_dedup_remap_type(struct btf_dedup *d, __u32 type_id)
3005 struct btf_type *t = d->btf->types[type_id];
3008 switch (btf_kind(t)) {
3014 case BTF_KIND_CONST:
3015 case BTF_KIND_VOLATILE:
3016 case BTF_KIND_RESTRICT:
3018 case BTF_KIND_TYPEDEF:
3021 r = btf_dedup_remap_type_id(d, t->type);
3027 case BTF_KIND_ARRAY: {
3028 struct btf_array *arr_info = btf_array(t);
3030 r = btf_dedup_remap_type_id(d, arr_info->type);
3034 r = btf_dedup_remap_type_id(d, arr_info->index_type);
3037 arr_info->index_type = r;
3041 case BTF_KIND_STRUCT:
3042 case BTF_KIND_UNION: {
3043 struct btf_member *member = btf_members(t);
3044 __u16 vlen = btf_vlen(t);
3046 for (i = 0; i < vlen; i++) {
3047 r = btf_dedup_remap_type_id(d, member->type);
3056 case BTF_KIND_FUNC_PROTO: {
3057 struct btf_param *param = btf_params(t);
3058 __u16 vlen = btf_vlen(t);
3060 r = btf_dedup_remap_type_id(d, t->type);
3065 for (i = 0; i < vlen; i++) {
3066 r = btf_dedup_remap_type_id(d, param->type);
3075 case BTF_KIND_DATASEC: {
3076 struct btf_var_secinfo *var = btf_var_secinfos(t);
3077 __u16 vlen = btf_vlen(t);
3079 for (i = 0; i < vlen; i++) {
3080 r = btf_dedup_remap_type_id(d, var->type);
3096 static int btf_dedup_remap_types(struct btf_dedup *d)
3100 for (i = 1; i <= d->btf->nr_types; i++) {
3101 r = btf_dedup_remap_type(d, i);
3109 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3110 * data out of it to use for target BTF.
3112 struct btf *libbpf_find_kernel_btf(void)
3115 const char *path_fmt;
3118 /* try canonical vmlinux BTF through sysfs first */
3119 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3120 /* fall back to trying to find vmlinux ELF on disk otherwise */
3121 { "/boot/vmlinux-%1$s" },
3122 { "/lib/modules/%1$s/vmlinux-%1$s" },
3123 { "/lib/modules/%1$s/build/vmlinux" },
3124 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3125 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3126 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3127 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
3129 char path[PATH_MAX + 1];
3136 for (i = 0; i < ARRAY_SIZE(locations); i++) {
3137 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
3139 if (access(path, R_OK))
3142 if (locations[i].raw_btf)
3143 btf = btf__parse_raw(path);
3145 btf = btf__parse_elf(path, NULL);
3147 pr_debug("loading kernel BTF '%s': %ld\n",
3148 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
3155 pr_warn("failed to find valid kernel BTF\n");
3156 return ERR_PTR(-ESRCH);