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