Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
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
27static struct btf_type btf_void;
28
29struct 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
43struct 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
53struct 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
63struct 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 */
71struct bpf_func_info_min {
72 __u32 insn_off;
73 __u32 type_id;
74};
75
76/* The minimum bpf_line_info checked by the loader */
77struct bpf_line_info_min {
78 __u32 insn_off;
79 __u32 file_name_off;
80 __u32 line_off;
81 __u32 line_col;
82};
83
84static inline __u64 ptr_to_u64(const void *ptr)
85{
86 return (__u64) (unsigned long) ptr;
87}
88
89static 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
117static 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
173static 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
190static 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
221static 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
250const 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
258static 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
263static 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
314done:
315 if (nelems && size > UINT32_MAX / nelems)
316 return -E2BIG;
317
318 return nelems * size;
319}
320
321int 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
359void 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
372struct 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
402done:
403 if (err) {
404 btf__free(btf);
405 return ERR_PTR(err);
406 }
407
408 return btf;
409}
410
411int 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
436done:
437 free(log_buf);
438 return err;
439}
440
441int btf__fd(const struct btf *btf)
442{
443 return btf->fd;
444}
445
446const void *btf__get_raw_data(const struct btf *btf, __u32 *size)
447{
448 *size = btf->data_size;
449 return btf->data;
450}
451
452const 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
460int 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
517exit_free:
518 close(btf_fd);
519 free(ptr);
520
521 return err;
522}
523
524int 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
596struct 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
604static 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
690static 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
703static 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
716static 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
749void 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
757struct 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
786done:
787 if (err) {
788 btf_ext__free(btf_ext);
789 return ERR_PTR(err);
790 }
791
792 return btf_ext;
793}
794
795const 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
801static 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
849int 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
858int 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
877struct btf_dedup;
878
879static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
880 const struct btf_dedup_opts *opts);
881static void btf_dedup_free(struct btf_dedup *d);
882static int btf_dedup_strings(struct btf_dedup *d);
883static int btf_dedup_prim_types(struct btf_dedup *d);
884static int btf_dedup_struct_types(struct btf_dedup *d);
885static int btf_dedup_ref_types(struct btf_dedup *d);
886static int btf_dedup_compact_types(struct btf_dedup *d);
887static 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 */
1026int 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
1068done:
1069 btf_dedup_free(d);
1070 return err;
1071}
1072
1073#define BTF_DEDUP_TABLE_DEFAULT_SIZE (1 << 14)
1074#define BTF_DEDUP_TABLE_MAX_SIZE_LOG 31
1075#define BTF_UNPROCESSED_ID ((__u32)-1)
1076#define BTF_IN_PROGRESS_ID ((__u32)-2)
1077
1078struct btf_dedup_node {
1079 struct btf_dedup_node *next;
1080 __u32 type_id;
1081};
1082
1083struct 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
1110struct btf_str_ptr {
1111 const char *str;
1112 __u32 new_off;
1113 bool used;
1114};
1115
1116struct btf_str_ptrs {
1117 struct btf_str_ptr *ptrs;
1118 const char *data;
1119 __u32 cnt;
1120 __u32 cap;
1121};
1122
1123static 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_dedup_cand(d, hash, node) \
1132 for (node = d->dedup_table[hash & (d->opts.dedup_table_size - 1)]; \
1133 node; \
1134 node = node->next)
1135
1136static int btf_dedup_table_add(struct btf_dedup *d, __u32 hash, __u32 type_id)
1137{
1138 struct btf_dedup_node *node = malloc(sizeof(struct btf_dedup_node));
1139 int bucket = hash & (d->opts.dedup_table_size - 1);
1140
1141 if (!node)
1142 return -ENOMEM;
1143 node->type_id = type_id;
1144 node->next = d->dedup_table[bucket];
1145 d->dedup_table[bucket] = node;
1146 return 0;
1147}
1148
1149static int btf_dedup_hypot_map_add(struct btf_dedup *d,
1150 __u32 from_id, __u32 to_id)
1151{
1152 if (d->hypot_cnt == d->hypot_cap) {
1153 __u32 *new_list;
1154
1155 d->hypot_cap += max(16, d->hypot_cap / 2);
1156 new_list = realloc(d->hypot_list, sizeof(__u32) * d->hypot_cap);
1157 if (!new_list)
1158 return -ENOMEM;
1159 d->hypot_list = new_list;
1160 }
1161 d->hypot_list[d->hypot_cnt++] = from_id;
1162 d->hypot_map[from_id] = to_id;
1163 return 0;
1164}
1165
1166static void btf_dedup_clear_hypot_map(struct btf_dedup *d)
1167{
1168 int i;
1169
1170 for (i = 0; i < d->hypot_cnt; i++)
1171 d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID;
1172 d->hypot_cnt = 0;
1173}
1174
1175static void btf_dedup_table_free(struct btf_dedup *d)
1176{
1177 struct btf_dedup_node *head, *tmp;
1178 int i;
1179
1180 if (!d->dedup_table)
1181 return;
1182
1183 for (i = 0; i < d->opts.dedup_table_size; i++) {
1184 while (d->dedup_table[i]) {
1185 tmp = d->dedup_table[i];
1186 d->dedup_table[i] = tmp->next;
1187 free(tmp);
1188 }
1189
1190 head = d->dedup_table[i];
1191 while (head) {
1192 tmp = head;
1193 head = head->next;
1194 free(tmp);
1195 }
1196 }
1197
1198 free(d->dedup_table);
1199 d->dedup_table = NULL;
1200}
1201
1202static void btf_dedup_free(struct btf_dedup *d)
1203{
1204 btf_dedup_table_free(d);
1205
1206 free(d->map);
1207 d->map = NULL;
1208
1209 free(d->hypot_map);
1210 d->hypot_map = NULL;
1211
1212 free(d->hypot_list);
1213 d->hypot_list = NULL;
1214
1215 free(d);
1216}
1217
1218/* Find closest power of two >= to size, capped at 2^max_size_log */
1219static __u32 roundup_pow2_max(__u32 size, int max_size_log)
1220{
1221 int i;
1222
1223 for (i = 0; i < max_size_log && (1U << i) < size; i++)
1224 ;
1225 return 1U << i;
1226}
1227
1228
1229static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
1230 const struct btf_dedup_opts *opts)
1231{
1232 struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup));
1233 int i, err = 0;
1234 __u32 sz;
1235
1236 if (!d)
1237 return ERR_PTR(-ENOMEM);
1238
1239 d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds;
1240 sz = opts && opts->dedup_table_size ? opts->dedup_table_size
1241 : BTF_DEDUP_TABLE_DEFAULT_SIZE;
1242 sz = roundup_pow2_max(sz, BTF_DEDUP_TABLE_MAX_SIZE_LOG);
1243 d->opts.dedup_table_size = sz;
1244
1245 d->btf = btf;
1246 d->btf_ext = btf_ext;
1247
1248 d->dedup_table = calloc(d->opts.dedup_table_size,
1249 sizeof(struct btf_dedup_node *));
1250 if (!d->dedup_table) {
1251 err = -ENOMEM;
1252 goto done;
1253 }
1254
1255 d->map = malloc(sizeof(__u32) * (1 + btf->nr_types));
1256 if (!d->map) {
1257 err = -ENOMEM;
1258 goto done;
1259 }
1260 /* special BTF "void" type is made canonical immediately */
1261 d->map[0] = 0;
1262 for (i = 1; i <= btf->nr_types; i++)
1263 d->map[i] = BTF_UNPROCESSED_ID;
1264
1265 d->hypot_map = malloc(sizeof(__u32) * (1 + btf->nr_types));
1266 if (!d->hypot_map) {
1267 err = -ENOMEM;
1268 goto done;
1269 }
1270 for (i = 0; i <= btf->nr_types; i++)
1271 d->hypot_map[i] = BTF_UNPROCESSED_ID;
1272
1273done:
1274 if (err) {
1275 btf_dedup_free(d);
1276 return ERR_PTR(err);
1277 }
1278
1279 return d;
1280}
1281
1282typedef int (*str_off_fn_t)(__u32 *str_off_ptr, void *ctx);
1283
1284/*
1285 * Iterate over all possible places in .BTF and .BTF.ext that can reference
1286 * string and pass pointer to it to a provided callback `fn`.
1287 */
1288static int btf_for_each_str_off(struct btf_dedup *d, str_off_fn_t fn, void *ctx)
1289{
1290 void *line_data_cur, *line_data_end;
1291 int i, j, r, rec_size;
1292 struct btf_type *t;
1293
1294 for (i = 1; i <= d->btf->nr_types; i++) {
1295 t = d->btf->types[i];
1296 r = fn(&t->name_off, ctx);
1297 if (r)
1298 return r;
1299
1300 switch (BTF_INFO_KIND(t->info)) {
1301 case BTF_KIND_STRUCT:
1302 case BTF_KIND_UNION: {
1303 struct btf_member *m = (struct btf_member *)(t + 1);
1304 __u16 vlen = BTF_INFO_VLEN(t->info);
1305
1306 for (j = 0; j < vlen; j++) {
1307 r = fn(&m->name_off, ctx);
1308 if (r)
1309 return r;
1310 m++;
1311 }
1312 break;
1313 }
1314 case BTF_KIND_ENUM: {
1315 struct btf_enum *m = (struct btf_enum *)(t + 1);
1316 __u16 vlen = BTF_INFO_VLEN(t->info);
1317
1318 for (j = 0; j < vlen; j++) {
1319 r = fn(&m->name_off, ctx);
1320 if (r)
1321 return r;
1322 m++;
1323 }
1324 break;
1325 }
1326 case BTF_KIND_FUNC_PROTO: {
1327 struct btf_param *m = (struct btf_param *)(t + 1);
1328 __u16 vlen = BTF_INFO_VLEN(t->info);
1329
1330 for (j = 0; j < vlen; j++) {
1331 r = fn(&m->name_off, ctx);
1332 if (r)
1333 return r;
1334 m++;
1335 }
1336 break;
1337 }
1338 default:
1339 break;
1340 }
1341 }
1342
1343 if (!d->btf_ext)
1344 return 0;
1345
1346 line_data_cur = d->btf_ext->line_info.info;
1347 line_data_end = d->btf_ext->line_info.info + d->btf_ext->line_info.len;
1348 rec_size = d->btf_ext->line_info.rec_size;
1349
1350 while (line_data_cur < line_data_end) {
1351 struct btf_ext_info_sec *sec = line_data_cur;
1352 struct bpf_line_info_min *line_info;
1353 __u32 num_info = sec->num_info;
1354
1355 r = fn(&sec->sec_name_off, ctx);
1356 if (r)
1357 return r;
1358
1359 line_data_cur += sizeof(struct btf_ext_info_sec);
1360 for (i = 0; i < num_info; i++) {
1361 line_info = line_data_cur;
1362 r = fn(&line_info->file_name_off, ctx);
1363 if (r)
1364 return r;
1365 r = fn(&line_info->line_off, ctx);
1366 if (r)
1367 return r;
1368 line_data_cur += rec_size;
1369 }
1370 }
1371
1372 return 0;
1373}
1374
1375static int str_sort_by_content(const void *a1, const void *a2)
1376{
1377 const struct btf_str_ptr *p1 = a1;
1378 const struct btf_str_ptr *p2 = a2;
1379
1380 return strcmp(p1->str, p2->str);
1381}
1382
1383static int str_sort_by_offset(const void *a1, const void *a2)
1384{
1385 const struct btf_str_ptr *p1 = a1;
1386 const struct btf_str_ptr *p2 = a2;
1387
1388 if (p1->str != p2->str)
1389 return p1->str < p2->str ? -1 : 1;
1390 return 0;
1391}
1392
1393static int btf_dedup_str_ptr_cmp(const void *str_ptr, const void *pelem)
1394{
1395 const struct btf_str_ptr *p = pelem;
1396
1397 if (str_ptr != p->str)
1398 return (const char *)str_ptr < p->str ? -1 : 1;
1399 return 0;
1400}
1401
1402static int btf_str_mark_as_used(__u32 *str_off_ptr, void *ctx)
1403{
1404 struct btf_str_ptrs *strs;
1405 struct btf_str_ptr *s;
1406
1407 if (*str_off_ptr == 0)
1408 return 0;
1409
1410 strs = ctx;
1411 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt,
1412 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp);
1413 if (!s)
1414 return -EINVAL;
1415 s->used = true;
1416 return 0;
1417}
1418
1419static int btf_str_remap_offset(__u32 *str_off_ptr, void *ctx)
1420{
1421 struct btf_str_ptrs *strs;
1422 struct btf_str_ptr *s;
1423
1424 if (*str_off_ptr == 0)
1425 return 0;
1426
1427 strs = ctx;
1428 s = bsearch(strs->data + *str_off_ptr, strs->ptrs, strs->cnt,
1429 sizeof(struct btf_str_ptr), btf_dedup_str_ptr_cmp);
1430 if (!s)
1431 return -EINVAL;
1432 *str_off_ptr = s->new_off;
1433 return 0;
1434}
1435
1436/*
1437 * Dedup string and filter out those that are not referenced from either .BTF
1438 * or .BTF.ext (if provided) sections.
1439 *
1440 * This is done by building index of all strings in BTF's string section,
1441 * then iterating over all entities that can reference strings (e.g., type
1442 * names, struct field names, .BTF.ext line info, etc) and marking corresponding
1443 * strings as used. After that all used strings are deduped and compacted into
1444 * sequential blob of memory and new offsets are calculated. Then all the string
1445 * references are iterated again and rewritten using new offsets.
1446 */
1447static int btf_dedup_strings(struct btf_dedup *d)
1448{
1449 const struct btf_header *hdr = d->btf->hdr;
1450 char *start = (char *)d->btf->nohdr_data + hdr->str_off;
1451 char *end = start + d->btf->hdr->str_len;
1452 char *p = start, *tmp_strs = NULL;
1453 struct btf_str_ptrs strs = {
1454 .cnt = 0,
1455 .cap = 0,
1456 .ptrs = NULL,
1457 .data = start,
1458 };
1459 int i, j, err = 0, grp_idx;
1460 bool grp_used;
1461
1462 /* build index of all strings */
1463 while (p < end) {
1464 if (strs.cnt + 1 > strs.cap) {
1465 struct btf_str_ptr *new_ptrs;
1466
1467 strs.cap += max(strs.cnt / 2, 16);
1468 new_ptrs = realloc(strs.ptrs,
1469 sizeof(strs.ptrs[0]) * strs.cap);
1470 if (!new_ptrs) {
1471 err = -ENOMEM;
1472 goto done;
1473 }
1474 strs.ptrs = new_ptrs;
1475 }
1476
1477 strs.ptrs[strs.cnt].str = p;
1478 strs.ptrs[strs.cnt].used = false;
1479
1480 p += strlen(p) + 1;
1481 strs.cnt++;
1482 }
1483
1484 /* temporary storage for deduplicated strings */
1485 tmp_strs = malloc(d->btf->hdr->str_len);
1486 if (!tmp_strs) {
1487 err = -ENOMEM;
1488 goto done;
1489 }
1490
1491 /* mark all used strings */
1492 strs.ptrs[0].used = true;
1493 err = btf_for_each_str_off(d, btf_str_mark_as_used, &strs);
1494 if (err)
1495 goto done;
1496
1497 /* sort strings by context, so that we can identify duplicates */
1498 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_content);
1499
1500 /*
1501 * iterate groups of equal strings and if any instance in a group was
1502 * referenced, emit single instance and remember new offset
1503 */
1504 p = tmp_strs;
1505 grp_idx = 0;
1506 grp_used = strs.ptrs[0].used;
1507 /* iterate past end to avoid code duplication after loop */
1508 for (i = 1; i <= strs.cnt; i++) {
1509 /*
1510 * when i == strs.cnt, we want to skip string comparison and go
1511 * straight to handling last group of strings (otherwise we'd
1512 * need to handle last group after the loop w/ duplicated code)
1513 */
1514 if (i < strs.cnt &&
1515 !strcmp(strs.ptrs[i].str, strs.ptrs[grp_idx].str)) {
1516 grp_used = grp_used || strs.ptrs[i].used;
1517 continue;
1518 }
1519
1520 /*
1521 * this check would have been required after the loop to handle
1522 * last group of strings, but due to <= condition in a loop
1523 * we avoid that duplication
1524 */
1525 if (grp_used) {
1526 int new_off = p - tmp_strs;
1527 __u32 len = strlen(strs.ptrs[grp_idx].str);
1528
1529 memmove(p, strs.ptrs[grp_idx].str, len + 1);
1530 for (j = grp_idx; j < i; j++)
1531 strs.ptrs[j].new_off = new_off;
1532 p += len + 1;
1533 }
1534
1535 if (i < strs.cnt) {
1536 grp_idx = i;
1537 grp_used = strs.ptrs[i].used;
1538 }
1539 }
1540
1541 /* replace original strings with deduped ones */
1542 d->btf->hdr->str_len = p - tmp_strs;
1543 memmove(start, tmp_strs, d->btf->hdr->str_len);
1544 end = start + d->btf->hdr->str_len;
1545
1546 /* restore original order for further binary search lookups */
1547 qsort(strs.ptrs, strs.cnt, sizeof(strs.ptrs[0]), str_sort_by_offset);
1548
1549 /* remap string offsets */
1550 err = btf_for_each_str_off(d, btf_str_remap_offset, &strs);
1551 if (err)
1552 goto done;
1553
1554 d->btf->hdr->str_len = end - start;
1555
1556done:
1557 free(tmp_strs);
1558 free(strs.ptrs);
1559 return err;
1560}
1561
1562static __u32 btf_hash_common(struct btf_type *t)
1563{
1564 __u32 h;
1565
1566 h = hash_combine(0, t->name_off);
1567 h = hash_combine(h, t->info);
1568 h = hash_combine(h, t->size);
1569 return h;
1570}
1571
1572static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2)
1573{
1574 return t1->name_off == t2->name_off &&
1575 t1->info == t2->info &&
1576 t1->size == t2->size;
1577}
1578
1579/* Calculate type signature hash of INT. */
1580static __u32 btf_hash_int(struct btf_type *t)
1581{
1582 __u32 info = *(__u32 *)(t + 1);
1583 __u32 h;
1584
1585 h = btf_hash_common(t);
1586 h = hash_combine(h, info);
1587 return h;
1588}
1589
1590/* Check structural equality of two INTs. */
1591static bool btf_equal_int(struct btf_type *t1, struct btf_type *t2)
1592{
1593 __u32 info1, info2;
1594
1595 if (!btf_equal_common(t1, t2))
1596 return false;
1597 info1 = *(__u32 *)(t1 + 1);
1598 info2 = *(__u32 *)(t2 + 1);
1599 return info1 == info2;
1600}
1601
1602/* Calculate type signature hash of ENUM. */
1603static __u32 btf_hash_enum(struct btf_type *t)
1604{
1605 struct btf_enum *member = (struct btf_enum *)(t + 1);
1606 __u32 vlen = BTF_INFO_VLEN(t->info);
1607 __u32 h = btf_hash_common(t);
1608 int i;
1609
1610 for (i = 0; i < vlen; i++) {
1611 h = hash_combine(h, member->name_off);
1612 h = hash_combine(h, member->val);
1613 member++;
1614 }
1615 return h;
1616}
1617
1618/* Check structural equality of two ENUMs. */
1619static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2)
1620{
1621 struct btf_enum *m1, *m2;
1622 __u16 vlen;
1623 int i;
1624
1625 if (!btf_equal_common(t1, t2))
1626 return false;
1627
1628 vlen = BTF_INFO_VLEN(t1->info);
1629 m1 = (struct btf_enum *)(t1 + 1);
1630 m2 = (struct btf_enum *)(t2 + 1);
1631 for (i = 0; i < vlen; i++) {
1632 if (m1->name_off != m2->name_off || m1->val != m2->val)
1633 return false;
1634 m1++;
1635 m2++;
1636 }
1637 return true;
1638}
1639
1640/*
1641 * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs,
1642 * as referenced type IDs equivalence is established separately during type
1643 * graph equivalence check algorithm.
1644 */
1645static __u32 btf_hash_struct(struct btf_type *t)
1646{
1647 struct btf_member *member = (struct btf_member *)(t + 1);
1648 __u32 vlen = BTF_INFO_VLEN(t->info);
1649 __u32 h = btf_hash_common(t);
1650 int i;
1651
1652 for (i = 0; i < vlen; i++) {
1653 h = hash_combine(h, member->name_off);
1654 h = hash_combine(h, member->offset);
1655 /* no hashing of referenced type ID, it can be unresolved yet */
1656 member++;
1657 }
1658 return h;
1659}
1660
1661/*
1662 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
1663 * IDs. This check is performed during type graph equivalence check and
1664 * referenced types equivalence is checked separately.
1665 */
1666static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2)
1667{
1668 struct btf_member *m1, *m2;
1669 __u16 vlen;
1670 int i;
1671
1672 if (!btf_equal_common(t1, t2))
1673 return false;
1674
1675 vlen = BTF_INFO_VLEN(t1->info);
1676 m1 = (struct btf_member *)(t1 + 1);
1677 m2 = (struct btf_member *)(t2 + 1);
1678 for (i = 0; i < vlen; i++) {
1679 if (m1->name_off != m2->name_off || m1->offset != m2->offset)
1680 return false;
1681 m1++;
1682 m2++;
1683 }
1684 return true;
1685}
1686
1687/*
1688 * Calculate type signature hash of ARRAY, including referenced type IDs,
1689 * under assumption that they were already resolved to canonical type IDs and
1690 * are not going to change.
1691 */
1692static __u32 btf_hash_array(struct btf_type *t)
1693{
1694 struct btf_array *info = (struct btf_array *)(t + 1);
1695 __u32 h = btf_hash_common(t);
1696
1697 h = hash_combine(h, info->type);
1698 h = hash_combine(h, info->index_type);
1699 h = hash_combine(h, info->nelems);
1700 return h;
1701}
1702
1703/*
1704 * Check exact equality of two ARRAYs, taking into account referenced
1705 * type IDs, under assumption that they were already resolved to canonical
1706 * type IDs and are not going to change.
1707 * This function is called during reference types deduplication to compare
1708 * ARRAY to potential canonical representative.
1709 */
1710static bool btf_equal_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->type == info2->type &&
1720 info1->index_type == info2->index_type &&
1721 info1->nelems == info2->nelems;
1722}
1723
1724/*
1725 * Check structural compatibility of two ARRAYs, ignoring referenced type
1726 * IDs. This check is performed during type graph equivalence check and
1727 * referenced types equivalence is checked separately.
1728 */
1729static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2)
1730{
1731 struct btf_array *info1, *info2;
1732
1733 if (!btf_equal_common(t1, t2))
1734 return false;
1735
1736 info1 = (struct btf_array *)(t1 + 1);
1737 info2 = (struct btf_array *)(t2 + 1);
1738 return info1->nelems == info2->nelems;
1739}
1740
1741/*
1742 * Calculate type signature hash of FUNC_PROTO, including referenced type IDs,
1743 * under assumption that they were already resolved to canonical type IDs and
1744 * are not going to change.
1745 */
1746static inline __u32 btf_hash_fnproto(struct btf_type *t)
1747{
1748 struct btf_param *member = (struct btf_param *)(t + 1);
1749 __u16 vlen = BTF_INFO_VLEN(t->info);
1750 __u32 h = btf_hash_common(t);
1751 int i;
1752
1753 for (i = 0; i < vlen; i++) {
1754 h = hash_combine(h, member->name_off);
1755 h = hash_combine(h, member->type);
1756 member++;
1757 }
1758 return h;
1759}
1760
1761/*
1762 * Check exact equality of two FUNC_PROTOs, taking into account referenced
1763 * type IDs, under assumption that they were already resolved to canonical
1764 * type IDs and are not going to change.
1765 * This function is called during reference types deduplication to compare
1766 * FUNC_PROTO to potential canonical representative.
1767 */
1768static inline bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2)
1769{
1770 struct btf_param *m1, *m2;
1771 __u16 vlen;
1772 int i;
1773
1774 if (!btf_equal_common(t1, t2))
1775 return false;
1776
1777 vlen = BTF_INFO_VLEN(t1->info);
1778 m1 = (struct btf_param *)(t1 + 1);
1779 m2 = (struct btf_param *)(t2 + 1);
1780 for (i = 0; i < vlen; i++) {
1781 if (m1->name_off != m2->name_off || m1->type != m2->type)
1782 return false;
1783 m1++;
1784 m2++;
1785 }
1786 return true;
1787}
1788
1789/*
1790 * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
1791 * IDs. This check is performed during type graph equivalence check and
1792 * referenced types equivalence is checked separately.
1793 */
1794static inline bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2)
1795{
1796 struct btf_param *m1, *m2;
1797 __u16 vlen;
1798 int i;
1799
1800 /* skip return type ID */
1801 if (t1->name_off != t2->name_off || t1->info != t2->info)
1802 return false;
1803
1804 vlen = BTF_INFO_VLEN(t1->info);
1805 m1 = (struct btf_param *)(t1 + 1);
1806 m2 = (struct btf_param *)(t2 + 1);
1807 for (i = 0; i < vlen; i++) {
1808 if (m1->name_off != m2->name_off)
1809 return false;
1810 m1++;
1811 m2++;
1812 }
1813 return true;
1814}
1815
1816/*
1817 * Deduplicate primitive types, that can't reference other types, by calculating
1818 * their type signature hash and comparing them with any possible canonical
1819 * candidate. If no canonical candidate matches, type itself is marked as
1820 * canonical and is added into `btf_dedup->dedup_table` as another candidate.
1821 */
1822static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id)
1823{
1824 struct btf_type *t = d->btf->types[type_id];
1825 struct btf_type *cand;
1826 struct btf_dedup_node *cand_node;
1827 /* if we don't find equivalent type, then we are canonical */
1828 __u32 new_id = type_id;
1829 __u32 h;
1830
1831 switch (BTF_INFO_KIND(t->info)) {
1832 case BTF_KIND_CONST:
1833 case BTF_KIND_VOLATILE:
1834 case BTF_KIND_RESTRICT:
1835 case BTF_KIND_PTR:
1836 case BTF_KIND_TYPEDEF:
1837 case BTF_KIND_ARRAY:
1838 case BTF_KIND_STRUCT:
1839 case BTF_KIND_UNION:
1840 case BTF_KIND_FUNC:
1841 case BTF_KIND_FUNC_PROTO:
1842 return 0;
1843
1844 case BTF_KIND_INT:
1845 h = btf_hash_int(t);
1846 for_each_dedup_cand(d, h, cand_node) {
1847 cand = d->btf->types[cand_node->type_id];
1848 if (btf_equal_int(t, cand)) {
1849 new_id = cand_node->type_id;
1850 break;
1851 }
1852 }
1853 break;
1854
1855 case BTF_KIND_ENUM:
1856 h = btf_hash_enum(t);
1857 for_each_dedup_cand(d, h, cand_node) {
1858 cand = d->btf->types[cand_node->type_id];
1859 if (btf_equal_enum(t, cand)) {
1860 new_id = cand_node->type_id;
1861 break;
1862 }
1863 }
1864 break;
1865
1866 case BTF_KIND_FWD:
1867 h = btf_hash_common(t);
1868 for_each_dedup_cand(d, h, cand_node) {
1869 cand = d->btf->types[cand_node->type_id];
1870 if (btf_equal_common(t, cand)) {
1871 new_id = cand_node->type_id;
1872 break;
1873 }
1874 }
1875 break;
1876
1877 default:
1878 return -EINVAL;
1879 }
1880
1881 d->map[type_id] = new_id;
1882 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
1883 return -ENOMEM;
1884
1885 return 0;
1886}
1887
1888static int btf_dedup_prim_types(struct btf_dedup *d)
1889{
1890 int i, err;
1891
1892 for (i = 1; i <= d->btf->nr_types; i++) {
1893 err = btf_dedup_prim_type(d, i);
1894 if (err)
1895 return err;
1896 }
1897 return 0;
1898}
1899
1900/*
1901 * Check whether type is already mapped into canonical one (could be to itself).
1902 */
1903static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id)
1904{
1905 return d->map[type_id] <= BTF_MAX_NR_TYPES;
1906}
1907
1908/*
1909 * Resolve type ID into its canonical type ID, if any; otherwise return original
1910 * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow
1911 * STRUCT/UNION link and resolve it into canonical type ID as well.
1912 */
1913static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id)
1914{
1915 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
1916 type_id = d->map[type_id];
1917 return type_id;
1918}
1919
1920/*
1921 * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original
1922 * type ID.
1923 */
1924static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id)
1925{
1926 __u32 orig_type_id = type_id;
1927
1928 if (BTF_INFO_KIND(d->btf->types[type_id]->info) != BTF_KIND_FWD)
1929 return type_id;
1930
1931 while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
1932 type_id = d->map[type_id];
1933
1934 if (BTF_INFO_KIND(d->btf->types[type_id]->info) != BTF_KIND_FWD)
1935 return type_id;
1936
1937 return orig_type_id;
1938}
1939
1940
1941static inline __u16 btf_fwd_kind(struct btf_type *t)
1942{
1943 return BTF_INFO_KFLAG(t->info) ? BTF_KIND_UNION : BTF_KIND_STRUCT;
1944}
1945
1946/*
1947 * Check equivalence of BTF type graph formed by candidate struct/union (we'll
1948 * call it "candidate graph" in this description for brevity) to a type graph
1949 * formed by (potential) canonical struct/union ("canonical graph" for brevity
1950 * here, though keep in mind that not all types in canonical graph are
1951 * necessarily canonical representatives themselves, some of them might be
1952 * duplicates or its uniqueness might not have been established yet).
1953 * Returns:
1954 * - >0, if type graphs are equivalent;
1955 * - 0, if not equivalent;
1956 * - <0, on error.
1957 *
1958 * Algorithm performs side-by-side DFS traversal of both type graphs and checks
1959 * equivalence of BTF types at each step. If at any point BTF types in candidate
1960 * and canonical graphs are not compatible structurally, whole graphs are
1961 * incompatible. If types are structurally equivalent (i.e., all information
1962 * except referenced type IDs is exactly the same), a mapping from `canon_id` to
1963 * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`).
1964 * If a type references other types, then those referenced types are checked
1965 * for equivalence recursively.
1966 *
1967 * During DFS traversal, if we find that for current `canon_id` type we
1968 * already have some mapping in hypothetical map, we check for two possible
1969 * situations:
1970 * - `canon_id` is mapped to exactly the same type as `cand_id`. This will
1971 * happen when type graphs have cycles. In this case we assume those two
1972 * types are equivalent.
1973 * - `canon_id` is mapped to different type. This is contradiction in our
1974 * hypothetical mapping, because same graph in canonical graph corresponds
1975 * to two different types in candidate graph, which for equivalent type
1976 * graphs shouldn't happen. This condition terminates equivalence check
1977 * with negative result.
1978 *
1979 * If type graphs traversal exhausts types to check and find no contradiction,
1980 * then type graphs are equivalent.
1981 *
1982 * When checking types for equivalence, there is one special case: FWD types.
1983 * If FWD type resolution is allowed and one of the types (either from canonical
1984 * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind
1985 * flag) and their names match, hypothetical mapping is updated to point from
1986 * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully,
1987 * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently.
1988 *
1989 * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution,
1990 * if there are two exactly named (or anonymous) structs/unions that are
1991 * compatible structurally, one of which has FWD field, while other is concrete
1992 * STRUCT/UNION, but according to C sources they are different structs/unions
1993 * that are referencing different types with the same name. This is extremely
1994 * unlikely to happen, but btf_dedup API allows to disable FWD resolution if
1995 * this logic is causing problems.
1996 *
1997 * Doing FWD resolution means that both candidate and/or canonical graphs can
1998 * consists of portions of the graph that come from multiple compilation units.
1999 * This is due to the fact that types within single compilation unit are always
2000 * deduplicated and FWDs are already resolved, if referenced struct/union
2001 * definiton is available. So, if we had unresolved FWD and found corresponding
2002 * STRUCT/UNION, they will be from different compilation units. This
2003 * consequently means that when we "link" FWD to corresponding STRUCT/UNION,
2004 * type graph will likely have at least two different BTF types that describe
2005 * same type (e.g., most probably there will be two different BTF types for the
2006 * same 'int' primitive type) and could even have "overlapping" parts of type
2007 * graph that describe same subset of types.
2008 *
2009 * This in turn means that our assumption that each type in canonical graph
2010 * must correspond to exactly one type in candidate graph might not hold
2011 * anymore and will make it harder to detect contradictions using hypothetical
2012 * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION
2013 * resolution only in canonical graph. FWDs in candidate graphs are never
2014 * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs
2015 * that can occur:
2016 * - Both types in canonical and candidate graphs are FWDs. If they are
2017 * structurally equivalent, then they can either be both resolved to the
2018 * same STRUCT/UNION or not resolved at all. In both cases they are
2019 * equivalent and there is no need to resolve FWD on candidate side.
2020 * - Both types in canonical and candidate graphs are concrete STRUCT/UNION,
2021 * so nothing to resolve as well, algorithm will check equivalence anyway.
2022 * - Type in canonical graph is FWD, while type in candidate is concrete
2023 * STRUCT/UNION. In this case candidate graph comes from single compilation
2024 * unit, so there is exactly one BTF type for each unique C type. After
2025 * resolving FWD into STRUCT/UNION, there might be more than one BTF type
2026 * in canonical graph mapping to single BTF type in candidate graph, but
2027 * because hypothetical mapping maps from canonical to candidate types, it's
2028 * alright, and we still maintain the property of having single `canon_id`
2029 * mapping to single `cand_id` (there could be two different `canon_id`
2030 * mapped to the same `cand_id`, but it's not contradictory).
2031 * - Type in canonical graph is concrete STRUCT/UNION, while type in candidate
2032 * graph is FWD. In this case we are just going to check compatibility of
2033 * STRUCT/UNION and corresponding FWD, and if they are compatible, we'll
2034 * assume that whatever STRUCT/UNION FWD resolves to must be equivalent to
2035 * a concrete STRUCT/UNION from canonical graph. If the rest of type graphs
2036 * turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from
2037 * canonical graph.
2038 */
2039static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id,
2040 __u32 canon_id)
2041{
2042 struct btf_type *cand_type;
2043 struct btf_type *canon_type;
2044 __u32 hypot_type_id;
2045 __u16 cand_kind;
2046 __u16 canon_kind;
2047 int i, eq;
2048
2049 /* if both resolve to the same canonical, they must be equivalent */
2050 if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id))
2051 return 1;
2052
2053 canon_id = resolve_fwd_id(d, canon_id);
2054
2055 hypot_type_id = d->hypot_map[canon_id];
2056 if (hypot_type_id <= BTF_MAX_NR_TYPES)
2057 return hypot_type_id == cand_id;
2058
2059 if (btf_dedup_hypot_map_add(d, canon_id, cand_id))
2060 return -ENOMEM;
2061
2062 cand_type = d->btf->types[cand_id];
2063 canon_type = d->btf->types[canon_id];
2064 cand_kind = BTF_INFO_KIND(cand_type->info);
2065 canon_kind = BTF_INFO_KIND(canon_type->info);
2066
2067 if (cand_type->name_off != canon_type->name_off)
2068 return 0;
2069
2070 /* FWD <--> STRUCT/UNION equivalence check, if enabled */
2071 if (!d->opts.dont_resolve_fwds
2072 && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD)
2073 && cand_kind != canon_kind) {
2074 __u16 real_kind;
2075 __u16 fwd_kind;
2076
2077 if (cand_kind == BTF_KIND_FWD) {
2078 real_kind = canon_kind;
2079 fwd_kind = btf_fwd_kind(cand_type);
2080 } else {
2081 real_kind = cand_kind;
2082 fwd_kind = btf_fwd_kind(canon_type);
2083 }
2084 return fwd_kind == real_kind;
2085 }
2086
2087 if (cand_type->info != canon_type->info)
2088 return 0;
2089
2090 switch (cand_kind) {
2091 case BTF_KIND_INT:
2092 return btf_equal_int(cand_type, canon_type);
2093
2094 case BTF_KIND_ENUM:
2095 return btf_equal_enum(cand_type, canon_type);
2096
2097 case BTF_KIND_FWD:
2098 return btf_equal_common(cand_type, canon_type);
2099
2100 case BTF_KIND_CONST:
2101 case BTF_KIND_VOLATILE:
2102 case BTF_KIND_RESTRICT:
2103 case BTF_KIND_PTR:
2104 case BTF_KIND_TYPEDEF:
2105 case BTF_KIND_FUNC:
2106 return btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
2107
2108 case BTF_KIND_ARRAY: {
2109 struct btf_array *cand_arr, *canon_arr;
2110
2111 if (!btf_compat_array(cand_type, canon_type))
2112 return 0;
2113 cand_arr = (struct btf_array *)(cand_type + 1);
2114 canon_arr = (struct btf_array *)(canon_type + 1);
2115 eq = btf_dedup_is_equiv(d,
2116 cand_arr->index_type, canon_arr->index_type);
2117 if (eq <= 0)
2118 return eq;
2119 return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type);
2120 }
2121
2122 case BTF_KIND_STRUCT:
2123 case BTF_KIND_UNION: {
2124 struct btf_member *cand_m, *canon_m;
2125 __u16 vlen;
2126
2127 if (!btf_shallow_equal_struct(cand_type, canon_type))
2128 return 0;
2129 vlen = BTF_INFO_VLEN(cand_type->info);
2130 cand_m = (struct btf_member *)(cand_type + 1);
2131 canon_m = (struct btf_member *)(canon_type + 1);
2132 for (i = 0; i < vlen; i++) {
2133 eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type);
2134 if (eq <= 0)
2135 return eq;
2136 cand_m++;
2137 canon_m++;
2138 }
2139
2140 return 1;
2141 }
2142
2143 case BTF_KIND_FUNC_PROTO: {
2144 struct btf_param *cand_p, *canon_p;
2145 __u16 vlen;
2146
2147 if (!btf_compat_fnproto(cand_type, canon_type))
2148 return 0;
2149 eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
2150 if (eq <= 0)
2151 return eq;
2152 vlen = BTF_INFO_VLEN(cand_type->info);
2153 cand_p = (struct btf_param *)(cand_type + 1);
2154 canon_p = (struct btf_param *)(canon_type + 1);
2155 for (i = 0; i < vlen; i++) {
2156 eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type);
2157 if (eq <= 0)
2158 return eq;
2159 cand_p++;
2160 canon_p++;
2161 }
2162 return 1;
2163 }
2164
2165 default:
2166 return -EINVAL;
2167 }
2168 return 0;
2169}
2170
2171/*
2172 * Use hypothetical mapping, produced by successful type graph equivalence
2173 * check, to augment existing struct/union canonical mapping, where possible.
2174 *
2175 * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record
2176 * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional:
2177 * it doesn't matter if FWD type was part of canonical graph or candidate one,
2178 * we are recording the mapping anyway. As opposed to carefulness required
2179 * for struct/union correspondence mapping (described below), for FWD resolution
2180 * it's not important, as by the time that FWD type (reference type) will be
2181 * deduplicated all structs/unions will be deduped already anyway.
2182 *
2183 * Recording STRUCT/UNION mapping is purely a performance optimization and is
2184 * not required for correctness. It needs to be done carefully to ensure that
2185 * struct/union from candidate's type graph is not mapped into corresponding
2186 * struct/union from canonical type graph that itself hasn't been resolved into
2187 * canonical representative. The only guarantee we have is that canonical
2188 * struct/union was determined as canonical and that won't change. But any
2189 * types referenced through that struct/union fields could have been not yet
2190 * resolved, so in case like that it's too early to establish any kind of
2191 * correspondence between structs/unions.
2192 *
2193 * No canonical correspondence is derived for primitive types (they are already
2194 * deduplicated completely already anyway) or reference types (they rely on
2195 * stability of struct/union canonical relationship for equivalence checks).
2196 */
2197static void btf_dedup_merge_hypot_map(struct btf_dedup *d)
2198{
2199 __u32 cand_type_id, targ_type_id;
2200 __u16 t_kind, c_kind;
2201 __u32 t_id, c_id;
2202 int i;
2203
2204 for (i = 0; i < d->hypot_cnt; i++) {
2205 cand_type_id = d->hypot_list[i];
2206 targ_type_id = d->hypot_map[cand_type_id];
2207 t_id = resolve_type_id(d, targ_type_id);
2208 c_id = resolve_type_id(d, cand_type_id);
2209 t_kind = BTF_INFO_KIND(d->btf->types[t_id]->info);
2210 c_kind = BTF_INFO_KIND(d->btf->types[c_id]->info);
2211 /*
2212 * Resolve FWD into STRUCT/UNION.
2213 * It's ok to resolve FWD into STRUCT/UNION that's not yet
2214 * mapped to canonical representative (as opposed to
2215 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because
2216 * eventually that struct is going to be mapped and all resolved
2217 * FWDs will automatically resolve to correct canonical
2218 * representative. This will happen before ref type deduping,
2219 * which critically depends on stability of these mapping. This
2220 * stability is not a requirement for STRUCT/UNION equivalence
2221 * checks, though.
2222 */
2223 if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD)
2224 d->map[c_id] = t_id;
2225 else if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD)
2226 d->map[t_id] = c_id;
2227
2228 if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) &&
2229 c_kind != BTF_KIND_FWD &&
2230 is_type_mapped(d, c_id) &&
2231 !is_type_mapped(d, t_id)) {
2232 /*
2233 * as a perf optimization, we can map struct/union
2234 * that's part of type graph we just verified for
2235 * equivalence. We can do that for struct/union that has
2236 * canonical representative only, though.
2237 */
2238 d->map[t_id] = c_id;
2239 }
2240 }
2241}
2242
2243/*
2244 * Deduplicate struct/union types.
2245 *
2246 * For each struct/union type its type signature hash is calculated, taking
2247 * into account type's name, size, number, order and names of fields, but
2248 * ignoring type ID's referenced from fields, because they might not be deduped
2249 * completely until after reference types deduplication phase. This type hash
2250 * is used to iterate over all potential canonical types, sharing same hash.
2251 * For each canonical candidate we check whether type graphs that they form
2252 * (through referenced types in fields and so on) are equivalent using algorithm
2253 * implemented in `btf_dedup_is_equiv`. If such equivalence is found and
2254 * BTF_KIND_FWD resolution is allowed, then hypothetical mapping
2255 * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence
2256 * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to
2257 * potentially map other structs/unions to their canonical representatives,
2258 * if such relationship hasn't yet been established. This speeds up algorithm
2259 * by eliminating some of the duplicate work.
2260 *
2261 * If no matching canonical representative was found, struct/union is marked
2262 * as canonical for itself and is added into btf_dedup->dedup_table hash map
2263 * for further look ups.
2264 */
2265static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id)
2266{
2267 struct btf_dedup_node *cand_node;
2268 struct btf_type *cand_type, *t;
2269 /* if we don't find equivalent type, then we are canonical */
2270 __u32 new_id = type_id;
2271 __u16 kind;
2272 __u32 h;
2273
2274 /* already deduped or is in process of deduping (loop detected) */
2275 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
2276 return 0;
2277
2278 t = d->btf->types[type_id];
2279 kind = BTF_INFO_KIND(t->info);
2280
2281 if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION)
2282 return 0;
2283
2284 h = btf_hash_struct(t);
2285 for_each_dedup_cand(d, h, cand_node) {
2286 int eq;
2287
2288 /*
2289 * Even though btf_dedup_is_equiv() checks for
2290 * btf_shallow_equal_struct() internally when checking two
2291 * structs (unions) for equivalence, we need to guard here
2292 * from picking matching FWD type as a dedup candidate.
2293 * This can happen due to hash collision. In such case just
2294 * relying on btf_dedup_is_equiv() would lead to potentially
2295 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because
2296 * FWD and compatible STRUCT/UNION are considered equivalent.
2297 */
2298 cand_type = d->btf->types[cand_node->type_id];
2299 if (!btf_shallow_equal_struct(t, cand_type))
2300 continue;
2301
2302 btf_dedup_clear_hypot_map(d);
2303 eq = btf_dedup_is_equiv(d, type_id, cand_node->type_id);
2304 if (eq < 0)
2305 return eq;
2306 if (!eq)
2307 continue;
2308 new_id = cand_node->type_id;
2309 btf_dedup_merge_hypot_map(d);
2310 break;
2311 }
2312
2313 d->map[type_id] = new_id;
2314 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
2315 return -ENOMEM;
2316
2317 return 0;
2318}
2319
2320static int btf_dedup_struct_types(struct btf_dedup *d)
2321{
2322 int i, err;
2323
2324 for (i = 1; i <= d->btf->nr_types; i++) {
2325 err = btf_dedup_struct_type(d, i);
2326 if (err)
2327 return err;
2328 }
2329 return 0;
2330}
2331
2332/*
2333 * Deduplicate reference type.
2334 *
2335 * Once all primitive and struct/union types got deduplicated, we can easily
2336 * deduplicate all other (reference) BTF types. This is done in two steps:
2337 *
2338 * 1. Resolve all referenced type IDs into their canonical type IDs. This
2339 * resolution can be done either immediately for primitive or struct/union types
2340 * (because they were deduped in previous two phases) or recursively for
2341 * reference types. Recursion will always terminate at either primitive or
2342 * struct/union type, at which point we can "unwind" chain of reference types
2343 * one by one. There is no danger of encountering cycles because in C type
2344 * system the only way to form type cycle is through struct/union, so any chain
2345 * of reference types, even those taking part in a type cycle, will inevitably
2346 * reach struct/union at some point.
2347 *
2348 * 2. Once all referenced type IDs are resolved into canonical ones, BTF type
2349 * becomes "stable", in the sense that no further deduplication will cause
2350 * any changes to it. With that, it's now possible to calculate type's signature
2351 * hash (this time taking into account referenced type IDs) and loop over all
2352 * potential canonical representatives. If no match was found, current type
2353 * will become canonical representative of itself and will be added into
2354 * btf_dedup->dedup_table as another possible canonical representative.
2355 */
2356static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id)
2357{
2358 struct btf_dedup_node *cand_node;
2359 struct btf_type *t, *cand;
2360 /* if we don't find equivalent type, then we are representative type */
2361 __u32 new_id = type_id;
2362 int ref_type_id;
2363 __u32 h;
2364
2365 if (d->map[type_id] == BTF_IN_PROGRESS_ID)
2366 return -ELOOP;
2367 if (d->map[type_id] <= BTF_MAX_NR_TYPES)
2368 return resolve_type_id(d, type_id);
2369
2370 t = d->btf->types[type_id];
2371 d->map[type_id] = BTF_IN_PROGRESS_ID;
2372
2373 switch (BTF_INFO_KIND(t->info)) {
2374 case BTF_KIND_CONST:
2375 case BTF_KIND_VOLATILE:
2376 case BTF_KIND_RESTRICT:
2377 case BTF_KIND_PTR:
2378 case BTF_KIND_TYPEDEF:
2379 case BTF_KIND_FUNC:
2380 ref_type_id = btf_dedup_ref_type(d, t->type);
2381 if (ref_type_id < 0)
2382 return ref_type_id;
2383 t->type = ref_type_id;
2384
2385 h = btf_hash_common(t);
2386 for_each_dedup_cand(d, h, cand_node) {
2387 cand = d->btf->types[cand_node->type_id];
2388 if (btf_equal_common(t, cand)) {
2389 new_id = cand_node->type_id;
2390 break;
2391 }
2392 }
2393 break;
2394
2395 case BTF_KIND_ARRAY: {
2396 struct btf_array *info = (struct btf_array *)(t + 1);
2397
2398 ref_type_id = btf_dedup_ref_type(d, info->type);
2399 if (ref_type_id < 0)
2400 return ref_type_id;
2401 info->type = ref_type_id;
2402
2403 ref_type_id = btf_dedup_ref_type(d, info->index_type);
2404 if (ref_type_id < 0)
2405 return ref_type_id;
2406 info->index_type = ref_type_id;
2407
2408 h = btf_hash_array(t);
2409 for_each_dedup_cand(d, h, cand_node) {
2410 cand = d->btf->types[cand_node->type_id];
2411 if (btf_equal_array(t, cand)) {
2412 new_id = cand_node->type_id;
2413 break;
2414 }
2415 }
2416 break;
2417 }
2418
2419 case BTF_KIND_FUNC_PROTO: {
2420 struct btf_param *param;
2421 __u16 vlen;
2422 int i;
2423
2424 ref_type_id = btf_dedup_ref_type(d, t->type);
2425 if (ref_type_id < 0)
2426 return ref_type_id;
2427 t->type = ref_type_id;
2428
2429 vlen = BTF_INFO_VLEN(t->info);
2430 param = (struct btf_param *)(t + 1);
2431 for (i = 0; i < vlen; i++) {
2432 ref_type_id = btf_dedup_ref_type(d, param->type);
2433 if (ref_type_id < 0)
2434 return ref_type_id;
2435 param->type = ref_type_id;
2436 param++;
2437 }
2438
2439 h = btf_hash_fnproto(t);
2440 for_each_dedup_cand(d, h, cand_node) {
2441 cand = d->btf->types[cand_node->type_id];
2442 if (btf_equal_fnproto(t, cand)) {
2443 new_id = cand_node->type_id;
2444 break;
2445 }
2446 }
2447 break;
2448 }
2449
2450 default:
2451 return -EINVAL;
2452 }
2453
2454 d->map[type_id] = new_id;
2455 if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
2456 return -ENOMEM;
2457
2458 return new_id;
2459}
2460
2461static int btf_dedup_ref_types(struct btf_dedup *d)
2462{
2463 int i, err;
2464
2465 for (i = 1; i <= d->btf->nr_types; i++) {
2466 err = btf_dedup_ref_type(d, i);
2467 if (err < 0)
2468 return err;
2469 }
2470 btf_dedup_table_free(d);
2471 return 0;
2472}
2473
2474/*
2475 * Compact types.
2476 *
2477 * After we established for each type its corresponding canonical representative
2478 * type, we now can eliminate types that are not canonical and leave only
2479 * canonical ones layed out sequentially in memory by copying them over
2480 * duplicates. During compaction btf_dedup->hypot_map array is reused to store
2481 * a map from original type ID to a new compacted type ID, which will be used
2482 * during next phase to "fix up" type IDs, referenced from struct/union and
2483 * reference types.
2484 */
2485static int btf_dedup_compact_types(struct btf_dedup *d)
2486{
2487 struct btf_type **new_types;
2488 __u32 next_type_id = 1;
2489 char *types_start, *p;
2490 int i, len;
2491
2492 /* we are going to reuse hypot_map to store compaction remapping */
2493 d->hypot_map[0] = 0;
2494 for (i = 1; i <= d->btf->nr_types; i++)
2495 d->hypot_map[i] = BTF_UNPROCESSED_ID;
2496
2497 types_start = d->btf->nohdr_data + d->btf->hdr->type_off;
2498 p = types_start;
2499
2500 for (i = 1; i <= d->btf->nr_types; i++) {
2501 if (d->map[i] != i)
2502 continue;
2503
2504 len = btf_type_size(d->btf->types[i]);
2505 if (len < 0)
2506 return len;
2507
2508 memmove(p, d->btf->types[i], len);
2509 d->hypot_map[i] = next_type_id;
2510 d->btf->types[next_type_id] = (struct btf_type *)p;
2511 p += len;
2512 next_type_id++;
2513 }
2514
2515 /* shrink struct btf's internal types index and update btf_header */
2516 d->btf->nr_types = next_type_id - 1;
2517 d->btf->types_size = d->btf->nr_types;
2518 d->btf->hdr->type_len = p - types_start;
2519 new_types = realloc(d->btf->types,
2520 (1 + d->btf->nr_types) * sizeof(struct btf_type *));
2521 if (!new_types)
2522 return -ENOMEM;
2523 d->btf->types = new_types;
2524
2525 /* make sure string section follows type information without gaps */
2526 d->btf->hdr->str_off = p - (char *)d->btf->nohdr_data;
2527 memmove(p, d->btf->strings, d->btf->hdr->str_len);
2528 d->btf->strings = p;
2529 p += d->btf->hdr->str_len;
2530
2531 d->btf->data_size = p - (char *)d->btf->data;
2532 return 0;
2533}
2534
2535/*
2536 * Figure out final (deduplicated and compacted) type ID for provided original
2537 * `type_id` by first resolving it into corresponding canonical type ID and
2538 * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map,
2539 * which is populated during compaction phase.
2540 */
2541static int btf_dedup_remap_type_id(struct btf_dedup *d, __u32 type_id)
2542{
2543 __u32 resolved_type_id, new_type_id;
2544
2545 resolved_type_id = resolve_type_id(d, type_id);
2546 new_type_id = d->hypot_map[resolved_type_id];
2547 if (new_type_id > BTF_MAX_NR_TYPES)
2548 return -EINVAL;
2549 return new_type_id;
2550}
2551
2552/*
2553 * Remap referenced type IDs into deduped type IDs.
2554 *
2555 * After BTF types are deduplicated and compacted, their final type IDs may
2556 * differ from original ones. The map from original to a corresponding
2557 * deduped type ID is stored in btf_dedup->hypot_map and is populated during
2558 * compaction phase. During remapping phase we are rewriting all type IDs
2559 * referenced from any BTF type (e.g., struct fields, func proto args, etc) to
2560 * their final deduped type IDs.
2561 */
2562static int btf_dedup_remap_type(struct btf_dedup *d, __u32 type_id)
2563{
2564 struct btf_type *t = d->btf->types[type_id];
2565 int i, r;
2566
2567 switch (BTF_INFO_KIND(t->info)) {
2568 case BTF_KIND_INT:
2569 case BTF_KIND_ENUM:
2570 break;
2571
2572 case BTF_KIND_FWD:
2573 case BTF_KIND_CONST:
2574 case BTF_KIND_VOLATILE:
2575 case BTF_KIND_RESTRICT:
2576 case BTF_KIND_PTR:
2577 case BTF_KIND_TYPEDEF:
2578 case BTF_KIND_FUNC:
2579 r = btf_dedup_remap_type_id(d, t->type);
2580 if (r < 0)
2581 return r;
2582 t->type = r;
2583 break;
2584
2585 case BTF_KIND_ARRAY: {
2586 struct btf_array *arr_info = (struct btf_array *)(t + 1);
2587
2588 r = btf_dedup_remap_type_id(d, arr_info->type);
2589 if (r < 0)
2590 return r;
2591 arr_info->type = r;
2592 r = btf_dedup_remap_type_id(d, arr_info->index_type);
2593 if (r < 0)
2594 return r;
2595 arr_info->index_type = r;
2596 break;
2597 }
2598
2599 case BTF_KIND_STRUCT:
2600 case BTF_KIND_UNION: {
2601 struct btf_member *member = (struct btf_member *)(t + 1);
2602 __u16 vlen = BTF_INFO_VLEN(t->info);
2603
2604 for (i = 0; i < vlen; i++) {
2605 r = btf_dedup_remap_type_id(d, member->type);
2606 if (r < 0)
2607 return r;
2608 member->type = r;
2609 member++;
2610 }
2611 break;
2612 }
2613
2614 case BTF_KIND_FUNC_PROTO: {
2615 struct btf_param *param = (struct btf_param *)(t + 1);
2616 __u16 vlen = BTF_INFO_VLEN(t->info);
2617
2618 r = btf_dedup_remap_type_id(d, t->type);
2619 if (r < 0)
2620 return r;
2621 t->type = r;
2622
2623 for (i = 0; i < vlen; i++) {
2624 r = btf_dedup_remap_type_id(d, param->type);
2625 if (r < 0)
2626 return r;
2627 param->type = r;
2628 param++;
2629 }
2630 break;
2631 }
2632
2633 default:
2634 return -EINVAL;
2635 }
2636
2637 return 0;
2638}
2639
2640static int btf_dedup_remap_types(struct btf_dedup *d)
2641{
2642 int i, r;
2643
2644 for (i = 1; i <= d->btf->nr_types; i++) {
2645 r = btf_dedup_remap_type(d, i);
2646 if (r < 0)
2647 return r;
2648 }
2649 return 0;
2650}