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