1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) 2 /* Copyright (c) 2018 Facebook */ 3 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include <unistd.h> 8 #include <errno.h> 9 #include <linux/err.h> 10 #include <linux/btf.h> 11 #include "btf.h" 12 #include "bpf.h" 13 #include "libbpf.h" 14 #include "libbpf_util.h" 15 16 #define max(a, b) ((a) > (b) ? (a) : (b)) 17 #define min(a, b) ((a) < (b) ? (a) : (b)) 18 19 #define BTF_MAX_NR_TYPES 0x7fffffff 20 #define BTF_MAX_STR_OFFSET 0x7fffffff 21 22 #define IS_MODIFIER(k) (((k) == BTF_KIND_TYPEDEF) || \ 23 ((k) == BTF_KIND_VOLATILE) || \ 24 ((k) == BTF_KIND_CONST) || \ 25 ((k) == BTF_KIND_RESTRICT)) 26 27 static struct btf_type btf_void; 28 29 struct btf { 30 union { 31 struct btf_header *hdr; 32 void *data; 33 }; 34 struct btf_type **types; 35 const char *strings; 36 void *nohdr_data; 37 __u32 nr_types; 38 __u32 types_size; 39 __u32 data_size; 40 int fd; 41 }; 42 43 struct btf_ext_info { 44 /* 45 * info points to the individual info section (e.g. func_info and 46 * line_info) from the .BTF.ext. It does not include the __u32 rec_size. 47 */ 48 void *info; 49 __u32 rec_size; 50 __u32 len; 51 }; 52 53 struct btf_ext { 54 union { 55 struct btf_ext_header *hdr; 56 void *data; 57 }; 58 struct btf_ext_info func_info; 59 struct btf_ext_info line_info; 60 __u32 data_size; 61 }; 62 63 struct btf_ext_info_sec { 64 __u32 sec_name_off; 65 __u32 num_info; 66 /* Followed by num_info * record_size number of bytes */ 67 __u8 data[0]; 68 }; 69 70 /* The minimum bpf_func_info checked by the loader */ 71 struct bpf_func_info_min { 72 __u32 insn_off; 73 __u32 type_id; 74 }; 75 76 /* The minimum bpf_line_info checked by the loader */ 77 struct bpf_line_info_min { 78 __u32 insn_off; 79 __u32 file_name_off; 80 __u32 line_off; 81 __u32 line_col; 82 }; 83 84 static inline __u64 ptr_to_u64(const void *ptr) 85 { 86 return (__u64) (unsigned long) ptr; 87 } 88 89 static int btf_add_type(struct btf *btf, struct btf_type *t) 90 { 91 if (btf->types_size - btf->nr_types < 2) { 92 struct btf_type **new_types; 93 __u32 expand_by, new_size; 94 95 if (btf->types_size == BTF_MAX_NR_TYPES) 96 return -E2BIG; 97 98 expand_by = max(btf->types_size >> 2, 16); 99 new_size = min(BTF_MAX_NR_TYPES, btf->types_size + expand_by); 100 101 new_types = realloc(btf->types, sizeof(*new_types) * new_size); 102 if (!new_types) 103 return -ENOMEM; 104 105 if (btf->nr_types == 0) 106 new_types[0] = &btf_void; 107 108 btf->types = new_types; 109 btf->types_size = new_size; 110 } 111 112 btf->types[++(btf->nr_types)] = t; 113 114 return 0; 115 } 116 117 static int btf_parse_hdr(struct btf *btf) 118 { 119 const struct btf_header *hdr = btf->hdr; 120 __u32 meta_left; 121 122 if (btf->data_size < sizeof(struct btf_header)) { 123 pr_debug("BTF header not found\n"); 124 return -EINVAL; 125 } 126 127 if (hdr->magic != BTF_MAGIC) { 128 pr_debug("Invalid BTF magic:%x\n", hdr->magic); 129 return -EINVAL; 130 } 131 132 if (hdr->version != BTF_VERSION) { 133 pr_debug("Unsupported BTF version:%u\n", hdr->version); 134 return -ENOTSUP; 135 } 136 137 if (hdr->flags) { 138 pr_debug("Unsupported BTF flags:%x\n", hdr->flags); 139 return -ENOTSUP; 140 } 141 142 meta_left = btf->data_size - sizeof(*hdr); 143 if (!meta_left) { 144 pr_debug("BTF has no data\n"); 145 return -EINVAL; 146 } 147 148 if (meta_left < hdr->type_off) { 149 pr_debug("Invalid BTF type section offset:%u\n", hdr->type_off); 150 return -EINVAL; 151 } 152 153 if (meta_left < hdr->str_off) { 154 pr_debug("Invalid BTF string section offset:%u\n", hdr->str_off); 155 return -EINVAL; 156 } 157 158 if (hdr->type_off >= hdr->str_off) { 159 pr_debug("BTF type section offset >= string section offset. No type?\n"); 160 return -EINVAL; 161 } 162 163 if (hdr->type_off & 0x02) { 164 pr_debug("BTF type section is not aligned to 4 bytes\n"); 165 return -EINVAL; 166 } 167 168 btf->nohdr_data = btf->hdr + 1; 169 170 return 0; 171 } 172 173 static int btf_parse_str_sec(struct btf *btf) 174 { 175 const struct btf_header *hdr = btf->hdr; 176 const char *start = btf->nohdr_data + hdr->str_off; 177 const char *end = start + btf->hdr->str_len; 178 179 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_STR_OFFSET || 180 start[0] || end[-1]) { 181 pr_debug("Invalid BTF string section\n"); 182 return -EINVAL; 183 } 184 185 btf->strings = start; 186 187 return 0; 188 } 189 190 static int btf_type_size(struct btf_type *t) 191 { 192 int base_size = sizeof(struct btf_type); 193 __u16 vlen = BTF_INFO_VLEN(t->info); 194 195 switch (BTF_INFO_KIND(t->info)) { 196 case BTF_KIND_FWD: 197 case BTF_KIND_CONST: 198 case BTF_KIND_VOLATILE: 199 case BTF_KIND_RESTRICT: 200 case BTF_KIND_PTR: 201 case BTF_KIND_TYPEDEF: 202 case BTF_KIND_FUNC: 203 return base_size; 204 case BTF_KIND_INT: 205 return base_size + sizeof(__u32); 206 case BTF_KIND_ENUM: 207 return base_size + vlen * sizeof(struct btf_enum); 208 case BTF_KIND_ARRAY: 209 return base_size + sizeof(struct btf_array); 210 case BTF_KIND_STRUCT: 211 case BTF_KIND_UNION: 212 return base_size + vlen * sizeof(struct btf_member); 213 case BTF_KIND_FUNC_PROTO: 214 return base_size + vlen * sizeof(struct btf_param); 215 default: 216 pr_debug("Unsupported BTF_KIND:%u\n", BTF_INFO_KIND(t->info)); 217 return -EINVAL; 218 } 219 } 220 221 static int btf_parse_type_sec(struct btf *btf) 222 { 223 struct btf_header *hdr = btf->hdr; 224 void *nohdr_data = btf->nohdr_data; 225 void *next_type = nohdr_data + hdr->type_off; 226 void *end_type = nohdr_data + hdr->str_off; 227 228 while (next_type < end_type) { 229 struct btf_type *t = next_type; 230 int type_size; 231 int err; 232 233 type_size = btf_type_size(t); 234 if (type_size < 0) 235 return type_size; 236 next_type += type_size; 237 err = btf_add_type(btf, t); 238 if (err) 239 return err; 240 } 241 242 return 0; 243 } 244 245 __u32 btf__get_nr_types(const struct btf *btf) 246 { 247 return btf->nr_types; 248 } 249 250 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id) 251 { 252 if (type_id > btf->nr_types) 253 return NULL; 254 255 return btf->types[type_id]; 256 } 257 258 static bool btf_type_is_void(const struct btf_type *t) 259 { 260 return t == &btf_void || BTF_INFO_KIND(t->info) == BTF_KIND_FWD; 261 } 262 263 static bool btf_type_is_void_or_null(const struct btf_type *t) 264 { 265 return !t || btf_type_is_void(t); 266 } 267 268 #define MAX_RESOLVE_DEPTH 32 269 270 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id) 271 { 272 const struct btf_array *array; 273 const struct btf_type *t; 274 __u32 nelems = 1; 275 __s64 size = -1; 276 int i; 277 278 t = btf__type_by_id(btf, type_id); 279 for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t); 280 i++) { 281 switch (BTF_INFO_KIND(t->info)) { 282 case BTF_KIND_INT: 283 case BTF_KIND_STRUCT: 284 case BTF_KIND_UNION: 285 case BTF_KIND_ENUM: 286 size = t->size; 287 goto done; 288 case BTF_KIND_PTR: 289 size = sizeof(void *); 290 goto done; 291 case BTF_KIND_TYPEDEF: 292 case BTF_KIND_VOLATILE: 293 case BTF_KIND_CONST: 294 case BTF_KIND_RESTRICT: 295 type_id = t->type; 296 break; 297 case BTF_KIND_ARRAY: 298 array = (const struct btf_array *)(t + 1); 299 if (nelems && array->nelems > UINT32_MAX / nelems) 300 return -E2BIG; 301 nelems *= array->nelems; 302 type_id = array->type; 303 break; 304 default: 305 return -EINVAL; 306 } 307 308 t = btf__type_by_id(btf, type_id); 309 } 310 311 if (size < 0) 312 return -EINVAL; 313 314 done: 315 if (nelems && size > UINT32_MAX / nelems) 316 return -E2BIG; 317 318 return nelems * size; 319 } 320 321 int btf__resolve_type(const struct btf *btf, __u32 type_id) 322 { 323 const struct btf_type *t; 324 int depth = 0; 325 326 t = btf__type_by_id(btf, type_id); 327 while (depth < MAX_RESOLVE_DEPTH && 328 !btf_type_is_void_or_null(t) && 329 IS_MODIFIER(BTF_INFO_KIND(t->info))) { 330 type_id = t->type; 331 t = btf__type_by_id(btf, type_id); 332 depth++; 333 } 334 335 if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t)) 336 return -EINVAL; 337 338 return type_id; 339 } 340 341 __s32 btf__find_by_name(const struct btf *btf, const char *type_name) 342 { 343 __u32 i; 344 345 if (!strcmp(type_name, "void")) 346 return 0; 347 348 for (i = 1; i <= btf->nr_types; i++) { 349 const struct btf_type *t = btf->types[i]; 350 const char *name = btf__name_by_offset(btf, t->name_off); 351 352 if (name && !strcmp(type_name, name)) 353 return i; 354 } 355 356 return -ENOENT; 357 } 358 359 void btf__free(struct btf *btf) 360 { 361 if (!btf) 362 return; 363 364 if (btf->fd != -1) 365 close(btf->fd); 366 367 free(btf->data); 368 free(btf->types); 369 free(btf); 370 } 371 372 struct btf *btf__new(__u8 *data, __u32 size) 373 { 374 struct btf *btf; 375 int err; 376 377 btf = calloc(1, sizeof(struct btf)); 378 if (!btf) 379 return ERR_PTR(-ENOMEM); 380 381 btf->fd = -1; 382 383 btf->data = malloc(size); 384 if (!btf->data) { 385 err = -ENOMEM; 386 goto done; 387 } 388 389 memcpy(btf->data, data, size); 390 btf->data_size = size; 391 392 err = btf_parse_hdr(btf); 393 if (err) 394 goto done; 395 396 err = btf_parse_str_sec(btf); 397 if (err) 398 goto done; 399 400 err = btf_parse_type_sec(btf); 401 402 done: 403 if (err) { 404 btf__free(btf); 405 return ERR_PTR(err); 406 } 407 408 return btf; 409 } 410 411 int btf__load(struct btf *btf) 412 { 413 __u32 log_buf_size = BPF_LOG_BUF_SIZE; 414 char *log_buf = NULL; 415 int err = 0; 416 417 if (btf->fd >= 0) 418 return -EEXIST; 419 420 log_buf = malloc(log_buf_size); 421 if (!log_buf) 422 return -ENOMEM; 423 424 *log_buf = 0; 425 426 btf->fd = bpf_load_btf(btf->data, btf->data_size, 427 log_buf, log_buf_size, false); 428 if (btf->fd < 0) { 429 err = -errno; 430 pr_warning("Error loading BTF: %s(%d)\n", strerror(errno), errno); 431 if (*log_buf) 432 pr_warning("%s\n", log_buf); 433 goto done; 434 } 435 436 done: 437 free(log_buf); 438 return err; 439 } 440 441 int btf__fd(const struct btf *btf) 442 { 443 return btf->fd; 444 } 445 446 const void *btf__get_raw_data(const struct btf *btf, __u32 *size) 447 { 448 *size = btf->data_size; 449 return btf->data; 450 } 451 452 const char *btf__name_by_offset(const struct btf *btf, __u32 offset) 453 { 454 if (offset < btf->hdr->str_len) 455 return &btf->strings[offset]; 456 else 457 return NULL; 458 } 459 460 int btf__get_from_id(__u32 id, struct btf **btf) 461 { 462 struct bpf_btf_info btf_info = { 0 }; 463 __u32 len = sizeof(btf_info); 464 __u32 last_size; 465 int btf_fd; 466 void *ptr; 467 int err; 468 469 err = 0; 470 *btf = NULL; 471 btf_fd = bpf_btf_get_fd_by_id(id); 472 if (btf_fd < 0) 473 return 0; 474 475 /* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so 476 * let's start with a sane default - 4KiB here - and resize it only if 477 * bpf_obj_get_info_by_fd() needs a bigger buffer. 478 */ 479 btf_info.btf_size = 4096; 480 last_size = btf_info.btf_size; 481 ptr = malloc(last_size); 482 if (!ptr) { 483 err = -ENOMEM; 484 goto exit_free; 485 } 486 487 memset(ptr, 0, last_size); 488 btf_info.btf = ptr_to_u64(ptr); 489 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len); 490 491 if (!err && btf_info.btf_size > last_size) { 492 void *temp_ptr; 493 494 last_size = btf_info.btf_size; 495 temp_ptr = realloc(ptr, last_size); 496 if (!temp_ptr) { 497 err = -ENOMEM; 498 goto exit_free; 499 } 500 ptr = temp_ptr; 501 memset(ptr, 0, last_size); 502 btf_info.btf = ptr_to_u64(ptr); 503 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len); 504 } 505 506 if (err || btf_info.btf_size > last_size) { 507 err = errno; 508 goto exit_free; 509 } 510 511 *btf = btf__new((__u8 *)(long)btf_info.btf, btf_info.btf_size); 512 if (IS_ERR(*btf)) { 513 err = PTR_ERR(*btf); 514 *btf = NULL; 515 } 516 517 exit_free: 518 close(btf_fd); 519 free(ptr); 520 521 return err; 522 } 523 524 int btf__get_map_kv_tids(const struct btf *btf, const char *map_name, 525 __u32 expected_key_size, __u32 expected_value_size, 526 __u32 *key_type_id, __u32 *value_type_id) 527 { 528 const struct btf_type *container_type; 529 const struct btf_member *key, *value; 530 const size_t max_name = 256; 531 char container_name[max_name]; 532 __s64 key_size, value_size; 533 __s32 container_id; 534 535 if (snprintf(container_name, max_name, "____btf_map_%s", map_name) == 536 max_name) { 537 pr_warning("map:%s length of '____btf_map_%s' is too long\n", 538 map_name, map_name); 539 return -EINVAL; 540 } 541 542 container_id = btf__find_by_name(btf, container_name); 543 if (container_id < 0) { 544 pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n", 545 map_name, container_name); 546 return container_id; 547 } 548 549 container_type = btf__type_by_id(btf, container_id); 550 if (!container_type) { 551 pr_warning("map:%s cannot find BTF type for container_id:%u\n", 552 map_name, container_id); 553 return -EINVAL; 554 } 555 556 if (BTF_INFO_KIND(container_type->info) != BTF_KIND_STRUCT || 557 BTF_INFO_VLEN(container_type->info) < 2) { 558 pr_warning("map:%s container_name:%s is an invalid container struct\n", 559 map_name, container_name); 560 return -EINVAL; 561 } 562 563 key = (struct btf_member *)(container_type + 1); 564 value = key + 1; 565 566 key_size = btf__resolve_size(btf, key->type); 567 if (key_size < 0) { 568 pr_warning("map:%s invalid BTF key_type_size\n", map_name); 569 return key_size; 570 } 571 572 if (expected_key_size != key_size) { 573 pr_warning("map:%s btf_key_type_size:%u != map_def_key_size:%u\n", 574 map_name, (__u32)key_size, expected_key_size); 575 return -EINVAL; 576 } 577 578 value_size = btf__resolve_size(btf, value->type); 579 if (value_size < 0) { 580 pr_warning("map:%s invalid BTF value_type_size\n", map_name); 581 return value_size; 582 } 583 584 if (expected_value_size != value_size) { 585 pr_warning("map:%s btf_value_type_size:%u != map_def_value_size:%u\n", 586 map_name, (__u32)value_size, expected_value_size); 587 return -EINVAL; 588 } 589 590 *key_type_id = key->type; 591 *value_type_id = value->type; 592 593 return 0; 594 } 595 596 struct btf_ext_sec_setup_param { 597 __u32 off; 598 __u32 len; 599 __u32 min_rec_size; 600 struct btf_ext_info *ext_info; 601 const char *desc; 602 }; 603 604 static int btf_ext_setup_info(struct btf_ext *btf_ext, 605 struct btf_ext_sec_setup_param *ext_sec) 606 { 607 const struct btf_ext_info_sec *sinfo; 608 struct btf_ext_info *ext_info; 609 __u32 info_left, record_size; 610 /* The start of the info sec (including the __u32 record_size). */ 611 void *info; 612 613 if (ext_sec->off & 0x03) { 614 pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n", 615 ext_sec->desc); 616 return -EINVAL; 617 } 618 619 info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off; 620 info_left = ext_sec->len; 621 622 if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) { 623 pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n", 624 ext_sec->desc, ext_sec->off, ext_sec->len); 625 return -EINVAL; 626 } 627 628 /* At least a record size */ 629 if (info_left < sizeof(__u32)) { 630 pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc); 631 return -EINVAL; 632 } 633 634 /* The record size needs to meet the minimum standard */ 635 record_size = *(__u32 *)info; 636 if (record_size < ext_sec->min_rec_size || 637 record_size & 0x03) { 638 pr_debug("%s section in .BTF.ext has invalid record size %u\n", 639 ext_sec->desc, record_size); 640 return -EINVAL; 641 } 642 643 sinfo = info + sizeof(__u32); 644 info_left -= sizeof(__u32); 645 646 /* If no records, return failure now so .BTF.ext won't be used. */ 647 if (!info_left) { 648 pr_debug("%s section in .BTF.ext has no records", ext_sec->desc); 649 return -EINVAL; 650 } 651 652 while (info_left) { 653 unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec); 654 __u64 total_record_size; 655 __u32 num_records; 656 657 if (info_left < sec_hdrlen) { 658 pr_debug("%s section header is not found in .BTF.ext\n", 659 ext_sec->desc); 660 return -EINVAL; 661 } 662 663 num_records = sinfo->num_info; 664 if (num_records == 0) { 665 pr_debug("%s section has incorrect num_records in .BTF.ext\n", 666 ext_sec->desc); 667 return -EINVAL; 668 } 669 670 total_record_size = sec_hdrlen + 671 (__u64)num_records * record_size; 672 if (info_left < total_record_size) { 673 pr_debug("%s section has incorrect num_records in .BTF.ext\n", 674 ext_sec->desc); 675 return -EINVAL; 676 } 677 678 info_left -= total_record_size; 679 sinfo = (void *)sinfo + total_record_size; 680 } 681 682 ext_info = ext_sec->ext_info; 683 ext_info->len = ext_sec->len - sizeof(__u32); 684 ext_info->rec_size = record_size; 685 ext_info->info = info + sizeof(__u32); 686 687 return 0; 688 } 689 690 static int btf_ext_setup_func_info(struct btf_ext *btf_ext) 691 { 692 struct btf_ext_sec_setup_param param = { 693 .off = btf_ext->hdr->func_info_off, 694 .len = btf_ext->hdr->func_info_len, 695 .min_rec_size = sizeof(struct bpf_func_info_min), 696 .ext_info = &btf_ext->func_info, 697 .desc = "func_info" 698 }; 699 700 return btf_ext_setup_info(btf_ext, ¶m); 701 } 702 703 static int btf_ext_setup_line_info(struct btf_ext *btf_ext) 704 { 705 struct btf_ext_sec_setup_param param = { 706 .off = btf_ext->hdr->line_info_off, 707 .len = btf_ext->hdr->line_info_len, 708 .min_rec_size = sizeof(struct bpf_line_info_min), 709 .ext_info = &btf_ext->line_info, 710 .desc = "line_info", 711 }; 712 713 return btf_ext_setup_info(btf_ext, ¶m); 714 } 715 716 static int btf_ext_parse_hdr(__u8 *data, __u32 data_size) 717 { 718 const struct btf_ext_header *hdr = (struct btf_ext_header *)data; 719 720 if (data_size < offsetof(struct btf_ext_header, func_info_off) || 721 data_size < hdr->hdr_len) { 722 pr_debug("BTF.ext header not found"); 723 return -EINVAL; 724 } 725 726 if (hdr->magic != BTF_MAGIC) { 727 pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic); 728 return -EINVAL; 729 } 730 731 if (hdr->version != BTF_VERSION) { 732 pr_debug("Unsupported BTF.ext version:%u\n", hdr->version); 733 return -ENOTSUP; 734 } 735 736 if (hdr->flags) { 737 pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags); 738 return -ENOTSUP; 739 } 740 741 if (data_size == hdr->hdr_len) { 742 pr_debug("BTF.ext has no data\n"); 743 return -EINVAL; 744 } 745 746 return 0; 747 } 748 749 void btf_ext__free(struct btf_ext *btf_ext) 750 { 751 if (!btf_ext) 752 return; 753 free(btf_ext->data); 754 free(btf_ext); 755 } 756 757 struct btf_ext *btf_ext__new(__u8 *data, __u32 size) 758 { 759 struct btf_ext *btf_ext; 760 int err; 761 762 err = btf_ext_parse_hdr(data, size); 763 if (err) 764 return ERR_PTR(err); 765 766 btf_ext = calloc(1, sizeof(struct btf_ext)); 767 if (!btf_ext) 768 return ERR_PTR(-ENOMEM); 769 770 btf_ext->data_size = size; 771 btf_ext->data = malloc(size); 772 if (!btf_ext->data) { 773 err = -ENOMEM; 774 goto done; 775 } 776 memcpy(btf_ext->data, data, size); 777 778 err = btf_ext_setup_func_info(btf_ext); 779 if (err) 780 goto done; 781 782 err = btf_ext_setup_line_info(btf_ext); 783 if (err) 784 goto done; 785 786 done: 787 if (err) { 788 btf_ext__free(btf_ext); 789 return ERR_PTR(err); 790 } 791 792 return btf_ext; 793 } 794 795 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size) 796 { 797 *size = btf_ext->data_size; 798 return btf_ext->data; 799 } 800 801 static int btf_ext_reloc_info(const struct btf *btf, 802 const struct btf_ext_info *ext_info, 803 const char *sec_name, __u32 insns_cnt, 804 void **info, __u32 *cnt) 805 { 806 __u32 sec_hdrlen = sizeof(struct btf_ext_info_sec); 807 __u32 i, record_size, existing_len, records_len; 808 struct btf_ext_info_sec *sinfo; 809 const char *info_sec_name; 810 __u64 remain_len; 811 void *data; 812 813 record_size = ext_info->rec_size; 814 sinfo = ext_info->info; 815 remain_len = ext_info->len; 816 while (remain_len > 0) { 817 records_len = sinfo->num_info * record_size; 818 info_sec_name = btf__name_by_offset(btf, sinfo->sec_name_off); 819 if (strcmp(info_sec_name, sec_name)) { 820 remain_len -= sec_hdrlen + records_len; 821 sinfo = (void *)sinfo + sec_hdrlen + records_len; 822 continue; 823 } 824 825 existing_len = (*cnt) * record_size; 826 data = realloc(*info, existing_len + records_len); 827 if (!data) 828 return -ENOMEM; 829 830 memcpy(data + existing_len, sinfo->data, records_len); 831 /* adjust insn_off only, the rest data will be passed 832 * to the kernel. 833 */ 834 for (i = 0; i < sinfo->num_info; i++) { 835 __u32 *insn_off; 836 837 insn_off = data + existing_len + (i * record_size); 838 *insn_off = *insn_off / sizeof(struct bpf_insn) + 839 insns_cnt; 840 } 841 *info = data; 842 *cnt += sinfo->num_info; 843 return 0; 844 } 845 846 return -ENOENT; 847 } 848 849 int btf_ext__reloc_func_info(const struct btf *btf, 850 const struct btf_ext *btf_ext, 851 const char *sec_name, __u32 insns_cnt, 852 void **func_info, __u32 *cnt) 853 { 854 return btf_ext_reloc_info(btf, &btf_ext->func_info, sec_name, 855 insns_cnt, func_info, cnt); 856 } 857 858 int btf_ext__reloc_line_info(const struct btf *btf, 859 const struct btf_ext *btf_ext, 860 const char *sec_name, __u32 insns_cnt, 861 void **line_info, __u32 *cnt) 862 { 863 return btf_ext_reloc_info(btf, &btf_ext->line_info, sec_name, 864 insns_cnt, line_info, cnt); 865 } 866 867 __u32 btf_ext__func_info_rec_size(const struct btf_ext *btf_ext) 868 { 869 return btf_ext->func_info.rec_size; 870 } 871 872 __u32 btf_ext__line_info_rec_size(const struct btf_ext *btf_ext) 873 { 874 return btf_ext->line_info.rec_size; 875 } 876 877 struct btf_dedup; 878 879 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext, 880 const struct btf_dedup_opts *opts); 881 static void btf_dedup_free(struct btf_dedup *d); 882 static int btf_dedup_strings(struct btf_dedup *d); 883 static int btf_dedup_prim_types(struct btf_dedup *d); 884 static int btf_dedup_struct_types(struct btf_dedup *d); 885 static int btf_dedup_ref_types(struct btf_dedup *d); 886 static int btf_dedup_compact_types(struct btf_dedup *d); 887 static int btf_dedup_remap_types(struct btf_dedup *d); 888 889 /* 890 * Deduplicate BTF types and strings. 891 * 892 * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF 893 * section with all BTF type descriptors and string data. It overwrites that 894 * memory in-place with deduplicated types and strings without any loss of 895 * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section 896 * is provided, all the strings referenced from .BTF.ext section are honored 897 * and updated to point to the right offsets after deduplication. 898 * 899 * If function returns with error, type/string data might be garbled and should 900 * be discarded. 901 * 902 * More verbose and detailed description of both problem btf_dedup is solving, 903 * as well as solution could be found at: 904 * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html 905 * 906 * Problem description and justification 907 * ===================================== 908 * 909 * BTF type information is typically emitted either as a result of conversion 910 * from DWARF to BTF or directly by compiler. In both cases, each compilation 911 * unit contains information about a subset of all the types that are used 912 * in an application. These subsets are frequently overlapping and contain a lot 913 * of duplicated information when later concatenated together into a single 914 * binary. This algorithm ensures that each unique type is represented by single 915 * BTF type descriptor, greatly reducing resulting size of BTF data. 916 * 917 * Compilation unit isolation and subsequent duplication of data is not the only 918 * problem. The same type hierarchy (e.g., struct and all the type that struct 919 * references) in different compilation units can be represented in BTF to 920 * various degrees of completeness (or, rather, incompleteness) due to 921 * struct/union forward declarations. 922 * 923 * Let's take a look at an example, that we'll use to better understand the 924 * problem (and solution). Suppose we have two compilation units, each using 925 * same `struct S`, but each of them having incomplete type information about 926 * struct's fields: 927 * 928 * // CU #1: 929 * struct S; 930 * struct A { 931 * int a; 932 * struct A* self; 933 * struct S* parent; 934 * }; 935 * struct B; 936 * struct S { 937 * struct A* a_ptr; 938 * struct B* b_ptr; 939 * }; 940 * 941 * // CU #2: 942 * struct S; 943 * struct A; 944 * struct B { 945 * int b; 946 * struct B* self; 947 * struct S* parent; 948 * }; 949 * struct S { 950 * struct A* a_ptr; 951 * struct B* b_ptr; 952 * }; 953 * 954 * In case of CU #1, BTF data will know only that `struct B` exist (but no 955 * more), but will know the complete type information about `struct A`. While 956 * for CU #2, it will know full type information about `struct B`, but will 957 * only know about forward declaration of `struct A` (in BTF terms, it will 958 * have `BTF_KIND_FWD` type descriptor with name `B`). 959 * 960 * This compilation unit isolation means that it's possible that there is no 961 * single CU with complete type information describing structs `S`, `A`, and 962 * `B`. Also, we might get tons of duplicated and redundant type information. 963 * 964 * Additional complication we need to keep in mind comes from the fact that 965 * types, in general, can form graphs containing cycles, not just DAGs. 966 * 967 * While algorithm does deduplication, it also merges and resolves type 968 * information (unless disabled throught `struct btf_opts`), whenever possible. 969 * E.g., in the example above with two compilation units having partial type 970 * information for structs `A` and `B`, the output of algorithm will emit 971 * a single copy of each BTF type that describes structs `A`, `B`, and `S` 972 * (as well as type information for `int` and pointers), as if they were defined 973 * in a single compilation unit as: 974 * 975 * struct A { 976 * int a; 977 * struct A* self; 978 * struct S* parent; 979 * }; 980 * struct B { 981 * int b; 982 * struct B* self; 983 * struct S* parent; 984 * }; 985 * struct S { 986 * struct A* a_ptr; 987 * struct B* b_ptr; 988 * }; 989 * 990 * Algorithm summary 991 * ================= 992 * 993 * Algorithm completes its work in 6 separate passes: 994 * 995 * 1. Strings deduplication. 996 * 2. Primitive types deduplication (int, enum, fwd). 997 * 3. Struct/union types deduplication. 998 * 4. Reference types deduplication (pointers, typedefs, arrays, funcs, func 999 * protos, and const/volatile/restrict modifiers). 1000 * 5. Types compaction. 1001 * 6. Types remapping. 1002 * 1003 * Algorithm determines canonical type descriptor, which is a single 1004 * representative type for each truly unique type. This canonical type is the 1005 * one that will go into final deduplicated BTF type information. For 1006 * struct/unions, it is also the type that algorithm will merge additional type 1007 * information into (while resolving FWDs), as it discovers it from data in 1008 * other CUs. Each input BTF type eventually gets either mapped to itself, if 1009 * that type is canonical, or to some other type, if that type is equivalent 1010 * and was chosen as canonical representative. This mapping is stored in 1011 * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that 1012 * FWD type got resolved to. 1013 * 1014 * To facilitate fast discovery of canonical types, we also maintain canonical 1015 * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash 1016 * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types 1017 * that match that signature. With sufficiently good choice of type signature 1018 * hashing function, we can limit number of canonical types for each unique type 1019 * signature to a very small number, allowing to find canonical type for any 1020 * duplicated type very quickly. 1021 * 1022 * Struct/union deduplication is the most critical part and algorithm for 1023 * deduplicating structs/unions is described in greater details in comments for 1024 * `btf_dedup_is_equiv` function. 1025 */ 1026 int btf__dedup(struct btf *btf, struct btf_ext *btf_ext, 1027 const struct btf_dedup_opts *opts) 1028 { 1029 struct btf_dedup *d = btf_dedup_new(btf, btf_ext, opts); 1030 int err; 1031 1032 if (IS_ERR(d)) { 1033 pr_debug("btf_dedup_new failed: %ld", PTR_ERR(d)); 1034 return -EINVAL; 1035 } 1036 1037 err = btf_dedup_strings(d); 1038 if (err < 0) { 1039 pr_debug("btf_dedup_strings failed:%d\n", err); 1040 goto done; 1041 } 1042 err = btf_dedup_prim_types(d); 1043 if (err < 0) { 1044 pr_debug("btf_dedup_prim_types failed:%d\n", err); 1045 goto done; 1046 } 1047 err = btf_dedup_struct_types(d); 1048 if (err < 0) { 1049 pr_debug("btf_dedup_struct_types failed:%d\n", err); 1050 goto done; 1051 } 1052 err = btf_dedup_ref_types(d); 1053 if (err < 0) { 1054 pr_debug("btf_dedup_ref_types failed:%d\n", err); 1055 goto done; 1056 } 1057 err = btf_dedup_compact_types(d); 1058 if (err < 0) { 1059 pr_debug("btf_dedup_compact_types failed:%d\n", err); 1060 goto done; 1061 } 1062 err = btf_dedup_remap_types(d); 1063 if (err < 0) { 1064 pr_debug("btf_dedup_remap_types failed:%d\n", err); 1065 goto done; 1066 } 1067 1068 done: 1069 btf_dedup_free(d); 1070 return err; 1071 } 1072 1073 #define BTF_DEDUP_TABLE_SIZE_LOG 14 1074 #define BTF_DEDUP_TABLE_MOD ((1 << BTF_DEDUP_TABLE_SIZE_LOG) - 1) 1075 #define BTF_UNPROCESSED_ID ((__u32)-1) 1076 #define BTF_IN_PROGRESS_ID ((__u32)-2) 1077 1078 struct btf_dedup_node { 1079 struct btf_dedup_node *next; 1080 __u32 type_id; 1081 }; 1082 1083 struct btf_dedup { 1084 /* .BTF section to be deduped in-place */ 1085 struct btf *btf; 1086 /* 1087 * Optional .BTF.ext section. When provided, any strings referenced 1088 * from it will be taken into account when deduping strings 1089 */ 1090 struct btf_ext *btf_ext; 1091 /* 1092 * This is a map from any type's signature hash to a list of possible 1093 * canonical representative type candidates. Hash collisions are 1094 * ignored, so even types of various kinds can share same list of 1095 * candidates, which is fine because we rely on subsequent 1096 * btf_xxx_equal() checks to authoritatively verify type equality. 1097 */ 1098 struct btf_dedup_node **dedup_table; 1099 /* Canonical types map */ 1100 __u32 *map; 1101 /* Hypothetical mapping, used during type graph equivalence checks */ 1102 __u32 *hypot_map; 1103 __u32 *hypot_list; 1104 size_t hypot_cnt; 1105 size_t hypot_cap; 1106 /* Various option modifying behavior of algorithm */ 1107 struct btf_dedup_opts opts; 1108 }; 1109 1110 struct btf_str_ptr { 1111 const char *str; 1112 __u32 new_off; 1113 bool used; 1114 }; 1115 1116 struct btf_str_ptrs { 1117 struct btf_str_ptr *ptrs; 1118 const char *data; 1119 __u32 cnt; 1120 __u32 cap; 1121 }; 1122 1123 static inline __u32 hash_combine(__u32 h, __u32 value) 1124 { 1125 /* 2^31 + 2^29 - 2^25 + 2^22 - 2^19 - 2^16 + 1 */ 1126 #define GOLDEN_RATIO_PRIME 0x9e370001UL 1127 return h * 37 + value * GOLDEN_RATIO_PRIME; 1128 #undef GOLDEN_RATIO_PRIME 1129 } 1130 1131 #define for_each_hash_node(table, hash, node) \ 1132 for (node = table[hash & BTF_DEDUP_TABLE_MOD]; node; node = node->next) 1133 1134 static int btf_dedup_table_add(struct btf_dedup *d, __u32 hash, __u32 type_id) 1135 { 1136 struct btf_dedup_node *node = malloc(sizeof(struct btf_dedup_node)); 1137 1138 if (!node) 1139 return -ENOMEM; 1140 node->type_id = type_id; 1141 node->next = d->dedup_table[hash & BTF_DEDUP_TABLE_MOD]; 1142 d->dedup_table[hash & BTF_DEDUP_TABLE_MOD] = node; 1143 return 0; 1144 } 1145 1146 static int btf_dedup_hypot_map_add(struct btf_dedup *d, 1147 __u32 from_id, __u32 to_id) 1148 { 1149 if (d->hypot_cnt == d->hypot_cap) { 1150 __u32 *new_list; 1151 1152 d->hypot_cap += max(16, d->hypot_cap / 2); 1153 new_list = realloc(d->hypot_list, sizeof(__u32) * d->hypot_cap); 1154 if (!new_list) 1155 return -ENOMEM; 1156 d->hypot_list = new_list; 1157 } 1158 d->hypot_list[d->hypot_cnt++] = from_id; 1159 d->hypot_map[from_id] = to_id; 1160 return 0; 1161 } 1162 1163 static void btf_dedup_clear_hypot_map(struct btf_dedup *d) 1164 { 1165 int i; 1166 1167 for (i = 0; i < d->hypot_cnt; i++) 1168 d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID; 1169 d->hypot_cnt = 0; 1170 } 1171 1172 static void btf_dedup_table_free(struct btf_dedup *d) 1173 { 1174 struct btf_dedup_node *head, *tmp; 1175 int i; 1176 1177 if (!d->dedup_table) 1178 return; 1179 1180 for (i = 0; i < (1 << BTF_DEDUP_TABLE_SIZE_LOG); i++) { 1181 while (d->dedup_table[i]) { 1182 tmp = d->dedup_table[i]; 1183 d->dedup_table[i] = tmp->next; 1184 free(tmp); 1185 } 1186 1187 head = d->dedup_table[i]; 1188 while (head) { 1189 tmp = head; 1190 head = head->next; 1191 free(tmp); 1192 } 1193 } 1194 1195 free(d->dedup_table); 1196 d->dedup_table = NULL; 1197 } 1198 1199 static void btf_dedup_free(struct btf_dedup *d) 1200 { 1201 btf_dedup_table_free(d); 1202 1203 free(d->map); 1204 d->map = NULL; 1205 1206 free(d->hypot_map); 1207 d->hypot_map = NULL; 1208 1209 free(d->hypot_list); 1210 d->hypot_list = NULL; 1211 1212 free(d); 1213 } 1214 1215 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext, 1216 const struct btf_dedup_opts *opts) 1217 { 1218 struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup)); 1219 int i, err = 0; 1220 1221 if (!d) 1222 return ERR_PTR(-ENOMEM); 1223 1224 d->btf = btf; 1225 d->btf_ext = btf_ext; 1226 1227 d->dedup_table = calloc(1 << BTF_DEDUP_TABLE_SIZE_LOG, 1228 sizeof(struct btf_dedup_node *)); 1229 if (!d->dedup_table) { 1230 err = -ENOMEM; 1231 goto done; 1232 } 1233 1234 d->map = malloc(sizeof(__u32) * (1 + btf->nr_types)); 1235 if (!d->map) { 1236 err = -ENOMEM; 1237 goto done; 1238 } 1239 /* special BTF "void" type is made canonical immediately */ 1240 d->map[0] = 0; 1241 for (i = 1; i <= btf->nr_types; i++) 1242 d->map[i] = BTF_UNPROCESSED_ID; 1243 1244 d->hypot_map = malloc(sizeof(__u32) * (1 + btf->nr_types)); 1245 if (!d->hypot_map) { 1246 err = -ENOMEM; 1247 goto done; 1248 } 1249 for (i = 0; i <= btf->nr_types; i++) 1250 d->hypot_map[i] = BTF_UNPROCESSED_ID; 1251 1252 d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds; 1253 1254 done: 1255 if (err) { 1256 btf_dedup_free(d); 1257 return ERR_PTR(err); 1258 } 1259 1260 return d; 1261 } 1262 1263 typedef int (*str_off_fn_t)(__u32 *str_off_ptr, void *ctx); 1264 1265 /* 1266 * Iterate over all possible places in .BTF and .BTF.ext that can reference 1267 * string and pass pointer to it to a provided callback `fn`. 1268 */ 1269 static int btf_for_each_str_off(struct btf_dedup *d, str_off_fn_t fn, void *ctx) 1270 { 1271 void *line_data_cur, *line_data_end; 1272 int i, j, r, rec_size; 1273 struct btf_type *t; 1274 1275 for (i = 1; i <= d->btf->nr_types; i++) { 1276 t = d->btf->types[i]; 1277 r = fn(&t->name_off, ctx); 1278 if (r) 1279 return r; 1280 1281 switch (BTF_INFO_KIND(t->info)) { 1282 case BTF_KIND_STRUCT: 1283 case BTF_KIND_UNION: { 1284 struct btf_member *m = (struct btf_member *)(t + 1); 1285 __u16 vlen = BTF_INFO_VLEN(t->info); 1286 1287 for (j = 0; j < vlen; j++) { 1288 r = fn(&m->name_off, ctx); 1289 if (r) 1290 return r; 1291 m++; 1292 } 1293 break; 1294 } 1295 case BTF_KIND_ENUM: { 1296 struct btf_enum *m = (struct btf_enum *)(t + 1); 1297 __u16 vlen = BTF_INFO_VLEN(t->info); 1298 1299 for (j = 0; j < vlen; j++) { 1300 r = fn(&m->name_off, ctx); 1301 if (r) 1302 return r; 1303 m++; 1304 } 1305 break; 1306 } 1307 case BTF_KIND_FUNC_PROTO: { 1308 struct btf_param *m = (struct btf_param *)(t + 1); 1309 __u16 vlen = BTF_INFO_VLEN(t->info); 1310 1311 for (j = 0; j < vlen; j++) { 1312 r = fn(&m->name_off, ctx); 1313 if (r) 1314 return r; 1315 m++; 1316 } 1317 break; 1318 } 1319 default: 1320 break; 1321 } 1322 } 1323 1324 if (!d->btf_ext) 1325 return 0; 1326 1327 line_data_cur = d->btf_ext->line_info.info; 1328 line_data_end = d->btf_ext->line_info.info + d->btf_ext->line_info.len; 1329 rec_size = d->btf_ext->line_info.rec_size; 1330 1331 while (line_data_cur < line_data_end) { 1332 struct btf_ext_info_sec *sec = line_data_cur; 1333 struct bpf_line_info_min *line_info; 1334 __u32 num_info = sec->num_info; 1335 1336 r = fn(&sec->sec_name_off, ctx); 1337 if (r) 1338 return r; 1339 1340 line_data_cur += sizeof(struct btf_ext_info_sec); 1341 for (i = 0; i < num_info; i++) { 1342 line_info = line_data_cur; 1343 r = fn(&line_info->file_name_off, ctx); 1344 if (r) 1345 return r; 1346 r = fn(&line_info->line_off, ctx); 1347 if (r) 1348 return r; 1349 line_data_cur += rec_size; 1350 } 1351 } 1352 1353 return 0; 1354 } 1355 1356 static int str_sort_by_content(const void *a1, const void *a2) 1357 { 1358 const struct btf_str_ptr *p1 = a1; 1359 const struct btf_str_ptr *p2 = a2; 1360 1361 return strcmp(p1->str, p2->str); 1362 } 1363 1364 static int str_sort_by_offset(const void *a1, const void *a2) 1365 { 1366 const struct btf_str_ptr *p1 = a1; 1367 const struct btf_str_ptr *p2 = a2; 1368 1369 if (p1->str != p2->str) 1370 return p1->str < p2->str ? -1 : 1; 1371 return 0; 1372 } 1373 1374 static int btf_dedup_str_ptr_cmp(const void *str_ptr, const void *pelem) 1375 { 1376 const struct btf_str_ptr *p = pelem; 1377 1378 if (str_ptr != p->str) 1379 return (const char *)str_ptr < p->str ? -1 : 1; 1380 return 0; 1381 } 1382 1383 static int btf_str_mark_as_used(__u32 *str_off_ptr, void *ctx) 1384 { 1385 struct btf_str_ptrs *strs; 1386 struct btf_str_ptr *s; 1387 1388 if (*str_off_ptr == 0) 1389 return 0; 1390 1391 strs = ctx; 1392 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt, 1393 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp); 1394 if (!s) 1395 return -EINVAL; 1396 s->used = true; 1397 return 0; 1398 } 1399 1400 static int btf_str_remap_offset(__u32 *str_off_ptr, void *ctx) 1401 { 1402 struct btf_str_ptrs *strs; 1403 struct btf_str_ptr *s; 1404 1405 if (*str_off_ptr == 0) 1406 return 0; 1407 1408 strs = ctx; 1409 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt, 1410 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp); 1411 if (!s) 1412 return -EINVAL; 1413 *str_off_ptr = s->new_off; 1414 return 0; 1415 } 1416 1417 /* 1418 * Dedup string and filter out those that are not referenced from either .BTF 1419 * or .BTF.ext (if provided) sections. 1420 * 1421 * This is done by building index of all strings in BTF's string section, 1422 * then iterating over all entities that can reference strings (e.g., type 1423 * names, struct field names, .BTF.ext line info, etc) and marking corresponding 1424 * strings as used. After that all used strings are deduped and compacted into 1425 * sequential blob of memory and new offsets are calculated. Then all the string 1426 * references are iterated again and rewritten using new offsets. 1427 */ 1428 static int btf_dedup_strings(struct btf_dedup *d) 1429 { 1430 const struct btf_header *hdr = d->btf->hdr; 1431 char *start = (char *)d->btf->nohdr_data + hdr->str_off; 1432 char *end = start + d->btf->hdr->str_len; 1433 char *p = start, *tmp_strs = NULL; 1434 struct btf_str_ptrs strs = { 1435 .cnt = 0, 1436 .cap = 0, 1437 .ptrs = NULL, 1438 .data = start, 1439 }; 1440 int i, j, err = 0, grp_idx; 1441 bool grp_used; 1442 1443 /* build index of all strings */ 1444 while (p < end) { 1445 if (strs.cnt + 1 > strs.cap) { 1446 struct btf_str_ptr *new_ptrs; 1447 1448 strs.cap += max(strs.cnt / 2, 16); 1449 new_ptrs = realloc(strs.ptrs, 1450 sizeof(strs.ptrs[0]) * strs.cap); 1451 if (!new_ptrs) { 1452 err = -ENOMEM; 1453 goto done; 1454 } 1455 strs.ptrs = new_ptrs; 1456 } 1457 1458 strs.ptrs[strs.cnt].str = p; 1459 strs.ptrs[strs.cnt].used = false; 1460 1461 p += strlen(p) + 1; 1462 strs.cnt++; 1463 } 1464 1465 /* temporary storage for deduplicated strings */ 1466 tmp_strs = malloc(d->btf->hdr->str_len); 1467 if (!tmp_strs) { 1468 err = -ENOMEM; 1469 goto done; 1470 } 1471 1472 /* mark all used strings */ 1473 strs.ptrs[0].used = true; 1474 err = btf_for_each_str_off(d, btf_str_mark_as_used, &strs); 1475 if (err) 1476 goto done; 1477 1478 /* sort strings by context, so that we can identify duplicates */ 1479 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_content); 1480 1481 /* 1482 * iterate groups of equal strings and if any instance in a group was 1483 * referenced, emit single instance and remember new offset 1484 */ 1485 p = tmp_strs; 1486 grp_idx = 0; 1487 grp_used = strs.ptrs[0].used; 1488 /* iterate past end to avoid code duplication after loop */ 1489 for (i = 1; i <= strs.cnt; i++) { 1490 /* 1491 * when i == strs.cnt, we want to skip string comparison and go 1492 * straight to handling last group of strings (otherwise we'd 1493 * need to handle last group after the loop w/ duplicated code) 1494 */ 1495 if (i < strs.cnt && 1496 !strcmp(strs.ptrs[i].str, strs.ptrs[grp_idx].str)) { 1497 grp_used = grp_used || strs.ptrs[i].used; 1498 continue; 1499 } 1500 1501 /* 1502 * this check would have been required after the loop to handle 1503 * last group of strings, but due to <= condition in a loop 1504 * we avoid that duplication 1505 */ 1506 if (grp_used) { 1507 int new_off = p - tmp_strs; 1508 __u32 len = strlen(strs.ptrs[grp_idx].str); 1509 1510 memmove(p, strs.ptrs[grp_idx].str, len + 1); 1511 for (j = grp_idx; j < i; j++) 1512 strs.ptrs[j].new_off = new_off; 1513 p += len + 1; 1514 } 1515 1516 if (i < strs.cnt) { 1517 grp_idx = i; 1518 grp_used = strs.ptrs[i].used; 1519 } 1520 } 1521 1522 /* replace original strings with deduped ones */ 1523 d->btf->hdr->str_len = p - tmp_strs; 1524 memmove(start, tmp_strs, d->btf->hdr->str_len); 1525 end = start + d->btf->hdr->str_len; 1526 1527 /* restore original order for further binary search lookups */ 1528 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_offset); 1529 1530 /* remap string offsets */ 1531 err = btf_for_each_str_off(d, btf_str_remap_offset, &strs); 1532 if (err) 1533 goto done; 1534 1535 d->btf->hdr->str_len = end - start; 1536 1537 done: 1538 free(tmp_strs); 1539 free(strs.ptrs); 1540 return err; 1541 } 1542 1543 static __u32 btf_hash_common(struct btf_type *t) 1544 { 1545 __u32 h; 1546 1547 h = hash_combine(0, t->name_off); 1548 h = hash_combine(h, t->info); 1549 h = hash_combine(h, t->size); 1550 return h; 1551 } 1552 1553 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2) 1554 { 1555 return t1->name_off == t2->name_off && 1556 t1->info == t2->info && 1557 t1->size == t2->size; 1558 } 1559 1560 /* Calculate type signature hash of INT. */ 1561 static __u32 btf_hash_int(struct btf_type *t) 1562 { 1563 __u32 info = *(__u32 *)(t + 1); 1564 __u32 h; 1565 1566 h = btf_hash_common(t); 1567 h = hash_combine(h, info); 1568 return h; 1569 } 1570 1571 /* Check structural equality of two INTs. */ 1572 static bool btf_equal_int(struct btf_type *t1, struct btf_type *t2) 1573 { 1574 __u32 info1, info2; 1575 1576 if (!btf_equal_common(t1, t2)) 1577 return false; 1578 info1 = *(__u32 *)(t1 + 1); 1579 info2 = *(__u32 *)(t2 + 1); 1580 return info1 == info2; 1581 } 1582 1583 /* Calculate type signature hash of ENUM. */ 1584 static __u32 btf_hash_enum(struct btf_type *t) 1585 { 1586 struct btf_enum *member = (struct btf_enum *)(t + 1); 1587 __u32 vlen = BTF_INFO_VLEN(t->info); 1588 __u32 h = btf_hash_common(t); 1589 int i; 1590 1591 for (i = 0; i < vlen; i++) { 1592 h = hash_combine(h, member->name_off); 1593 h = hash_combine(h, member->val); 1594 member++; 1595 } 1596 return h; 1597 } 1598 1599 /* Check structural equality of two ENUMs. */ 1600 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2) 1601 { 1602 struct btf_enum *m1, *m2; 1603 __u16 vlen; 1604 int i; 1605 1606 if (!btf_equal_common(t1, t2)) 1607 return false; 1608 1609 vlen = BTF_INFO_VLEN(t1->info); 1610 m1 = (struct btf_enum *)(t1 + 1); 1611 m2 = (struct btf_enum *)(t2 + 1); 1612 for (i = 0; i < vlen; i++) { 1613 if (m1->name_off != m2->name_off || m1->val != m2->val) 1614 return false; 1615 m1++; 1616 m2++; 1617 } 1618 return true; 1619 } 1620 1621 /* 1622 * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs, 1623 * as referenced type IDs equivalence is established separately during type 1624 * graph equivalence check algorithm. 1625 */ 1626 static __u32 btf_hash_struct(struct btf_type *t) 1627 { 1628 struct btf_member *member = (struct btf_member *)(t + 1); 1629 __u32 vlen = BTF_INFO_VLEN(t->info); 1630 __u32 h = btf_hash_common(t); 1631 int i; 1632 1633 for (i = 0; i < vlen; i++) { 1634 h = hash_combine(h, member->name_off); 1635 h = hash_combine(h, member->offset); 1636 /* no hashing of referenced type ID, it can be unresolved yet */ 1637 member++; 1638 } 1639 return h; 1640 } 1641 1642 /* 1643 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type 1644 * IDs. This check is performed during type graph equivalence check and 1645 * referenced types equivalence is checked separately. 1646 */ 1647 static bool btf_equal_struct(struct btf_type *t1, struct btf_type *t2) 1648 { 1649 struct btf_member *m1, *m2; 1650 __u16 vlen; 1651 int i; 1652 1653 if (!btf_equal_common(t1, t2)) 1654 return false; 1655 1656 vlen = BTF_INFO_VLEN(t1->info); 1657 m1 = (struct btf_member *)(t1 + 1); 1658 m2 = (struct btf_member *)(t2 + 1); 1659 for (i = 0; i < vlen; i++) { 1660 if (m1->name_off != m2->name_off || m1->offset != m2->offset) 1661 return false; 1662 m1++; 1663 m2++; 1664 } 1665 return true; 1666 } 1667 1668 /* 1669 * Calculate type signature hash of ARRAY, including referenced type IDs, 1670 * under assumption that they were already resolved to canonical type IDs and 1671 * are not going to change. 1672 */ 1673 static __u32 btf_hash_array(struct btf_type *t) 1674 { 1675 struct btf_array *info = (struct btf_array *)(t + 1); 1676 __u32 h = btf_hash_common(t); 1677 1678 h = hash_combine(h, info->type); 1679 h = hash_combine(h, info->index_type); 1680 h = hash_combine(h, info->nelems); 1681 return h; 1682 } 1683 1684 /* 1685 * Check exact equality of two ARRAYs, taking into account referenced 1686 * type IDs, under assumption that they were already resolved to canonical 1687 * type IDs and are not going to change. 1688 * This function is called during reference types deduplication to compare 1689 * ARRAY to potential canonical representative. 1690 */ 1691 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2) 1692 { 1693 struct btf_array *info1, *info2; 1694 1695 if (!btf_equal_common(t1, t2)) 1696 return false; 1697 1698 info1 = (struct btf_array *)(t1 + 1); 1699 info2 = (struct btf_array *)(t2 + 1); 1700 return info1->type == info2->type && 1701 info1->index_type == info2->index_type && 1702 info1->nelems == info2->nelems; 1703 } 1704 1705 /* 1706 * Check structural compatibility of two ARRAYs, ignoring referenced type 1707 * IDs. This check is performed during type graph equivalence check and 1708 * referenced types equivalence is checked separately. 1709 */ 1710 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2) 1711 { 1712 struct btf_array *info1, *info2; 1713 1714 if (!btf_equal_common(t1, t2)) 1715 return false; 1716 1717 info1 = (struct btf_array *)(t1 + 1); 1718 info2 = (struct btf_array *)(t2 + 1); 1719 return info1->nelems == info2->nelems; 1720 } 1721 1722 /* 1723 * Calculate type signature hash of FUNC_PROTO, including referenced type IDs, 1724 * under assumption that they were already resolved to canonical type IDs and 1725 * are not going to change. 1726 */ 1727 static inline __u32 btf_hash_fnproto(struct btf_type *t) 1728 { 1729 struct btf_param *member = (struct btf_param *)(t + 1); 1730 __u16 vlen = BTF_INFO_VLEN(t->info); 1731 __u32 h = btf_hash_common(t); 1732 int i; 1733 1734 for (i = 0; i < vlen; i++) { 1735 h = hash_combine(h, member->name_off); 1736 h = hash_combine(h, member->type); 1737 member++; 1738 } 1739 return h; 1740 } 1741 1742 /* 1743 * Check exact equality of two FUNC_PROTOs, taking into account referenced 1744 * type IDs, under assumption that they were already resolved to canonical 1745 * type IDs and are not going to change. 1746 * This function is called during reference types deduplication to compare 1747 * FUNC_PROTO to potential canonical representative. 1748 */ 1749 static inline bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2) 1750 { 1751 struct btf_param *m1, *m2; 1752 __u16 vlen; 1753 int i; 1754 1755 if (!btf_equal_common(t1, t2)) 1756 return false; 1757 1758 vlen = BTF_INFO_VLEN(t1->info); 1759 m1 = (struct btf_param *)(t1 + 1); 1760 m2 = (struct btf_param *)(t2 + 1); 1761 for (i = 0; i < vlen; i++) { 1762 if (m1->name_off != m2->name_off || m1->type != m2->type) 1763 return false; 1764 m1++; 1765 m2++; 1766 } 1767 return true; 1768 } 1769 1770 /* 1771 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type 1772 * IDs. This check is performed during type graph equivalence check and 1773 * referenced types equivalence is checked separately. 1774 */ 1775 static inline bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2) 1776 { 1777 struct btf_param *m1, *m2; 1778 __u16 vlen; 1779 int i; 1780 1781 /* skip return type ID */ 1782 if (t1->name_off != t2->name_off || t1->info != t2->info) 1783 return false; 1784 1785 vlen = BTF_INFO_VLEN(t1->info); 1786 m1 = (struct btf_param *)(t1 + 1); 1787 m2 = (struct btf_param *)(t2 + 1); 1788 for (i = 0; i < vlen; i++) { 1789 if (m1->name_off != m2->name_off) 1790 return false; 1791 m1++; 1792 m2++; 1793 } 1794 return true; 1795 } 1796 1797 /* 1798 * Deduplicate primitive types, that can't reference other types, by calculating 1799 * their type signature hash and comparing them with any possible canonical 1800 * candidate. If no canonical candidate matches, type itself is marked as 1801 * canonical and is added into `btf_dedup->dedup_table` as another candidate. 1802 */ 1803 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id) 1804 { 1805 struct btf_type *t = d->btf->types[type_id]; 1806 struct btf_type *cand; 1807 struct btf_dedup_node *cand_node; 1808 /* if we don't find equivalent type, then we are canonical */ 1809 __u32 new_id = type_id; 1810 __u32 h; 1811 1812 switch (BTF_INFO_KIND(t->info)) { 1813 case BTF_KIND_CONST: 1814 case BTF_KIND_VOLATILE: 1815 case BTF_KIND_RESTRICT: 1816 case BTF_KIND_PTR: 1817 case BTF_KIND_TYPEDEF: 1818 case BTF_KIND_ARRAY: 1819 case BTF_KIND_STRUCT: 1820 case BTF_KIND_UNION: 1821 case BTF_KIND_FUNC: 1822 case BTF_KIND_FUNC_PROTO: 1823 return 0; 1824 1825 case BTF_KIND_INT: 1826 h = btf_hash_int(t); 1827 for_each_hash_node(d->dedup_table, h, cand_node) { 1828 cand = d->btf->types[cand_node->type_id]; 1829 if (btf_equal_int(t, cand)) { 1830 new_id = cand_node->type_id; 1831 break; 1832 } 1833 } 1834 break; 1835 1836 case BTF_KIND_ENUM: 1837 h = btf_hash_enum(t); 1838 for_each_hash_node(d->dedup_table, h, cand_node) { 1839 cand = d->btf->types[cand_node->type_id]; 1840 if (btf_equal_enum(t, cand)) { 1841 new_id = cand_node->type_id; 1842 break; 1843 } 1844 } 1845 break; 1846 1847 case BTF_KIND_FWD: 1848 h = btf_hash_common(t); 1849 for_each_hash_node(d->dedup_table, h, cand_node) { 1850 cand = d->btf->types[cand_node->type_id]; 1851 if (btf_equal_common(t, cand)) { 1852 new_id = cand_node->type_id; 1853 break; 1854 } 1855 } 1856 break; 1857 1858 default: 1859 return -EINVAL; 1860 } 1861 1862 d->map[type_id] = new_id; 1863 if (type_id == new_id && btf_dedup_table_add(d, h, type_id)) 1864 return -ENOMEM; 1865 1866 return 0; 1867 } 1868 1869 static int btf_dedup_prim_types(struct btf_dedup *d) 1870 { 1871 int i, err; 1872 1873 for (i = 1; i <= d->btf->nr_types; i++) { 1874 err = btf_dedup_prim_type(d, i); 1875 if (err) 1876 return err; 1877 } 1878 return 0; 1879 } 1880 1881 /* 1882 * Check whether type is already mapped into canonical one (could be to itself). 1883 */ 1884 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id) 1885 { 1886 return d->map[type_id] <= BTF_MAX_NR_TYPES; 1887 } 1888 1889 /* 1890 * Resolve type ID into its canonical type ID, if any; otherwise return original 1891 * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow 1892 * STRUCT/UNION link and resolve it into canonical type ID as well. 1893 */ 1894 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id) 1895 { 1896 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id) 1897 type_id = d->map[type_id]; 1898 return type_id; 1899 } 1900 1901 /* 1902 * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original 1903 * type ID. 1904 */ 1905 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id) 1906 { 1907 __u32 orig_type_id = type_id; 1908 1909 if (BTF_INFO_KIND(d->btf->types[type_id]->info) != BTF_KIND_FWD) 1910 return type_id; 1911 1912 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id) 1913 type_id = d->map[type_id]; 1914 1915 if (BTF_INFO_KIND(d->btf->types[type_id]->info) != BTF_KIND_FWD) 1916 return type_id; 1917 1918 return orig_type_id; 1919 } 1920 1921 1922 static inline __u16 btf_fwd_kind(struct btf_type *t) 1923 { 1924 return BTF_INFO_KFLAG(t->info) ? BTF_KIND_UNION : BTF_KIND_STRUCT; 1925 } 1926 1927 /* 1928 * Check equivalence of BTF type graph formed by candidate struct/union (we'll 1929 * call it "candidate graph" in this description for brevity) to a type graph 1930 * formed by (potential) canonical struct/union ("canonical graph" for brevity 1931 * here, though keep in mind that not all types in canonical graph are 1932 * necessarily canonical representatives themselves, some of them might be 1933 * duplicates or its uniqueness might not have been established yet). 1934 * Returns: 1935 * - >0, if type graphs are equivalent; 1936 * - 0, if not equivalent; 1937 * - <0, on error. 1938 * 1939 * Algorithm performs side-by-side DFS traversal of both type graphs and checks 1940 * equivalence of BTF types at each step. If at any point BTF types in candidate 1941 * and canonical graphs are not compatible structurally, whole graphs are 1942 * incompatible. If types are structurally equivalent (i.e., all information 1943 * except referenced type IDs is exactly the same), a mapping from `canon_id` to 1944 * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`). 1945 * If a type references other types, then those referenced types are checked 1946 * for equivalence recursively. 1947 * 1948 * During DFS traversal, if we find that for current `canon_id` type we 1949 * already have some mapping in hypothetical map, we check for two possible 1950 * situations: 1951 * - `canon_id` is mapped to exactly the same type as `cand_id`. This will 1952 * happen when type graphs have cycles. In this case we assume those two 1953 * types are equivalent. 1954 * - `canon_id` is mapped to different type. This is contradiction in our 1955 * hypothetical mapping, because same graph in canonical graph corresponds 1956 * to two different types in candidate graph, which for equivalent type 1957 * graphs shouldn't happen. This condition terminates equivalence check 1958 * with negative result. 1959 * 1960 * If type graphs traversal exhausts types to check and find no contradiction, 1961 * then type graphs are equivalent. 1962 * 1963 * When checking types for equivalence, there is one special case: FWD types. 1964 * If FWD type resolution is allowed and one of the types (either from canonical 1965 * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind 1966 * flag) and their names match, hypothetical mapping is updated to point from 1967 * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully, 1968 * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently. 1969 * 1970 * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution, 1971 * if there are two exactly named (or anonymous) structs/unions that are 1972 * compatible structurally, one of which has FWD field, while other is concrete 1973 * STRUCT/UNION, but according to C sources they are different structs/unions 1974 * that are referencing different types with the same name. This is extremely 1975 * unlikely to happen, but btf_dedup API allows to disable FWD resolution if 1976 * this logic is causing problems. 1977 * 1978 * Doing FWD resolution means that both candidate and/or canonical graphs can 1979 * consists of portions of the graph that come from multiple compilation units. 1980 * This is due to the fact that types within single compilation unit are always 1981 * deduplicated and FWDs are already resolved, if referenced struct/union 1982 * definiton is available. So, if we had unresolved FWD and found corresponding 1983 * STRUCT/UNION, they will be from different compilation units. This 1984 * consequently means that when we "link" FWD to corresponding STRUCT/UNION, 1985 * type graph will likely have at least two different BTF types that describe 1986 * same type (e.g., most probably there will be two different BTF types for the 1987 * same 'int' primitive type) and could even have "overlapping" parts of type 1988 * graph that describe same subset of types. 1989 * 1990 * This in turn means that our assumption that each type in canonical graph 1991 * must correspond to exactly one type in candidate graph might not hold 1992 * anymore and will make it harder to detect contradictions using hypothetical 1993 * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION 1994 * resolution only in canonical graph. FWDs in candidate graphs are never 1995 * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs 1996 * that can occur: 1997 * - Both types in canonical and candidate graphs are FWDs. If they are 1998 * structurally equivalent, then they can either be both resolved to the 1999 * same STRUCT/UNION or not resolved at all. In both cases they are 2000 * equivalent and there is no need to resolve FWD on candidate side. 2001 * - Both types in canonical and candidate graphs are concrete STRUCT/UNION, 2002 * so nothing to resolve as well, algorithm will check equivalence anyway. 2003 * - Type in canonical graph is FWD, while type in candidate is concrete 2004 * STRUCT/UNION. In this case candidate graph comes from single compilation 2005 * unit, so there is exactly one BTF type for each unique C type. After 2006 * resolving FWD into STRUCT/UNION, there might be more than one BTF type 2007 * in canonical graph mapping to single BTF type in candidate graph, but 2008 * because hypothetical mapping maps from canonical to candidate types, it's 2009 * alright, and we still maintain the property of having single `canon_id` 2010 * mapping to single `cand_id` (there could be two different `canon_id` 2011 * mapped to the same `cand_id`, but it's not contradictory). 2012 * - Type in canonical graph is concrete STRUCT/UNION, while type in candidate 2013 * graph is FWD. In this case we are just going to check compatibility of 2014 * STRUCT/UNION and corresponding FWD, and if they are compatible, we'll 2015 * assume that whatever STRUCT/UNION FWD resolves to must be equivalent to 2016 * a concrete STRUCT/UNION from canonical graph. If the rest of type graphs 2017 * turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from 2018 * canonical graph. 2019 */ 2020 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id, 2021 __u32 canon_id) 2022 { 2023 struct btf_type *cand_type; 2024 struct btf_type *canon_type; 2025 __u32 hypot_type_id; 2026 __u16 cand_kind; 2027 __u16 canon_kind; 2028 int i, eq; 2029 2030 /* if both resolve to the same canonical, they must be equivalent */ 2031 if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id)) 2032 return 1; 2033 2034 canon_id = resolve_fwd_id(d, canon_id); 2035 2036 hypot_type_id = d->hypot_map[canon_id]; 2037 if (hypot_type_id <= BTF_MAX_NR_TYPES) 2038 return hypot_type_id == cand_id; 2039 2040 if (btf_dedup_hypot_map_add(d, canon_id, cand_id)) 2041 return -ENOMEM; 2042 2043 cand_type = d->btf->types[cand_id]; 2044 canon_type = d->btf->types[canon_id]; 2045 cand_kind = BTF_INFO_KIND(cand_type->info); 2046 canon_kind = BTF_INFO_KIND(canon_type->info); 2047 2048 if (cand_type->name_off != canon_type->name_off) 2049 return 0; 2050 2051 /* FWD <--> STRUCT/UNION equivalence check, if enabled */ 2052 if (!d->opts.dont_resolve_fwds 2053 && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD) 2054 && cand_kind != canon_kind) { 2055 __u16 real_kind; 2056 __u16 fwd_kind; 2057 2058 if (cand_kind == BTF_KIND_FWD) { 2059 real_kind = canon_kind; 2060 fwd_kind = btf_fwd_kind(cand_type); 2061 } else { 2062 real_kind = cand_kind; 2063 fwd_kind = btf_fwd_kind(canon_type); 2064 } 2065 return fwd_kind == real_kind; 2066 } 2067 2068 if (cand_type->info != canon_type->info) 2069 return 0; 2070 2071 switch (cand_kind) { 2072 case BTF_KIND_INT: 2073 return btf_equal_int(cand_type, canon_type); 2074 2075 case BTF_KIND_ENUM: 2076 return btf_equal_enum(cand_type, canon_type); 2077 2078 case BTF_KIND_FWD: 2079 return btf_equal_common(cand_type, canon_type); 2080 2081 case BTF_KIND_CONST: 2082 case BTF_KIND_VOLATILE: 2083 case BTF_KIND_RESTRICT: 2084 case BTF_KIND_PTR: 2085 case BTF_KIND_TYPEDEF: 2086 case BTF_KIND_FUNC: 2087 return btf_dedup_is_equiv(d, cand_type->type, canon_type->type); 2088 2089 case BTF_KIND_ARRAY: { 2090 struct btf_array *cand_arr, *canon_arr; 2091 2092 if (!btf_compat_array(cand_type, canon_type)) 2093 return 0; 2094 cand_arr = (struct btf_array *)(cand_type + 1); 2095 canon_arr = (struct btf_array *)(canon_type + 1); 2096 eq = btf_dedup_is_equiv(d, 2097 cand_arr->index_type, canon_arr->index_type); 2098 if (eq <= 0) 2099 return eq; 2100 return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type); 2101 } 2102 2103 case BTF_KIND_STRUCT: 2104 case BTF_KIND_UNION: { 2105 struct btf_member *cand_m, *canon_m; 2106 __u16 vlen; 2107 2108 if (!btf_equal_struct(cand_type, canon_type)) 2109 return 0; 2110 vlen = BTF_INFO_VLEN(cand_type->info); 2111 cand_m = (struct btf_member *)(cand_type + 1); 2112 canon_m = (struct btf_member *)(canon_type + 1); 2113 for (i = 0; i < vlen; i++) { 2114 eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type); 2115 if (eq <= 0) 2116 return eq; 2117 cand_m++; 2118 canon_m++; 2119 } 2120 2121 return 1; 2122 } 2123 2124 case BTF_KIND_FUNC_PROTO: { 2125 struct btf_param *cand_p, *canon_p; 2126 __u16 vlen; 2127 2128 if (!btf_compat_fnproto(cand_type, canon_type)) 2129 return 0; 2130 eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type); 2131 if (eq <= 0) 2132 return eq; 2133 vlen = BTF_INFO_VLEN(cand_type->info); 2134 cand_p = (struct btf_param *)(cand_type + 1); 2135 canon_p = (struct btf_param *)(canon_type + 1); 2136 for (i = 0; i < vlen; i++) { 2137 eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type); 2138 if (eq <= 0) 2139 return eq; 2140 cand_p++; 2141 canon_p++; 2142 } 2143 return 1; 2144 } 2145 2146 default: 2147 return -EINVAL; 2148 } 2149 return 0; 2150 } 2151 2152 /* 2153 * Use hypothetical mapping, produced by successful type graph equivalence 2154 * check, to augment existing struct/union canonical mapping, where possible. 2155 * 2156 * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record 2157 * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional: 2158 * it doesn't matter if FWD type was part of canonical graph or candidate one, 2159 * we are recording the mapping anyway. As opposed to carefulness required 2160 * for struct/union correspondence mapping (described below), for FWD resolution 2161 * it's not important, as by the time that FWD type (reference type) will be 2162 * deduplicated all structs/unions will be deduped already anyway. 2163 * 2164 * Recording STRUCT/UNION mapping is purely a performance optimization and is 2165 * not required for correctness. It needs to be done carefully to ensure that 2166 * struct/union from candidate's type graph is not mapped into corresponding 2167 * struct/union from canonical type graph that itself hasn't been resolved into 2168 * canonical representative. The only guarantee we have is that canonical 2169 * struct/union was determined as canonical and that won't change. But any 2170 * types referenced through that struct/union fields could have been not yet 2171 * resolved, so in case like that it's too early to establish any kind of 2172 * correspondence between structs/unions. 2173 * 2174 * No canonical correspondence is derived for primitive types (they are already 2175 * deduplicated completely already anyway) or reference types (they rely on 2176 * stability of struct/union canonical relationship for equivalence checks). 2177 */ 2178 static void btf_dedup_merge_hypot_map(struct btf_dedup *d) 2179 { 2180 __u32 cand_type_id, targ_type_id; 2181 __u16 t_kind, c_kind; 2182 __u32 t_id, c_id; 2183 int i; 2184 2185 for (i = 0; i < d->hypot_cnt; i++) { 2186 cand_type_id = d->hypot_list[i]; 2187 targ_type_id = d->hypot_map[cand_type_id]; 2188 t_id = resolve_type_id(d, targ_type_id); 2189 c_id = resolve_type_id(d, cand_type_id); 2190 t_kind = BTF_INFO_KIND(d->btf->types[t_id]->info); 2191 c_kind = BTF_INFO_KIND(d->btf->types[c_id]->info); 2192 /* 2193 * Resolve FWD into STRUCT/UNION. 2194 * It's ok to resolve FWD into STRUCT/UNION that's not yet 2195 * mapped to canonical representative (as opposed to 2196 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because 2197 * eventually that struct is going to be mapped and all resolved 2198 * FWDs will automatically resolve to correct canonical 2199 * representative. This will happen before ref type deduping, 2200 * which critically depends on stability of these mapping. This 2201 * stability is not a requirement for STRUCT/UNION equivalence 2202 * checks, though. 2203 */ 2204 if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD) 2205 d->map[c_id] = t_id; 2206 else if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD) 2207 d->map[t_id] = c_id; 2208 2209 if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) && 2210 c_kind != BTF_KIND_FWD && 2211 is_type_mapped(d, c_id) && 2212 !is_type_mapped(d, t_id)) { 2213 /* 2214 * as a perf optimization, we can map struct/union 2215 * that's part of type graph we just verified for 2216 * equivalence. We can do that for struct/union that has 2217 * canonical representative only, though. 2218 */ 2219 d->map[t_id] = c_id; 2220 } 2221 } 2222 } 2223 2224 /* 2225 * Deduplicate struct/union types. 2226 * 2227 * For each struct/union type its type signature hash is calculated, taking 2228 * into account type's name, size, number, order and names of fields, but 2229 * ignoring type ID's referenced from fields, because they might not be deduped 2230 * completely until after reference types deduplication phase. This type hash 2231 * is used to iterate over all potential canonical types, sharing same hash. 2232 * For each canonical candidate we check whether type graphs that they form 2233 * (through referenced types in fields and so on) are equivalent using algorithm 2234 * implemented in `btf_dedup_is_equiv`. If such equivalence is found and 2235 * BTF_KIND_FWD resolution is allowed, then hypothetical mapping 2236 * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence 2237 * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to 2238 * potentially map other structs/unions to their canonical representatives, 2239 * if such relationship hasn't yet been established. This speeds up algorithm 2240 * by eliminating some of the duplicate work. 2241 * 2242 * If no matching canonical representative was found, struct/union is marked 2243 * as canonical for itself and is added into btf_dedup->dedup_table hash map 2244 * for further look ups. 2245 */ 2246 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id) 2247 { 2248 struct btf_dedup_node *cand_node; 2249 struct btf_type *t; 2250 /* if we don't find equivalent type, then we are canonical */ 2251 __u32 new_id = type_id; 2252 __u16 kind; 2253 __u32 h; 2254 2255 /* already deduped or is in process of deduping (loop detected) */ 2256 if (d->map[type_id] <= BTF_MAX_NR_TYPES) 2257 return 0; 2258 2259 t = d->btf->types[type_id]; 2260 kind = BTF_INFO_KIND(t->info); 2261 2262 if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION) 2263 return 0; 2264 2265 h = btf_hash_struct(t); 2266 for_each_hash_node(d->dedup_table, h, cand_node) { 2267 int eq; 2268 2269 btf_dedup_clear_hypot_map(d); 2270 eq = btf_dedup_is_equiv(d, type_id, cand_node->type_id); 2271 if (eq < 0) 2272 return eq; 2273 if (!eq) 2274 continue; 2275 new_id = cand_node->type_id; 2276 btf_dedup_merge_hypot_map(d); 2277 break; 2278 } 2279 2280 d->map[type_id] = new_id; 2281 if (type_id == new_id && btf_dedup_table_add(d, h, type_id)) 2282 return -ENOMEM; 2283 2284 return 0; 2285 } 2286 2287 static int btf_dedup_struct_types(struct btf_dedup *d) 2288 { 2289 int i, err; 2290 2291 for (i = 1; i <= d->btf->nr_types; i++) { 2292 err = btf_dedup_struct_type(d, i); 2293 if (err) 2294 return err; 2295 } 2296 return 0; 2297 } 2298 2299 /* 2300 * Deduplicate reference type. 2301 * 2302 * Once all primitive and struct/union types got deduplicated, we can easily 2303 * deduplicate all other (reference) BTF types. This is done in two steps: 2304 * 2305 * 1. Resolve all referenced type IDs into their canonical type IDs. This 2306 * resolution can be done either immediately for primitive or struct/union types 2307 * (because they were deduped in previous two phases) or recursively for 2308 * reference types. Recursion will always terminate at either primitive or 2309 * struct/union type, at which point we can "unwind" chain of reference types 2310 * one by one. There is no danger of encountering cycles because in C type 2311 * system the only way to form type cycle is through struct/union, so any chain 2312 * of reference types, even those taking part in a type cycle, will inevitably 2313 * reach struct/union at some point. 2314 * 2315 * 2. Once all referenced type IDs are resolved into canonical ones, BTF type 2316 * becomes "stable", in the sense that no further deduplication will cause 2317 * any changes to it. With that, it's now possible to calculate type's signature 2318 * hash (this time taking into account referenced type IDs) and loop over all 2319 * potential canonical representatives. If no match was found, current type 2320 * will become canonical representative of itself and will be added into 2321 * btf_dedup->dedup_table as another possible canonical representative. 2322 */ 2323 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id) 2324 { 2325 struct btf_dedup_node *cand_node; 2326 struct btf_type *t, *cand; 2327 /* if we don't find equivalent type, then we are representative type */ 2328 __u32 new_id = type_id; 2329 __u32 h, ref_type_id; 2330 2331 if (d->map[type_id] == BTF_IN_PROGRESS_ID) 2332 return -ELOOP; 2333 if (d->map[type_id] <= BTF_MAX_NR_TYPES) 2334 return resolve_type_id(d, type_id); 2335 2336 t = d->btf->types[type_id]; 2337 d->map[type_id] = BTF_IN_PROGRESS_ID; 2338 2339 switch (BTF_INFO_KIND(t->info)) { 2340 case BTF_KIND_CONST: 2341 case BTF_KIND_VOLATILE: 2342 case BTF_KIND_RESTRICT: 2343 case BTF_KIND_PTR: 2344 case BTF_KIND_TYPEDEF: 2345 case BTF_KIND_FUNC: 2346 ref_type_id = btf_dedup_ref_type(d, t->type); 2347 if (ref_type_id < 0) 2348 return ref_type_id; 2349 t->type = ref_type_id; 2350 2351 h = btf_hash_common(t); 2352 for_each_hash_node(d->dedup_table, h, cand_node) { 2353 cand = d->btf->types[cand_node->type_id]; 2354 if (btf_equal_common(t, cand)) { 2355 new_id = cand_node->type_id; 2356 break; 2357 } 2358 } 2359 break; 2360 2361 case BTF_KIND_ARRAY: { 2362 struct btf_array *info = (struct btf_array *)(t + 1); 2363 2364 ref_type_id = btf_dedup_ref_type(d, info->type); 2365 if (ref_type_id < 0) 2366 return ref_type_id; 2367 info->type = ref_type_id; 2368 2369 ref_type_id = btf_dedup_ref_type(d, info->index_type); 2370 if (ref_type_id < 0) 2371 return ref_type_id; 2372 info->index_type = ref_type_id; 2373 2374 h = btf_hash_array(t); 2375 for_each_hash_node(d->dedup_table, h, cand_node) { 2376 cand = d->btf->types[cand_node->type_id]; 2377 if (btf_equal_array(t, cand)) { 2378 new_id = cand_node->type_id; 2379 break; 2380 } 2381 } 2382 break; 2383 } 2384 2385 case BTF_KIND_FUNC_PROTO: { 2386 struct btf_param *param; 2387 __u16 vlen; 2388 int i; 2389 2390 ref_type_id = btf_dedup_ref_type(d, t->type); 2391 if (ref_type_id < 0) 2392 return ref_type_id; 2393 t->type = ref_type_id; 2394 2395 vlen = BTF_INFO_VLEN(t->info); 2396 param = (struct btf_param *)(t + 1); 2397 for (i = 0; i < vlen; i++) { 2398 ref_type_id = btf_dedup_ref_type(d, param->type); 2399 if (ref_type_id < 0) 2400 return ref_type_id; 2401 param->type = ref_type_id; 2402 param++; 2403 } 2404 2405 h = btf_hash_fnproto(t); 2406 for_each_hash_node(d->dedup_table, h, cand_node) { 2407 cand = d->btf->types[cand_node->type_id]; 2408 if (btf_equal_fnproto(t, cand)) { 2409 new_id = cand_node->type_id; 2410 break; 2411 } 2412 } 2413 break; 2414 } 2415 2416 default: 2417 return -EINVAL; 2418 } 2419 2420 d->map[type_id] = new_id; 2421 if (type_id == new_id && btf_dedup_table_add(d, h, type_id)) 2422 return -ENOMEM; 2423 2424 return new_id; 2425 } 2426 2427 static int btf_dedup_ref_types(struct btf_dedup *d) 2428 { 2429 int i, err; 2430 2431 for (i = 1; i <= d->btf->nr_types; i++) { 2432 err = btf_dedup_ref_type(d, i); 2433 if (err < 0) 2434 return err; 2435 } 2436 btf_dedup_table_free(d); 2437 return 0; 2438 } 2439 2440 /* 2441 * Compact types. 2442 * 2443 * After we established for each type its corresponding canonical representative 2444 * type, we now can eliminate types that are not canonical and leave only 2445 * canonical ones layed out sequentially in memory by copying them over 2446 * duplicates. During compaction btf_dedup->hypot_map array is reused to store 2447 * a map from original type ID to a new compacted type ID, which will be used 2448 * during next phase to "fix up" type IDs, referenced from struct/union and 2449 * reference types. 2450 */ 2451 static int btf_dedup_compact_types(struct btf_dedup *d) 2452 { 2453 struct btf_type **new_types; 2454 __u32 next_type_id = 1; 2455 char *types_start, *p; 2456 int i, len; 2457 2458 /* we are going to reuse hypot_map to store compaction remapping */ 2459 d->hypot_map[0] = 0; 2460 for (i = 1; i <= d->btf->nr_types; i++) 2461 d->hypot_map[i] = BTF_UNPROCESSED_ID; 2462 2463 types_start = d->btf->nohdr_data + d->btf->hdr->type_off; 2464 p = types_start; 2465 2466 for (i = 1; i <= d->btf->nr_types; i++) { 2467 if (d->map[i] != i) 2468 continue; 2469 2470 len = btf_type_size(d->btf->types[i]); 2471 if (len < 0) 2472 return len; 2473 2474 memmove(p, d->btf->types[i], len); 2475 d->hypot_map[i] = next_type_id; 2476 d->btf->types[next_type_id] = (struct btf_type *)p; 2477 p += len; 2478 next_type_id++; 2479 } 2480 2481 /* shrink struct btf's internal types index and update btf_header */ 2482 d->btf->nr_types = next_type_id - 1; 2483 d->btf->types_size = d->btf->nr_types; 2484 d->btf->hdr->type_len = p - types_start; 2485 new_types = realloc(d->btf->types, 2486 (1 + d->btf->nr_types) * sizeof(struct btf_type *)); 2487 if (!new_types) 2488 return -ENOMEM; 2489 d->btf->types = new_types; 2490 2491 /* make sure string section follows type information without gaps */ 2492 d->btf->hdr->str_off = p - (char *)d->btf->nohdr_data; 2493 memmove(p, d->btf->strings, d->btf->hdr->str_len); 2494 d->btf->strings = p; 2495 p += d->btf->hdr->str_len; 2496 2497 d->btf->data_size = p - (char *)d->btf->data; 2498 return 0; 2499 } 2500 2501 /* 2502 * Figure out final (deduplicated and compacted) type ID for provided original 2503 * `type_id` by first resolving it into corresponding canonical type ID and 2504 * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map, 2505 * which is populated during compaction phase. 2506 */ 2507 static int btf_dedup_remap_type_id(struct btf_dedup *d, __u32 type_id) 2508 { 2509 __u32 resolved_type_id, new_type_id; 2510 2511 resolved_type_id = resolve_type_id(d, type_id); 2512 new_type_id = d->hypot_map[resolved_type_id]; 2513 if (new_type_id > BTF_MAX_NR_TYPES) 2514 return -EINVAL; 2515 return new_type_id; 2516 } 2517 2518 /* 2519 * Remap referenced type IDs into deduped type IDs. 2520 * 2521 * After BTF types are deduplicated and compacted, their final type IDs may 2522 * differ from original ones. The map from original to a corresponding 2523 * deduped type ID is stored in btf_dedup->hypot_map and is populated during 2524 * compaction phase. During remapping phase we are rewriting all type IDs 2525 * referenced from any BTF type (e.g., struct fields, func proto args, etc) to 2526 * their final deduped type IDs. 2527 */ 2528 static int btf_dedup_remap_type(struct btf_dedup *d, __u32 type_id) 2529 { 2530 struct btf_type *t = d->btf->types[type_id]; 2531 int i, r; 2532 2533 switch (BTF_INFO_KIND(t->info)) { 2534 case BTF_KIND_INT: 2535 case BTF_KIND_ENUM: 2536 break; 2537 2538 case BTF_KIND_FWD: 2539 case BTF_KIND_CONST: 2540 case BTF_KIND_VOLATILE: 2541 case BTF_KIND_RESTRICT: 2542 case BTF_KIND_PTR: 2543 case BTF_KIND_TYPEDEF: 2544 case BTF_KIND_FUNC: 2545 r = btf_dedup_remap_type_id(d, t->type); 2546 if (r < 0) 2547 return r; 2548 t->type = r; 2549 break; 2550 2551 case BTF_KIND_ARRAY: { 2552 struct btf_array *arr_info = (struct btf_array *)(t + 1); 2553 2554 r = btf_dedup_remap_type_id(d, arr_info->type); 2555 if (r < 0) 2556 return r; 2557 arr_info->type = r; 2558 r = btf_dedup_remap_type_id(d, arr_info->index_type); 2559 if (r < 0) 2560 return r; 2561 arr_info->index_type = r; 2562 break; 2563 } 2564 2565 case BTF_KIND_STRUCT: 2566 case BTF_KIND_UNION: { 2567 struct btf_member *member = (struct btf_member *)(t + 1); 2568 __u16 vlen = BTF_INFO_VLEN(t->info); 2569 2570 for (i = 0; i < vlen; i++) { 2571 r = btf_dedup_remap_type_id(d, member->type); 2572 if (r < 0) 2573 return r; 2574 member->type = r; 2575 member++; 2576 } 2577 break; 2578 } 2579 2580 case BTF_KIND_FUNC_PROTO: { 2581 struct btf_param *param = (struct btf_param *)(t + 1); 2582 __u16 vlen = BTF_INFO_VLEN(t->info); 2583 2584 r = btf_dedup_remap_type_id(d, t->type); 2585 if (r < 0) 2586 return r; 2587 t->type = r; 2588 2589 for (i = 0; i < vlen; i++) { 2590 r = btf_dedup_remap_type_id(d, param->type); 2591 if (r < 0) 2592 return r; 2593 param->type = r; 2594 param++; 2595 } 2596 break; 2597 } 2598 2599 default: 2600 return -EINVAL; 2601 } 2602 2603 return 0; 2604 } 2605 2606 static int btf_dedup_remap_types(struct btf_dedup *d) 2607 { 2608 int i, r; 2609 2610 for (i = 1; i <= d->btf->nr_types; i++) { 2611 r = btf_dedup_remap_type(d, i); 2612 if (r < 0) 2613 return r; 2614 } 2615 return 0; 2616 } 2617