1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 /* Copyright (c) 2018 Facebook */ 3 4 #include <byteswap.h> 5 #include <endian.h> 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <string.h> 9 #include <fcntl.h> 10 #include <unistd.h> 11 #include <errno.h> 12 #include <sys/utsname.h> 13 #include <sys/param.h> 14 #include <sys/stat.h> 15 #include <linux/kernel.h> 16 #include <linux/err.h> 17 #include <linux/btf.h> 18 #include <gelf.h> 19 #include "btf.h" 20 #include "bpf.h" 21 #include "libbpf.h" 22 #include "libbpf_internal.h" 23 #include "hashmap.h" 24 25 #define BTF_MAX_NR_TYPES 0x7fffffffU 26 #define BTF_MAX_STR_OFFSET 0x7fffffffU 27 28 static struct btf_type btf_void; 29 30 struct btf { 31 /* raw BTF data in native endianness */ 32 void *raw_data; 33 /* raw BTF data in non-native endianness */ 34 void *raw_data_swapped; 35 __u32 raw_size; 36 /* whether target endianness differs from the native one */ 37 bool swapped_endian; 38 39 /* 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 43 * representation: 44 * 45 * +--------------------------------+ 46 * | Header | Types | Strings | 47 * +--------------------------------+ 48 * ^ ^ ^ 49 * | | | 50 * hdr | | 51 * types_data-+ | 52 * strs_data------------+ 53 * 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 61 * strings: 62 * 63 * +----------+ +---------+ +-----------+ 64 * | Header | | Types | | Strings | 65 * +----------+ +---------+ +-----------+ 66 * ^ ^ ^ 67 * | | | 68 * hdr | | 69 * types_data----+ | 70 * strs_data------------------+ 71 * 72 * +----------+---------+-----------+ 73 * | Header | Types | Strings | 74 * raw_data----->+----------+---------+-----------+ 75 */ 76 struct btf_header *hdr; 77 78 void *types_data; 79 size_t types_data_cap; /* used size stored in hdr->type_len */ 80 81 /* type ID to `struct btf_type *` lookup index 82 * type_offs[0] corresponds to the first non-VOID type: 83 * - for base BTF it's type [1]; 84 * - for split BTF it's the first non-base BTF type. 85 */ 86 __u32 *type_offs; 87 size_t type_offs_cap; 88 /* number of types in this BTF instance: 89 * - doesn't include special [0] void type; 90 * - for split BTF counts number of types added on top of base BTF. 91 */ 92 __u32 nr_types; 93 /* if not NULL, points to the base BTF on top of which the current 94 * split BTF is based 95 */ 96 struct btf *base_btf; 97 /* BTF type ID of the first type in this BTF instance: 98 * - for base BTF it's equal to 1; 99 * - for split BTF it's equal to biggest type ID of base BTF plus 1. 100 */ 101 int start_id; 102 /* logical string offset of this BTF instance: 103 * - for base BTF it's equal to 0; 104 * - for split BTF it's equal to total size of base BTF's string section size. 105 */ 106 int start_str_off; 107 108 void *strs_data; 109 size_t strs_data_cap; /* used size stored in hdr->str_len */ 110 111 /* lookup index for each unique string in strings section */ 112 struct hashmap *strs_hash; 113 /* whether strings are already deduplicated */ 114 bool strs_deduped; 115 /* extra indirection layer to make strings hashmap work with stable 116 * string offsets and ability to transparently choose between 117 * btf->strs_data or btf_dedup->strs_data as a source of strings. 118 * This is used for BTF strings dedup to transfer deduplicated strings 119 * data back to struct btf without re-building strings index. 120 */ 121 void **strs_data_ptr; 122 123 /* BTF object FD, if loaded into kernel */ 124 int fd; 125 126 /* Pointer size (in bytes) for a target architecture of this BTF */ 127 int ptr_sz; 128 }; 129 130 static inline __u64 ptr_to_u64(const void *ptr) 131 { 132 return (__u64) (unsigned long) ptr; 133 } 134 135 /* Ensure given dynamically allocated memory region pointed to by *data* with 136 * capacity of *cap_cnt* elements each taking *elem_sz* bytes has enough 137 * memory to accomodate *add_cnt* new elements, assuming *cur_cnt* elements 138 * are already used. At most *max_cnt* elements can be ever allocated. 139 * If necessary, memory is reallocated and all existing data is copied over, 140 * new pointer to the memory region is stored at *data, new memory region 141 * capacity (in number of elements) is stored in *cap. 142 * On success, memory pointer to the beginning of unused memory is returned. 143 * On error, NULL is returned. 144 */ 145 void *btf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz, 146 size_t cur_cnt, size_t max_cnt, size_t add_cnt) 147 { 148 size_t new_cnt; 149 void *new_data; 150 151 if (cur_cnt + add_cnt <= *cap_cnt) 152 return *data + cur_cnt * elem_sz; 153 154 /* requested more than the set limit */ 155 if (cur_cnt + add_cnt > max_cnt) 156 return NULL; 157 158 new_cnt = *cap_cnt; 159 new_cnt += new_cnt / 4; /* expand by 25% */ 160 if (new_cnt < 16) /* but at least 16 elements */ 161 new_cnt = 16; 162 if (new_cnt > max_cnt) /* but not exceeding a set limit */ 163 new_cnt = max_cnt; 164 if (new_cnt < cur_cnt + add_cnt) /* also ensure we have enough memory */ 165 new_cnt = cur_cnt + add_cnt; 166 167 new_data = libbpf_reallocarray(*data, new_cnt, elem_sz); 168 if (!new_data) 169 return NULL; 170 171 /* zero out newly allocated portion of memory */ 172 memset(new_data + (*cap_cnt) * elem_sz, 0, (new_cnt - *cap_cnt) * elem_sz); 173 174 *data = new_data; 175 *cap_cnt = new_cnt; 176 return new_data + cur_cnt * elem_sz; 177 } 178 179 /* Ensure given dynamically allocated memory region has enough allocated space 180 * to accommodate *need_cnt* elements of size *elem_sz* bytes each 181 */ 182 int btf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt) 183 { 184 void *p; 185 186 if (need_cnt <= *cap_cnt) 187 return 0; 188 189 p = btf_add_mem(data, cap_cnt, elem_sz, *cap_cnt, SIZE_MAX, need_cnt - *cap_cnt); 190 if (!p) 191 return -ENOMEM; 192 193 return 0; 194 } 195 196 static int btf_add_type_idx_entry(struct btf *btf, __u32 type_off) 197 { 198 __u32 *p; 199 200 p = btf_add_mem((void **)&btf->type_offs, &btf->type_offs_cap, sizeof(__u32), 201 btf->nr_types, BTF_MAX_NR_TYPES, 1); 202 if (!p) 203 return -ENOMEM; 204 205 *p = type_off; 206 return 0; 207 } 208 209 static void btf_bswap_hdr(struct btf_header *h) 210 { 211 h->magic = bswap_16(h->magic); 212 h->hdr_len = bswap_32(h->hdr_len); 213 h->type_off = bswap_32(h->type_off); 214 h->type_len = bswap_32(h->type_len); 215 h->str_off = bswap_32(h->str_off); 216 h->str_len = bswap_32(h->str_len); 217 } 218 219 static int btf_parse_hdr(struct btf *btf) 220 { 221 struct btf_header *hdr = btf->hdr; 222 __u32 meta_left; 223 224 if (btf->raw_size < sizeof(struct btf_header)) { 225 pr_debug("BTF header not found\n"); 226 return -EINVAL; 227 } 228 229 if (hdr->magic == bswap_16(BTF_MAGIC)) { 230 btf->swapped_endian = true; 231 if (bswap_32(hdr->hdr_len) != sizeof(struct btf_header)) { 232 pr_warn("Can't load BTF with non-native endianness due to unsupported header length %u\n", 233 bswap_32(hdr->hdr_len)); 234 return -ENOTSUP; 235 } 236 btf_bswap_hdr(hdr); 237 } else if (hdr->magic != BTF_MAGIC) { 238 pr_debug("Invalid BTF magic:%x\n", hdr->magic); 239 return -EINVAL; 240 } 241 242 meta_left = btf->raw_size - sizeof(*hdr); 243 if (meta_left < hdr->str_off + hdr->str_len) { 244 pr_debug("Invalid BTF total size:%u\n", btf->raw_size); 245 return -EINVAL; 246 } 247 248 if (hdr->type_off + hdr->type_len > hdr->str_off) { 249 pr_debug("Invalid BTF data sections layout: type data at %u + %u, strings data at %u + %u\n", 250 hdr->type_off, hdr->type_len, hdr->str_off, hdr->str_len); 251 return -EINVAL; 252 } 253 254 if (hdr->type_off % 4) { 255 pr_debug("BTF type section is not aligned to 4 bytes\n"); 256 return -EINVAL; 257 } 258 259 return 0; 260 } 261 262 static int btf_parse_str_sec(struct btf *btf) 263 { 264 const struct btf_header *hdr = btf->hdr; 265 const char *start = btf->strs_data; 266 const char *end = start + btf->hdr->str_len; 267 268 if (btf->base_btf && hdr->str_len == 0) 269 return 0; 270 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_STR_OFFSET || end[-1]) { 271 pr_debug("Invalid BTF string section\n"); 272 return -EINVAL; 273 } 274 if (!btf->base_btf && start[0]) { 275 pr_debug("Invalid BTF string section\n"); 276 return -EINVAL; 277 } 278 return 0; 279 } 280 281 static int btf_type_size(const struct btf_type *t) 282 { 283 const int base_size = sizeof(struct btf_type); 284 __u16 vlen = btf_vlen(t); 285 286 switch (btf_kind(t)) { 287 case BTF_KIND_FWD: 288 case BTF_KIND_CONST: 289 case BTF_KIND_VOLATILE: 290 case BTF_KIND_RESTRICT: 291 case BTF_KIND_PTR: 292 case BTF_KIND_TYPEDEF: 293 case BTF_KIND_FUNC: 294 case BTF_KIND_FLOAT: 295 return base_size; 296 case BTF_KIND_INT: 297 return base_size + sizeof(__u32); 298 case BTF_KIND_ENUM: 299 return base_size + vlen * sizeof(struct btf_enum); 300 case BTF_KIND_ARRAY: 301 return base_size + sizeof(struct btf_array); 302 case BTF_KIND_STRUCT: 303 case BTF_KIND_UNION: 304 return base_size + vlen * sizeof(struct btf_member); 305 case BTF_KIND_FUNC_PROTO: 306 return base_size + vlen * sizeof(struct btf_param); 307 case BTF_KIND_VAR: 308 return base_size + sizeof(struct btf_var); 309 case BTF_KIND_DATASEC: 310 return base_size + vlen * sizeof(struct btf_var_secinfo); 311 default: 312 pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t)); 313 return -EINVAL; 314 } 315 } 316 317 static void btf_bswap_type_base(struct btf_type *t) 318 { 319 t->name_off = bswap_32(t->name_off); 320 t->info = bswap_32(t->info); 321 t->type = bswap_32(t->type); 322 } 323 324 static int btf_bswap_type_rest(struct btf_type *t) 325 { 326 struct btf_var_secinfo *v; 327 struct btf_member *m; 328 struct btf_array *a; 329 struct btf_param *p; 330 struct btf_enum *e; 331 __u16 vlen = btf_vlen(t); 332 int i; 333 334 switch (btf_kind(t)) { 335 case BTF_KIND_FWD: 336 case BTF_KIND_CONST: 337 case BTF_KIND_VOLATILE: 338 case BTF_KIND_RESTRICT: 339 case BTF_KIND_PTR: 340 case BTF_KIND_TYPEDEF: 341 case BTF_KIND_FUNC: 342 case BTF_KIND_FLOAT: 343 return 0; 344 case BTF_KIND_INT: 345 *(__u32 *)(t + 1) = bswap_32(*(__u32 *)(t + 1)); 346 return 0; 347 case BTF_KIND_ENUM: 348 for (i = 0, e = btf_enum(t); i < vlen; i++, e++) { 349 e->name_off = bswap_32(e->name_off); 350 e->val = bswap_32(e->val); 351 } 352 return 0; 353 case BTF_KIND_ARRAY: 354 a = btf_array(t); 355 a->type = bswap_32(a->type); 356 a->index_type = bswap_32(a->index_type); 357 a->nelems = bswap_32(a->nelems); 358 return 0; 359 case BTF_KIND_STRUCT: 360 case BTF_KIND_UNION: 361 for (i = 0, m = btf_members(t); i < vlen; i++, m++) { 362 m->name_off = bswap_32(m->name_off); 363 m->type = bswap_32(m->type); 364 m->offset = bswap_32(m->offset); 365 } 366 return 0; 367 case BTF_KIND_FUNC_PROTO: 368 for (i = 0, p = btf_params(t); i < vlen; i++, p++) { 369 p->name_off = bswap_32(p->name_off); 370 p->type = bswap_32(p->type); 371 } 372 return 0; 373 case BTF_KIND_VAR: 374 btf_var(t)->linkage = bswap_32(btf_var(t)->linkage); 375 return 0; 376 case BTF_KIND_DATASEC: 377 for (i = 0, v = btf_var_secinfos(t); i < vlen; i++, v++) { 378 v->type = bswap_32(v->type); 379 v->offset = bswap_32(v->offset); 380 v->size = bswap_32(v->size); 381 } 382 return 0; 383 default: 384 pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t)); 385 return -EINVAL; 386 } 387 } 388 389 static int btf_parse_type_sec(struct btf *btf) 390 { 391 struct btf_header *hdr = btf->hdr; 392 void *next_type = btf->types_data; 393 void *end_type = next_type + hdr->type_len; 394 int err, type_size; 395 396 while (next_type + sizeof(struct btf_type) <= end_type) { 397 if (btf->swapped_endian) 398 btf_bswap_type_base(next_type); 399 400 type_size = btf_type_size(next_type); 401 if (type_size < 0) 402 return type_size; 403 if (next_type + type_size > end_type) { 404 pr_warn("BTF type [%d] is malformed\n", btf->start_id + btf->nr_types); 405 return -EINVAL; 406 } 407 408 if (btf->swapped_endian && btf_bswap_type_rest(next_type)) 409 return -EINVAL; 410 411 err = btf_add_type_idx_entry(btf, next_type - btf->types_data); 412 if (err) 413 return err; 414 415 next_type += type_size; 416 btf->nr_types++; 417 } 418 419 if (next_type != end_type) { 420 pr_warn("BTF types data is malformed\n"); 421 return -EINVAL; 422 } 423 424 return 0; 425 } 426 427 __u32 btf__get_nr_types(const struct btf *btf) 428 { 429 return btf->start_id + btf->nr_types - 1; 430 } 431 432 const struct btf *btf__base_btf(const struct btf *btf) 433 { 434 return btf->base_btf; 435 } 436 437 /* internal helper returning non-const pointer to a type */ 438 static struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id) 439 { 440 if (type_id == 0) 441 return &btf_void; 442 if (type_id < btf->start_id) 443 return btf_type_by_id(btf->base_btf, type_id); 444 return btf->types_data + btf->type_offs[type_id - btf->start_id]; 445 } 446 447 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id) 448 { 449 if (type_id >= btf->start_id + btf->nr_types) 450 return NULL; 451 return btf_type_by_id((struct btf *)btf, type_id); 452 } 453 454 static int determine_ptr_size(const struct btf *btf) 455 { 456 const struct btf_type *t; 457 const char *name; 458 int i, n; 459 460 if (btf->base_btf && btf->base_btf->ptr_sz > 0) 461 return btf->base_btf->ptr_sz; 462 463 n = btf__get_nr_types(btf); 464 for (i = 1; i <= n; i++) { 465 t = btf__type_by_id(btf, i); 466 if (!btf_is_int(t)) 467 continue; 468 469 name = btf__name_by_offset(btf, t->name_off); 470 if (!name) 471 continue; 472 473 if (strcmp(name, "long int") == 0 || 474 strcmp(name, "long unsigned int") == 0) { 475 if (t->size != 4 && t->size != 8) 476 continue; 477 return t->size; 478 } 479 } 480 481 return -1; 482 } 483 484 static size_t btf_ptr_sz(const struct btf *btf) 485 { 486 if (!btf->ptr_sz) 487 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf); 488 return btf->ptr_sz < 0 ? sizeof(void *) : btf->ptr_sz; 489 } 490 491 /* Return pointer size this BTF instance assumes. The size is heuristically 492 * determined by looking for 'long' or 'unsigned long' integer type and 493 * recording its size in bytes. If BTF type information doesn't have any such 494 * type, this function returns 0. In the latter case, native architecture's 495 * pointer size is assumed, so will be either 4 or 8, depending on 496 * architecture that libbpf was compiled for. It's possible to override 497 * guessed value by using btf__set_pointer_size() API. 498 */ 499 size_t btf__pointer_size(const struct btf *btf) 500 { 501 if (!btf->ptr_sz) 502 ((struct btf *)btf)->ptr_sz = determine_ptr_size(btf); 503 504 if (btf->ptr_sz < 0) 505 /* not enough BTF type info to guess */ 506 return 0; 507 508 return btf->ptr_sz; 509 } 510 511 /* Override or set pointer size in bytes. Only values of 4 and 8 are 512 * supported. 513 */ 514 int btf__set_pointer_size(struct btf *btf, size_t ptr_sz) 515 { 516 if (ptr_sz != 4 && ptr_sz != 8) 517 return -EINVAL; 518 btf->ptr_sz = ptr_sz; 519 return 0; 520 } 521 522 static bool is_host_big_endian(void) 523 { 524 #if __BYTE_ORDER == __LITTLE_ENDIAN 525 return false; 526 #elif __BYTE_ORDER == __BIG_ENDIAN 527 return true; 528 #else 529 # error "Unrecognized __BYTE_ORDER__" 530 #endif 531 } 532 533 enum btf_endianness btf__endianness(const struct btf *btf) 534 { 535 if (is_host_big_endian()) 536 return btf->swapped_endian ? BTF_LITTLE_ENDIAN : BTF_BIG_ENDIAN; 537 else 538 return btf->swapped_endian ? BTF_BIG_ENDIAN : BTF_LITTLE_ENDIAN; 539 } 540 541 int btf__set_endianness(struct btf *btf, enum btf_endianness endian) 542 { 543 if (endian != BTF_LITTLE_ENDIAN && endian != BTF_BIG_ENDIAN) 544 return -EINVAL; 545 546 btf->swapped_endian = is_host_big_endian() != (endian == BTF_BIG_ENDIAN); 547 if (!btf->swapped_endian) { 548 free(btf->raw_data_swapped); 549 btf->raw_data_swapped = NULL; 550 } 551 return 0; 552 } 553 554 static bool btf_type_is_void(const struct btf_type *t) 555 { 556 return t == &btf_void || btf_is_fwd(t); 557 } 558 559 static bool btf_type_is_void_or_null(const struct btf_type *t) 560 { 561 return !t || btf_type_is_void(t); 562 } 563 564 #define MAX_RESOLVE_DEPTH 32 565 566 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id) 567 { 568 const struct btf_array *array; 569 const struct btf_type *t; 570 __u32 nelems = 1; 571 __s64 size = -1; 572 int i; 573 574 t = btf__type_by_id(btf, type_id); 575 for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t); 576 i++) { 577 switch (btf_kind(t)) { 578 case BTF_KIND_INT: 579 case BTF_KIND_STRUCT: 580 case BTF_KIND_UNION: 581 case BTF_KIND_ENUM: 582 case BTF_KIND_DATASEC: 583 case BTF_KIND_FLOAT: 584 size = t->size; 585 goto done; 586 case BTF_KIND_PTR: 587 size = btf_ptr_sz(btf); 588 goto done; 589 case BTF_KIND_TYPEDEF: 590 case BTF_KIND_VOLATILE: 591 case BTF_KIND_CONST: 592 case BTF_KIND_RESTRICT: 593 case BTF_KIND_VAR: 594 type_id = t->type; 595 break; 596 case BTF_KIND_ARRAY: 597 array = btf_array(t); 598 if (nelems && array->nelems > UINT32_MAX / nelems) 599 return -E2BIG; 600 nelems *= array->nelems; 601 type_id = array->type; 602 break; 603 default: 604 return -EINVAL; 605 } 606 607 t = btf__type_by_id(btf, type_id); 608 } 609 610 done: 611 if (size < 0) 612 return -EINVAL; 613 if (nelems && size > UINT32_MAX / nelems) 614 return -E2BIG; 615 616 return nelems * size; 617 } 618 619 int btf__align_of(const struct btf *btf, __u32 id) 620 { 621 const struct btf_type *t = btf__type_by_id(btf, id); 622 __u16 kind = btf_kind(t); 623 624 switch (kind) { 625 case BTF_KIND_INT: 626 case BTF_KIND_ENUM: 627 case BTF_KIND_FLOAT: 628 return min(btf_ptr_sz(btf), (size_t)t->size); 629 case BTF_KIND_PTR: 630 return btf_ptr_sz(btf); 631 case BTF_KIND_TYPEDEF: 632 case BTF_KIND_VOLATILE: 633 case BTF_KIND_CONST: 634 case BTF_KIND_RESTRICT: 635 return btf__align_of(btf, t->type); 636 case BTF_KIND_ARRAY: 637 return btf__align_of(btf, btf_array(t)->type); 638 case BTF_KIND_STRUCT: 639 case BTF_KIND_UNION: { 640 const struct btf_member *m = btf_members(t); 641 __u16 vlen = btf_vlen(t); 642 int i, max_align = 1, align; 643 644 for (i = 0; i < vlen; i++, m++) { 645 align = btf__align_of(btf, m->type); 646 if (align <= 0) 647 return align; 648 max_align = max(max_align, align); 649 } 650 651 return max_align; 652 } 653 default: 654 pr_warn("unsupported BTF_KIND:%u\n", btf_kind(t)); 655 return 0; 656 } 657 } 658 659 int btf__resolve_type(const struct btf *btf, __u32 type_id) 660 { 661 const struct btf_type *t; 662 int depth = 0; 663 664 t = btf__type_by_id(btf, type_id); 665 while (depth < MAX_RESOLVE_DEPTH && 666 !btf_type_is_void_or_null(t) && 667 (btf_is_mod(t) || btf_is_typedef(t) || btf_is_var(t))) { 668 type_id = t->type; 669 t = btf__type_by_id(btf, type_id); 670 depth++; 671 } 672 673 if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t)) 674 return -EINVAL; 675 676 return type_id; 677 } 678 679 __s32 btf__find_by_name(const struct btf *btf, const char *type_name) 680 { 681 __u32 i, nr_types = btf__get_nr_types(btf); 682 683 if (!strcmp(type_name, "void")) 684 return 0; 685 686 for (i = 1; i <= nr_types; i++) { 687 const struct btf_type *t = btf__type_by_id(btf, i); 688 const char *name = btf__name_by_offset(btf, t->name_off); 689 690 if (name && !strcmp(type_name, name)) 691 return i; 692 } 693 694 return -ENOENT; 695 } 696 697 __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name, 698 __u32 kind) 699 { 700 __u32 i, nr_types = btf__get_nr_types(btf); 701 702 if (kind == BTF_KIND_UNKN || !strcmp(type_name, "void")) 703 return 0; 704 705 for (i = 1; i <= nr_types; i++) { 706 const struct btf_type *t = btf__type_by_id(btf, i); 707 const char *name; 708 709 if (btf_kind(t) != kind) 710 continue; 711 name = btf__name_by_offset(btf, t->name_off); 712 if (name && !strcmp(type_name, name)) 713 return i; 714 } 715 716 return -ENOENT; 717 } 718 719 static bool btf_is_modifiable(const struct btf *btf) 720 { 721 return (void *)btf->hdr != btf->raw_data; 722 } 723 724 void btf__free(struct btf *btf) 725 { 726 if (IS_ERR_OR_NULL(btf)) 727 return; 728 729 if (btf->fd >= 0) 730 close(btf->fd); 731 732 if (btf_is_modifiable(btf)) { 733 /* if BTF was modified after loading, it will have a split 734 * in-memory representation for header, types, and strings 735 * sections, so we need to free all of them individually. It 736 * might still have a cached contiguous raw data present, 737 * which will be unconditionally freed below. 738 */ 739 free(btf->hdr); 740 free(btf->types_data); 741 free(btf->strs_data); 742 } 743 free(btf->raw_data); 744 free(btf->raw_data_swapped); 745 free(btf->type_offs); 746 free(btf); 747 } 748 749 static struct btf *btf_new_empty(struct btf *base_btf) 750 { 751 struct btf *btf; 752 753 btf = calloc(1, sizeof(*btf)); 754 if (!btf) 755 return ERR_PTR(-ENOMEM); 756 757 btf->nr_types = 0; 758 btf->start_id = 1; 759 btf->start_str_off = 0; 760 btf->fd = -1; 761 btf->ptr_sz = sizeof(void *); 762 btf->swapped_endian = false; 763 764 if (base_btf) { 765 btf->base_btf = base_btf; 766 btf->start_id = btf__get_nr_types(base_btf) + 1; 767 btf->start_str_off = base_btf->hdr->str_len; 768 } 769 770 /* +1 for empty string at offset 0 */ 771 btf->raw_size = sizeof(struct btf_header) + (base_btf ? 0 : 1); 772 btf->raw_data = calloc(1, btf->raw_size); 773 if (!btf->raw_data) { 774 free(btf); 775 return ERR_PTR(-ENOMEM); 776 } 777 778 btf->hdr = btf->raw_data; 779 btf->hdr->hdr_len = sizeof(struct btf_header); 780 btf->hdr->magic = BTF_MAGIC; 781 btf->hdr->version = BTF_VERSION; 782 783 btf->types_data = btf->raw_data + btf->hdr->hdr_len; 784 btf->strs_data = btf->raw_data + btf->hdr->hdr_len; 785 btf->hdr->str_len = base_btf ? 0 : 1; /* empty string at offset 0 */ 786 787 return btf; 788 } 789 790 struct btf *btf__new_empty(void) 791 { 792 return btf_new_empty(NULL); 793 } 794 795 struct btf *btf__new_empty_split(struct btf *base_btf) 796 { 797 return btf_new_empty(base_btf); 798 } 799 800 static struct btf *btf_new(const void *data, __u32 size, struct btf *base_btf) 801 { 802 struct btf *btf; 803 int err; 804 805 btf = calloc(1, sizeof(struct btf)); 806 if (!btf) 807 return ERR_PTR(-ENOMEM); 808 809 btf->nr_types = 0; 810 btf->start_id = 1; 811 btf->start_str_off = 0; 812 813 if (base_btf) { 814 btf->base_btf = base_btf; 815 btf->start_id = btf__get_nr_types(base_btf) + 1; 816 btf->start_str_off = base_btf->hdr->str_len; 817 } 818 819 btf->raw_data = malloc(size); 820 if (!btf->raw_data) { 821 err = -ENOMEM; 822 goto done; 823 } 824 memcpy(btf->raw_data, data, size); 825 btf->raw_size = size; 826 827 btf->hdr = btf->raw_data; 828 err = btf_parse_hdr(btf); 829 if (err) 830 goto done; 831 832 btf->strs_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->str_off; 833 btf->types_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->type_off; 834 835 err = btf_parse_str_sec(btf); 836 err = err ?: btf_parse_type_sec(btf); 837 if (err) 838 goto done; 839 840 btf->fd = -1; 841 842 done: 843 if (err) { 844 btf__free(btf); 845 return ERR_PTR(err); 846 } 847 848 return btf; 849 } 850 851 struct btf *btf__new(const void *data, __u32 size) 852 { 853 return btf_new(data, size, NULL); 854 } 855 856 static struct btf *btf_parse_elf(const char *path, struct btf *base_btf, 857 struct btf_ext **btf_ext) 858 { 859 Elf_Data *btf_data = NULL, *btf_ext_data = NULL; 860 int err = 0, fd = -1, idx = 0; 861 struct btf *btf = NULL; 862 Elf_Scn *scn = NULL; 863 Elf *elf = NULL; 864 GElf_Ehdr ehdr; 865 size_t shstrndx; 866 867 if (elf_version(EV_CURRENT) == EV_NONE) { 868 pr_warn("failed to init libelf for %s\n", path); 869 return ERR_PTR(-LIBBPF_ERRNO__LIBELF); 870 } 871 872 fd = open(path, O_RDONLY); 873 if (fd < 0) { 874 err = -errno; 875 pr_warn("failed to open %s: %s\n", path, strerror(errno)); 876 return ERR_PTR(err); 877 } 878 879 err = -LIBBPF_ERRNO__FORMAT; 880 881 elf = elf_begin(fd, ELF_C_READ, NULL); 882 if (!elf) { 883 pr_warn("failed to open %s as ELF file\n", path); 884 goto done; 885 } 886 if (!gelf_getehdr(elf, &ehdr)) { 887 pr_warn("failed to get EHDR from %s\n", path); 888 goto done; 889 } 890 891 if (elf_getshdrstrndx(elf, &shstrndx)) { 892 pr_warn("failed to get section names section index for %s\n", 893 path); 894 goto done; 895 } 896 897 if (!elf_rawdata(elf_getscn(elf, shstrndx), NULL)) { 898 pr_warn("failed to get e_shstrndx from %s\n", path); 899 goto done; 900 } 901 902 while ((scn = elf_nextscn(elf, scn)) != NULL) { 903 GElf_Shdr sh; 904 char *name; 905 906 idx++; 907 if (gelf_getshdr(scn, &sh) != &sh) { 908 pr_warn("failed to get section(%d) header from %s\n", 909 idx, path); 910 goto done; 911 } 912 name = elf_strptr(elf, shstrndx, sh.sh_name); 913 if (!name) { 914 pr_warn("failed to get section(%d) name from %s\n", 915 idx, path); 916 goto done; 917 } 918 if (strcmp(name, BTF_ELF_SEC) == 0) { 919 btf_data = elf_getdata(scn, 0); 920 if (!btf_data) { 921 pr_warn("failed to get section(%d, %s) data from %s\n", 922 idx, name, path); 923 goto done; 924 } 925 continue; 926 } else if (btf_ext && strcmp(name, BTF_EXT_ELF_SEC) == 0) { 927 btf_ext_data = elf_getdata(scn, 0); 928 if (!btf_ext_data) { 929 pr_warn("failed to get section(%d, %s) data from %s\n", 930 idx, name, path); 931 goto done; 932 } 933 continue; 934 } 935 } 936 937 err = 0; 938 939 if (!btf_data) { 940 err = -ENOENT; 941 goto done; 942 } 943 btf = btf_new(btf_data->d_buf, btf_data->d_size, base_btf); 944 if (IS_ERR(btf)) 945 goto done; 946 947 switch (gelf_getclass(elf)) { 948 case ELFCLASS32: 949 btf__set_pointer_size(btf, 4); 950 break; 951 case ELFCLASS64: 952 btf__set_pointer_size(btf, 8); 953 break; 954 default: 955 pr_warn("failed to get ELF class (bitness) for %s\n", path); 956 break; 957 } 958 959 if (btf_ext && btf_ext_data) { 960 *btf_ext = btf_ext__new(btf_ext_data->d_buf, 961 btf_ext_data->d_size); 962 if (IS_ERR(*btf_ext)) 963 goto done; 964 } else if (btf_ext) { 965 *btf_ext = NULL; 966 } 967 done: 968 if (elf) 969 elf_end(elf); 970 close(fd); 971 972 if (err) 973 return ERR_PTR(err); 974 /* 975 * btf is always parsed before btf_ext, so no need to clean up 976 * btf_ext, if btf loading failed 977 */ 978 if (IS_ERR(btf)) 979 return btf; 980 if (btf_ext && IS_ERR(*btf_ext)) { 981 btf__free(btf); 982 err = PTR_ERR(*btf_ext); 983 return ERR_PTR(err); 984 } 985 return btf; 986 } 987 988 struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext) 989 { 990 return btf_parse_elf(path, NULL, btf_ext); 991 } 992 993 struct btf *btf__parse_elf_split(const char *path, struct btf *base_btf) 994 { 995 return btf_parse_elf(path, base_btf, NULL); 996 } 997 998 static struct btf *btf_parse_raw(const char *path, struct btf *base_btf) 999 { 1000 struct btf *btf = NULL; 1001 void *data = NULL; 1002 FILE *f = NULL; 1003 __u16 magic; 1004 int err = 0; 1005 long sz; 1006 1007 f = fopen(path, "rb"); 1008 if (!f) { 1009 err = -errno; 1010 goto err_out; 1011 } 1012 1013 /* check BTF magic */ 1014 if (fread(&magic, 1, sizeof(magic), f) < sizeof(magic)) { 1015 err = -EIO; 1016 goto err_out; 1017 } 1018 if (magic != BTF_MAGIC && magic != bswap_16(BTF_MAGIC)) { 1019 /* definitely not a raw BTF */ 1020 err = -EPROTO; 1021 goto err_out; 1022 } 1023 1024 /* get file size */ 1025 if (fseek(f, 0, SEEK_END)) { 1026 err = -errno; 1027 goto err_out; 1028 } 1029 sz = ftell(f); 1030 if (sz < 0) { 1031 err = -errno; 1032 goto err_out; 1033 } 1034 /* rewind to the start */ 1035 if (fseek(f, 0, SEEK_SET)) { 1036 err = -errno; 1037 goto err_out; 1038 } 1039 1040 /* pre-alloc memory and read all of BTF data */ 1041 data = malloc(sz); 1042 if (!data) { 1043 err = -ENOMEM; 1044 goto err_out; 1045 } 1046 if (fread(data, 1, sz, f) < sz) { 1047 err = -EIO; 1048 goto err_out; 1049 } 1050 1051 /* finally parse BTF data */ 1052 btf = btf_new(data, sz, base_btf); 1053 1054 err_out: 1055 free(data); 1056 if (f) 1057 fclose(f); 1058 return err ? ERR_PTR(err) : btf; 1059 } 1060 1061 struct btf *btf__parse_raw(const char *path) 1062 { 1063 return btf_parse_raw(path, NULL); 1064 } 1065 1066 struct btf *btf__parse_raw_split(const char *path, struct btf *base_btf) 1067 { 1068 return btf_parse_raw(path, base_btf); 1069 } 1070 1071 static struct btf *btf_parse(const char *path, struct btf *base_btf, struct btf_ext **btf_ext) 1072 { 1073 struct btf *btf; 1074 1075 if (btf_ext) 1076 *btf_ext = NULL; 1077 1078 btf = btf_parse_raw(path, base_btf); 1079 if (!IS_ERR(btf) || PTR_ERR(btf) != -EPROTO) 1080 return btf; 1081 1082 return btf_parse_elf(path, base_btf, btf_ext); 1083 } 1084 1085 struct btf *btf__parse(const char *path, struct btf_ext **btf_ext) 1086 { 1087 return btf_parse(path, NULL, btf_ext); 1088 } 1089 1090 struct btf *btf__parse_split(const char *path, struct btf *base_btf) 1091 { 1092 return btf_parse(path, base_btf, NULL); 1093 } 1094 1095 static int compare_vsi_off(const void *_a, const void *_b) 1096 { 1097 const struct btf_var_secinfo *a = _a; 1098 const struct btf_var_secinfo *b = _b; 1099 1100 return a->offset - b->offset; 1101 } 1102 1103 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf, 1104 struct btf_type *t) 1105 { 1106 __u32 size = 0, off = 0, i, vars = btf_vlen(t); 1107 const char *name = btf__name_by_offset(btf, t->name_off); 1108 const struct btf_type *t_var; 1109 struct btf_var_secinfo *vsi; 1110 const struct btf_var *var; 1111 int ret; 1112 1113 if (!name) { 1114 pr_debug("No name found in string section for DATASEC kind.\n"); 1115 return -ENOENT; 1116 } 1117 1118 /* .extern datasec size and var offsets were set correctly during 1119 * extern collection step, so just skip straight to sorting variables 1120 */ 1121 if (t->size) 1122 goto sort_vars; 1123 1124 ret = bpf_object__section_size(obj, name, &size); 1125 if (ret || !size || (t->size && t->size != size)) { 1126 pr_debug("Invalid size for section %s: %u bytes\n", name, size); 1127 return -ENOENT; 1128 } 1129 1130 t->size = size; 1131 1132 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) { 1133 t_var = btf__type_by_id(btf, vsi->type); 1134 var = btf_var(t_var); 1135 1136 if (!btf_is_var(t_var)) { 1137 pr_debug("Non-VAR type seen in section %s\n", name); 1138 return -EINVAL; 1139 } 1140 1141 if (var->linkage == BTF_VAR_STATIC) 1142 continue; 1143 1144 name = btf__name_by_offset(btf, t_var->name_off); 1145 if (!name) { 1146 pr_debug("No name found in string section for VAR kind\n"); 1147 return -ENOENT; 1148 } 1149 1150 ret = bpf_object__variable_offset(obj, name, &off); 1151 if (ret) { 1152 pr_debug("No offset found in symbol table for VAR %s\n", 1153 name); 1154 return -ENOENT; 1155 } 1156 1157 vsi->offset = off; 1158 } 1159 1160 sort_vars: 1161 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off); 1162 return 0; 1163 } 1164 1165 int btf__finalize_data(struct bpf_object *obj, struct btf *btf) 1166 { 1167 int err = 0; 1168 __u32 i; 1169 1170 for (i = 1; i <= btf->nr_types; i++) { 1171 struct btf_type *t = btf_type_by_id(btf, i); 1172 1173 /* Loader needs to fix up some of the things compiler 1174 * couldn't get its hands on while emitting BTF. This 1175 * is section size and global variable offset. We use 1176 * the info from the ELF itself for this purpose. 1177 */ 1178 if (btf_is_datasec(t)) { 1179 err = btf_fixup_datasec(obj, btf, t); 1180 if (err) 1181 break; 1182 } 1183 } 1184 1185 return err; 1186 } 1187 1188 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian); 1189 1190 int btf__load(struct btf *btf) 1191 { 1192 __u32 log_buf_size = 0, raw_size; 1193 char *log_buf = NULL; 1194 void *raw_data; 1195 int err = 0; 1196 1197 if (btf->fd >= 0) 1198 return -EEXIST; 1199 1200 retry_load: 1201 if (log_buf_size) { 1202 log_buf = malloc(log_buf_size); 1203 if (!log_buf) 1204 return -ENOMEM; 1205 1206 *log_buf = 0; 1207 } 1208 1209 raw_data = btf_get_raw_data(btf, &raw_size, false); 1210 if (!raw_data) { 1211 err = -ENOMEM; 1212 goto done; 1213 } 1214 /* cache native raw data representation */ 1215 btf->raw_size = raw_size; 1216 btf->raw_data = raw_data; 1217 1218 btf->fd = bpf_load_btf(raw_data, raw_size, log_buf, log_buf_size, false); 1219 if (btf->fd < 0) { 1220 if (!log_buf || errno == ENOSPC) { 1221 log_buf_size = max((__u32)BPF_LOG_BUF_SIZE, 1222 log_buf_size << 1); 1223 free(log_buf); 1224 goto retry_load; 1225 } 1226 1227 err = -errno; 1228 pr_warn("Error loading BTF: %s(%d)\n", strerror(errno), errno); 1229 if (*log_buf) 1230 pr_warn("%s\n", log_buf); 1231 goto done; 1232 } 1233 1234 done: 1235 free(log_buf); 1236 return err; 1237 } 1238 1239 int btf__fd(const struct btf *btf) 1240 { 1241 return btf->fd; 1242 } 1243 1244 void btf__set_fd(struct btf *btf, int fd) 1245 { 1246 btf->fd = fd; 1247 } 1248 1249 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian) 1250 { 1251 struct btf_header *hdr = btf->hdr; 1252 struct btf_type *t; 1253 void *data, *p; 1254 __u32 data_sz; 1255 int i; 1256 1257 data = swap_endian ? btf->raw_data_swapped : btf->raw_data; 1258 if (data) { 1259 *size = btf->raw_size; 1260 return data; 1261 } 1262 1263 data_sz = hdr->hdr_len + hdr->type_len + hdr->str_len; 1264 data = calloc(1, data_sz); 1265 if (!data) 1266 return NULL; 1267 p = data; 1268 1269 memcpy(p, hdr, hdr->hdr_len); 1270 if (swap_endian) 1271 btf_bswap_hdr(p); 1272 p += hdr->hdr_len; 1273 1274 memcpy(p, btf->types_data, hdr->type_len); 1275 if (swap_endian) { 1276 for (i = 0; i < btf->nr_types; i++) { 1277 t = p + btf->type_offs[i]; 1278 /* btf_bswap_type_rest() relies on native t->info, so 1279 * we swap base type info after we swapped all the 1280 * additional information 1281 */ 1282 if (btf_bswap_type_rest(t)) 1283 goto err_out; 1284 btf_bswap_type_base(t); 1285 } 1286 } 1287 p += hdr->type_len; 1288 1289 memcpy(p, btf->strs_data, hdr->str_len); 1290 p += hdr->str_len; 1291 1292 *size = data_sz; 1293 return data; 1294 err_out: 1295 free(data); 1296 return NULL; 1297 } 1298 1299 const void *btf__get_raw_data(const struct btf *btf_ro, __u32 *size) 1300 { 1301 struct btf *btf = (struct btf *)btf_ro; 1302 __u32 data_sz; 1303 void *data; 1304 1305 data = btf_get_raw_data(btf, &data_sz, btf->swapped_endian); 1306 if (!data) 1307 return NULL; 1308 1309 btf->raw_size = data_sz; 1310 if (btf->swapped_endian) 1311 btf->raw_data_swapped = data; 1312 else 1313 btf->raw_data = data; 1314 *size = data_sz; 1315 return data; 1316 } 1317 1318 const char *btf__str_by_offset(const struct btf *btf, __u32 offset) 1319 { 1320 if (offset < btf->start_str_off) 1321 return btf__str_by_offset(btf->base_btf, offset); 1322 else if (offset - btf->start_str_off < btf->hdr->str_len) 1323 return btf->strs_data + (offset - btf->start_str_off); 1324 else 1325 return NULL; 1326 } 1327 1328 const char *btf__name_by_offset(const struct btf *btf, __u32 offset) 1329 { 1330 return btf__str_by_offset(btf, offset); 1331 } 1332 1333 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf) 1334 { 1335 struct bpf_btf_info btf_info; 1336 __u32 len = sizeof(btf_info); 1337 __u32 last_size; 1338 struct btf *btf; 1339 void *ptr; 1340 int err; 1341 1342 /* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so 1343 * let's start with a sane default - 4KiB here - and resize it only if 1344 * bpf_obj_get_info_by_fd() needs a bigger buffer. 1345 */ 1346 last_size = 4096; 1347 ptr = malloc(last_size); 1348 if (!ptr) 1349 return ERR_PTR(-ENOMEM); 1350 1351 memset(&btf_info, 0, sizeof(btf_info)); 1352 btf_info.btf = ptr_to_u64(ptr); 1353 btf_info.btf_size = last_size; 1354 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len); 1355 1356 if (!err && btf_info.btf_size > last_size) { 1357 void *temp_ptr; 1358 1359 last_size = btf_info.btf_size; 1360 temp_ptr = realloc(ptr, last_size); 1361 if (!temp_ptr) { 1362 btf = ERR_PTR(-ENOMEM); 1363 goto exit_free; 1364 } 1365 ptr = temp_ptr; 1366 1367 len = sizeof(btf_info); 1368 memset(&btf_info, 0, sizeof(btf_info)); 1369 btf_info.btf = ptr_to_u64(ptr); 1370 btf_info.btf_size = last_size; 1371 1372 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len); 1373 } 1374 1375 if (err || btf_info.btf_size > last_size) { 1376 btf = err ? ERR_PTR(-errno) : ERR_PTR(-E2BIG); 1377 goto exit_free; 1378 } 1379 1380 btf = btf_new(ptr, btf_info.btf_size, base_btf); 1381 1382 exit_free: 1383 free(ptr); 1384 return btf; 1385 } 1386 1387 int btf__get_from_id(__u32 id, struct btf **btf) 1388 { 1389 struct btf *res; 1390 int btf_fd; 1391 1392 *btf = NULL; 1393 btf_fd = bpf_btf_get_fd_by_id(id); 1394 if (btf_fd < 0) 1395 return -errno; 1396 1397 res = btf_get_from_fd(btf_fd, NULL); 1398 close(btf_fd); 1399 if (IS_ERR(res)) 1400 return PTR_ERR(res); 1401 1402 *btf = res; 1403 return 0; 1404 } 1405 1406 int btf__get_map_kv_tids(const struct btf *btf, const char *map_name, 1407 __u32 expected_key_size, __u32 expected_value_size, 1408 __u32 *key_type_id, __u32 *value_type_id) 1409 { 1410 const struct btf_type *container_type; 1411 const struct btf_member *key, *value; 1412 const size_t max_name = 256; 1413 char container_name[max_name]; 1414 __s64 key_size, value_size; 1415 __s32 container_id; 1416 1417 if (snprintf(container_name, max_name, "____btf_map_%s", map_name) == 1418 max_name) { 1419 pr_warn("map:%s length of '____btf_map_%s' is too long\n", 1420 map_name, map_name); 1421 return -EINVAL; 1422 } 1423 1424 container_id = btf__find_by_name(btf, container_name); 1425 if (container_id < 0) { 1426 pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n", 1427 map_name, container_name); 1428 return container_id; 1429 } 1430 1431 container_type = btf__type_by_id(btf, container_id); 1432 if (!container_type) { 1433 pr_warn("map:%s cannot find BTF type for container_id:%u\n", 1434 map_name, container_id); 1435 return -EINVAL; 1436 } 1437 1438 if (!btf_is_struct(container_type) || btf_vlen(container_type) < 2) { 1439 pr_warn("map:%s container_name:%s is an invalid container struct\n", 1440 map_name, container_name); 1441 return -EINVAL; 1442 } 1443 1444 key = btf_members(container_type); 1445 value = key + 1; 1446 1447 key_size = btf__resolve_size(btf, key->type); 1448 if (key_size < 0) { 1449 pr_warn("map:%s invalid BTF key_type_size\n", map_name); 1450 return key_size; 1451 } 1452 1453 if (expected_key_size != key_size) { 1454 pr_warn("map:%s btf_key_type_size:%u != map_def_key_size:%u\n", 1455 map_name, (__u32)key_size, expected_key_size); 1456 return -EINVAL; 1457 } 1458 1459 value_size = btf__resolve_size(btf, value->type); 1460 if (value_size < 0) { 1461 pr_warn("map:%s invalid BTF value_type_size\n", map_name); 1462 return value_size; 1463 } 1464 1465 if (expected_value_size != value_size) { 1466 pr_warn("map:%s btf_value_type_size:%u != map_def_value_size:%u\n", 1467 map_name, (__u32)value_size, expected_value_size); 1468 return -EINVAL; 1469 } 1470 1471 *key_type_id = key->type; 1472 *value_type_id = value->type; 1473 1474 return 0; 1475 } 1476 1477 static size_t strs_hash_fn(const void *key, void *ctx) 1478 { 1479 const struct btf *btf = ctx; 1480 const char *strs = *btf->strs_data_ptr; 1481 const char *str = strs + (long)key; 1482 1483 return str_hash(str); 1484 } 1485 1486 static bool strs_hash_equal_fn(const void *key1, const void *key2, void *ctx) 1487 { 1488 const struct btf *btf = ctx; 1489 const char *strs = *btf->strs_data_ptr; 1490 const char *str1 = strs + (long)key1; 1491 const char *str2 = strs + (long)key2; 1492 1493 return strcmp(str1, str2) == 0; 1494 } 1495 1496 static void btf_invalidate_raw_data(struct btf *btf) 1497 { 1498 if (btf->raw_data) { 1499 free(btf->raw_data); 1500 btf->raw_data = NULL; 1501 } 1502 if (btf->raw_data_swapped) { 1503 free(btf->raw_data_swapped); 1504 btf->raw_data_swapped = NULL; 1505 } 1506 } 1507 1508 /* Ensure BTF is ready to be modified (by splitting into a three memory 1509 * regions for header, types, and strings). Also invalidate cached 1510 * raw_data, if any. 1511 */ 1512 static int btf_ensure_modifiable(struct btf *btf) 1513 { 1514 void *hdr, *types, *strs, *strs_end, *s; 1515 struct hashmap *hash = NULL; 1516 long off; 1517 int err; 1518 1519 if (btf_is_modifiable(btf)) { 1520 /* any BTF modification invalidates raw_data */ 1521 btf_invalidate_raw_data(btf); 1522 return 0; 1523 } 1524 1525 /* split raw data into three memory regions */ 1526 hdr = malloc(btf->hdr->hdr_len); 1527 types = malloc(btf->hdr->type_len); 1528 strs = malloc(btf->hdr->str_len); 1529 if (!hdr || !types || !strs) 1530 goto err_out; 1531 1532 memcpy(hdr, btf->hdr, btf->hdr->hdr_len); 1533 memcpy(types, btf->types_data, btf->hdr->type_len); 1534 memcpy(strs, btf->strs_data, btf->hdr->str_len); 1535 1536 /* make hashmap below use btf->strs_data as a source of strings */ 1537 btf->strs_data_ptr = &btf->strs_data; 1538 1539 /* build lookup index for all strings */ 1540 hash = hashmap__new(strs_hash_fn, strs_hash_equal_fn, btf); 1541 if (IS_ERR(hash)) { 1542 err = PTR_ERR(hash); 1543 hash = NULL; 1544 goto err_out; 1545 } 1546 1547 strs_end = strs + btf->hdr->str_len; 1548 for (off = 0, s = strs; s < strs_end; off += strlen(s) + 1, s = strs + off) { 1549 /* hashmap__add() returns EEXIST if string with the same 1550 * content already is in the hash map 1551 */ 1552 err = hashmap__add(hash, (void *)off, (void *)off); 1553 if (err == -EEXIST) 1554 continue; /* duplicate */ 1555 if (err) 1556 goto err_out; 1557 } 1558 1559 /* only when everything was successful, update internal state */ 1560 btf->hdr = hdr; 1561 btf->types_data = types; 1562 btf->types_data_cap = btf->hdr->type_len; 1563 btf->strs_data = strs; 1564 btf->strs_data_cap = btf->hdr->str_len; 1565 btf->strs_hash = hash; 1566 /* if BTF was created from scratch, all strings are guaranteed to be 1567 * unique and deduplicated 1568 */ 1569 if (btf->hdr->str_len == 0) 1570 btf->strs_deduped = true; 1571 if (!btf->base_btf && btf->hdr->str_len == 1) 1572 btf->strs_deduped = true; 1573 1574 /* invalidate raw_data representation */ 1575 btf_invalidate_raw_data(btf); 1576 1577 return 0; 1578 1579 err_out: 1580 hashmap__free(hash); 1581 free(hdr); 1582 free(types); 1583 free(strs); 1584 return -ENOMEM; 1585 } 1586 1587 static void *btf_add_str_mem(struct btf *btf, size_t add_sz) 1588 { 1589 return btf_add_mem(&btf->strs_data, &btf->strs_data_cap, 1, 1590 btf->hdr->str_len, BTF_MAX_STR_OFFSET, add_sz); 1591 } 1592 1593 /* Find an offset in BTF string section that corresponds to a given string *s*. 1594 * Returns: 1595 * - >0 offset into string section, if string is found; 1596 * - -ENOENT, if string is not in the string section; 1597 * - <0, on any other error. 1598 */ 1599 int btf__find_str(struct btf *btf, const char *s) 1600 { 1601 long old_off, new_off, len; 1602 void *p; 1603 1604 if (btf->base_btf) { 1605 int ret; 1606 1607 ret = btf__find_str(btf->base_btf, s); 1608 if (ret != -ENOENT) 1609 return ret; 1610 } 1611 1612 /* BTF needs to be in a modifiable state to build string lookup index */ 1613 if (btf_ensure_modifiable(btf)) 1614 return -ENOMEM; 1615 1616 /* see btf__add_str() for why we do this */ 1617 len = strlen(s) + 1; 1618 p = btf_add_str_mem(btf, len); 1619 if (!p) 1620 return -ENOMEM; 1621 1622 new_off = btf->hdr->str_len; 1623 memcpy(p, s, len); 1624 1625 if (hashmap__find(btf->strs_hash, (void *)new_off, (void **)&old_off)) 1626 return btf->start_str_off + old_off; 1627 1628 return -ENOENT; 1629 } 1630 1631 /* Add a string s to the BTF string section. 1632 * Returns: 1633 * - > 0 offset into string section, on success; 1634 * - < 0, on error. 1635 */ 1636 int btf__add_str(struct btf *btf, const char *s) 1637 { 1638 long old_off, new_off, len; 1639 void *p; 1640 int err; 1641 1642 if (btf->base_btf) { 1643 int ret; 1644 1645 ret = btf__find_str(btf->base_btf, s); 1646 if (ret != -ENOENT) 1647 return ret; 1648 } 1649 1650 if (btf_ensure_modifiable(btf)) 1651 return -ENOMEM; 1652 1653 /* Hashmap keys are always offsets within btf->strs_data, so to even 1654 * look up some string from the "outside", we need to first append it 1655 * at the end, so that it can be addressed with an offset. Luckily, 1656 * until btf->hdr->str_len is incremented, that string is just a piece 1657 * of garbage for the rest of BTF code, so no harm, no foul. On the 1658 * other hand, if the string is unique, it's already appended and 1659 * ready to be used, only a simple btf->hdr->str_len increment away. 1660 */ 1661 len = strlen(s) + 1; 1662 p = btf_add_str_mem(btf, len); 1663 if (!p) 1664 return -ENOMEM; 1665 1666 new_off = btf->hdr->str_len; 1667 memcpy(p, s, len); 1668 1669 /* Now attempt to add the string, but only if the string with the same 1670 * contents doesn't exist already (HASHMAP_ADD strategy). If such 1671 * string exists, we'll get its offset in old_off (that's old_key). 1672 */ 1673 err = hashmap__insert(btf->strs_hash, (void *)new_off, (void *)new_off, 1674 HASHMAP_ADD, (const void **)&old_off, NULL); 1675 if (err == -EEXIST) 1676 return btf->start_str_off + old_off; /* duplicated string, return existing offset */ 1677 if (err) 1678 return err; 1679 1680 btf->hdr->str_len += len; /* new unique string, adjust data length */ 1681 return btf->start_str_off + new_off; 1682 } 1683 1684 static void *btf_add_type_mem(struct btf *btf, size_t add_sz) 1685 { 1686 return btf_add_mem(&btf->types_data, &btf->types_data_cap, 1, 1687 btf->hdr->type_len, UINT_MAX, add_sz); 1688 } 1689 1690 static __u32 btf_type_info(int kind, int vlen, int kflag) 1691 { 1692 return (kflag << 31) | (kind << 24) | vlen; 1693 } 1694 1695 static void btf_type_inc_vlen(struct btf_type *t) 1696 { 1697 t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, btf_kflag(t)); 1698 } 1699 1700 static int btf_commit_type(struct btf *btf, int data_sz) 1701 { 1702 int err; 1703 1704 err = btf_add_type_idx_entry(btf, btf->hdr->type_len); 1705 if (err) 1706 return err; 1707 1708 btf->hdr->type_len += data_sz; 1709 btf->hdr->str_off += data_sz; 1710 btf->nr_types++; 1711 return btf->start_id + btf->nr_types - 1; 1712 } 1713 1714 /* 1715 * Append new BTF_KIND_INT type with: 1716 * - *name* - non-empty, non-NULL type name; 1717 * - *sz* - power-of-2 (1, 2, 4, ..) size of the type, in bytes; 1718 * - encoding is a combination of BTF_INT_SIGNED, BTF_INT_CHAR, BTF_INT_BOOL. 1719 * Returns: 1720 * - >0, type ID of newly added BTF type; 1721 * - <0, on error. 1722 */ 1723 int btf__add_int(struct btf *btf, const char *name, size_t byte_sz, int encoding) 1724 { 1725 struct btf_type *t; 1726 int sz, name_off; 1727 1728 /* non-empty name */ 1729 if (!name || !name[0]) 1730 return -EINVAL; 1731 /* byte_sz must be power of 2 */ 1732 if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 16) 1733 return -EINVAL; 1734 if (encoding & ~(BTF_INT_SIGNED | BTF_INT_CHAR | BTF_INT_BOOL)) 1735 return -EINVAL; 1736 1737 /* deconstruct BTF, if necessary, and invalidate raw_data */ 1738 if (btf_ensure_modifiable(btf)) 1739 return -ENOMEM; 1740 1741 sz = sizeof(struct btf_type) + sizeof(int); 1742 t = btf_add_type_mem(btf, sz); 1743 if (!t) 1744 return -ENOMEM; 1745 1746 /* if something goes wrong later, we might end up with an extra string, 1747 * but that shouldn't be a problem, because BTF can't be constructed 1748 * completely anyway and will most probably be just discarded 1749 */ 1750 name_off = btf__add_str(btf, name); 1751 if (name_off < 0) 1752 return name_off; 1753 1754 t->name_off = name_off; 1755 t->info = btf_type_info(BTF_KIND_INT, 0, 0); 1756 t->size = byte_sz; 1757 /* set INT info, we don't allow setting legacy bit offset/size */ 1758 *(__u32 *)(t + 1) = (encoding << 24) | (byte_sz * 8); 1759 1760 return btf_commit_type(btf, sz); 1761 } 1762 1763 /* 1764 * Append new BTF_KIND_FLOAT type with: 1765 * - *name* - non-empty, non-NULL type name; 1766 * - *sz* - size of the type, in bytes; 1767 * Returns: 1768 * - >0, type ID of newly added BTF type; 1769 * - <0, on error. 1770 */ 1771 int btf__add_float(struct btf *btf, const char *name, size_t byte_sz) 1772 { 1773 struct btf_type *t; 1774 int sz, name_off; 1775 1776 /* non-empty name */ 1777 if (!name || !name[0]) 1778 return -EINVAL; 1779 1780 /* byte_sz must be one of the explicitly allowed values */ 1781 if (byte_sz != 2 && byte_sz != 4 && byte_sz != 8 && byte_sz != 12 && 1782 byte_sz != 16) 1783 return -EINVAL; 1784 1785 if (btf_ensure_modifiable(btf)) 1786 return -ENOMEM; 1787 1788 sz = sizeof(struct btf_type); 1789 t = btf_add_type_mem(btf, sz); 1790 if (!t) 1791 return -ENOMEM; 1792 1793 name_off = btf__add_str(btf, name); 1794 if (name_off < 0) 1795 return name_off; 1796 1797 t->name_off = name_off; 1798 t->info = btf_type_info(BTF_KIND_FLOAT, 0, 0); 1799 t->size = byte_sz; 1800 1801 return btf_commit_type(btf, sz); 1802 } 1803 1804 /* it's completely legal to append BTF types with type IDs pointing forward to 1805 * types that haven't been appended yet, so we only make sure that id looks 1806 * sane, we can't guarantee that ID will always be valid 1807 */ 1808 static int validate_type_id(int id) 1809 { 1810 if (id < 0 || id > BTF_MAX_NR_TYPES) 1811 return -EINVAL; 1812 return 0; 1813 } 1814 1815 /* generic append function for PTR, TYPEDEF, CONST/VOLATILE/RESTRICT */ 1816 static int btf_add_ref_kind(struct btf *btf, int kind, const char *name, int ref_type_id) 1817 { 1818 struct btf_type *t; 1819 int sz, name_off = 0; 1820 1821 if (validate_type_id(ref_type_id)) 1822 return -EINVAL; 1823 1824 if (btf_ensure_modifiable(btf)) 1825 return -ENOMEM; 1826 1827 sz = sizeof(struct btf_type); 1828 t = btf_add_type_mem(btf, sz); 1829 if (!t) 1830 return -ENOMEM; 1831 1832 if (name && name[0]) { 1833 name_off = btf__add_str(btf, name); 1834 if (name_off < 0) 1835 return name_off; 1836 } 1837 1838 t->name_off = name_off; 1839 t->info = btf_type_info(kind, 0, 0); 1840 t->type = ref_type_id; 1841 1842 return btf_commit_type(btf, sz); 1843 } 1844 1845 /* 1846 * Append new BTF_KIND_PTR type with: 1847 * - *ref_type_id* - referenced type ID, it might not exist yet; 1848 * Returns: 1849 * - >0, type ID of newly added BTF type; 1850 * - <0, on error. 1851 */ 1852 int btf__add_ptr(struct btf *btf, int ref_type_id) 1853 { 1854 return btf_add_ref_kind(btf, BTF_KIND_PTR, NULL, ref_type_id); 1855 } 1856 1857 /* 1858 * Append new BTF_KIND_ARRAY type with: 1859 * - *index_type_id* - type ID of the type describing array index; 1860 * - *elem_type_id* - type ID of the type describing array element; 1861 * - *nr_elems* - the size of the array; 1862 * Returns: 1863 * - >0, type ID of newly added BTF type; 1864 * - <0, on error. 1865 */ 1866 int btf__add_array(struct btf *btf, int index_type_id, int elem_type_id, __u32 nr_elems) 1867 { 1868 struct btf_type *t; 1869 struct btf_array *a; 1870 int sz; 1871 1872 if (validate_type_id(index_type_id) || validate_type_id(elem_type_id)) 1873 return -EINVAL; 1874 1875 if (btf_ensure_modifiable(btf)) 1876 return -ENOMEM; 1877 1878 sz = sizeof(struct btf_type) + sizeof(struct btf_array); 1879 t = btf_add_type_mem(btf, sz); 1880 if (!t) 1881 return -ENOMEM; 1882 1883 t->name_off = 0; 1884 t->info = btf_type_info(BTF_KIND_ARRAY, 0, 0); 1885 t->size = 0; 1886 1887 a = btf_array(t); 1888 a->type = elem_type_id; 1889 a->index_type = index_type_id; 1890 a->nelems = nr_elems; 1891 1892 return btf_commit_type(btf, sz); 1893 } 1894 1895 /* generic STRUCT/UNION append function */ 1896 static int btf_add_composite(struct btf *btf, int kind, const char *name, __u32 bytes_sz) 1897 { 1898 struct btf_type *t; 1899 int sz, name_off = 0; 1900 1901 if (btf_ensure_modifiable(btf)) 1902 return -ENOMEM; 1903 1904 sz = sizeof(struct btf_type); 1905 t = btf_add_type_mem(btf, sz); 1906 if (!t) 1907 return -ENOMEM; 1908 1909 if (name && name[0]) { 1910 name_off = btf__add_str(btf, name); 1911 if (name_off < 0) 1912 return name_off; 1913 } 1914 1915 /* start out with vlen=0 and no kflag; this will be adjusted when 1916 * adding each member 1917 */ 1918 t->name_off = name_off; 1919 t->info = btf_type_info(kind, 0, 0); 1920 t->size = bytes_sz; 1921 1922 return btf_commit_type(btf, sz); 1923 } 1924 1925 /* 1926 * Append new BTF_KIND_STRUCT type with: 1927 * - *name* - name of the struct, can be NULL or empty for anonymous structs; 1928 * - *byte_sz* - size of the struct, in bytes; 1929 * 1930 * Struct initially has no fields in it. Fields can be added by 1931 * btf__add_field() right after btf__add_struct() succeeds. 1932 * 1933 * Returns: 1934 * - >0, type ID of newly added BTF type; 1935 * - <0, on error. 1936 */ 1937 int btf__add_struct(struct btf *btf, const char *name, __u32 byte_sz) 1938 { 1939 return btf_add_composite(btf, BTF_KIND_STRUCT, name, byte_sz); 1940 } 1941 1942 /* 1943 * Append new BTF_KIND_UNION type with: 1944 * - *name* - name of the union, can be NULL or empty for anonymous union; 1945 * - *byte_sz* - size of the union, in bytes; 1946 * 1947 * Union initially has no fields in it. Fields can be added by 1948 * btf__add_field() right after btf__add_union() succeeds. All fields 1949 * should have *bit_offset* of 0. 1950 * 1951 * Returns: 1952 * - >0, type ID of newly added BTF type; 1953 * - <0, on error. 1954 */ 1955 int btf__add_union(struct btf *btf, const char *name, __u32 byte_sz) 1956 { 1957 return btf_add_composite(btf, BTF_KIND_UNION, name, byte_sz); 1958 } 1959 1960 static struct btf_type *btf_last_type(struct btf *btf) 1961 { 1962 return btf_type_by_id(btf, btf__get_nr_types(btf)); 1963 } 1964 1965 /* 1966 * Append new field for the current STRUCT/UNION type with: 1967 * - *name* - name of the field, can be NULL or empty for anonymous field; 1968 * - *type_id* - type ID for the type describing field type; 1969 * - *bit_offset* - bit offset of the start of the field within struct/union; 1970 * - *bit_size* - bit size of a bitfield, 0 for non-bitfield fields; 1971 * Returns: 1972 * - 0, on success; 1973 * - <0, on error. 1974 */ 1975 int btf__add_field(struct btf *btf, const char *name, int type_id, 1976 __u32 bit_offset, __u32 bit_size) 1977 { 1978 struct btf_type *t; 1979 struct btf_member *m; 1980 bool is_bitfield; 1981 int sz, name_off = 0; 1982 1983 /* last type should be union/struct */ 1984 if (btf->nr_types == 0) 1985 return -EINVAL; 1986 t = btf_last_type(btf); 1987 if (!btf_is_composite(t)) 1988 return -EINVAL; 1989 1990 if (validate_type_id(type_id)) 1991 return -EINVAL; 1992 /* best-effort bit field offset/size enforcement */ 1993 is_bitfield = bit_size || (bit_offset % 8 != 0); 1994 if (is_bitfield && (bit_size == 0 || bit_size > 255 || bit_offset > 0xffffff)) 1995 return -EINVAL; 1996 1997 /* only offset 0 is allowed for unions */ 1998 if (btf_is_union(t) && bit_offset) 1999 return -EINVAL; 2000 2001 /* decompose and invalidate raw data */ 2002 if (btf_ensure_modifiable(btf)) 2003 return -ENOMEM; 2004 2005 sz = sizeof(struct btf_member); 2006 m = btf_add_type_mem(btf, sz); 2007 if (!m) 2008 return -ENOMEM; 2009 2010 if (name && name[0]) { 2011 name_off = btf__add_str(btf, name); 2012 if (name_off < 0) 2013 return name_off; 2014 } 2015 2016 m->name_off = name_off; 2017 m->type = type_id; 2018 m->offset = bit_offset | (bit_size << 24); 2019 2020 /* btf_add_type_mem can invalidate t pointer */ 2021 t = btf_last_type(btf); 2022 /* update parent type's vlen and kflag */ 2023 t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, is_bitfield || btf_kflag(t)); 2024 2025 btf->hdr->type_len += sz; 2026 btf->hdr->str_off += sz; 2027 return 0; 2028 } 2029 2030 /* 2031 * Append new BTF_KIND_ENUM type with: 2032 * - *name* - name of the enum, can be NULL or empty for anonymous enums; 2033 * - *byte_sz* - size of the enum, in bytes. 2034 * 2035 * Enum initially has no enum values in it (and corresponds to enum forward 2036 * declaration). Enumerator values can be added by btf__add_enum_value() 2037 * immediately after btf__add_enum() succeeds. 2038 * 2039 * Returns: 2040 * - >0, type ID of newly added BTF type; 2041 * - <0, on error. 2042 */ 2043 int btf__add_enum(struct btf *btf, const char *name, __u32 byte_sz) 2044 { 2045 struct btf_type *t; 2046 int sz, name_off = 0; 2047 2048 /* byte_sz must be power of 2 */ 2049 if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 8) 2050 return -EINVAL; 2051 2052 if (btf_ensure_modifiable(btf)) 2053 return -ENOMEM; 2054 2055 sz = sizeof(struct btf_type); 2056 t = btf_add_type_mem(btf, sz); 2057 if (!t) 2058 return -ENOMEM; 2059 2060 if (name && name[0]) { 2061 name_off = btf__add_str(btf, name); 2062 if (name_off < 0) 2063 return name_off; 2064 } 2065 2066 /* start out with vlen=0; it will be adjusted when adding enum values */ 2067 t->name_off = name_off; 2068 t->info = btf_type_info(BTF_KIND_ENUM, 0, 0); 2069 t->size = byte_sz; 2070 2071 return btf_commit_type(btf, sz); 2072 } 2073 2074 /* 2075 * Append new enum value for the current ENUM type with: 2076 * - *name* - name of the enumerator value, can't be NULL or empty; 2077 * - *value* - integer value corresponding to enum value *name*; 2078 * Returns: 2079 * - 0, on success; 2080 * - <0, on error. 2081 */ 2082 int btf__add_enum_value(struct btf *btf, const char *name, __s64 value) 2083 { 2084 struct btf_type *t; 2085 struct btf_enum *v; 2086 int sz, name_off; 2087 2088 /* last type should be BTF_KIND_ENUM */ 2089 if (btf->nr_types == 0) 2090 return -EINVAL; 2091 t = btf_last_type(btf); 2092 if (!btf_is_enum(t)) 2093 return -EINVAL; 2094 2095 /* non-empty name */ 2096 if (!name || !name[0]) 2097 return -EINVAL; 2098 if (value < INT_MIN || value > UINT_MAX) 2099 return -E2BIG; 2100 2101 /* decompose and invalidate raw data */ 2102 if (btf_ensure_modifiable(btf)) 2103 return -ENOMEM; 2104 2105 sz = sizeof(struct btf_enum); 2106 v = btf_add_type_mem(btf, sz); 2107 if (!v) 2108 return -ENOMEM; 2109 2110 name_off = btf__add_str(btf, name); 2111 if (name_off < 0) 2112 return name_off; 2113 2114 v->name_off = name_off; 2115 v->val = value; 2116 2117 /* update parent type's vlen */ 2118 t = btf_last_type(btf); 2119 btf_type_inc_vlen(t); 2120 2121 btf->hdr->type_len += sz; 2122 btf->hdr->str_off += sz; 2123 return 0; 2124 } 2125 2126 /* 2127 * Append new BTF_KIND_FWD type with: 2128 * - *name*, non-empty/non-NULL name; 2129 * - *fwd_kind*, kind of forward declaration, one of BTF_FWD_STRUCT, 2130 * BTF_FWD_UNION, or BTF_FWD_ENUM; 2131 * Returns: 2132 * - >0, type ID of newly added BTF type; 2133 * - <0, on error. 2134 */ 2135 int btf__add_fwd(struct btf *btf, const char *name, enum btf_fwd_kind fwd_kind) 2136 { 2137 if (!name || !name[0]) 2138 return -EINVAL; 2139 2140 switch (fwd_kind) { 2141 case BTF_FWD_STRUCT: 2142 case BTF_FWD_UNION: { 2143 struct btf_type *t; 2144 int id; 2145 2146 id = btf_add_ref_kind(btf, BTF_KIND_FWD, name, 0); 2147 if (id <= 0) 2148 return id; 2149 t = btf_type_by_id(btf, id); 2150 t->info = btf_type_info(BTF_KIND_FWD, 0, fwd_kind == BTF_FWD_UNION); 2151 return id; 2152 } 2153 case BTF_FWD_ENUM: 2154 /* enum forward in BTF currently is just an enum with no enum 2155 * values; we also assume a standard 4-byte size for it 2156 */ 2157 return btf__add_enum(btf, name, sizeof(int)); 2158 default: 2159 return -EINVAL; 2160 } 2161 } 2162 2163 /* 2164 * Append new BTF_KING_TYPEDEF type with: 2165 * - *name*, non-empty/non-NULL name; 2166 * - *ref_type_id* - referenced type ID, it might not exist yet; 2167 * Returns: 2168 * - >0, type ID of newly added BTF type; 2169 * - <0, on error. 2170 */ 2171 int btf__add_typedef(struct btf *btf, const char *name, int ref_type_id) 2172 { 2173 if (!name || !name[0]) 2174 return -EINVAL; 2175 2176 return btf_add_ref_kind(btf, BTF_KIND_TYPEDEF, name, ref_type_id); 2177 } 2178 2179 /* 2180 * Append new BTF_KIND_VOLATILE type with: 2181 * - *ref_type_id* - referenced type ID, it might not exist yet; 2182 * Returns: 2183 * - >0, type ID of newly added BTF type; 2184 * - <0, on error. 2185 */ 2186 int btf__add_volatile(struct btf *btf, int ref_type_id) 2187 { 2188 return btf_add_ref_kind(btf, BTF_KIND_VOLATILE, NULL, ref_type_id); 2189 } 2190 2191 /* 2192 * Append new BTF_KIND_CONST type with: 2193 * - *ref_type_id* - referenced type ID, it might not exist yet; 2194 * Returns: 2195 * - >0, type ID of newly added BTF type; 2196 * - <0, on error. 2197 */ 2198 int btf__add_const(struct btf *btf, int ref_type_id) 2199 { 2200 return btf_add_ref_kind(btf, BTF_KIND_CONST, NULL, ref_type_id); 2201 } 2202 2203 /* 2204 * Append new BTF_KIND_RESTRICT type with: 2205 * - *ref_type_id* - referenced type ID, it might not exist yet; 2206 * Returns: 2207 * - >0, type ID of newly added BTF type; 2208 * - <0, on error. 2209 */ 2210 int btf__add_restrict(struct btf *btf, int ref_type_id) 2211 { 2212 return btf_add_ref_kind(btf, BTF_KIND_RESTRICT, NULL, ref_type_id); 2213 } 2214 2215 /* 2216 * Append new BTF_KIND_FUNC type with: 2217 * - *name*, non-empty/non-NULL name; 2218 * - *proto_type_id* - FUNC_PROTO's type ID, it might not exist yet; 2219 * Returns: 2220 * - >0, type ID of newly added BTF type; 2221 * - <0, on error. 2222 */ 2223 int btf__add_func(struct btf *btf, const char *name, 2224 enum btf_func_linkage linkage, int proto_type_id) 2225 { 2226 int id; 2227 2228 if (!name || !name[0]) 2229 return -EINVAL; 2230 if (linkage != BTF_FUNC_STATIC && linkage != BTF_FUNC_GLOBAL && 2231 linkage != BTF_FUNC_EXTERN) 2232 return -EINVAL; 2233 2234 id = btf_add_ref_kind(btf, BTF_KIND_FUNC, name, proto_type_id); 2235 if (id > 0) { 2236 struct btf_type *t = btf_type_by_id(btf, id); 2237 2238 t->info = btf_type_info(BTF_KIND_FUNC, linkage, 0); 2239 } 2240 return id; 2241 } 2242 2243 /* 2244 * Append new BTF_KIND_FUNC_PROTO with: 2245 * - *ret_type_id* - type ID for return result of a function. 2246 * 2247 * Function prototype initially has no arguments, but they can be added by 2248 * btf__add_func_param() one by one, immediately after 2249 * btf__add_func_proto() succeeded. 2250 * 2251 * Returns: 2252 * - >0, type ID of newly added BTF type; 2253 * - <0, on error. 2254 */ 2255 int btf__add_func_proto(struct btf *btf, int ret_type_id) 2256 { 2257 struct btf_type *t; 2258 int sz; 2259 2260 if (validate_type_id(ret_type_id)) 2261 return -EINVAL; 2262 2263 if (btf_ensure_modifiable(btf)) 2264 return -ENOMEM; 2265 2266 sz = sizeof(struct btf_type); 2267 t = btf_add_type_mem(btf, sz); 2268 if (!t) 2269 return -ENOMEM; 2270 2271 /* start out with vlen=0; this will be adjusted when adding enum 2272 * values, if necessary 2273 */ 2274 t->name_off = 0; 2275 t->info = btf_type_info(BTF_KIND_FUNC_PROTO, 0, 0); 2276 t->type = ret_type_id; 2277 2278 return btf_commit_type(btf, sz); 2279 } 2280 2281 /* 2282 * Append new function parameter for current FUNC_PROTO type with: 2283 * - *name* - parameter name, can be NULL or empty; 2284 * - *type_id* - type ID describing the type of the parameter. 2285 * Returns: 2286 * - 0, on success; 2287 * - <0, on error. 2288 */ 2289 int btf__add_func_param(struct btf *btf, const char *name, int type_id) 2290 { 2291 struct btf_type *t; 2292 struct btf_param *p; 2293 int sz, name_off = 0; 2294 2295 if (validate_type_id(type_id)) 2296 return -EINVAL; 2297 2298 /* last type should be BTF_KIND_FUNC_PROTO */ 2299 if (btf->nr_types == 0) 2300 return -EINVAL; 2301 t = btf_last_type(btf); 2302 if (!btf_is_func_proto(t)) 2303 return -EINVAL; 2304 2305 /* decompose and invalidate raw data */ 2306 if (btf_ensure_modifiable(btf)) 2307 return -ENOMEM; 2308 2309 sz = sizeof(struct btf_param); 2310 p = btf_add_type_mem(btf, sz); 2311 if (!p) 2312 return -ENOMEM; 2313 2314 if (name && name[0]) { 2315 name_off = btf__add_str(btf, name); 2316 if (name_off < 0) 2317 return name_off; 2318 } 2319 2320 p->name_off = name_off; 2321 p->type = type_id; 2322 2323 /* update parent type's vlen */ 2324 t = btf_last_type(btf); 2325 btf_type_inc_vlen(t); 2326 2327 btf->hdr->type_len += sz; 2328 btf->hdr->str_off += sz; 2329 return 0; 2330 } 2331 2332 /* 2333 * Append new BTF_KIND_VAR type with: 2334 * - *name* - non-empty/non-NULL name; 2335 * - *linkage* - variable linkage, one of BTF_VAR_STATIC, 2336 * BTF_VAR_GLOBAL_ALLOCATED, or BTF_VAR_GLOBAL_EXTERN; 2337 * - *type_id* - type ID of the type describing the type of the variable. 2338 * Returns: 2339 * - >0, type ID of newly added BTF type; 2340 * - <0, on error. 2341 */ 2342 int btf__add_var(struct btf *btf, const char *name, int linkage, int type_id) 2343 { 2344 struct btf_type *t; 2345 struct btf_var *v; 2346 int sz, name_off; 2347 2348 /* non-empty name */ 2349 if (!name || !name[0]) 2350 return -EINVAL; 2351 if (linkage != BTF_VAR_STATIC && linkage != BTF_VAR_GLOBAL_ALLOCATED && 2352 linkage != BTF_VAR_GLOBAL_EXTERN) 2353 return -EINVAL; 2354 if (validate_type_id(type_id)) 2355 return -EINVAL; 2356 2357 /* deconstruct BTF, if necessary, and invalidate raw_data */ 2358 if (btf_ensure_modifiable(btf)) 2359 return -ENOMEM; 2360 2361 sz = sizeof(struct btf_type) + sizeof(struct btf_var); 2362 t = btf_add_type_mem(btf, sz); 2363 if (!t) 2364 return -ENOMEM; 2365 2366 name_off = btf__add_str(btf, name); 2367 if (name_off < 0) 2368 return name_off; 2369 2370 t->name_off = name_off; 2371 t->info = btf_type_info(BTF_KIND_VAR, 0, 0); 2372 t->type = type_id; 2373 2374 v = btf_var(t); 2375 v->linkage = linkage; 2376 2377 return btf_commit_type(btf, sz); 2378 } 2379 2380 /* 2381 * Append new BTF_KIND_DATASEC type with: 2382 * - *name* - non-empty/non-NULL name; 2383 * - *byte_sz* - data section size, in bytes. 2384 * 2385 * Data section is initially empty. Variables info can be added with 2386 * btf__add_datasec_var_info() calls, after btf__add_datasec() succeeds. 2387 * 2388 * Returns: 2389 * - >0, type ID of newly added BTF type; 2390 * - <0, on error. 2391 */ 2392 int btf__add_datasec(struct btf *btf, const char *name, __u32 byte_sz) 2393 { 2394 struct btf_type *t; 2395 int sz, name_off; 2396 2397 /* non-empty name */ 2398 if (!name || !name[0]) 2399 return -EINVAL; 2400 2401 if (btf_ensure_modifiable(btf)) 2402 return -ENOMEM; 2403 2404 sz = sizeof(struct btf_type); 2405 t = btf_add_type_mem(btf, sz); 2406 if (!t) 2407 return -ENOMEM; 2408 2409 name_off = btf__add_str(btf, name); 2410 if (name_off < 0) 2411 return name_off; 2412 2413 /* start with vlen=0, which will be update as var_secinfos are added */ 2414 t->name_off = name_off; 2415 t->info = btf_type_info(BTF_KIND_DATASEC, 0, 0); 2416 t->size = byte_sz; 2417 2418 return btf_commit_type(btf, sz); 2419 } 2420 2421 /* 2422 * Append new data section variable information entry for current DATASEC type: 2423 * - *var_type_id* - type ID, describing type of the variable; 2424 * - *offset* - variable offset within data section, in bytes; 2425 * - *byte_sz* - variable size, in bytes. 2426 * 2427 * Returns: 2428 * - 0, on success; 2429 * - <0, on error. 2430 */ 2431 int btf__add_datasec_var_info(struct btf *btf, int var_type_id, __u32 offset, __u32 byte_sz) 2432 { 2433 struct btf_type *t; 2434 struct btf_var_secinfo *v; 2435 int sz; 2436 2437 /* last type should be BTF_KIND_DATASEC */ 2438 if (btf->nr_types == 0) 2439 return -EINVAL; 2440 t = btf_last_type(btf); 2441 if (!btf_is_datasec(t)) 2442 return -EINVAL; 2443 2444 if (validate_type_id(var_type_id)) 2445 return -EINVAL; 2446 2447 /* decompose and invalidate raw data */ 2448 if (btf_ensure_modifiable(btf)) 2449 return -ENOMEM; 2450 2451 sz = sizeof(struct btf_var_secinfo); 2452 v = btf_add_type_mem(btf, sz); 2453 if (!v) 2454 return -ENOMEM; 2455 2456 v->type = var_type_id; 2457 v->offset = offset; 2458 v->size = byte_sz; 2459 2460 /* update parent type's vlen */ 2461 t = btf_last_type(btf); 2462 btf_type_inc_vlen(t); 2463 2464 btf->hdr->type_len += sz; 2465 btf->hdr->str_off += sz; 2466 return 0; 2467 } 2468 2469 struct btf_ext_sec_setup_param { 2470 __u32 off; 2471 __u32 len; 2472 __u32 min_rec_size; 2473 struct btf_ext_info *ext_info; 2474 const char *desc; 2475 }; 2476 2477 static int btf_ext_setup_info(struct btf_ext *btf_ext, 2478 struct btf_ext_sec_setup_param *ext_sec) 2479 { 2480 const struct btf_ext_info_sec *sinfo; 2481 struct btf_ext_info *ext_info; 2482 __u32 info_left, record_size; 2483 /* The start of the info sec (including the __u32 record_size). */ 2484 void *info; 2485 2486 if (ext_sec->len == 0) 2487 return 0; 2488 2489 if (ext_sec->off & 0x03) { 2490 pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n", 2491 ext_sec->desc); 2492 return -EINVAL; 2493 } 2494 2495 info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off; 2496 info_left = ext_sec->len; 2497 2498 if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) { 2499 pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n", 2500 ext_sec->desc, ext_sec->off, ext_sec->len); 2501 return -EINVAL; 2502 } 2503 2504 /* At least a record size */ 2505 if (info_left < sizeof(__u32)) { 2506 pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc); 2507 return -EINVAL; 2508 } 2509 2510 /* The record size needs to meet the minimum standard */ 2511 record_size = *(__u32 *)info; 2512 if (record_size < ext_sec->min_rec_size || 2513 record_size & 0x03) { 2514 pr_debug("%s section in .BTF.ext has invalid record size %u\n", 2515 ext_sec->desc, record_size); 2516 return -EINVAL; 2517 } 2518 2519 sinfo = info + sizeof(__u32); 2520 info_left -= sizeof(__u32); 2521 2522 /* If no records, return failure now so .BTF.ext won't be used. */ 2523 if (!info_left) { 2524 pr_debug("%s section in .BTF.ext has no records", ext_sec->desc); 2525 return -EINVAL; 2526 } 2527 2528 while (info_left) { 2529 unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec); 2530 __u64 total_record_size; 2531 __u32 num_records; 2532 2533 if (info_left < sec_hdrlen) { 2534 pr_debug("%s section header is not found in .BTF.ext\n", 2535 ext_sec->desc); 2536 return -EINVAL; 2537 } 2538 2539 num_records = sinfo->num_info; 2540 if (num_records == 0) { 2541 pr_debug("%s section has incorrect num_records in .BTF.ext\n", 2542 ext_sec->desc); 2543 return -EINVAL; 2544 } 2545 2546 total_record_size = sec_hdrlen + 2547 (__u64)num_records * record_size; 2548 if (info_left < total_record_size) { 2549 pr_debug("%s section has incorrect num_records in .BTF.ext\n", 2550 ext_sec->desc); 2551 return -EINVAL; 2552 } 2553 2554 info_left -= total_record_size; 2555 sinfo = (void *)sinfo + total_record_size; 2556 } 2557 2558 ext_info = ext_sec->ext_info; 2559 ext_info->len = ext_sec->len - sizeof(__u32); 2560 ext_info->rec_size = record_size; 2561 ext_info->info = info + sizeof(__u32); 2562 2563 return 0; 2564 } 2565 2566 static int btf_ext_setup_func_info(struct btf_ext *btf_ext) 2567 { 2568 struct btf_ext_sec_setup_param param = { 2569 .off = btf_ext->hdr->func_info_off, 2570 .len = btf_ext->hdr->func_info_len, 2571 .min_rec_size = sizeof(struct bpf_func_info_min), 2572 .ext_info = &btf_ext->func_info, 2573 .desc = "func_info" 2574 }; 2575 2576 return btf_ext_setup_info(btf_ext, ¶m); 2577 } 2578 2579 static int btf_ext_setup_line_info(struct btf_ext *btf_ext) 2580 { 2581 struct btf_ext_sec_setup_param param = { 2582 .off = btf_ext->hdr->line_info_off, 2583 .len = btf_ext->hdr->line_info_len, 2584 .min_rec_size = sizeof(struct bpf_line_info_min), 2585 .ext_info = &btf_ext->line_info, 2586 .desc = "line_info", 2587 }; 2588 2589 return btf_ext_setup_info(btf_ext, ¶m); 2590 } 2591 2592 static int btf_ext_setup_core_relos(struct btf_ext *btf_ext) 2593 { 2594 struct btf_ext_sec_setup_param param = { 2595 .off = btf_ext->hdr->core_relo_off, 2596 .len = btf_ext->hdr->core_relo_len, 2597 .min_rec_size = sizeof(struct bpf_core_relo), 2598 .ext_info = &btf_ext->core_relo_info, 2599 .desc = "core_relo", 2600 }; 2601 2602 return btf_ext_setup_info(btf_ext, ¶m); 2603 } 2604 2605 static int btf_ext_parse_hdr(__u8 *data, __u32 data_size) 2606 { 2607 const struct btf_ext_header *hdr = (struct btf_ext_header *)data; 2608 2609 if (data_size < offsetofend(struct btf_ext_header, hdr_len) || 2610 data_size < hdr->hdr_len) { 2611 pr_debug("BTF.ext header not found"); 2612 return -EINVAL; 2613 } 2614 2615 if (hdr->magic == bswap_16(BTF_MAGIC)) { 2616 pr_warn("BTF.ext in non-native endianness is not supported\n"); 2617 return -ENOTSUP; 2618 } else if (hdr->magic != BTF_MAGIC) { 2619 pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic); 2620 return -EINVAL; 2621 } 2622 2623 if (hdr->version != BTF_VERSION) { 2624 pr_debug("Unsupported BTF.ext version:%u\n", hdr->version); 2625 return -ENOTSUP; 2626 } 2627 2628 if (hdr->flags) { 2629 pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags); 2630 return -ENOTSUP; 2631 } 2632 2633 if (data_size == hdr->hdr_len) { 2634 pr_debug("BTF.ext has no data\n"); 2635 return -EINVAL; 2636 } 2637 2638 return 0; 2639 } 2640 2641 void btf_ext__free(struct btf_ext *btf_ext) 2642 { 2643 if (IS_ERR_OR_NULL(btf_ext)) 2644 return; 2645 free(btf_ext->data); 2646 free(btf_ext); 2647 } 2648 2649 struct btf_ext *btf_ext__new(__u8 *data, __u32 size) 2650 { 2651 struct btf_ext *btf_ext; 2652 int err; 2653 2654 err = btf_ext_parse_hdr(data, size); 2655 if (err) 2656 return ERR_PTR(err); 2657 2658 btf_ext = calloc(1, sizeof(struct btf_ext)); 2659 if (!btf_ext) 2660 return ERR_PTR(-ENOMEM); 2661 2662 btf_ext->data_size = size; 2663 btf_ext->data = malloc(size); 2664 if (!btf_ext->data) { 2665 err = -ENOMEM; 2666 goto done; 2667 } 2668 memcpy(btf_ext->data, data, size); 2669 2670 if (btf_ext->hdr->hdr_len < 2671 offsetofend(struct btf_ext_header, line_info_len)) 2672 goto done; 2673 err = btf_ext_setup_func_info(btf_ext); 2674 if (err) 2675 goto done; 2676 2677 err = btf_ext_setup_line_info(btf_ext); 2678 if (err) 2679 goto done; 2680 2681 if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len)) 2682 goto done; 2683 err = btf_ext_setup_core_relos(btf_ext); 2684 if (err) 2685 goto done; 2686 2687 done: 2688 if (err) { 2689 btf_ext__free(btf_ext); 2690 return ERR_PTR(err); 2691 } 2692 2693 return btf_ext; 2694 } 2695 2696 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size) 2697 { 2698 *size = btf_ext->data_size; 2699 return btf_ext->data; 2700 } 2701 2702 static int btf_ext_reloc_info(const struct btf *btf, 2703 const struct btf_ext_info *ext_info, 2704 const char *sec_name, __u32 insns_cnt, 2705 void **info, __u32 *cnt) 2706 { 2707 __u32 sec_hdrlen = sizeof(struct btf_ext_info_sec); 2708 __u32 i, record_size, existing_len, records_len; 2709 struct btf_ext_info_sec *sinfo; 2710 const char *info_sec_name; 2711 __u64 remain_len; 2712 void *data; 2713 2714 record_size = ext_info->rec_size; 2715 sinfo = ext_info->info; 2716 remain_len = ext_info->len; 2717 while (remain_len > 0) { 2718 records_len = sinfo->num_info * record_size; 2719 info_sec_name = btf__name_by_offset(btf, sinfo->sec_name_off); 2720 if (strcmp(info_sec_name, sec_name)) { 2721 remain_len -= sec_hdrlen + records_len; 2722 sinfo = (void *)sinfo + sec_hdrlen + records_len; 2723 continue; 2724 } 2725 2726 existing_len = (*cnt) * record_size; 2727 data = realloc(*info, existing_len + records_len); 2728 if (!data) 2729 return -ENOMEM; 2730 2731 memcpy(data + existing_len, sinfo->data, records_len); 2732 /* adjust insn_off only, the rest data will be passed 2733 * to the kernel. 2734 */ 2735 for (i = 0; i < sinfo->num_info; i++) { 2736 __u32 *insn_off; 2737 2738 insn_off = data + existing_len + (i * record_size); 2739 *insn_off = *insn_off / sizeof(struct bpf_insn) + 2740 insns_cnt; 2741 } 2742 *info = data; 2743 *cnt += sinfo->num_info; 2744 return 0; 2745 } 2746 2747 return -ENOENT; 2748 } 2749 2750 int btf_ext__reloc_func_info(const struct btf *btf, 2751 const struct btf_ext *btf_ext, 2752 const char *sec_name, __u32 insns_cnt, 2753 void **func_info, __u32 *cnt) 2754 { 2755 return btf_ext_reloc_info(btf, &btf_ext->func_info, sec_name, 2756 insns_cnt, func_info, cnt); 2757 } 2758 2759 int btf_ext__reloc_line_info(const struct btf *btf, 2760 const struct btf_ext *btf_ext, 2761 const char *sec_name, __u32 insns_cnt, 2762 void **line_info, __u32 *cnt) 2763 { 2764 return btf_ext_reloc_info(btf, &btf_ext->line_info, sec_name, 2765 insns_cnt, line_info, cnt); 2766 } 2767 2768 __u32 btf_ext__func_info_rec_size(const struct btf_ext *btf_ext) 2769 { 2770 return btf_ext->func_info.rec_size; 2771 } 2772 2773 __u32 btf_ext__line_info_rec_size(const struct btf_ext *btf_ext) 2774 { 2775 return btf_ext->line_info.rec_size; 2776 } 2777 2778 struct btf_dedup; 2779 2780 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext, 2781 const struct btf_dedup_opts *opts); 2782 static void btf_dedup_free(struct btf_dedup *d); 2783 static int btf_dedup_prep(struct btf_dedup *d); 2784 static int btf_dedup_strings(struct btf_dedup *d); 2785 static int btf_dedup_prim_types(struct btf_dedup *d); 2786 static int btf_dedup_struct_types(struct btf_dedup *d); 2787 static int btf_dedup_ref_types(struct btf_dedup *d); 2788 static int btf_dedup_compact_types(struct btf_dedup *d); 2789 static int btf_dedup_remap_types(struct btf_dedup *d); 2790 2791 /* 2792 * Deduplicate BTF types and strings. 2793 * 2794 * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF 2795 * section with all BTF type descriptors and string data. It overwrites that 2796 * memory in-place with deduplicated types and strings without any loss of 2797 * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section 2798 * is provided, all the strings referenced from .BTF.ext section are honored 2799 * and updated to point to the right offsets after deduplication. 2800 * 2801 * If function returns with error, type/string data might be garbled and should 2802 * be discarded. 2803 * 2804 * More verbose and detailed description of both problem btf_dedup is solving, 2805 * as well as solution could be found at: 2806 * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html 2807 * 2808 * Problem description and justification 2809 * ===================================== 2810 * 2811 * BTF type information is typically emitted either as a result of conversion 2812 * from DWARF to BTF or directly by compiler. In both cases, each compilation 2813 * unit contains information about a subset of all the types that are used 2814 * in an application. These subsets are frequently overlapping and contain a lot 2815 * of duplicated information when later concatenated together into a single 2816 * binary. This algorithm ensures that each unique type is represented by single 2817 * BTF type descriptor, greatly reducing resulting size of BTF data. 2818 * 2819 * Compilation unit isolation and subsequent duplication of data is not the only 2820 * problem. The same type hierarchy (e.g., struct and all the type that struct 2821 * references) in different compilation units can be represented in BTF to 2822 * various degrees of completeness (or, rather, incompleteness) due to 2823 * struct/union forward declarations. 2824 * 2825 * Let's take a look at an example, that we'll use to better understand the 2826 * problem (and solution). Suppose we have two compilation units, each using 2827 * same `struct S`, but each of them having incomplete type information about 2828 * struct's fields: 2829 * 2830 * // CU #1: 2831 * struct S; 2832 * struct A { 2833 * int a; 2834 * struct A* self; 2835 * struct S* parent; 2836 * }; 2837 * struct B; 2838 * struct S { 2839 * struct A* a_ptr; 2840 * struct B* b_ptr; 2841 * }; 2842 * 2843 * // CU #2: 2844 * struct S; 2845 * struct A; 2846 * struct B { 2847 * int b; 2848 * struct B* self; 2849 * struct S* parent; 2850 * }; 2851 * struct S { 2852 * struct A* a_ptr; 2853 * struct B* b_ptr; 2854 * }; 2855 * 2856 * In case of CU #1, BTF data will know only that `struct B` exist (but no 2857 * more), but will know the complete type information about `struct A`. While 2858 * for CU #2, it will know full type information about `struct B`, but will 2859 * only know about forward declaration of `struct A` (in BTF terms, it will 2860 * have `BTF_KIND_FWD` type descriptor with name `B`). 2861 * 2862 * This compilation unit isolation means that it's possible that there is no 2863 * single CU with complete type information describing structs `S`, `A`, and 2864 * `B`. Also, we might get tons of duplicated and redundant type information. 2865 * 2866 * Additional complication we need to keep in mind comes from the fact that 2867 * types, in general, can form graphs containing cycles, not just DAGs. 2868 * 2869 * While algorithm does deduplication, it also merges and resolves type 2870 * information (unless disabled throught `struct btf_opts`), whenever possible. 2871 * E.g., in the example above with two compilation units having partial type 2872 * information for structs `A` and `B`, the output of algorithm will emit 2873 * a single copy of each BTF type that describes structs `A`, `B`, and `S` 2874 * (as well as type information for `int` and pointers), as if they were defined 2875 * in a single compilation unit as: 2876 * 2877 * struct A { 2878 * int a; 2879 * struct A* self; 2880 * struct S* parent; 2881 * }; 2882 * struct B { 2883 * int b; 2884 * struct B* self; 2885 * struct S* parent; 2886 * }; 2887 * struct S { 2888 * struct A* a_ptr; 2889 * struct B* b_ptr; 2890 * }; 2891 * 2892 * Algorithm summary 2893 * ================= 2894 * 2895 * Algorithm completes its work in 6 separate passes: 2896 * 2897 * 1. Strings deduplication. 2898 * 2. Primitive types deduplication (int, enum, fwd). 2899 * 3. Struct/union types deduplication. 2900 * 4. Reference types deduplication (pointers, typedefs, arrays, funcs, func 2901 * protos, and const/volatile/restrict modifiers). 2902 * 5. Types compaction. 2903 * 6. Types remapping. 2904 * 2905 * Algorithm determines canonical type descriptor, which is a single 2906 * representative type for each truly unique type. This canonical type is the 2907 * one that will go into final deduplicated BTF type information. For 2908 * struct/unions, it is also the type that algorithm will merge additional type 2909 * information into (while resolving FWDs), as it discovers it from data in 2910 * other CUs. Each input BTF type eventually gets either mapped to itself, if 2911 * that type is canonical, or to some other type, if that type is equivalent 2912 * and was chosen as canonical representative. This mapping is stored in 2913 * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that 2914 * FWD type got resolved to. 2915 * 2916 * To facilitate fast discovery of canonical types, we also maintain canonical 2917 * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash 2918 * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types 2919 * that match that signature. With sufficiently good choice of type signature 2920 * hashing function, we can limit number of canonical types for each unique type 2921 * signature to a very small number, allowing to find canonical type for any 2922 * duplicated type very quickly. 2923 * 2924 * Struct/union deduplication is the most critical part and algorithm for 2925 * deduplicating structs/unions is described in greater details in comments for 2926 * `btf_dedup_is_equiv` function. 2927 */ 2928 int btf__dedup(struct btf *btf, struct btf_ext *btf_ext, 2929 const struct btf_dedup_opts *opts) 2930 { 2931 struct btf_dedup *d = btf_dedup_new(btf, btf_ext, opts); 2932 int err; 2933 2934 if (IS_ERR(d)) { 2935 pr_debug("btf_dedup_new failed: %ld", PTR_ERR(d)); 2936 return -EINVAL; 2937 } 2938 2939 if (btf_ensure_modifiable(btf)) 2940 return -ENOMEM; 2941 2942 err = btf_dedup_prep(d); 2943 if (err) { 2944 pr_debug("btf_dedup_prep failed:%d\n", err); 2945 goto done; 2946 } 2947 err = btf_dedup_strings(d); 2948 if (err < 0) { 2949 pr_debug("btf_dedup_strings failed:%d\n", err); 2950 goto done; 2951 } 2952 err = btf_dedup_prim_types(d); 2953 if (err < 0) { 2954 pr_debug("btf_dedup_prim_types failed:%d\n", err); 2955 goto done; 2956 } 2957 err = btf_dedup_struct_types(d); 2958 if (err < 0) { 2959 pr_debug("btf_dedup_struct_types failed:%d\n", err); 2960 goto done; 2961 } 2962 err = btf_dedup_ref_types(d); 2963 if (err < 0) { 2964 pr_debug("btf_dedup_ref_types failed:%d\n", err); 2965 goto done; 2966 } 2967 err = btf_dedup_compact_types(d); 2968 if (err < 0) { 2969 pr_debug("btf_dedup_compact_types failed:%d\n", err); 2970 goto done; 2971 } 2972 err = btf_dedup_remap_types(d); 2973 if (err < 0) { 2974 pr_debug("btf_dedup_remap_types failed:%d\n", err); 2975 goto done; 2976 } 2977 2978 done: 2979 btf_dedup_free(d); 2980 return err; 2981 } 2982 2983 #define BTF_UNPROCESSED_ID ((__u32)-1) 2984 #define BTF_IN_PROGRESS_ID ((__u32)-2) 2985 2986 struct btf_dedup { 2987 /* .BTF section to be deduped in-place */ 2988 struct btf *btf; 2989 /* 2990 * Optional .BTF.ext section. When provided, any strings referenced 2991 * from it will be taken into account when deduping strings 2992 */ 2993 struct btf_ext *btf_ext; 2994 /* 2995 * This is a map from any type's signature hash to a list of possible 2996 * canonical representative type candidates. Hash collisions are 2997 * ignored, so even types of various kinds can share same list of 2998 * candidates, which is fine because we rely on subsequent 2999 * btf_xxx_equal() checks to authoritatively verify type equality. 3000 */ 3001 struct hashmap *dedup_table; 3002 /* Canonical types map */ 3003 __u32 *map; 3004 /* Hypothetical mapping, used during type graph equivalence checks */ 3005 __u32 *hypot_map; 3006 __u32 *hypot_list; 3007 size_t hypot_cnt; 3008 size_t hypot_cap; 3009 /* Whether hypothetical mapping, if successful, would need to adjust 3010 * already canonicalized types (due to a new forward declaration to 3011 * concrete type resolution). In such case, during split BTF dedup 3012 * candidate type would still be considered as different, because base 3013 * BTF is considered to be immutable. 3014 */ 3015 bool hypot_adjust_canon; 3016 /* Various option modifying behavior of algorithm */ 3017 struct btf_dedup_opts opts; 3018 /* temporary strings deduplication state */ 3019 void *strs_data; 3020 size_t strs_cap; 3021 size_t strs_len; 3022 struct hashmap* strs_hash; 3023 }; 3024 3025 static long hash_combine(long h, long value) 3026 { 3027 return h * 31 + value; 3028 } 3029 3030 #define for_each_dedup_cand(d, node, hash) \ 3031 hashmap__for_each_key_entry(d->dedup_table, node, (void *)hash) 3032 3033 static int btf_dedup_table_add(struct btf_dedup *d, long hash, __u32 type_id) 3034 { 3035 return hashmap__append(d->dedup_table, 3036 (void *)hash, (void *)(long)type_id); 3037 } 3038 3039 static int btf_dedup_hypot_map_add(struct btf_dedup *d, 3040 __u32 from_id, __u32 to_id) 3041 { 3042 if (d->hypot_cnt == d->hypot_cap) { 3043 __u32 *new_list; 3044 3045 d->hypot_cap += max((size_t)16, d->hypot_cap / 2); 3046 new_list = libbpf_reallocarray(d->hypot_list, d->hypot_cap, sizeof(__u32)); 3047 if (!new_list) 3048 return -ENOMEM; 3049 d->hypot_list = new_list; 3050 } 3051 d->hypot_list[d->hypot_cnt++] = from_id; 3052 d->hypot_map[from_id] = to_id; 3053 return 0; 3054 } 3055 3056 static void btf_dedup_clear_hypot_map(struct btf_dedup *d) 3057 { 3058 int i; 3059 3060 for (i = 0; i < d->hypot_cnt; i++) 3061 d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID; 3062 d->hypot_cnt = 0; 3063 d->hypot_adjust_canon = false; 3064 } 3065 3066 static void btf_dedup_free(struct btf_dedup *d) 3067 { 3068 hashmap__free(d->dedup_table); 3069 d->dedup_table = NULL; 3070 3071 free(d->map); 3072 d->map = NULL; 3073 3074 free(d->hypot_map); 3075 d->hypot_map = NULL; 3076 3077 free(d->hypot_list); 3078 d->hypot_list = NULL; 3079 3080 free(d); 3081 } 3082 3083 static size_t btf_dedup_identity_hash_fn(const void *key, void *ctx) 3084 { 3085 return (size_t)key; 3086 } 3087 3088 static size_t btf_dedup_collision_hash_fn(const void *key, void *ctx) 3089 { 3090 return 0; 3091 } 3092 3093 static bool btf_dedup_equal_fn(const void *k1, const void *k2, void *ctx) 3094 { 3095 return k1 == k2; 3096 } 3097 3098 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext, 3099 const struct btf_dedup_opts *opts) 3100 { 3101 struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup)); 3102 hashmap_hash_fn hash_fn = btf_dedup_identity_hash_fn; 3103 int i, err = 0, type_cnt; 3104 3105 if (!d) 3106 return ERR_PTR(-ENOMEM); 3107 3108 d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds; 3109 /* dedup_table_size is now used only to force collisions in tests */ 3110 if (opts && opts->dedup_table_size == 1) 3111 hash_fn = btf_dedup_collision_hash_fn; 3112 3113 d->btf = btf; 3114 d->btf_ext = btf_ext; 3115 3116 d->dedup_table = hashmap__new(hash_fn, btf_dedup_equal_fn, NULL); 3117 if (IS_ERR(d->dedup_table)) { 3118 err = PTR_ERR(d->dedup_table); 3119 d->dedup_table = NULL; 3120 goto done; 3121 } 3122 3123 type_cnt = btf__get_nr_types(btf) + 1; 3124 d->map = malloc(sizeof(__u32) * type_cnt); 3125 if (!d->map) { 3126 err = -ENOMEM; 3127 goto done; 3128 } 3129 /* special BTF "void" type is made canonical immediately */ 3130 d->map[0] = 0; 3131 for (i = 1; i < type_cnt; i++) { 3132 struct btf_type *t = btf_type_by_id(d->btf, i); 3133 3134 /* VAR and DATASEC are never deduped and are self-canonical */ 3135 if (btf_is_var(t) || btf_is_datasec(t)) 3136 d->map[i] = i; 3137 else 3138 d->map[i] = BTF_UNPROCESSED_ID; 3139 } 3140 3141 d->hypot_map = malloc(sizeof(__u32) * type_cnt); 3142 if (!d->hypot_map) { 3143 err = -ENOMEM; 3144 goto done; 3145 } 3146 for (i = 0; i < type_cnt; i++) 3147 d->hypot_map[i] = BTF_UNPROCESSED_ID; 3148 3149 done: 3150 if (err) { 3151 btf_dedup_free(d); 3152 return ERR_PTR(err); 3153 } 3154 3155 return d; 3156 } 3157 3158 typedef int (*str_off_fn_t)(__u32 *str_off_ptr, void *ctx); 3159 3160 /* 3161 * Iterate over all possible places in .BTF and .BTF.ext that can reference 3162 * string and pass pointer to it to a provided callback `fn`. 3163 */ 3164 static int btf_for_each_str_off(struct btf_dedup *d, str_off_fn_t fn, void *ctx) 3165 { 3166 void *line_data_cur, *line_data_end; 3167 int i, j, r, rec_size; 3168 struct btf_type *t; 3169 3170 for (i = 0; i < d->btf->nr_types; i++) { 3171 t = btf_type_by_id(d->btf, d->btf->start_id + i); 3172 r = fn(&t->name_off, ctx); 3173 if (r) 3174 return r; 3175 3176 switch (btf_kind(t)) { 3177 case BTF_KIND_STRUCT: 3178 case BTF_KIND_UNION: { 3179 struct btf_member *m = btf_members(t); 3180 __u16 vlen = btf_vlen(t); 3181 3182 for (j = 0; j < vlen; j++) { 3183 r = fn(&m->name_off, ctx); 3184 if (r) 3185 return r; 3186 m++; 3187 } 3188 break; 3189 } 3190 case BTF_KIND_ENUM: { 3191 struct btf_enum *m = btf_enum(t); 3192 __u16 vlen = btf_vlen(t); 3193 3194 for (j = 0; j < vlen; j++) { 3195 r = fn(&m->name_off, ctx); 3196 if (r) 3197 return r; 3198 m++; 3199 } 3200 break; 3201 } 3202 case BTF_KIND_FUNC_PROTO: { 3203 struct btf_param *m = btf_params(t); 3204 __u16 vlen = btf_vlen(t); 3205 3206 for (j = 0; j < vlen; j++) { 3207 r = fn(&m->name_off, ctx); 3208 if (r) 3209 return r; 3210 m++; 3211 } 3212 break; 3213 } 3214 default: 3215 break; 3216 } 3217 } 3218 3219 if (!d->btf_ext) 3220 return 0; 3221 3222 line_data_cur = d->btf_ext->line_info.info; 3223 line_data_end = d->btf_ext->line_info.info + d->btf_ext->line_info.len; 3224 rec_size = d->btf_ext->line_info.rec_size; 3225 3226 while (line_data_cur < line_data_end) { 3227 struct btf_ext_info_sec *sec = line_data_cur; 3228 struct bpf_line_info_min *line_info; 3229 __u32 num_info = sec->num_info; 3230 3231 r = fn(&sec->sec_name_off, ctx); 3232 if (r) 3233 return r; 3234 3235 line_data_cur += sizeof(struct btf_ext_info_sec); 3236 for (i = 0; i < num_info; i++) { 3237 line_info = line_data_cur; 3238 r = fn(&line_info->file_name_off, ctx); 3239 if (r) 3240 return r; 3241 r = fn(&line_info->line_off, ctx); 3242 if (r) 3243 return r; 3244 line_data_cur += rec_size; 3245 } 3246 } 3247 3248 return 0; 3249 } 3250 3251 static int strs_dedup_remap_str_off(__u32 *str_off_ptr, void *ctx) 3252 { 3253 struct btf_dedup *d = ctx; 3254 __u32 str_off = *str_off_ptr; 3255 long old_off, new_off, len; 3256 const char *s; 3257 void *p; 3258 int err; 3259 3260 /* don't touch empty string or string in main BTF */ 3261 if (str_off == 0 || str_off < d->btf->start_str_off) 3262 return 0; 3263 3264 s = btf__str_by_offset(d->btf, str_off); 3265 if (d->btf->base_btf) { 3266 err = btf__find_str(d->btf->base_btf, s); 3267 if (err >= 0) { 3268 *str_off_ptr = err; 3269 return 0; 3270 } 3271 if (err != -ENOENT) 3272 return err; 3273 } 3274 3275 len = strlen(s) + 1; 3276 3277 new_off = d->strs_len; 3278 p = btf_add_mem(&d->strs_data, &d->strs_cap, 1, new_off, BTF_MAX_STR_OFFSET, len); 3279 if (!p) 3280 return -ENOMEM; 3281 3282 memcpy(p, s, len); 3283 3284 /* Now attempt to add the string, but only if the string with the same 3285 * contents doesn't exist already (HASHMAP_ADD strategy). If such 3286 * string exists, we'll get its offset in old_off (that's old_key). 3287 */ 3288 err = hashmap__insert(d->strs_hash, (void *)new_off, (void *)new_off, 3289 HASHMAP_ADD, (const void **)&old_off, NULL); 3290 if (err == -EEXIST) { 3291 *str_off_ptr = d->btf->start_str_off + old_off; 3292 } else if (err) { 3293 return err; 3294 } else { 3295 *str_off_ptr = d->btf->start_str_off + new_off; 3296 d->strs_len += len; 3297 } 3298 return 0; 3299 } 3300 3301 /* 3302 * Dedup string and filter out those that are not referenced from either .BTF 3303 * or .BTF.ext (if provided) sections. 3304 * 3305 * This is done by building index of all strings in BTF's string section, 3306 * then iterating over all entities that can reference strings (e.g., type 3307 * names, struct field names, .BTF.ext line info, etc) and marking corresponding 3308 * strings as used. After that all used strings are deduped and compacted into 3309 * sequential blob of memory and new offsets are calculated. Then all the string 3310 * references are iterated again and rewritten using new offsets. 3311 */ 3312 static int btf_dedup_strings(struct btf_dedup *d) 3313 { 3314 char *s; 3315 int err; 3316 3317 if (d->btf->strs_deduped) 3318 return 0; 3319 3320 /* temporarily switch to use btf_dedup's strs_data for strings for hash 3321 * functions; later we'll just transfer hashmap to struct btf as is, 3322 * along the strs_data 3323 */ 3324 d->btf->strs_data_ptr = &d->strs_data; 3325 3326 d->strs_hash = hashmap__new(strs_hash_fn, strs_hash_equal_fn, d->btf); 3327 if (IS_ERR(d->strs_hash)) { 3328 err = PTR_ERR(d->strs_hash); 3329 d->strs_hash = NULL; 3330 goto err_out; 3331 } 3332 3333 if (!d->btf->base_btf) { 3334 s = btf_add_mem(&d->strs_data, &d->strs_cap, 1, d->strs_len, BTF_MAX_STR_OFFSET, 1); 3335 if (!s) 3336 return -ENOMEM; 3337 /* initial empty string */ 3338 s[0] = 0; 3339 d->strs_len = 1; 3340 3341 /* insert empty string; we won't be looking it up during strings 3342 * dedup, but it's good to have it for generic BTF string lookups 3343 */ 3344 err = hashmap__insert(d->strs_hash, (void *)0, (void *)0, 3345 HASHMAP_ADD, NULL, NULL); 3346 if (err) 3347 goto err_out; 3348 } 3349 3350 /* remap string offsets */ 3351 err = btf_for_each_str_off(d, strs_dedup_remap_str_off, d); 3352 if (err) 3353 goto err_out; 3354 3355 /* replace BTF string data and hash with deduped ones */ 3356 free(d->btf->strs_data); 3357 hashmap__free(d->btf->strs_hash); 3358 d->btf->strs_data = d->strs_data; 3359 d->btf->strs_data_cap = d->strs_cap; 3360 d->btf->hdr->str_len = d->strs_len; 3361 d->btf->strs_hash = d->strs_hash; 3362 /* now point strs_data_ptr back to btf->strs_data */ 3363 d->btf->strs_data_ptr = &d->btf->strs_data; 3364 3365 d->strs_data = d->strs_hash = NULL; 3366 d->strs_len = d->strs_cap = 0; 3367 d->btf->strs_deduped = true; 3368 return 0; 3369 3370 err_out: 3371 free(d->strs_data); 3372 hashmap__free(d->strs_hash); 3373 d->strs_data = d->strs_hash = NULL; 3374 d->strs_len = d->strs_cap = 0; 3375 3376 /* restore strings pointer for existing d->btf->strs_hash back */ 3377 d->btf->strs_data_ptr = &d->strs_data; 3378 3379 return err; 3380 } 3381 3382 static long btf_hash_common(struct btf_type *t) 3383 { 3384 long h; 3385 3386 h = hash_combine(0, t->name_off); 3387 h = hash_combine(h, t->info); 3388 h = hash_combine(h, t->size); 3389 return h; 3390 } 3391 3392 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2) 3393 { 3394 return t1->name_off == t2->name_off && 3395 t1->info == t2->info && 3396 t1->size == t2->size; 3397 } 3398 3399 /* Calculate type signature hash of INT. */ 3400 static long btf_hash_int(struct btf_type *t) 3401 { 3402 __u32 info = *(__u32 *)(t + 1); 3403 long h; 3404 3405 h = btf_hash_common(t); 3406 h = hash_combine(h, info); 3407 return h; 3408 } 3409 3410 /* Check structural equality of two INTs. */ 3411 static bool btf_equal_int(struct btf_type *t1, struct btf_type *t2) 3412 { 3413 __u32 info1, info2; 3414 3415 if (!btf_equal_common(t1, t2)) 3416 return false; 3417 info1 = *(__u32 *)(t1 + 1); 3418 info2 = *(__u32 *)(t2 + 1); 3419 return info1 == info2; 3420 } 3421 3422 /* Calculate type signature hash of ENUM. */ 3423 static long btf_hash_enum(struct btf_type *t) 3424 { 3425 long h; 3426 3427 /* don't hash vlen and enum members to support enum fwd resolving */ 3428 h = hash_combine(0, t->name_off); 3429 h = hash_combine(h, t->info & ~0xffff); 3430 h = hash_combine(h, t->size); 3431 return h; 3432 } 3433 3434 /* Check structural equality of two ENUMs. */ 3435 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2) 3436 { 3437 const struct btf_enum *m1, *m2; 3438 __u16 vlen; 3439 int i; 3440 3441 if (!btf_equal_common(t1, t2)) 3442 return false; 3443 3444 vlen = btf_vlen(t1); 3445 m1 = btf_enum(t1); 3446 m2 = btf_enum(t2); 3447 for (i = 0; i < vlen; i++) { 3448 if (m1->name_off != m2->name_off || m1->val != m2->val) 3449 return false; 3450 m1++; 3451 m2++; 3452 } 3453 return true; 3454 } 3455 3456 static inline bool btf_is_enum_fwd(struct btf_type *t) 3457 { 3458 return btf_is_enum(t) && btf_vlen(t) == 0; 3459 } 3460 3461 static bool btf_compat_enum(struct btf_type *t1, struct btf_type *t2) 3462 { 3463 if (!btf_is_enum_fwd(t1) && !btf_is_enum_fwd(t2)) 3464 return btf_equal_enum(t1, t2); 3465 /* ignore vlen when comparing */ 3466 return t1->name_off == t2->name_off && 3467 (t1->info & ~0xffff) == (t2->info & ~0xffff) && 3468 t1->size == t2->size; 3469 } 3470 3471 /* 3472 * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs, 3473 * as referenced type IDs equivalence is established separately during type 3474 * graph equivalence check algorithm. 3475 */ 3476 static long btf_hash_struct(struct btf_type *t) 3477 { 3478 const struct btf_member *member = btf_members(t); 3479 __u32 vlen = btf_vlen(t); 3480 long h = btf_hash_common(t); 3481 int i; 3482 3483 for (i = 0; i < vlen; i++) { 3484 h = hash_combine(h, member->name_off); 3485 h = hash_combine(h, member->offset); 3486 /* no hashing of referenced type ID, it can be unresolved yet */ 3487 member++; 3488 } 3489 return h; 3490 } 3491 3492 /* 3493 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type 3494 * IDs. This check is performed during type graph equivalence check and 3495 * referenced types equivalence is checked separately. 3496 */ 3497 static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2) 3498 { 3499 const struct btf_member *m1, *m2; 3500 __u16 vlen; 3501 int i; 3502 3503 if (!btf_equal_common(t1, t2)) 3504 return false; 3505 3506 vlen = btf_vlen(t1); 3507 m1 = btf_members(t1); 3508 m2 = btf_members(t2); 3509 for (i = 0; i < vlen; i++) { 3510 if (m1->name_off != m2->name_off || m1->offset != m2->offset) 3511 return false; 3512 m1++; 3513 m2++; 3514 } 3515 return true; 3516 } 3517 3518 /* 3519 * Calculate type signature hash of ARRAY, including referenced type IDs, 3520 * under assumption that they were already resolved to canonical type IDs and 3521 * are not going to change. 3522 */ 3523 static long btf_hash_array(struct btf_type *t) 3524 { 3525 const struct btf_array *info = btf_array(t); 3526 long h = btf_hash_common(t); 3527 3528 h = hash_combine(h, info->type); 3529 h = hash_combine(h, info->index_type); 3530 h = hash_combine(h, info->nelems); 3531 return h; 3532 } 3533 3534 /* 3535 * Check exact equality of two ARRAYs, taking into account referenced 3536 * type IDs, under assumption that they were already resolved to canonical 3537 * type IDs and are not going to change. 3538 * This function is called during reference types deduplication to compare 3539 * ARRAY to potential canonical representative. 3540 */ 3541 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2) 3542 { 3543 const struct btf_array *info1, *info2; 3544 3545 if (!btf_equal_common(t1, t2)) 3546 return false; 3547 3548 info1 = btf_array(t1); 3549 info2 = btf_array(t2); 3550 return info1->type == info2->type && 3551 info1->index_type == info2->index_type && 3552 info1->nelems == info2->nelems; 3553 } 3554 3555 /* 3556 * Check structural compatibility of two ARRAYs, ignoring referenced type 3557 * IDs. This check is performed during type graph equivalence check and 3558 * referenced types equivalence is checked separately. 3559 */ 3560 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2) 3561 { 3562 if (!btf_equal_common(t1, t2)) 3563 return false; 3564 3565 return btf_array(t1)->nelems == btf_array(t2)->nelems; 3566 } 3567 3568 /* 3569 * Calculate type signature hash of FUNC_PROTO, including referenced type IDs, 3570 * under assumption that they were already resolved to canonical type IDs and 3571 * are not going to change. 3572 */ 3573 static long btf_hash_fnproto(struct btf_type *t) 3574 { 3575 const struct btf_param *member = btf_params(t); 3576 __u16 vlen = btf_vlen(t); 3577 long h = btf_hash_common(t); 3578 int i; 3579 3580 for (i = 0; i < vlen; i++) { 3581 h = hash_combine(h, member->name_off); 3582 h = hash_combine(h, member->type); 3583 member++; 3584 } 3585 return h; 3586 } 3587 3588 /* 3589 * Check exact equality of two FUNC_PROTOs, taking into account referenced 3590 * type IDs, under assumption that they were already resolved to canonical 3591 * type IDs and are not going to change. 3592 * This function is called during reference types deduplication to compare 3593 * FUNC_PROTO to potential canonical representative. 3594 */ 3595 static bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2) 3596 { 3597 const struct btf_param *m1, *m2; 3598 __u16 vlen; 3599 int i; 3600 3601 if (!btf_equal_common(t1, t2)) 3602 return false; 3603 3604 vlen = btf_vlen(t1); 3605 m1 = btf_params(t1); 3606 m2 = btf_params(t2); 3607 for (i = 0; i < vlen; i++) { 3608 if (m1->name_off != m2->name_off || m1->type != m2->type) 3609 return false; 3610 m1++; 3611 m2++; 3612 } 3613 return true; 3614 } 3615 3616 /* 3617 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type 3618 * IDs. This check is performed during type graph equivalence check and 3619 * referenced types equivalence is checked separately. 3620 */ 3621 static bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2) 3622 { 3623 const struct btf_param *m1, *m2; 3624 __u16 vlen; 3625 int i; 3626 3627 /* skip return type ID */ 3628 if (t1->name_off != t2->name_off || t1->info != t2->info) 3629 return false; 3630 3631 vlen = btf_vlen(t1); 3632 m1 = btf_params(t1); 3633 m2 = btf_params(t2); 3634 for (i = 0; i < vlen; i++) { 3635 if (m1->name_off != m2->name_off) 3636 return false; 3637 m1++; 3638 m2++; 3639 } 3640 return true; 3641 } 3642 3643 /* Prepare split BTF for deduplication by calculating hashes of base BTF's 3644 * types and initializing the rest of the state (canonical type mapping) for 3645 * the fixed base BTF part. 3646 */ 3647 static int btf_dedup_prep(struct btf_dedup *d) 3648 { 3649 struct btf_type *t; 3650 int type_id; 3651 long h; 3652 3653 if (!d->btf->base_btf) 3654 return 0; 3655 3656 for (type_id = 1; type_id < d->btf->start_id; type_id++) { 3657 t = btf_type_by_id(d->btf, type_id); 3658 3659 /* all base BTF types are self-canonical by definition */ 3660 d->map[type_id] = type_id; 3661 3662 switch (btf_kind(t)) { 3663 case BTF_KIND_VAR: 3664 case BTF_KIND_DATASEC: 3665 /* VAR and DATASEC are never hash/deduplicated */ 3666 continue; 3667 case BTF_KIND_CONST: 3668 case BTF_KIND_VOLATILE: 3669 case BTF_KIND_RESTRICT: 3670 case BTF_KIND_PTR: 3671 case BTF_KIND_FWD: 3672 case BTF_KIND_TYPEDEF: 3673 case BTF_KIND_FUNC: 3674 case BTF_KIND_FLOAT: 3675 h = btf_hash_common(t); 3676 break; 3677 case BTF_KIND_INT: 3678 h = btf_hash_int(t); 3679 break; 3680 case BTF_KIND_ENUM: 3681 h = btf_hash_enum(t); 3682 break; 3683 case BTF_KIND_STRUCT: 3684 case BTF_KIND_UNION: 3685 h = btf_hash_struct(t); 3686 break; 3687 case BTF_KIND_ARRAY: 3688 h = btf_hash_array(t); 3689 break; 3690 case BTF_KIND_FUNC_PROTO: 3691 h = btf_hash_fnproto(t); 3692 break; 3693 default: 3694 pr_debug("unknown kind %d for type [%d]\n", btf_kind(t), type_id); 3695 return -EINVAL; 3696 } 3697 if (btf_dedup_table_add(d, h, type_id)) 3698 return -ENOMEM; 3699 } 3700 3701 return 0; 3702 } 3703 3704 /* 3705 * Deduplicate primitive types, that can't reference other types, by calculating 3706 * their type signature hash and comparing them with any possible canonical 3707 * candidate. If no canonical candidate matches, type itself is marked as 3708 * canonical and is added into `btf_dedup->dedup_table` as another candidate. 3709 */ 3710 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id) 3711 { 3712 struct btf_type *t = btf_type_by_id(d->btf, type_id); 3713 struct hashmap_entry *hash_entry; 3714 struct btf_type *cand; 3715 /* if we don't find equivalent type, then we are canonical */ 3716 __u32 new_id = type_id; 3717 __u32 cand_id; 3718 long h; 3719 3720 switch (btf_kind(t)) { 3721 case BTF_KIND_CONST: 3722 case BTF_KIND_VOLATILE: 3723 case BTF_KIND_RESTRICT: 3724 case BTF_KIND_PTR: 3725 case BTF_KIND_TYPEDEF: 3726 case BTF_KIND_ARRAY: 3727 case BTF_KIND_STRUCT: 3728 case BTF_KIND_UNION: 3729 case BTF_KIND_FUNC: 3730 case BTF_KIND_FUNC_PROTO: 3731 case BTF_KIND_VAR: 3732 case BTF_KIND_DATASEC: 3733 return 0; 3734 3735 case BTF_KIND_INT: 3736 h = btf_hash_int(t); 3737 for_each_dedup_cand(d, hash_entry, h) { 3738 cand_id = (__u32)(long)hash_entry->value; 3739 cand = btf_type_by_id(d->btf, cand_id); 3740 if (btf_equal_int(t, cand)) { 3741 new_id = cand_id; 3742 break; 3743 } 3744 } 3745 break; 3746 3747 case BTF_KIND_ENUM: 3748 h = btf_hash_enum(t); 3749 for_each_dedup_cand(d, hash_entry, h) { 3750 cand_id = (__u32)(long)hash_entry->value; 3751 cand = btf_type_by_id(d->btf, cand_id); 3752 if (btf_equal_enum(t, cand)) { 3753 new_id = cand_id; 3754 break; 3755 } 3756 if (d->opts.dont_resolve_fwds) 3757 continue; 3758 if (btf_compat_enum(t, cand)) { 3759 if (btf_is_enum_fwd(t)) { 3760 /* resolve fwd to full enum */ 3761 new_id = cand_id; 3762 break; 3763 } 3764 /* resolve canonical enum fwd to full enum */ 3765 d->map[cand_id] = type_id; 3766 } 3767 } 3768 break; 3769 3770 case BTF_KIND_FWD: 3771 case BTF_KIND_FLOAT: 3772 h = btf_hash_common(t); 3773 for_each_dedup_cand(d, hash_entry, h) { 3774 cand_id = (__u32)(long)hash_entry->value; 3775 cand = btf_type_by_id(d->btf, cand_id); 3776 if (btf_equal_common(t, cand)) { 3777 new_id = cand_id; 3778 break; 3779 } 3780 } 3781 break; 3782 3783 default: 3784 return -EINVAL; 3785 } 3786 3787 d->map[type_id] = new_id; 3788 if (type_id == new_id && btf_dedup_table_add(d, h, type_id)) 3789 return -ENOMEM; 3790 3791 return 0; 3792 } 3793 3794 static int btf_dedup_prim_types(struct btf_dedup *d) 3795 { 3796 int i, err; 3797 3798 for (i = 0; i < d->btf->nr_types; i++) { 3799 err = btf_dedup_prim_type(d, d->btf->start_id + i); 3800 if (err) 3801 return err; 3802 } 3803 return 0; 3804 } 3805 3806 /* 3807 * Check whether type is already mapped into canonical one (could be to itself). 3808 */ 3809 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id) 3810 { 3811 return d->map[type_id] <= BTF_MAX_NR_TYPES; 3812 } 3813 3814 /* 3815 * Resolve type ID into its canonical type ID, if any; otherwise return original 3816 * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow 3817 * STRUCT/UNION link and resolve it into canonical type ID as well. 3818 */ 3819 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id) 3820 { 3821 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id) 3822 type_id = d->map[type_id]; 3823 return type_id; 3824 } 3825 3826 /* 3827 * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original 3828 * type ID. 3829 */ 3830 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id) 3831 { 3832 __u32 orig_type_id = type_id; 3833 3834 if (!btf_is_fwd(btf__type_by_id(d->btf, type_id))) 3835 return type_id; 3836 3837 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id) 3838 type_id = d->map[type_id]; 3839 3840 if (!btf_is_fwd(btf__type_by_id(d->btf, type_id))) 3841 return type_id; 3842 3843 return orig_type_id; 3844 } 3845 3846 3847 static inline __u16 btf_fwd_kind(struct btf_type *t) 3848 { 3849 return btf_kflag(t) ? BTF_KIND_UNION : BTF_KIND_STRUCT; 3850 } 3851 3852 /* Check if given two types are identical ARRAY definitions */ 3853 static int btf_dedup_identical_arrays(struct btf_dedup *d, __u32 id1, __u32 id2) 3854 { 3855 struct btf_type *t1, *t2; 3856 3857 t1 = btf_type_by_id(d->btf, id1); 3858 t2 = btf_type_by_id(d->btf, id2); 3859 if (!btf_is_array(t1) || !btf_is_array(t2)) 3860 return 0; 3861 3862 return btf_equal_array(t1, t2); 3863 } 3864 3865 /* 3866 * Check equivalence of BTF type graph formed by candidate struct/union (we'll 3867 * call it "candidate graph" in this description for brevity) to a type graph 3868 * formed by (potential) canonical struct/union ("canonical graph" for brevity 3869 * here, though keep in mind that not all types in canonical graph are 3870 * necessarily canonical representatives themselves, some of them might be 3871 * duplicates or its uniqueness might not have been established yet). 3872 * Returns: 3873 * - >0, if type graphs are equivalent; 3874 * - 0, if not equivalent; 3875 * - <0, on error. 3876 * 3877 * Algorithm performs side-by-side DFS traversal of both type graphs and checks 3878 * equivalence of BTF types at each step. If at any point BTF types in candidate 3879 * and canonical graphs are not compatible structurally, whole graphs are 3880 * incompatible. If types are structurally equivalent (i.e., all information 3881 * except referenced type IDs is exactly the same), a mapping from `canon_id` to 3882 * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`). 3883 * If a type references other types, then those referenced types are checked 3884 * for equivalence recursively. 3885 * 3886 * During DFS traversal, if we find that for current `canon_id` type we 3887 * already have some mapping in hypothetical map, we check for two possible 3888 * situations: 3889 * - `canon_id` is mapped to exactly the same type as `cand_id`. This will 3890 * happen when type graphs have cycles. In this case we assume those two 3891 * types are equivalent. 3892 * - `canon_id` is mapped to different type. This is contradiction in our 3893 * hypothetical mapping, because same graph in canonical graph corresponds 3894 * to two different types in candidate graph, which for equivalent type 3895 * graphs shouldn't happen. This condition terminates equivalence check 3896 * with negative result. 3897 * 3898 * If type graphs traversal exhausts types to check and find no contradiction, 3899 * then type graphs are equivalent. 3900 * 3901 * When checking types for equivalence, there is one special case: FWD types. 3902 * If FWD type resolution is allowed and one of the types (either from canonical 3903 * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind 3904 * flag) and their names match, hypothetical mapping is updated to point from 3905 * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully, 3906 * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently. 3907 * 3908 * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution, 3909 * if there are two exactly named (or anonymous) structs/unions that are 3910 * compatible structurally, one of which has FWD field, while other is concrete 3911 * STRUCT/UNION, but according to C sources they are different structs/unions 3912 * that are referencing different types with the same name. This is extremely 3913 * unlikely to happen, but btf_dedup API allows to disable FWD resolution if 3914 * this logic is causing problems. 3915 * 3916 * Doing FWD resolution means that both candidate and/or canonical graphs can 3917 * consists of portions of the graph that come from multiple compilation units. 3918 * This is due to the fact that types within single compilation unit are always 3919 * deduplicated and FWDs are already resolved, if referenced struct/union 3920 * definiton is available. So, if we had unresolved FWD and found corresponding 3921 * STRUCT/UNION, they will be from different compilation units. This 3922 * consequently means that when we "link" FWD to corresponding STRUCT/UNION, 3923 * type graph will likely have at least two different BTF types that describe 3924 * same type (e.g., most probably there will be two different BTF types for the 3925 * same 'int' primitive type) and could even have "overlapping" parts of type 3926 * graph that describe same subset of types. 3927 * 3928 * This in turn means that our assumption that each type in canonical graph 3929 * must correspond to exactly one type in candidate graph might not hold 3930 * anymore and will make it harder to detect contradictions using hypothetical 3931 * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION 3932 * resolution only in canonical graph. FWDs in candidate graphs are never 3933 * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs 3934 * that can occur: 3935 * - Both types in canonical and candidate graphs are FWDs. If they are 3936 * structurally equivalent, then they can either be both resolved to the 3937 * same STRUCT/UNION or not resolved at all. In both cases they are 3938 * equivalent and there is no need to resolve FWD on candidate side. 3939 * - Both types in canonical and candidate graphs are concrete STRUCT/UNION, 3940 * so nothing to resolve as well, algorithm will check equivalence anyway. 3941 * - Type in canonical graph is FWD, while type in candidate is concrete 3942 * STRUCT/UNION. In this case candidate graph comes from single compilation 3943 * unit, so there is exactly one BTF type for each unique C type. After 3944 * resolving FWD into STRUCT/UNION, there might be more than one BTF type 3945 * in canonical graph mapping to single BTF type in candidate graph, but 3946 * because hypothetical mapping maps from canonical to candidate types, it's 3947 * alright, and we still maintain the property of having single `canon_id` 3948 * mapping to single `cand_id` (there could be two different `canon_id` 3949 * mapped to the same `cand_id`, but it's not contradictory). 3950 * - Type in canonical graph is concrete STRUCT/UNION, while type in candidate 3951 * graph is FWD. In this case we are just going to check compatibility of 3952 * STRUCT/UNION and corresponding FWD, and if they are compatible, we'll 3953 * assume that whatever STRUCT/UNION FWD resolves to must be equivalent to 3954 * a concrete STRUCT/UNION from canonical graph. If the rest of type graphs 3955 * turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from 3956 * canonical graph. 3957 */ 3958 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id, 3959 __u32 canon_id) 3960 { 3961 struct btf_type *cand_type; 3962 struct btf_type *canon_type; 3963 __u32 hypot_type_id; 3964 __u16 cand_kind; 3965 __u16 canon_kind; 3966 int i, eq; 3967 3968 /* if both resolve to the same canonical, they must be equivalent */ 3969 if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id)) 3970 return 1; 3971 3972 canon_id = resolve_fwd_id(d, canon_id); 3973 3974 hypot_type_id = d->hypot_map[canon_id]; 3975 if (hypot_type_id <= BTF_MAX_NR_TYPES) { 3976 /* In some cases compiler will generate different DWARF types 3977 * for *identical* array type definitions and use them for 3978 * different fields within the *same* struct. This breaks type 3979 * equivalence check, which makes an assumption that candidate 3980 * types sub-graph has a consistent and deduped-by-compiler 3981 * types within a single CU. So work around that by explicitly 3982 * allowing identical array types here. 3983 */ 3984 return hypot_type_id == cand_id || 3985 btf_dedup_identical_arrays(d, hypot_type_id, cand_id); 3986 } 3987 3988 if (btf_dedup_hypot_map_add(d, canon_id, cand_id)) 3989 return -ENOMEM; 3990 3991 cand_type = btf_type_by_id(d->btf, cand_id); 3992 canon_type = btf_type_by_id(d->btf, canon_id); 3993 cand_kind = btf_kind(cand_type); 3994 canon_kind = btf_kind(canon_type); 3995 3996 if (cand_type->name_off != canon_type->name_off) 3997 return 0; 3998 3999 /* FWD <--> STRUCT/UNION equivalence check, if enabled */ 4000 if (!d->opts.dont_resolve_fwds 4001 && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD) 4002 && cand_kind != canon_kind) { 4003 __u16 real_kind; 4004 __u16 fwd_kind; 4005 4006 if (cand_kind == BTF_KIND_FWD) { 4007 real_kind = canon_kind; 4008 fwd_kind = btf_fwd_kind(cand_type); 4009 } else { 4010 real_kind = cand_kind; 4011 fwd_kind = btf_fwd_kind(canon_type); 4012 /* we'd need to resolve base FWD to STRUCT/UNION */ 4013 if (fwd_kind == real_kind && canon_id < d->btf->start_id) 4014 d->hypot_adjust_canon = true; 4015 } 4016 return fwd_kind == real_kind; 4017 } 4018 4019 if (cand_kind != canon_kind) 4020 return 0; 4021 4022 switch (cand_kind) { 4023 case BTF_KIND_INT: 4024 return btf_equal_int(cand_type, canon_type); 4025 4026 case BTF_KIND_ENUM: 4027 if (d->opts.dont_resolve_fwds) 4028 return btf_equal_enum(cand_type, canon_type); 4029 else 4030 return btf_compat_enum(cand_type, canon_type); 4031 4032 case BTF_KIND_FWD: 4033 case BTF_KIND_FLOAT: 4034 return btf_equal_common(cand_type, canon_type); 4035 4036 case BTF_KIND_CONST: 4037 case BTF_KIND_VOLATILE: 4038 case BTF_KIND_RESTRICT: 4039 case BTF_KIND_PTR: 4040 case BTF_KIND_TYPEDEF: 4041 case BTF_KIND_FUNC: 4042 if (cand_type->info != canon_type->info) 4043 return 0; 4044 return btf_dedup_is_equiv(d, cand_type->type, canon_type->type); 4045 4046 case BTF_KIND_ARRAY: { 4047 const struct btf_array *cand_arr, *canon_arr; 4048 4049 if (!btf_compat_array(cand_type, canon_type)) 4050 return 0; 4051 cand_arr = btf_array(cand_type); 4052 canon_arr = btf_array(canon_type); 4053 eq = btf_dedup_is_equiv(d, cand_arr->index_type, canon_arr->index_type); 4054 if (eq <= 0) 4055 return eq; 4056 return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type); 4057 } 4058 4059 case BTF_KIND_STRUCT: 4060 case BTF_KIND_UNION: { 4061 const struct btf_member *cand_m, *canon_m; 4062 __u16 vlen; 4063 4064 if (!btf_shallow_equal_struct(cand_type, canon_type)) 4065 return 0; 4066 vlen = btf_vlen(cand_type); 4067 cand_m = btf_members(cand_type); 4068 canon_m = btf_members(canon_type); 4069 for (i = 0; i < vlen; i++) { 4070 eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type); 4071 if (eq <= 0) 4072 return eq; 4073 cand_m++; 4074 canon_m++; 4075 } 4076 4077 return 1; 4078 } 4079 4080 case BTF_KIND_FUNC_PROTO: { 4081 const struct btf_param *cand_p, *canon_p; 4082 __u16 vlen; 4083 4084 if (!btf_compat_fnproto(cand_type, canon_type)) 4085 return 0; 4086 eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type); 4087 if (eq <= 0) 4088 return eq; 4089 vlen = btf_vlen(cand_type); 4090 cand_p = btf_params(cand_type); 4091 canon_p = btf_params(canon_type); 4092 for (i = 0; i < vlen; i++) { 4093 eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type); 4094 if (eq <= 0) 4095 return eq; 4096 cand_p++; 4097 canon_p++; 4098 } 4099 return 1; 4100 } 4101 4102 default: 4103 return -EINVAL; 4104 } 4105 return 0; 4106 } 4107 4108 /* 4109 * Use hypothetical mapping, produced by successful type graph equivalence 4110 * check, to augment existing struct/union canonical mapping, where possible. 4111 * 4112 * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record 4113 * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional: 4114 * it doesn't matter if FWD type was part of canonical graph or candidate one, 4115 * we are recording the mapping anyway. As opposed to carefulness required 4116 * for struct/union correspondence mapping (described below), for FWD resolution 4117 * it's not important, as by the time that FWD type (reference type) will be 4118 * deduplicated all structs/unions will be deduped already anyway. 4119 * 4120 * Recording STRUCT/UNION mapping is purely a performance optimization and is 4121 * not required for correctness. It needs to be done carefully to ensure that 4122 * struct/union from candidate's type graph is not mapped into corresponding 4123 * struct/union from canonical type graph that itself hasn't been resolved into 4124 * canonical representative. The only guarantee we have is that canonical 4125 * struct/union was determined as canonical and that won't change. But any 4126 * types referenced through that struct/union fields could have been not yet 4127 * resolved, so in case like that it's too early to establish any kind of 4128 * correspondence between structs/unions. 4129 * 4130 * No canonical correspondence is derived for primitive types (they are already 4131 * deduplicated completely already anyway) or reference types (they rely on 4132 * stability of struct/union canonical relationship for equivalence checks). 4133 */ 4134 static void btf_dedup_merge_hypot_map(struct btf_dedup *d) 4135 { 4136 __u32 canon_type_id, targ_type_id; 4137 __u16 t_kind, c_kind; 4138 __u32 t_id, c_id; 4139 int i; 4140 4141 for (i = 0; i < d->hypot_cnt; i++) { 4142 canon_type_id = d->hypot_list[i]; 4143 targ_type_id = d->hypot_map[canon_type_id]; 4144 t_id = resolve_type_id(d, targ_type_id); 4145 c_id = resolve_type_id(d, canon_type_id); 4146 t_kind = btf_kind(btf__type_by_id(d->btf, t_id)); 4147 c_kind = btf_kind(btf__type_by_id(d->btf, c_id)); 4148 /* 4149 * Resolve FWD into STRUCT/UNION. 4150 * It's ok to resolve FWD into STRUCT/UNION that's not yet 4151 * mapped to canonical representative (as opposed to 4152 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because 4153 * eventually that struct is going to be mapped and all resolved 4154 * FWDs will automatically resolve to correct canonical 4155 * representative. This will happen before ref type deduping, 4156 * which critically depends on stability of these mapping. This 4157 * stability is not a requirement for STRUCT/UNION equivalence 4158 * checks, though. 4159 */ 4160 4161 /* if it's the split BTF case, we still need to point base FWD 4162 * to STRUCT/UNION in a split BTF, because FWDs from split BTF 4163 * will be resolved against base FWD. If we don't point base 4164 * canonical FWD to the resolved STRUCT/UNION, then all the 4165 * FWDs in split BTF won't be correctly resolved to a proper 4166 * STRUCT/UNION. 4167 */ 4168 if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD) 4169 d->map[c_id] = t_id; 4170 4171 /* if graph equivalence determined that we'd need to adjust 4172 * base canonical types, then we need to only point base FWDs 4173 * to STRUCTs/UNIONs and do no more modifications. For all 4174 * other purposes the type graphs were not equivalent. 4175 */ 4176 if (d->hypot_adjust_canon) 4177 continue; 4178 4179 if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD) 4180 d->map[t_id] = c_id; 4181 4182 if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) && 4183 c_kind != BTF_KIND_FWD && 4184 is_type_mapped(d, c_id) && 4185 !is_type_mapped(d, t_id)) { 4186 /* 4187 * as a perf optimization, we can map struct/union 4188 * that's part of type graph we just verified for 4189 * equivalence. We can do that for struct/union that has 4190 * canonical representative only, though. 4191 */ 4192 d->map[t_id] = c_id; 4193 } 4194 } 4195 } 4196 4197 /* 4198 * Deduplicate struct/union types. 4199 * 4200 * For each struct/union type its type signature hash is calculated, taking 4201 * into account type's name, size, number, order and names of fields, but 4202 * ignoring type ID's referenced from fields, because they might not be deduped 4203 * completely until after reference types deduplication phase. This type hash 4204 * is used to iterate over all potential canonical types, sharing same hash. 4205 * For each canonical candidate we check whether type graphs that they form 4206 * (through referenced types in fields and so on) are equivalent using algorithm 4207 * implemented in `btf_dedup_is_equiv`. If such equivalence is found and 4208 * BTF_KIND_FWD resolution is allowed, then hypothetical mapping 4209 * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence 4210 * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to 4211 * potentially map other structs/unions to their canonical representatives, 4212 * if such relationship hasn't yet been established. This speeds up algorithm 4213 * by eliminating some of the duplicate work. 4214 * 4215 * If no matching canonical representative was found, struct/union is marked 4216 * as canonical for itself and is added into btf_dedup->dedup_table hash map 4217 * for further look ups. 4218 */ 4219 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id) 4220 { 4221 struct btf_type *cand_type, *t; 4222 struct hashmap_entry *hash_entry; 4223 /* if we don't find equivalent type, then we are canonical */ 4224 __u32 new_id = type_id; 4225 __u16 kind; 4226 long h; 4227 4228 /* already deduped or is in process of deduping (loop detected) */ 4229 if (d->map[type_id] <= BTF_MAX_NR_TYPES) 4230 return 0; 4231 4232 t = btf_type_by_id(d->btf, type_id); 4233 kind = btf_kind(t); 4234 4235 if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION) 4236 return 0; 4237 4238 h = btf_hash_struct(t); 4239 for_each_dedup_cand(d, hash_entry, h) { 4240 __u32 cand_id = (__u32)(long)hash_entry->value; 4241 int eq; 4242 4243 /* 4244 * Even though btf_dedup_is_equiv() checks for 4245 * btf_shallow_equal_struct() internally when checking two 4246 * structs (unions) for equivalence, we need to guard here 4247 * from picking matching FWD type as a dedup candidate. 4248 * This can happen due to hash collision. In such case just 4249 * relying on btf_dedup_is_equiv() would lead to potentially 4250 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because 4251 * FWD and compatible STRUCT/UNION are considered equivalent. 4252 */ 4253 cand_type = btf_type_by_id(d->btf, cand_id); 4254 if (!btf_shallow_equal_struct(t, cand_type)) 4255 continue; 4256 4257 btf_dedup_clear_hypot_map(d); 4258 eq = btf_dedup_is_equiv(d, type_id, cand_id); 4259 if (eq < 0) 4260 return eq; 4261 if (!eq) 4262 continue; 4263 btf_dedup_merge_hypot_map(d); 4264 if (d->hypot_adjust_canon) /* not really equivalent */ 4265 continue; 4266 new_id = cand_id; 4267 break; 4268 } 4269 4270 d->map[type_id] = new_id; 4271 if (type_id == new_id && btf_dedup_table_add(d, h, type_id)) 4272 return -ENOMEM; 4273 4274 return 0; 4275 } 4276 4277 static int btf_dedup_struct_types(struct btf_dedup *d) 4278 { 4279 int i, err; 4280 4281 for (i = 0; i < d->btf->nr_types; i++) { 4282 err = btf_dedup_struct_type(d, d->btf->start_id + i); 4283 if (err) 4284 return err; 4285 } 4286 return 0; 4287 } 4288 4289 /* 4290 * Deduplicate reference type. 4291 * 4292 * Once all primitive and struct/union types got deduplicated, we can easily 4293 * deduplicate all other (reference) BTF types. This is done in two steps: 4294 * 4295 * 1. Resolve all referenced type IDs into their canonical type IDs. This 4296 * resolution can be done either immediately for primitive or struct/union types 4297 * (because they were deduped in previous two phases) or recursively for 4298 * reference types. Recursion will always terminate at either primitive or 4299 * struct/union type, at which point we can "unwind" chain of reference types 4300 * one by one. There is no danger of encountering cycles because in C type 4301 * system the only way to form type cycle is through struct/union, so any chain 4302 * of reference types, even those taking part in a type cycle, will inevitably 4303 * reach struct/union at some point. 4304 * 4305 * 2. Once all referenced type IDs are resolved into canonical ones, BTF type 4306 * becomes "stable", in the sense that no further deduplication will cause 4307 * any changes to it. With that, it's now possible to calculate type's signature 4308 * hash (this time taking into account referenced type IDs) and loop over all 4309 * potential canonical representatives. If no match was found, current type 4310 * will become canonical representative of itself and will be added into 4311 * btf_dedup->dedup_table as another possible canonical representative. 4312 */ 4313 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id) 4314 { 4315 struct hashmap_entry *hash_entry; 4316 __u32 new_id = type_id, cand_id; 4317 struct btf_type *t, *cand; 4318 /* if we don't find equivalent type, then we are representative type */ 4319 int ref_type_id; 4320 long h; 4321 4322 if (d->map[type_id] == BTF_IN_PROGRESS_ID) 4323 return -ELOOP; 4324 if (d->map[type_id] <= BTF_MAX_NR_TYPES) 4325 return resolve_type_id(d, type_id); 4326 4327 t = btf_type_by_id(d->btf, type_id); 4328 d->map[type_id] = BTF_IN_PROGRESS_ID; 4329 4330 switch (btf_kind(t)) { 4331 case BTF_KIND_CONST: 4332 case BTF_KIND_VOLATILE: 4333 case BTF_KIND_RESTRICT: 4334 case BTF_KIND_PTR: 4335 case BTF_KIND_TYPEDEF: 4336 case BTF_KIND_FUNC: 4337 ref_type_id = btf_dedup_ref_type(d, t->type); 4338 if (ref_type_id < 0) 4339 return ref_type_id; 4340 t->type = ref_type_id; 4341 4342 h = btf_hash_common(t); 4343 for_each_dedup_cand(d, hash_entry, h) { 4344 cand_id = (__u32)(long)hash_entry->value; 4345 cand = btf_type_by_id(d->btf, cand_id); 4346 if (btf_equal_common(t, cand)) { 4347 new_id = cand_id; 4348 break; 4349 } 4350 } 4351 break; 4352 4353 case BTF_KIND_ARRAY: { 4354 struct btf_array *info = btf_array(t); 4355 4356 ref_type_id = btf_dedup_ref_type(d, info->type); 4357 if (ref_type_id < 0) 4358 return ref_type_id; 4359 info->type = ref_type_id; 4360 4361 ref_type_id = btf_dedup_ref_type(d, info->index_type); 4362 if (ref_type_id < 0) 4363 return ref_type_id; 4364 info->index_type = ref_type_id; 4365 4366 h = btf_hash_array(t); 4367 for_each_dedup_cand(d, hash_entry, h) { 4368 cand_id = (__u32)(long)hash_entry->value; 4369 cand = btf_type_by_id(d->btf, cand_id); 4370 if (btf_equal_array(t, cand)) { 4371 new_id = cand_id; 4372 break; 4373 } 4374 } 4375 break; 4376 } 4377 4378 case BTF_KIND_FUNC_PROTO: { 4379 struct btf_param *param; 4380 __u16 vlen; 4381 int i; 4382 4383 ref_type_id = btf_dedup_ref_type(d, t->type); 4384 if (ref_type_id < 0) 4385 return ref_type_id; 4386 t->type = ref_type_id; 4387 4388 vlen = btf_vlen(t); 4389 param = btf_params(t); 4390 for (i = 0; i < vlen; i++) { 4391 ref_type_id = btf_dedup_ref_type(d, param->type); 4392 if (ref_type_id < 0) 4393 return ref_type_id; 4394 param->type = ref_type_id; 4395 param++; 4396 } 4397 4398 h = btf_hash_fnproto(t); 4399 for_each_dedup_cand(d, hash_entry, h) { 4400 cand_id = (__u32)(long)hash_entry->value; 4401 cand = btf_type_by_id(d->btf, cand_id); 4402 if (btf_equal_fnproto(t, cand)) { 4403 new_id = cand_id; 4404 break; 4405 } 4406 } 4407 break; 4408 } 4409 4410 default: 4411 return -EINVAL; 4412 } 4413 4414 d->map[type_id] = new_id; 4415 if (type_id == new_id && btf_dedup_table_add(d, h, type_id)) 4416 return -ENOMEM; 4417 4418 return new_id; 4419 } 4420 4421 static int btf_dedup_ref_types(struct btf_dedup *d) 4422 { 4423 int i, err; 4424 4425 for (i = 0; i < d->btf->nr_types; i++) { 4426 err = btf_dedup_ref_type(d, d->btf->start_id + i); 4427 if (err < 0) 4428 return err; 4429 } 4430 /* we won't need d->dedup_table anymore */ 4431 hashmap__free(d->dedup_table); 4432 d->dedup_table = NULL; 4433 return 0; 4434 } 4435 4436 /* 4437 * Compact types. 4438 * 4439 * After we established for each type its corresponding canonical representative 4440 * type, we now can eliminate types that are not canonical and leave only 4441 * canonical ones layed out sequentially in memory by copying them over 4442 * duplicates. During compaction btf_dedup->hypot_map array is reused to store 4443 * a map from original type ID to a new compacted type ID, which will be used 4444 * during next phase to "fix up" type IDs, referenced from struct/union and 4445 * reference types. 4446 */ 4447 static int btf_dedup_compact_types(struct btf_dedup *d) 4448 { 4449 __u32 *new_offs; 4450 __u32 next_type_id = d->btf->start_id; 4451 const struct btf_type *t; 4452 void *p; 4453 int i, id, len; 4454 4455 /* we are going to reuse hypot_map to store compaction remapping */ 4456 d->hypot_map[0] = 0; 4457 /* base BTF types are not renumbered */ 4458 for (id = 1; id < d->btf->start_id; id++) 4459 d->hypot_map[id] = id; 4460 for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++) 4461 d->hypot_map[id] = BTF_UNPROCESSED_ID; 4462 4463 p = d->btf->types_data; 4464 4465 for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++) { 4466 if (d->map[id] != id) 4467 continue; 4468 4469 t = btf__type_by_id(d->btf, id); 4470 len = btf_type_size(t); 4471 if (len < 0) 4472 return len; 4473 4474 memmove(p, t, len); 4475 d->hypot_map[id] = next_type_id; 4476 d->btf->type_offs[next_type_id - d->btf->start_id] = p - d->btf->types_data; 4477 p += len; 4478 next_type_id++; 4479 } 4480 4481 /* shrink struct btf's internal types index and update btf_header */ 4482 d->btf->nr_types = next_type_id - d->btf->start_id; 4483 d->btf->type_offs_cap = d->btf->nr_types; 4484 d->btf->hdr->type_len = p - d->btf->types_data; 4485 new_offs = libbpf_reallocarray(d->btf->type_offs, d->btf->type_offs_cap, 4486 sizeof(*new_offs)); 4487 if (d->btf->type_offs_cap && !new_offs) 4488 return -ENOMEM; 4489 d->btf->type_offs = new_offs; 4490 d->btf->hdr->str_off = d->btf->hdr->type_len; 4491 d->btf->raw_size = d->btf->hdr->hdr_len + d->btf->hdr->type_len + d->btf->hdr->str_len; 4492 return 0; 4493 } 4494 4495 /* 4496 * Figure out final (deduplicated and compacted) type ID for provided original 4497 * `type_id` by first resolving it into corresponding canonical type ID and 4498 * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map, 4499 * which is populated during compaction phase. 4500 */ 4501 static int btf_dedup_remap_type_id(struct btf_dedup *d, __u32 type_id) 4502 { 4503 __u32 resolved_type_id, new_type_id; 4504 4505 resolved_type_id = resolve_type_id(d, type_id); 4506 new_type_id = d->hypot_map[resolved_type_id]; 4507 if (new_type_id > BTF_MAX_NR_TYPES) 4508 return -EINVAL; 4509 return new_type_id; 4510 } 4511 4512 /* 4513 * Remap referenced type IDs into deduped type IDs. 4514 * 4515 * After BTF types are deduplicated and compacted, their final type IDs may 4516 * differ from original ones. The map from original to a corresponding 4517 * deduped type ID is stored in btf_dedup->hypot_map and is populated during 4518 * compaction phase. During remapping phase we are rewriting all type IDs 4519 * referenced from any BTF type (e.g., struct fields, func proto args, etc) to 4520 * their final deduped type IDs. 4521 */ 4522 static int btf_dedup_remap_type(struct btf_dedup *d, __u32 type_id) 4523 { 4524 struct btf_type *t = btf_type_by_id(d->btf, type_id); 4525 int i, r; 4526 4527 switch (btf_kind(t)) { 4528 case BTF_KIND_INT: 4529 case BTF_KIND_ENUM: 4530 case BTF_KIND_FLOAT: 4531 break; 4532 4533 case BTF_KIND_FWD: 4534 case BTF_KIND_CONST: 4535 case BTF_KIND_VOLATILE: 4536 case BTF_KIND_RESTRICT: 4537 case BTF_KIND_PTR: 4538 case BTF_KIND_TYPEDEF: 4539 case BTF_KIND_FUNC: 4540 case BTF_KIND_VAR: 4541 r = btf_dedup_remap_type_id(d, t->type); 4542 if (r < 0) 4543 return r; 4544 t->type = r; 4545 break; 4546 4547 case BTF_KIND_ARRAY: { 4548 struct btf_array *arr_info = btf_array(t); 4549 4550 r = btf_dedup_remap_type_id(d, arr_info->type); 4551 if (r < 0) 4552 return r; 4553 arr_info->type = r; 4554 r = btf_dedup_remap_type_id(d, arr_info->index_type); 4555 if (r < 0) 4556 return r; 4557 arr_info->index_type = r; 4558 break; 4559 } 4560 4561 case BTF_KIND_STRUCT: 4562 case BTF_KIND_UNION: { 4563 struct btf_member *member = btf_members(t); 4564 __u16 vlen = btf_vlen(t); 4565 4566 for (i = 0; i < vlen; i++) { 4567 r = btf_dedup_remap_type_id(d, member->type); 4568 if (r < 0) 4569 return r; 4570 member->type = r; 4571 member++; 4572 } 4573 break; 4574 } 4575 4576 case BTF_KIND_FUNC_PROTO: { 4577 struct btf_param *param = btf_params(t); 4578 __u16 vlen = btf_vlen(t); 4579 4580 r = btf_dedup_remap_type_id(d, t->type); 4581 if (r < 0) 4582 return r; 4583 t->type = r; 4584 4585 for (i = 0; i < vlen; i++) { 4586 r = btf_dedup_remap_type_id(d, param->type); 4587 if (r < 0) 4588 return r; 4589 param->type = r; 4590 param++; 4591 } 4592 break; 4593 } 4594 4595 case BTF_KIND_DATASEC: { 4596 struct btf_var_secinfo *var = btf_var_secinfos(t); 4597 __u16 vlen = btf_vlen(t); 4598 4599 for (i = 0; i < vlen; i++) { 4600 r = btf_dedup_remap_type_id(d, var->type); 4601 if (r < 0) 4602 return r; 4603 var->type = r; 4604 var++; 4605 } 4606 break; 4607 } 4608 4609 default: 4610 return -EINVAL; 4611 } 4612 4613 return 0; 4614 } 4615 4616 static int btf_dedup_remap_types(struct btf_dedup *d) 4617 { 4618 int i, r; 4619 4620 for (i = 0; i < d->btf->nr_types; i++) { 4621 r = btf_dedup_remap_type(d, d->btf->start_id + i); 4622 if (r < 0) 4623 return r; 4624 } 4625 return 0; 4626 } 4627 4628 /* 4629 * Probe few well-known locations for vmlinux kernel image and try to load BTF 4630 * data out of it to use for target BTF. 4631 */ 4632 struct btf *libbpf_find_kernel_btf(void) 4633 { 4634 struct { 4635 const char *path_fmt; 4636 bool raw_btf; 4637 } locations[] = { 4638 /* try canonical vmlinux BTF through sysfs first */ 4639 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ }, 4640 /* fall back to trying to find vmlinux ELF on disk otherwise */ 4641 { "/boot/vmlinux-%1$s" }, 4642 { "/lib/modules/%1$s/vmlinux-%1$s" }, 4643 { "/lib/modules/%1$s/build/vmlinux" }, 4644 { "/usr/lib/modules/%1$s/kernel/vmlinux" }, 4645 { "/usr/lib/debug/boot/vmlinux-%1$s" }, 4646 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" }, 4647 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" }, 4648 }; 4649 char path[PATH_MAX + 1]; 4650 struct utsname buf; 4651 struct btf *btf; 4652 int i; 4653 4654 uname(&buf); 4655 4656 for (i = 0; i < ARRAY_SIZE(locations); i++) { 4657 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release); 4658 4659 if (access(path, R_OK)) 4660 continue; 4661 4662 if (locations[i].raw_btf) 4663 btf = btf__parse_raw(path); 4664 else 4665 btf = btf__parse_elf(path, NULL); 4666 4667 pr_debug("loading kernel BTF '%s': %ld\n", 4668 path, IS_ERR(btf) ? PTR_ERR(btf) : 0); 4669 if (IS_ERR(btf)) 4670 continue; 4671 4672 return btf; 4673 } 4674 4675 pr_warn("failed to find valid kernel BTF\n"); 4676 return ERR_PTR(-ESRCH); 4677 } 4678