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