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