xref: /openbmc/linux/tools/lib/bpf/btf.c (revision e330fb14)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 /* Copyright (c) 2018 Facebook */
3 
4 #include <byteswap.h>
5 #include <endian.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <errno.h>
12 #include <sys/utsname.h>
13 #include <sys/param.h>
14 #include <sys/stat.h>
15 #include <linux/kernel.h>
16 #include <linux/err.h>
17 #include <linux/btf.h>
18 #include <gelf.h>
19 #include "btf.h"
20 #include "bpf.h"
21 #include "libbpf.h"
22 #include "libbpf_internal.h"
23 #include "hashmap.h"
24 #include "strset.h"
25 
26 #define BTF_MAX_NR_TYPES 0x7fffffffU
27 #define BTF_MAX_STR_OFFSET 0x7fffffffU
28 
29 static struct btf_type btf_void;
30 
31 struct btf {
32 	/* raw BTF data in native endianness */
33 	void *raw_data;
34 	/* raw BTF data in non-native endianness */
35 	void *raw_data_swapped;
36 	__u32 raw_size;
37 	/* whether target endianness differs from the native one */
38 	bool swapped_endian;
39 
40 	/*
41 	 * When BTF is loaded from an ELF or raw memory it is stored
42 	 * in a contiguous memory block. The hdr, type_data, and, strs_data
43 	 * point inside that memory region to their respective parts of BTF
44 	 * representation:
45 	 *
46 	 * +--------------------------------+
47 	 * |  Header  |  Types  |  Strings  |
48 	 * +--------------------------------+
49 	 * ^          ^         ^
50 	 * |          |         |
51 	 * hdr        |         |
52 	 * types_data-+         |
53 	 * strs_data------------+
54 	 *
55 	 * If BTF data is later modified, e.g., due to types added or
56 	 * removed, BTF deduplication performed, etc, this contiguous
57 	 * representation is broken up into three independently allocated
58 	 * memory regions to be able to modify them independently.
59 	 * raw_data is nulled out at that point, but can be later allocated
60 	 * and cached again if user calls btf__get_raw_data(), at which point
61 	 * raw_data will contain a contiguous copy of header, types, and
62 	 * strings:
63 	 *
64 	 * +----------+  +---------+  +-----------+
65 	 * |  Header  |  |  Types  |  |  Strings  |
66 	 * +----------+  +---------+  +-----------+
67 	 * ^             ^            ^
68 	 * |             |            |
69 	 * hdr           |            |
70 	 * types_data----+            |
71 	 * strset__data(strs_set)-----+
72 	 *
73 	 *               +----------+---------+-----------+
74 	 *               |  Header  |  Types  |  Strings  |
75 	 * raw_data----->+----------+---------+-----------+
76 	 */
77 	struct btf_header *hdr;
78 
79 	void *types_data;
80 	size_t types_data_cap; /* used size stored in hdr->type_len */
81 
82 	/* type ID to `struct btf_type *` lookup index
83 	 * type_offs[0] corresponds to the first non-VOID type:
84 	 *   - for base BTF it's type [1];
85 	 *   - for split BTF it's the first non-base BTF type.
86 	 */
87 	__u32 *type_offs;
88 	size_t type_offs_cap;
89 	/* number of types in this BTF instance:
90 	 *   - doesn't include special [0] void type;
91 	 *   - for split BTF counts number of types added on top of base BTF.
92 	 */
93 	__u32 nr_types;
94 	/* if not NULL, points to the base BTF on top of which the current
95 	 * split BTF is based
96 	 */
97 	struct btf *base_btf;
98 	/* BTF type ID of the first type in this BTF instance:
99 	 *   - for base BTF it's equal to 1;
100 	 *   - for split BTF it's equal to biggest type ID of base BTF plus 1.
101 	 */
102 	int start_id;
103 	/* logical string offset of this BTF instance:
104 	 *   - for base BTF it's equal to 0;
105 	 *   - for split BTF it's equal to total size of base BTF's string section size.
106 	 */
107 	int start_str_off;
108 
109 	/* only one of strs_data or strs_set can be non-NULL, depending on
110 	 * whether BTF is in a modifiable state (strs_set is used) or not
111 	 * (strs_data points inside raw_data)
112 	 */
113 	void *strs_data;
114 	/* a set of unique strings */
115 	struct strset *strs_set;
116 	/* whether strings are already deduplicated */
117 	bool strs_deduped;
118 
119 	/* BTF object FD, if loaded into kernel */
120 	int fd;
121 
122 	/* Pointer size (in bytes) for a target architecture of this BTF */
123 	int ptr_sz;
124 };
125 
126 static inline __u64 ptr_to_u64(const void *ptr)
127 {
128 	return (__u64) (unsigned long) ptr;
129 }
130 
131 /* Ensure given dynamically allocated memory region pointed to by *data* with
132  * capacity of *cap_cnt* elements each taking *elem_sz* bytes has enough
133  * memory to accomodate *add_cnt* new elements, assuming *cur_cnt* elements
134  * are already used. At most *max_cnt* elements can be ever allocated.
135  * If necessary, memory is reallocated and all existing data is copied over,
136  * new pointer to the memory region is stored at *data, new memory region
137  * capacity (in number of elements) is stored in *cap.
138  * On success, memory pointer to the beginning of unused memory is returned.
139  * On error, NULL is returned.
140  */
141 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
142 		     size_t cur_cnt, size_t max_cnt, size_t add_cnt)
143 {
144 	size_t new_cnt;
145 	void *new_data;
146 
147 	if (cur_cnt + add_cnt <= *cap_cnt)
148 		return *data + cur_cnt * elem_sz;
149 
150 	/* requested more than the set limit */
151 	if (cur_cnt + add_cnt > max_cnt)
152 		return NULL;
153 
154 	new_cnt = *cap_cnt;
155 	new_cnt += new_cnt / 4;		  /* expand by 25% */
156 	if (new_cnt < 16)		  /* but at least 16 elements */
157 		new_cnt = 16;
158 	if (new_cnt > max_cnt)		  /* but not exceeding a set limit */
159 		new_cnt = max_cnt;
160 	if (new_cnt < cur_cnt + add_cnt)  /* also ensure we have enough memory */
161 		new_cnt = cur_cnt + add_cnt;
162 
163 	new_data = libbpf_reallocarray(*data, new_cnt, elem_sz);
164 	if (!new_data)
165 		return NULL;
166 
167 	/* zero out newly allocated portion of memory */
168 	memset(new_data + (*cap_cnt) * elem_sz, 0, (new_cnt - *cap_cnt) * elem_sz);
169 
170 	*data = new_data;
171 	*cap_cnt = new_cnt;
172 	return new_data + cur_cnt * elem_sz;
173 }
174 
175 /* Ensure given dynamically allocated memory region has enough allocated space
176  * to accommodate *need_cnt* elements of size *elem_sz* bytes each
177  */
178 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt)
179 {
180 	void *p;
181 
182 	if (need_cnt <= *cap_cnt)
183 		return 0;
184 
185 	p = libbpf_add_mem(data, cap_cnt, elem_sz, *cap_cnt, SIZE_MAX, need_cnt - *cap_cnt);
186 	if (!p)
187 		return -ENOMEM;
188 
189 	return 0;
190 }
191 
192 static int btf_add_type_idx_entry(struct btf *btf, __u32 type_off)
193 {
194 	__u32 *p;
195 
196 	p = libbpf_add_mem((void **)&btf->type_offs, &btf->type_offs_cap, sizeof(__u32),
197 			   btf->nr_types, BTF_MAX_NR_TYPES, 1);
198 	if (!p)
199 		return -ENOMEM;
200 
201 	*p = type_off;
202 	return 0;
203 }
204 
205 static void btf_bswap_hdr(struct btf_header *h)
206 {
207 	h->magic = bswap_16(h->magic);
208 	h->hdr_len = bswap_32(h->hdr_len);
209 	h->type_off = bswap_32(h->type_off);
210 	h->type_len = bswap_32(h->type_len);
211 	h->str_off = bswap_32(h->str_off);
212 	h->str_len = bswap_32(h->str_len);
213 }
214 
215 static int btf_parse_hdr(struct btf *btf)
216 {
217 	struct btf_header *hdr = btf->hdr;
218 	__u32 meta_left;
219 
220 	if (btf->raw_size < sizeof(struct btf_header)) {
221 		pr_debug("BTF header not found\n");
222 		return -EINVAL;
223 	}
224 
225 	if (hdr->magic == bswap_16(BTF_MAGIC)) {
226 		btf->swapped_endian = true;
227 		if (bswap_32(hdr->hdr_len) != sizeof(struct btf_header)) {
228 			pr_warn("Can't load BTF with non-native endianness due to unsupported header length %u\n",
229 				bswap_32(hdr->hdr_len));
230 			return -ENOTSUP;
231 		}
232 		btf_bswap_hdr(hdr);
233 	} else if (hdr->magic != BTF_MAGIC) {
234 		pr_debug("Invalid BTF magic:%x\n", hdr->magic);
235 		return -EINVAL;
236 	}
237 
238 	meta_left = btf->raw_size - sizeof(*hdr);
239 	if (meta_left < hdr->str_off + hdr->str_len) {
240 		pr_debug("Invalid BTF total size:%u\n", btf->raw_size);
241 		return -EINVAL;
242 	}
243 
244 	if (hdr->type_off + hdr->type_len > hdr->str_off) {
245 		pr_debug("Invalid BTF data sections layout: type data at %u + %u, strings data at %u + %u\n",
246 			 hdr->type_off, hdr->type_len, hdr->str_off, hdr->str_len);
247 		return -EINVAL;
248 	}
249 
250 	if (hdr->type_off % 4) {
251 		pr_debug("BTF type section is not aligned to 4 bytes\n");
252 		return -EINVAL;
253 	}
254 
255 	return 0;
256 }
257 
258 static int btf_parse_str_sec(struct btf *btf)
259 {
260 	const struct btf_header *hdr = btf->hdr;
261 	const char *start = btf->strs_data;
262 	const char *end = start + btf->hdr->str_len;
263 
264 	if (btf->base_btf && hdr->str_len == 0)
265 		return 0;
266 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_STR_OFFSET || end[-1]) {
267 		pr_debug("Invalid BTF string section\n");
268 		return -EINVAL;
269 	}
270 	if (!btf->base_btf && start[0]) {
271 		pr_debug("Invalid BTF string section\n");
272 		return -EINVAL;
273 	}
274 	return 0;
275 }
276 
277 static int btf_type_size(const struct btf_type *t)
278 {
279 	const int base_size = sizeof(struct btf_type);
280 	__u16 vlen = btf_vlen(t);
281 
282 	switch (btf_kind(t)) {
283 	case BTF_KIND_FWD:
284 	case BTF_KIND_CONST:
285 	case BTF_KIND_VOLATILE:
286 	case BTF_KIND_RESTRICT:
287 	case BTF_KIND_PTR:
288 	case BTF_KIND_TYPEDEF:
289 	case BTF_KIND_FUNC:
290 	case BTF_KIND_FLOAT:
291 		return base_size;
292 	case BTF_KIND_INT:
293 		return base_size + sizeof(__u32);
294 	case BTF_KIND_ENUM:
295 		return base_size + vlen * sizeof(struct btf_enum);
296 	case BTF_KIND_ARRAY:
297 		return base_size + sizeof(struct btf_array);
298 	case BTF_KIND_STRUCT:
299 	case BTF_KIND_UNION:
300 		return base_size + vlen * sizeof(struct btf_member);
301 	case BTF_KIND_FUNC_PROTO:
302 		return base_size + vlen * sizeof(struct btf_param);
303 	case BTF_KIND_VAR:
304 		return base_size + sizeof(struct btf_var);
305 	case BTF_KIND_DATASEC:
306 		return base_size + vlen * sizeof(struct btf_var_secinfo);
307 	case BTF_KIND_TAG:
308 		return base_size + sizeof(struct btf_tag);
309 	default:
310 		pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
311 		return -EINVAL;
312 	}
313 }
314 
315 static void btf_bswap_type_base(struct btf_type *t)
316 {
317 	t->name_off = bswap_32(t->name_off);
318 	t->info = bswap_32(t->info);
319 	t->type = bswap_32(t->type);
320 }
321 
322 static int btf_bswap_type_rest(struct btf_type *t)
323 {
324 	struct btf_var_secinfo *v;
325 	struct btf_member *m;
326 	struct btf_array *a;
327 	struct btf_param *p;
328 	struct btf_enum *e;
329 	__u16 vlen = btf_vlen(t);
330 	int i;
331 
332 	switch (btf_kind(t)) {
333 	case BTF_KIND_FWD:
334 	case BTF_KIND_CONST:
335 	case BTF_KIND_VOLATILE:
336 	case BTF_KIND_RESTRICT:
337 	case BTF_KIND_PTR:
338 	case BTF_KIND_TYPEDEF:
339 	case BTF_KIND_FUNC:
340 	case BTF_KIND_FLOAT:
341 		return 0;
342 	case BTF_KIND_INT:
343 		*(__u32 *)(t + 1) = bswap_32(*(__u32 *)(t + 1));
344 		return 0;
345 	case BTF_KIND_ENUM:
346 		for (i = 0, e = btf_enum(t); i < vlen; i++, e++) {
347 			e->name_off = bswap_32(e->name_off);
348 			e->val = bswap_32(e->val);
349 		}
350 		return 0;
351 	case BTF_KIND_ARRAY:
352 		a = btf_array(t);
353 		a->type = bswap_32(a->type);
354 		a->index_type = bswap_32(a->index_type);
355 		a->nelems = bswap_32(a->nelems);
356 		return 0;
357 	case BTF_KIND_STRUCT:
358 	case BTF_KIND_UNION:
359 		for (i = 0, m = btf_members(t); i < vlen; i++, m++) {
360 			m->name_off = bswap_32(m->name_off);
361 			m->type = bswap_32(m->type);
362 			m->offset = bswap_32(m->offset);
363 		}
364 		return 0;
365 	case BTF_KIND_FUNC_PROTO:
366 		for (i = 0, p = btf_params(t); i < vlen; i++, p++) {
367 			p->name_off = bswap_32(p->name_off);
368 			p->type = bswap_32(p->type);
369 		}
370 		return 0;
371 	case BTF_KIND_VAR:
372 		btf_var(t)->linkage = bswap_32(btf_var(t)->linkage);
373 		return 0;
374 	case BTF_KIND_DATASEC:
375 		for (i = 0, v = btf_var_secinfos(t); i < vlen; i++, v++) {
376 			v->type = bswap_32(v->type);
377 			v->offset = bswap_32(v->offset);
378 			v->size = bswap_32(v->size);
379 		}
380 		return 0;
381 	case BTF_KIND_TAG:
382 		btf_tag(t)->component_idx = bswap_32(btf_tag(t)->component_idx);
383 		return 0;
384 	default:
385 		pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
386 		return -EINVAL;
387 	}
388 }
389 
390 static int btf_parse_type_sec(struct btf *btf)
391 {
392 	struct btf_header *hdr = btf->hdr;
393 	void *next_type = btf->types_data;
394 	void *end_type = next_type + hdr->type_len;
395 	int err, type_size;
396 
397 	while (next_type + sizeof(struct btf_type) <= end_type) {
398 		if (btf->swapped_endian)
399 			btf_bswap_type_base(next_type);
400 
401 		type_size = btf_type_size(next_type);
402 		if (type_size < 0)
403 			return type_size;
404 		if (next_type + type_size > end_type) {
405 			pr_warn("BTF type [%d] is malformed\n", btf->start_id + btf->nr_types);
406 			return -EINVAL;
407 		}
408 
409 		if (btf->swapped_endian && btf_bswap_type_rest(next_type))
410 			return -EINVAL;
411 
412 		err = btf_add_type_idx_entry(btf, next_type - btf->types_data);
413 		if (err)
414 			return err;
415 
416 		next_type += type_size;
417 		btf->nr_types++;
418 	}
419 
420 	if (next_type != end_type) {
421 		pr_warn("BTF types data is malformed\n");
422 		return -EINVAL;
423 	}
424 
425 	return 0;
426 }
427 
428 __u32 btf__get_nr_types(const struct btf *btf)
429 {
430 	return btf->start_id + btf->nr_types - 1;
431 }
432 
433 const struct btf *btf__base_btf(const struct btf *btf)
434 {
435 	return btf->base_btf;
436 }
437 
438 /* internal helper returning non-const pointer to a type */
439 struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id)
440 {
441 	if (type_id == 0)
442 		return &btf_void;
443 	if (type_id < btf->start_id)
444 		return btf_type_by_id(btf->base_btf, type_id);
445 	return btf->types_data + btf->type_offs[type_id - btf->start_id];
446 }
447 
448 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id)
449 {
450 	if (type_id >= btf->start_id + btf->nr_types)
451 		return errno = EINVAL, NULL;
452 	return btf_type_by_id((struct btf *)btf, type_id);
453 }
454 
455 static int determine_ptr_size(const struct btf *btf)
456 {
457 	const struct btf_type *t;
458 	const char *name;
459 	int i, n;
460 
461 	if (btf->base_btf && btf->base_btf->ptr_sz > 0)
462 		return btf->base_btf->ptr_sz;
463 
464 	n = btf__get_nr_types(btf);
465 	for (i = 1; i <= n; i++) {
466 		t = btf__type_by_id(btf, i);
467 		if (!btf_is_int(t))
468 			continue;
469 
470 		name = btf__name_by_offset(btf, t->name_off);
471 		if (!name)
472 			continue;
473 
474 		if (strcmp(name, "long int") == 0 ||
475 		    strcmp(name, "long unsigned int") == 0) {
476 			if (t->size != 4 && t->size != 8)
477 				continue;
478 			return t->size;
479 		}
480 	}
481 
482 	return -1;
483 }
484 
485 static size_t btf_ptr_sz(const struct btf *btf)
486 {
487 	if (!btf->ptr_sz)
488 		((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
489 	return btf->ptr_sz < 0 ? sizeof(void *) : btf->ptr_sz;
490 }
491 
492 /* Return pointer size this BTF instance assumes. The size is heuristically
493  * determined by looking for 'long' or 'unsigned long' integer type and
494  * recording its size in bytes. If BTF type information doesn't have any such
495  * type, this function returns 0. In the latter case, native architecture's
496  * pointer size is assumed, so will be either 4 or 8, depending on
497  * architecture that libbpf was compiled for. It's possible to override
498  * guessed value by using btf__set_pointer_size() API.
499  */
500 size_t btf__pointer_size(const struct btf *btf)
501 {
502 	if (!btf->ptr_sz)
503 		((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
504 
505 	if (btf->ptr_sz < 0)
506 		/* not enough BTF type info to guess */
507 		return 0;
508 
509 	return btf->ptr_sz;
510 }
511 
512 /* Override or set pointer size in bytes. Only values of 4 and 8 are
513  * supported.
514  */
515 int btf__set_pointer_size(struct btf *btf, size_t ptr_sz)
516 {
517 	if (ptr_sz != 4 && ptr_sz != 8)
518 		return libbpf_err(-EINVAL);
519 	btf->ptr_sz = ptr_sz;
520 	return 0;
521 }
522 
523 static bool is_host_big_endian(void)
524 {
525 #if __BYTE_ORDER == __LITTLE_ENDIAN
526 	return false;
527 #elif __BYTE_ORDER == __BIG_ENDIAN
528 	return true;
529 #else
530 # error "Unrecognized __BYTE_ORDER__"
531 #endif
532 }
533 
534 enum btf_endianness btf__endianness(const struct btf *btf)
535 {
536 	if (is_host_big_endian())
537 		return btf->swapped_endian ? BTF_LITTLE_ENDIAN : BTF_BIG_ENDIAN;
538 	else
539 		return btf->swapped_endian ? BTF_BIG_ENDIAN : BTF_LITTLE_ENDIAN;
540 }
541 
542 int btf__set_endianness(struct btf *btf, enum btf_endianness endian)
543 {
544 	if (endian != BTF_LITTLE_ENDIAN && endian != BTF_BIG_ENDIAN)
545 		return libbpf_err(-EINVAL);
546 
547 	btf->swapped_endian = is_host_big_endian() != (endian == BTF_BIG_ENDIAN);
548 	if (!btf->swapped_endian) {
549 		free(btf->raw_data_swapped);
550 		btf->raw_data_swapped = NULL;
551 	}
552 	return 0;
553 }
554 
555 static bool btf_type_is_void(const struct btf_type *t)
556 {
557 	return t == &btf_void || btf_is_fwd(t);
558 }
559 
560 static bool btf_type_is_void_or_null(const struct btf_type *t)
561 {
562 	return !t || btf_type_is_void(t);
563 }
564 
565 #define MAX_RESOLVE_DEPTH 32
566 
567 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id)
568 {
569 	const struct btf_array *array;
570 	const struct btf_type *t;
571 	__u32 nelems = 1;
572 	__s64 size = -1;
573 	int i;
574 
575 	t = btf__type_by_id(btf, type_id);
576 	for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t); i++) {
577 		switch (btf_kind(t)) {
578 		case BTF_KIND_INT:
579 		case BTF_KIND_STRUCT:
580 		case BTF_KIND_UNION:
581 		case BTF_KIND_ENUM:
582 		case BTF_KIND_DATASEC:
583 		case BTF_KIND_FLOAT:
584 			size = t->size;
585 			goto done;
586 		case BTF_KIND_PTR:
587 			size = btf_ptr_sz(btf);
588 			goto done;
589 		case BTF_KIND_TYPEDEF:
590 		case BTF_KIND_VOLATILE:
591 		case BTF_KIND_CONST:
592 		case BTF_KIND_RESTRICT:
593 		case BTF_KIND_VAR:
594 		case BTF_KIND_TAG:
595 			type_id = t->type;
596 			break;
597 		case BTF_KIND_ARRAY:
598 			array = btf_array(t);
599 			if (nelems && array->nelems > UINT32_MAX / nelems)
600 				return libbpf_err(-E2BIG);
601 			nelems *= array->nelems;
602 			type_id = array->type;
603 			break;
604 		default:
605 			return libbpf_err(-EINVAL);
606 		}
607 
608 		t = btf__type_by_id(btf, type_id);
609 	}
610 
611 done:
612 	if (size < 0)
613 		return libbpf_err(-EINVAL);
614 	if (nelems && size > UINT32_MAX / nelems)
615 		return libbpf_err(-E2BIG);
616 
617 	return nelems * size;
618 }
619 
620 int btf__align_of(const struct btf *btf, __u32 id)
621 {
622 	const struct btf_type *t = btf__type_by_id(btf, id);
623 	__u16 kind = btf_kind(t);
624 
625 	switch (kind) {
626 	case BTF_KIND_INT:
627 	case BTF_KIND_ENUM:
628 	case BTF_KIND_FLOAT:
629 		return min(btf_ptr_sz(btf), (size_t)t->size);
630 	case BTF_KIND_PTR:
631 		return btf_ptr_sz(btf);
632 	case BTF_KIND_TYPEDEF:
633 	case BTF_KIND_VOLATILE:
634 	case BTF_KIND_CONST:
635 	case BTF_KIND_RESTRICT:
636 		return btf__align_of(btf, t->type);
637 	case BTF_KIND_ARRAY:
638 		return btf__align_of(btf, btf_array(t)->type);
639 	case BTF_KIND_STRUCT:
640 	case BTF_KIND_UNION: {
641 		const struct btf_member *m = btf_members(t);
642 		__u16 vlen = btf_vlen(t);
643 		int i, max_align = 1, align;
644 
645 		for (i = 0; i < vlen; i++, m++) {
646 			align = btf__align_of(btf, m->type);
647 			if (align <= 0)
648 				return libbpf_err(align);
649 			max_align = max(max_align, align);
650 		}
651 
652 		return max_align;
653 	}
654 	default:
655 		pr_warn("unsupported BTF_KIND:%u\n", btf_kind(t));
656 		return errno = EINVAL, 0;
657 	}
658 }
659 
660 int btf__resolve_type(const struct btf *btf, __u32 type_id)
661 {
662 	const struct btf_type *t;
663 	int depth = 0;
664 
665 	t = btf__type_by_id(btf, type_id);
666 	while (depth < MAX_RESOLVE_DEPTH &&
667 	       !btf_type_is_void_or_null(t) &&
668 	       (btf_is_mod(t) || btf_is_typedef(t) || btf_is_var(t))) {
669 		type_id = t->type;
670 		t = btf__type_by_id(btf, type_id);
671 		depth++;
672 	}
673 
674 	if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t))
675 		return libbpf_err(-EINVAL);
676 
677 	return type_id;
678 }
679 
680 __s32 btf__find_by_name(const struct btf *btf, const char *type_name)
681 {
682 	__u32 i, nr_types = btf__get_nr_types(btf);
683 
684 	if (!strcmp(type_name, "void"))
685 		return 0;
686 
687 	for (i = 1; i <= nr_types; i++) {
688 		const struct btf_type *t = btf__type_by_id(btf, i);
689 		const char *name = btf__name_by_offset(btf, t->name_off);
690 
691 		if (name && !strcmp(type_name, name))
692 			return i;
693 	}
694 
695 	return libbpf_err(-ENOENT);
696 }
697 
698 __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,
699 			     __u32 kind)
700 {
701 	__u32 i, nr_types = btf__get_nr_types(btf);
702 
703 	if (kind == BTF_KIND_UNKN || !strcmp(type_name, "void"))
704 		return 0;
705 
706 	for (i = 1; i <= nr_types; i++) {
707 		const struct btf_type *t = btf__type_by_id(btf, i);
708 		const char *name;
709 
710 		if (btf_kind(t) != kind)
711 			continue;
712 		name = btf__name_by_offset(btf, t->name_off);
713 		if (name && !strcmp(type_name, name))
714 			return i;
715 	}
716 
717 	return libbpf_err(-ENOENT);
718 }
719 
720 static bool btf_is_modifiable(const struct btf *btf)
721 {
722 	return (void *)btf->hdr != btf->raw_data;
723 }
724 
725 void btf__free(struct btf *btf)
726 {
727 	if (IS_ERR_OR_NULL(btf))
728 		return;
729 
730 	if (btf->fd >= 0)
731 		close(btf->fd);
732 
733 	if (btf_is_modifiable(btf)) {
734 		/* if BTF was modified after loading, it will have a split
735 		 * in-memory representation for header, types, and strings
736 		 * sections, so we need to free all of them individually. It
737 		 * might still have a cached contiguous raw data present,
738 		 * which will be unconditionally freed below.
739 		 */
740 		free(btf->hdr);
741 		free(btf->types_data);
742 		strset__free(btf->strs_set);
743 	}
744 	free(btf->raw_data);
745 	free(btf->raw_data_swapped);
746 	free(btf->type_offs);
747 	free(btf);
748 }
749 
750 static struct btf *btf_new_empty(struct btf *base_btf)
751 {
752 	struct btf *btf;
753 
754 	btf = calloc(1, sizeof(*btf));
755 	if (!btf)
756 		return ERR_PTR(-ENOMEM);
757 
758 	btf->nr_types = 0;
759 	btf->start_id = 1;
760 	btf->start_str_off = 0;
761 	btf->fd = -1;
762 	btf->ptr_sz = sizeof(void *);
763 	btf->swapped_endian = false;
764 
765 	if (base_btf) {
766 		btf->base_btf = base_btf;
767 		btf->start_id = btf__get_nr_types(base_btf) + 1;
768 		btf->start_str_off = base_btf->hdr->str_len;
769 	}
770 
771 	/* +1 for empty string at offset 0 */
772 	btf->raw_size = sizeof(struct btf_header) + (base_btf ? 0 : 1);
773 	btf->raw_data = calloc(1, btf->raw_size);
774 	if (!btf->raw_data) {
775 		free(btf);
776 		return ERR_PTR(-ENOMEM);
777 	}
778 
779 	btf->hdr = btf->raw_data;
780 	btf->hdr->hdr_len = sizeof(struct btf_header);
781 	btf->hdr->magic = BTF_MAGIC;
782 	btf->hdr->version = BTF_VERSION;
783 
784 	btf->types_data = btf->raw_data + btf->hdr->hdr_len;
785 	btf->strs_data = btf->raw_data + btf->hdr->hdr_len;
786 	btf->hdr->str_len = base_btf ? 0 : 1; /* empty string at offset 0 */
787 
788 	return btf;
789 }
790 
791 struct btf *btf__new_empty(void)
792 {
793 	return libbpf_ptr(btf_new_empty(NULL));
794 }
795 
796 struct btf *btf__new_empty_split(struct btf *base_btf)
797 {
798 	return libbpf_ptr(btf_new_empty(base_btf));
799 }
800 
801 static struct btf *btf_new(const void *data, __u32 size, struct btf *base_btf)
802 {
803 	struct btf *btf;
804 	int err;
805 
806 	btf = calloc(1, sizeof(struct btf));
807 	if (!btf)
808 		return ERR_PTR(-ENOMEM);
809 
810 	btf->nr_types = 0;
811 	btf->start_id = 1;
812 	btf->start_str_off = 0;
813 	btf->fd = -1;
814 
815 	if (base_btf) {
816 		btf->base_btf = base_btf;
817 		btf->start_id = btf__get_nr_types(base_btf) + 1;
818 		btf->start_str_off = base_btf->hdr->str_len;
819 	}
820 
821 	btf->raw_data = malloc(size);
822 	if (!btf->raw_data) {
823 		err = -ENOMEM;
824 		goto done;
825 	}
826 	memcpy(btf->raw_data, data, size);
827 	btf->raw_size = size;
828 
829 	btf->hdr = btf->raw_data;
830 	err = btf_parse_hdr(btf);
831 	if (err)
832 		goto done;
833 
834 	btf->strs_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->str_off;
835 	btf->types_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->type_off;
836 
837 	err = btf_parse_str_sec(btf);
838 	err = err ?: btf_parse_type_sec(btf);
839 	if (err)
840 		goto done;
841 
842 done:
843 	if (err) {
844 		btf__free(btf);
845 		return ERR_PTR(err);
846 	}
847 
848 	return btf;
849 }
850 
851 struct btf *btf__new(const void *data, __u32 size)
852 {
853 	return libbpf_ptr(btf_new(data, size, NULL));
854 }
855 
856 static struct btf *btf_parse_elf(const char *path, struct btf *base_btf,
857 				 struct btf_ext **btf_ext)
858 {
859 	Elf_Data *btf_data = NULL, *btf_ext_data = NULL;
860 	int err = 0, fd = -1, idx = 0;
861 	struct btf *btf = NULL;
862 	Elf_Scn *scn = NULL;
863 	Elf *elf = NULL;
864 	GElf_Ehdr ehdr;
865 	size_t shstrndx;
866 
867 	if (elf_version(EV_CURRENT) == EV_NONE) {
868 		pr_warn("failed to init libelf for %s\n", path);
869 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
870 	}
871 
872 	fd = open(path, O_RDONLY);
873 	if (fd < 0) {
874 		err = -errno;
875 		pr_warn("failed to open %s: %s\n", path, strerror(errno));
876 		return ERR_PTR(err);
877 	}
878 
879 	err = -LIBBPF_ERRNO__FORMAT;
880 
881 	elf = elf_begin(fd, ELF_C_READ, NULL);
882 	if (!elf) {
883 		pr_warn("failed to open %s as ELF file\n", path);
884 		goto done;
885 	}
886 	if (!gelf_getehdr(elf, &ehdr)) {
887 		pr_warn("failed to get EHDR from %s\n", path);
888 		goto done;
889 	}
890 
891 	if (elf_getshdrstrndx(elf, &shstrndx)) {
892 		pr_warn("failed to get section names section index for %s\n",
893 			path);
894 		goto done;
895 	}
896 
897 	if (!elf_rawdata(elf_getscn(elf, shstrndx), NULL)) {
898 		pr_warn("failed to get e_shstrndx from %s\n", path);
899 		goto done;
900 	}
901 
902 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
903 		GElf_Shdr sh;
904 		char *name;
905 
906 		idx++;
907 		if (gelf_getshdr(scn, &sh) != &sh) {
908 			pr_warn("failed to get section(%d) header from %s\n",
909 				idx, path);
910 			goto done;
911 		}
912 		name = elf_strptr(elf, shstrndx, sh.sh_name);
913 		if (!name) {
914 			pr_warn("failed to get section(%d) name from %s\n",
915 				idx, path);
916 			goto done;
917 		}
918 		if (strcmp(name, BTF_ELF_SEC) == 0) {
919 			btf_data = elf_getdata(scn, 0);
920 			if (!btf_data) {
921 				pr_warn("failed to get section(%d, %s) data from %s\n",
922 					idx, name, path);
923 				goto done;
924 			}
925 			continue;
926 		} else if (btf_ext && strcmp(name, BTF_EXT_ELF_SEC) == 0) {
927 			btf_ext_data = elf_getdata(scn, 0);
928 			if (!btf_ext_data) {
929 				pr_warn("failed to get section(%d, %s) data from %s\n",
930 					idx, name, path);
931 				goto done;
932 			}
933 			continue;
934 		}
935 	}
936 
937 	err = 0;
938 
939 	if (!btf_data) {
940 		err = -ENOENT;
941 		goto done;
942 	}
943 	btf = btf_new(btf_data->d_buf, btf_data->d_size, base_btf);
944 	err = libbpf_get_error(btf);
945 	if (err)
946 		goto done;
947 
948 	switch (gelf_getclass(elf)) {
949 	case ELFCLASS32:
950 		btf__set_pointer_size(btf, 4);
951 		break;
952 	case ELFCLASS64:
953 		btf__set_pointer_size(btf, 8);
954 		break;
955 	default:
956 		pr_warn("failed to get ELF class (bitness) for %s\n", path);
957 		break;
958 	}
959 
960 	if (btf_ext && btf_ext_data) {
961 		*btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
962 		err = libbpf_get_error(*btf_ext);
963 		if (err)
964 			goto done;
965 	} else if (btf_ext) {
966 		*btf_ext = NULL;
967 	}
968 done:
969 	if (elf)
970 		elf_end(elf);
971 	close(fd);
972 
973 	if (!err)
974 		return btf;
975 
976 	if (btf_ext)
977 		btf_ext__free(*btf_ext);
978 	btf__free(btf);
979 
980 	return ERR_PTR(err);
981 }
982 
983 struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext)
984 {
985 	return libbpf_ptr(btf_parse_elf(path, NULL, btf_ext));
986 }
987 
988 struct btf *btf__parse_elf_split(const char *path, struct btf *base_btf)
989 {
990 	return libbpf_ptr(btf_parse_elf(path, base_btf, NULL));
991 }
992 
993 static struct btf *btf_parse_raw(const char *path, struct btf *base_btf)
994 {
995 	struct btf *btf = NULL;
996 	void *data = NULL;
997 	FILE *f = NULL;
998 	__u16 magic;
999 	int err = 0;
1000 	long sz;
1001 
1002 	f = fopen(path, "rb");
1003 	if (!f) {
1004 		err = -errno;
1005 		goto err_out;
1006 	}
1007 
1008 	/* check BTF magic */
1009 	if (fread(&magic, 1, sizeof(magic), f) < sizeof(magic)) {
1010 		err = -EIO;
1011 		goto err_out;
1012 	}
1013 	if (magic != BTF_MAGIC && magic != bswap_16(BTF_MAGIC)) {
1014 		/* definitely not a raw BTF */
1015 		err = -EPROTO;
1016 		goto err_out;
1017 	}
1018 
1019 	/* get file size */
1020 	if (fseek(f, 0, SEEK_END)) {
1021 		err = -errno;
1022 		goto err_out;
1023 	}
1024 	sz = ftell(f);
1025 	if (sz < 0) {
1026 		err = -errno;
1027 		goto err_out;
1028 	}
1029 	/* rewind to the start */
1030 	if (fseek(f, 0, SEEK_SET)) {
1031 		err = -errno;
1032 		goto err_out;
1033 	}
1034 
1035 	/* pre-alloc memory and read all of BTF data */
1036 	data = malloc(sz);
1037 	if (!data) {
1038 		err = -ENOMEM;
1039 		goto err_out;
1040 	}
1041 	if (fread(data, 1, sz, f) < sz) {
1042 		err = -EIO;
1043 		goto err_out;
1044 	}
1045 
1046 	/* finally parse BTF data */
1047 	btf = btf_new(data, sz, base_btf);
1048 
1049 err_out:
1050 	free(data);
1051 	if (f)
1052 		fclose(f);
1053 	return err ? ERR_PTR(err) : btf;
1054 }
1055 
1056 struct btf *btf__parse_raw(const char *path)
1057 {
1058 	return libbpf_ptr(btf_parse_raw(path, NULL));
1059 }
1060 
1061 struct btf *btf__parse_raw_split(const char *path, struct btf *base_btf)
1062 {
1063 	return libbpf_ptr(btf_parse_raw(path, base_btf));
1064 }
1065 
1066 static struct btf *btf_parse(const char *path, struct btf *base_btf, struct btf_ext **btf_ext)
1067 {
1068 	struct btf *btf;
1069 	int err;
1070 
1071 	if (btf_ext)
1072 		*btf_ext = NULL;
1073 
1074 	btf = btf_parse_raw(path, base_btf);
1075 	err = libbpf_get_error(btf);
1076 	if (!err)
1077 		return btf;
1078 	if (err != -EPROTO)
1079 		return ERR_PTR(err);
1080 	return btf_parse_elf(path, base_btf, btf_ext);
1081 }
1082 
1083 struct btf *btf__parse(const char *path, struct btf_ext **btf_ext)
1084 {
1085 	return libbpf_ptr(btf_parse(path, NULL, btf_ext));
1086 }
1087 
1088 struct btf *btf__parse_split(const char *path, struct btf *base_btf)
1089 {
1090 	return libbpf_ptr(btf_parse(path, base_btf, NULL));
1091 }
1092 
1093 static int compare_vsi_off(const void *_a, const void *_b)
1094 {
1095 	const struct btf_var_secinfo *a = _a;
1096 	const struct btf_var_secinfo *b = _b;
1097 
1098 	return a->offset - b->offset;
1099 }
1100 
1101 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
1102 			     struct btf_type *t)
1103 {
1104 	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
1105 	const char *name = btf__name_by_offset(btf, t->name_off);
1106 	const struct btf_type *t_var;
1107 	struct btf_var_secinfo *vsi;
1108 	const struct btf_var *var;
1109 	int ret;
1110 
1111 	if (!name) {
1112 		pr_debug("No name found in string section for DATASEC kind.\n");
1113 		return -ENOENT;
1114 	}
1115 
1116 	/* .extern datasec size and var offsets were set correctly during
1117 	 * extern collection step, so just skip straight to sorting variables
1118 	 */
1119 	if (t->size)
1120 		goto sort_vars;
1121 
1122 	ret = bpf_object__section_size(obj, name, &size);
1123 	if (ret || !size || (t->size && t->size != size)) {
1124 		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
1125 		return -ENOENT;
1126 	}
1127 
1128 	t->size = size;
1129 
1130 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
1131 		t_var = btf__type_by_id(btf, vsi->type);
1132 		var = btf_var(t_var);
1133 
1134 		if (!btf_is_var(t_var)) {
1135 			pr_debug("Non-VAR type seen in section %s\n", name);
1136 			return -EINVAL;
1137 		}
1138 
1139 		if (var->linkage == BTF_VAR_STATIC)
1140 			continue;
1141 
1142 		name = btf__name_by_offset(btf, t_var->name_off);
1143 		if (!name) {
1144 			pr_debug("No name found in string section for VAR kind\n");
1145 			return -ENOENT;
1146 		}
1147 
1148 		ret = bpf_object__variable_offset(obj, name, &off);
1149 		if (ret) {
1150 			pr_debug("No offset found in symbol table for VAR %s\n",
1151 				 name);
1152 			return -ENOENT;
1153 		}
1154 
1155 		vsi->offset = off;
1156 	}
1157 
1158 sort_vars:
1159 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
1160 	return 0;
1161 }
1162 
1163 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
1164 {
1165 	int err = 0;
1166 	__u32 i;
1167 
1168 	for (i = 1; i <= btf->nr_types; i++) {
1169 		struct btf_type *t = btf_type_by_id(btf, i);
1170 
1171 		/* Loader needs to fix up some of the things compiler
1172 		 * couldn't get its hands on while emitting BTF. This
1173 		 * is section size and global variable offset. We use
1174 		 * the info from the ELF itself for this purpose.
1175 		 */
1176 		if (btf_is_datasec(t)) {
1177 			err = btf_fixup_datasec(obj, btf, t);
1178 			if (err)
1179 				break;
1180 		}
1181 	}
1182 
1183 	return libbpf_err(err);
1184 }
1185 
1186 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian);
1187 
1188 int btf__load_into_kernel(struct btf *btf)
1189 {
1190 	__u32 log_buf_size = 0, raw_size;
1191 	char *log_buf = NULL;
1192 	void *raw_data;
1193 	int err = 0;
1194 
1195 	if (btf->fd >= 0)
1196 		return libbpf_err(-EEXIST);
1197 
1198 retry_load:
1199 	if (log_buf_size) {
1200 		log_buf = malloc(log_buf_size);
1201 		if (!log_buf)
1202 			return libbpf_err(-ENOMEM);
1203 
1204 		*log_buf = 0;
1205 	}
1206 
1207 	raw_data = btf_get_raw_data(btf, &raw_size, false);
1208 	if (!raw_data) {
1209 		err = -ENOMEM;
1210 		goto done;
1211 	}
1212 	/* cache native raw data representation */
1213 	btf->raw_size = raw_size;
1214 	btf->raw_data = raw_data;
1215 
1216 	btf->fd = bpf_load_btf(raw_data, raw_size, log_buf, log_buf_size, false);
1217 	if (btf->fd < 0) {
1218 		if (!log_buf || errno == ENOSPC) {
1219 			log_buf_size = max((__u32)BPF_LOG_BUF_SIZE,
1220 					   log_buf_size << 1);
1221 			free(log_buf);
1222 			goto retry_load;
1223 		}
1224 
1225 		err = -errno;
1226 		pr_warn("Error loading BTF: %s(%d)\n", strerror(errno), errno);
1227 		if (*log_buf)
1228 			pr_warn("%s\n", log_buf);
1229 		goto done;
1230 	}
1231 
1232 done:
1233 	free(log_buf);
1234 	return libbpf_err(err);
1235 }
1236 int btf__load(struct btf *) __attribute__((alias("btf__load_into_kernel")));
1237 
1238 int btf__fd(const struct btf *btf)
1239 {
1240 	return btf->fd;
1241 }
1242 
1243 void btf__set_fd(struct btf *btf, int fd)
1244 {
1245 	btf->fd = fd;
1246 }
1247 
1248 static const void *btf_strs_data(const struct btf *btf)
1249 {
1250 	return btf->strs_data ? btf->strs_data : strset__data(btf->strs_set);
1251 }
1252 
1253 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian)
1254 {
1255 	struct btf_header *hdr = btf->hdr;
1256 	struct btf_type *t;
1257 	void *data, *p;
1258 	__u32 data_sz;
1259 	int i;
1260 
1261 	data = swap_endian ? btf->raw_data_swapped : btf->raw_data;
1262 	if (data) {
1263 		*size = btf->raw_size;
1264 		return data;
1265 	}
1266 
1267 	data_sz = hdr->hdr_len + hdr->type_len + hdr->str_len;
1268 	data = calloc(1, data_sz);
1269 	if (!data)
1270 		return NULL;
1271 	p = data;
1272 
1273 	memcpy(p, hdr, hdr->hdr_len);
1274 	if (swap_endian)
1275 		btf_bswap_hdr(p);
1276 	p += hdr->hdr_len;
1277 
1278 	memcpy(p, btf->types_data, hdr->type_len);
1279 	if (swap_endian) {
1280 		for (i = 0; i < btf->nr_types; i++) {
1281 			t = p + btf->type_offs[i];
1282 			/* btf_bswap_type_rest() relies on native t->info, so
1283 			 * we swap base type info after we swapped all the
1284 			 * additional information
1285 			 */
1286 			if (btf_bswap_type_rest(t))
1287 				goto err_out;
1288 			btf_bswap_type_base(t);
1289 		}
1290 	}
1291 	p += hdr->type_len;
1292 
1293 	memcpy(p, btf_strs_data(btf), hdr->str_len);
1294 	p += hdr->str_len;
1295 
1296 	*size = data_sz;
1297 	return data;
1298 err_out:
1299 	free(data);
1300 	return NULL;
1301 }
1302 
1303 const void *btf__get_raw_data(const struct btf *btf_ro, __u32 *size)
1304 {
1305 	struct btf *btf = (struct btf *)btf_ro;
1306 	__u32 data_sz;
1307 	void *data;
1308 
1309 	data = btf_get_raw_data(btf, &data_sz, btf->swapped_endian);
1310 	if (!data)
1311 		return errno = -ENOMEM, NULL;
1312 
1313 	btf->raw_size = data_sz;
1314 	if (btf->swapped_endian)
1315 		btf->raw_data_swapped = data;
1316 	else
1317 		btf->raw_data = data;
1318 	*size = data_sz;
1319 	return data;
1320 }
1321 
1322 const char *btf__str_by_offset(const struct btf *btf, __u32 offset)
1323 {
1324 	if (offset < btf->start_str_off)
1325 		return btf__str_by_offset(btf->base_btf, offset);
1326 	else if (offset - btf->start_str_off < btf->hdr->str_len)
1327 		return btf_strs_data(btf) + (offset - btf->start_str_off);
1328 	else
1329 		return errno = EINVAL, NULL;
1330 }
1331 
1332 const char *btf__name_by_offset(const struct btf *btf, __u32 offset)
1333 {
1334 	return btf__str_by_offset(btf, offset);
1335 }
1336 
1337 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf)
1338 {
1339 	struct bpf_btf_info btf_info;
1340 	__u32 len = sizeof(btf_info);
1341 	__u32 last_size;
1342 	struct btf *btf;
1343 	void *ptr;
1344 	int err;
1345 
1346 	/* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so
1347 	 * let's start with a sane default - 4KiB here - and resize it only if
1348 	 * bpf_obj_get_info_by_fd() needs a bigger buffer.
1349 	 */
1350 	last_size = 4096;
1351 	ptr = malloc(last_size);
1352 	if (!ptr)
1353 		return ERR_PTR(-ENOMEM);
1354 
1355 	memset(&btf_info, 0, sizeof(btf_info));
1356 	btf_info.btf = ptr_to_u64(ptr);
1357 	btf_info.btf_size = last_size;
1358 	err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1359 
1360 	if (!err && btf_info.btf_size > last_size) {
1361 		void *temp_ptr;
1362 
1363 		last_size = btf_info.btf_size;
1364 		temp_ptr = realloc(ptr, last_size);
1365 		if (!temp_ptr) {
1366 			btf = ERR_PTR(-ENOMEM);
1367 			goto exit_free;
1368 		}
1369 		ptr = temp_ptr;
1370 
1371 		len = sizeof(btf_info);
1372 		memset(&btf_info, 0, sizeof(btf_info));
1373 		btf_info.btf = ptr_to_u64(ptr);
1374 		btf_info.btf_size = last_size;
1375 
1376 		err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1377 	}
1378 
1379 	if (err || btf_info.btf_size > last_size) {
1380 		btf = err ? ERR_PTR(-errno) : ERR_PTR(-E2BIG);
1381 		goto exit_free;
1382 	}
1383 
1384 	btf = btf_new(ptr, btf_info.btf_size, base_btf);
1385 
1386 exit_free:
1387 	free(ptr);
1388 	return btf;
1389 }
1390 
1391 struct btf *btf__load_from_kernel_by_id_split(__u32 id, struct btf *base_btf)
1392 {
1393 	struct btf *btf;
1394 	int btf_fd;
1395 
1396 	btf_fd = bpf_btf_get_fd_by_id(id);
1397 	if (btf_fd < 0)
1398 		return libbpf_err_ptr(-errno);
1399 
1400 	btf = btf_get_from_fd(btf_fd, base_btf);
1401 	close(btf_fd);
1402 
1403 	return libbpf_ptr(btf);
1404 }
1405 
1406 struct btf *btf__load_from_kernel_by_id(__u32 id)
1407 {
1408 	return btf__load_from_kernel_by_id_split(id, NULL);
1409 }
1410 
1411 int btf__get_from_id(__u32 id, struct btf **btf)
1412 {
1413 	struct btf *res;
1414 	int err;
1415 
1416 	*btf = NULL;
1417 	res = btf__load_from_kernel_by_id(id);
1418 	err = libbpf_get_error(res);
1419 
1420 	if (err)
1421 		return libbpf_err(err);
1422 
1423 	*btf = res;
1424 	return 0;
1425 }
1426 
1427 int btf__get_map_kv_tids(const struct btf *btf, const char *map_name,
1428 			 __u32 expected_key_size, __u32 expected_value_size,
1429 			 __u32 *key_type_id, __u32 *value_type_id)
1430 {
1431 	const struct btf_type *container_type;
1432 	const struct btf_member *key, *value;
1433 	const size_t max_name = 256;
1434 	char container_name[max_name];
1435 	__s64 key_size, value_size;
1436 	__s32 container_id;
1437 
1438 	if (snprintf(container_name, max_name, "____btf_map_%s", map_name) == max_name) {
1439 		pr_warn("map:%s length of '____btf_map_%s' is too long\n",
1440 			map_name, map_name);
1441 		return libbpf_err(-EINVAL);
1442 	}
1443 
1444 	container_id = btf__find_by_name(btf, container_name);
1445 	if (container_id < 0) {
1446 		pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n",
1447 			 map_name, container_name);
1448 		return libbpf_err(container_id);
1449 	}
1450 
1451 	container_type = btf__type_by_id(btf, container_id);
1452 	if (!container_type) {
1453 		pr_warn("map:%s cannot find BTF type for container_id:%u\n",
1454 			map_name, container_id);
1455 		return libbpf_err(-EINVAL);
1456 	}
1457 
1458 	if (!btf_is_struct(container_type) || btf_vlen(container_type) < 2) {
1459 		pr_warn("map:%s container_name:%s is an invalid container struct\n",
1460 			map_name, container_name);
1461 		return libbpf_err(-EINVAL);
1462 	}
1463 
1464 	key = btf_members(container_type);
1465 	value = key + 1;
1466 
1467 	key_size = btf__resolve_size(btf, key->type);
1468 	if (key_size < 0) {
1469 		pr_warn("map:%s invalid BTF key_type_size\n", map_name);
1470 		return libbpf_err(key_size);
1471 	}
1472 
1473 	if (expected_key_size != key_size) {
1474 		pr_warn("map:%s btf_key_type_size:%u != map_def_key_size:%u\n",
1475 			map_name, (__u32)key_size, expected_key_size);
1476 		return libbpf_err(-EINVAL);
1477 	}
1478 
1479 	value_size = btf__resolve_size(btf, value->type);
1480 	if (value_size < 0) {
1481 		pr_warn("map:%s invalid BTF value_type_size\n", map_name);
1482 		return libbpf_err(value_size);
1483 	}
1484 
1485 	if (expected_value_size != value_size) {
1486 		pr_warn("map:%s btf_value_type_size:%u != map_def_value_size:%u\n",
1487 			map_name, (__u32)value_size, expected_value_size);
1488 		return libbpf_err(-EINVAL);
1489 	}
1490 
1491 	*key_type_id = key->type;
1492 	*value_type_id = value->type;
1493 
1494 	return 0;
1495 }
1496 
1497 static void btf_invalidate_raw_data(struct btf *btf)
1498 {
1499 	if (btf->raw_data) {
1500 		free(btf->raw_data);
1501 		btf->raw_data = NULL;
1502 	}
1503 	if (btf->raw_data_swapped) {
1504 		free(btf->raw_data_swapped);
1505 		btf->raw_data_swapped = NULL;
1506 	}
1507 }
1508 
1509 /* Ensure BTF is ready to be modified (by splitting into a three memory
1510  * regions for header, types, and strings). Also invalidate cached
1511  * raw_data, if any.
1512  */
1513 static int btf_ensure_modifiable(struct btf *btf)
1514 {
1515 	void *hdr, *types;
1516 	struct strset *set = NULL;
1517 	int err = -ENOMEM;
1518 
1519 	if (btf_is_modifiable(btf)) {
1520 		/* any BTF modification invalidates raw_data */
1521 		btf_invalidate_raw_data(btf);
1522 		return 0;
1523 	}
1524 
1525 	/* split raw data into three memory regions */
1526 	hdr = malloc(btf->hdr->hdr_len);
1527 	types = malloc(btf->hdr->type_len);
1528 	if (!hdr || !types)
1529 		goto err_out;
1530 
1531 	memcpy(hdr, btf->hdr, btf->hdr->hdr_len);
1532 	memcpy(types, btf->types_data, btf->hdr->type_len);
1533 
1534 	/* build lookup index for all strings */
1535 	set = strset__new(BTF_MAX_STR_OFFSET, btf->strs_data, btf->hdr->str_len);
1536 	if (IS_ERR(set)) {
1537 		err = PTR_ERR(set);
1538 		goto err_out;
1539 	}
1540 
1541 	/* only when everything was successful, update internal state */
1542 	btf->hdr = hdr;
1543 	btf->types_data = types;
1544 	btf->types_data_cap = btf->hdr->type_len;
1545 	btf->strs_data = NULL;
1546 	btf->strs_set = set;
1547 	/* if BTF was created from scratch, all strings are guaranteed to be
1548 	 * unique and deduplicated
1549 	 */
1550 	if (btf->hdr->str_len == 0)
1551 		btf->strs_deduped = true;
1552 	if (!btf->base_btf && btf->hdr->str_len == 1)
1553 		btf->strs_deduped = true;
1554 
1555 	/* invalidate raw_data representation */
1556 	btf_invalidate_raw_data(btf);
1557 
1558 	return 0;
1559 
1560 err_out:
1561 	strset__free(set);
1562 	free(hdr);
1563 	free(types);
1564 	return err;
1565 }
1566 
1567 /* Find an offset in BTF string section that corresponds to a given string *s*.
1568  * Returns:
1569  *   - >0 offset into string section, if string is found;
1570  *   - -ENOENT, if string is not in the string section;
1571  *   - <0, on any other error.
1572  */
1573 int btf__find_str(struct btf *btf, const char *s)
1574 {
1575 	int off;
1576 
1577 	if (btf->base_btf) {
1578 		off = btf__find_str(btf->base_btf, s);
1579 		if (off != -ENOENT)
1580 			return off;
1581 	}
1582 
1583 	/* BTF needs to be in a modifiable state to build string lookup index */
1584 	if (btf_ensure_modifiable(btf))
1585 		return libbpf_err(-ENOMEM);
1586 
1587 	off = strset__find_str(btf->strs_set, s);
1588 	if (off < 0)
1589 		return libbpf_err(off);
1590 
1591 	return btf->start_str_off + off;
1592 }
1593 
1594 /* Add a string s to the BTF string section.
1595  * Returns:
1596  *   - > 0 offset into string section, on success;
1597  *   - < 0, on error.
1598  */
1599 int btf__add_str(struct btf *btf, const char *s)
1600 {
1601 	int off;
1602 
1603 	if (btf->base_btf) {
1604 		off = btf__find_str(btf->base_btf, s);
1605 		if (off != -ENOENT)
1606 			return off;
1607 	}
1608 
1609 	if (btf_ensure_modifiable(btf))
1610 		return libbpf_err(-ENOMEM);
1611 
1612 	off = strset__add_str(btf->strs_set, s);
1613 	if (off < 0)
1614 		return libbpf_err(off);
1615 
1616 	btf->hdr->str_len = strset__data_size(btf->strs_set);
1617 
1618 	return btf->start_str_off + off;
1619 }
1620 
1621 static void *btf_add_type_mem(struct btf *btf, size_t add_sz)
1622 {
1623 	return libbpf_add_mem(&btf->types_data, &btf->types_data_cap, 1,
1624 			      btf->hdr->type_len, UINT_MAX, add_sz);
1625 }
1626 
1627 static void btf_type_inc_vlen(struct btf_type *t)
1628 {
1629 	t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, btf_kflag(t));
1630 }
1631 
1632 static int btf_commit_type(struct btf *btf, int data_sz)
1633 {
1634 	int err;
1635 
1636 	err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1637 	if (err)
1638 		return libbpf_err(err);
1639 
1640 	btf->hdr->type_len += data_sz;
1641 	btf->hdr->str_off += data_sz;
1642 	btf->nr_types++;
1643 	return btf->start_id + btf->nr_types - 1;
1644 }
1645 
1646 struct btf_pipe {
1647 	const struct btf *src;
1648 	struct btf *dst;
1649 };
1650 
1651 static int btf_rewrite_str(__u32 *str_off, void *ctx)
1652 {
1653 	struct btf_pipe *p = ctx;
1654 	int off;
1655 
1656 	if (!*str_off) /* nothing to do for empty strings */
1657 		return 0;
1658 
1659 	off = btf__add_str(p->dst, btf__str_by_offset(p->src, *str_off));
1660 	if (off < 0)
1661 		return off;
1662 
1663 	*str_off = off;
1664 	return 0;
1665 }
1666 
1667 int btf__add_type(struct btf *btf, const struct btf *src_btf, const struct btf_type *src_type)
1668 {
1669 	struct btf_pipe p = { .src = src_btf, .dst = btf };
1670 	struct btf_type *t;
1671 	int sz, err;
1672 
1673 	sz = btf_type_size(src_type);
1674 	if (sz < 0)
1675 		return libbpf_err(sz);
1676 
1677 	/* deconstruct BTF, if necessary, and invalidate raw_data */
1678 	if (btf_ensure_modifiable(btf))
1679 		return libbpf_err(-ENOMEM);
1680 
1681 	t = btf_add_type_mem(btf, sz);
1682 	if (!t)
1683 		return libbpf_err(-ENOMEM);
1684 
1685 	memcpy(t, src_type, sz);
1686 
1687 	err = btf_type_visit_str_offs(t, btf_rewrite_str, &p);
1688 	if (err)
1689 		return libbpf_err(err);
1690 
1691 	return btf_commit_type(btf, sz);
1692 }
1693 
1694 /*
1695  * Append new BTF_KIND_INT type with:
1696  *   - *name* - non-empty, non-NULL type name;
1697  *   - *sz* - power-of-2 (1, 2, 4, ..) size of the type, in bytes;
1698  *   - encoding is a combination of BTF_INT_SIGNED, BTF_INT_CHAR, BTF_INT_BOOL.
1699  * Returns:
1700  *   - >0, type ID of newly added BTF type;
1701  *   - <0, on error.
1702  */
1703 int btf__add_int(struct btf *btf, const char *name, size_t byte_sz, int encoding)
1704 {
1705 	struct btf_type *t;
1706 	int sz, name_off;
1707 
1708 	/* non-empty name */
1709 	if (!name || !name[0])
1710 		return libbpf_err(-EINVAL);
1711 	/* byte_sz must be power of 2 */
1712 	if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 16)
1713 		return libbpf_err(-EINVAL);
1714 	if (encoding & ~(BTF_INT_SIGNED | BTF_INT_CHAR | BTF_INT_BOOL))
1715 		return libbpf_err(-EINVAL);
1716 
1717 	/* deconstruct BTF, if necessary, and invalidate raw_data */
1718 	if (btf_ensure_modifiable(btf))
1719 		return libbpf_err(-ENOMEM);
1720 
1721 	sz = sizeof(struct btf_type) + sizeof(int);
1722 	t = btf_add_type_mem(btf, sz);
1723 	if (!t)
1724 		return libbpf_err(-ENOMEM);
1725 
1726 	/* if something goes wrong later, we might end up with an extra string,
1727 	 * but that shouldn't be a problem, because BTF can't be constructed
1728 	 * completely anyway and will most probably be just discarded
1729 	 */
1730 	name_off = btf__add_str(btf, name);
1731 	if (name_off < 0)
1732 		return name_off;
1733 
1734 	t->name_off = name_off;
1735 	t->info = btf_type_info(BTF_KIND_INT, 0, 0);
1736 	t->size = byte_sz;
1737 	/* set INT info, we don't allow setting legacy bit offset/size */
1738 	*(__u32 *)(t + 1) = (encoding << 24) | (byte_sz * 8);
1739 
1740 	return btf_commit_type(btf, sz);
1741 }
1742 
1743 /*
1744  * Append new BTF_KIND_FLOAT type with:
1745  *   - *name* - non-empty, non-NULL type name;
1746  *   - *sz* - size of the type, in bytes;
1747  * Returns:
1748  *   - >0, type ID of newly added BTF type;
1749  *   - <0, on error.
1750  */
1751 int btf__add_float(struct btf *btf, const char *name, size_t byte_sz)
1752 {
1753 	struct btf_type *t;
1754 	int sz, name_off;
1755 
1756 	/* non-empty name */
1757 	if (!name || !name[0])
1758 		return libbpf_err(-EINVAL);
1759 
1760 	/* byte_sz must be one of the explicitly allowed values */
1761 	if (byte_sz != 2 && byte_sz != 4 && byte_sz != 8 && byte_sz != 12 &&
1762 	    byte_sz != 16)
1763 		return libbpf_err(-EINVAL);
1764 
1765 	if (btf_ensure_modifiable(btf))
1766 		return libbpf_err(-ENOMEM);
1767 
1768 	sz = sizeof(struct btf_type);
1769 	t = btf_add_type_mem(btf, sz);
1770 	if (!t)
1771 		return libbpf_err(-ENOMEM);
1772 
1773 	name_off = btf__add_str(btf, name);
1774 	if (name_off < 0)
1775 		return name_off;
1776 
1777 	t->name_off = name_off;
1778 	t->info = btf_type_info(BTF_KIND_FLOAT, 0, 0);
1779 	t->size = byte_sz;
1780 
1781 	return btf_commit_type(btf, sz);
1782 }
1783 
1784 /* it's completely legal to append BTF types with type IDs pointing forward to
1785  * types that haven't been appended yet, so we only make sure that id looks
1786  * sane, we can't guarantee that ID will always be valid
1787  */
1788 static int validate_type_id(int id)
1789 {
1790 	if (id < 0 || id > BTF_MAX_NR_TYPES)
1791 		return -EINVAL;
1792 	return 0;
1793 }
1794 
1795 /* generic append function for PTR, TYPEDEF, CONST/VOLATILE/RESTRICT */
1796 static int btf_add_ref_kind(struct btf *btf, int kind, const char *name, int ref_type_id)
1797 {
1798 	struct btf_type *t;
1799 	int sz, name_off = 0;
1800 
1801 	if (validate_type_id(ref_type_id))
1802 		return libbpf_err(-EINVAL);
1803 
1804 	if (btf_ensure_modifiable(btf))
1805 		return libbpf_err(-ENOMEM);
1806 
1807 	sz = sizeof(struct btf_type);
1808 	t = btf_add_type_mem(btf, sz);
1809 	if (!t)
1810 		return libbpf_err(-ENOMEM);
1811 
1812 	if (name && name[0]) {
1813 		name_off = btf__add_str(btf, name);
1814 		if (name_off < 0)
1815 			return name_off;
1816 	}
1817 
1818 	t->name_off = name_off;
1819 	t->info = btf_type_info(kind, 0, 0);
1820 	t->type = ref_type_id;
1821 
1822 	return btf_commit_type(btf, sz);
1823 }
1824 
1825 /*
1826  * Append new BTF_KIND_PTR type with:
1827  *   - *ref_type_id* - referenced type ID, it might not exist yet;
1828  * Returns:
1829  *   - >0, type ID of newly added BTF type;
1830  *   - <0, on error.
1831  */
1832 int btf__add_ptr(struct btf *btf, int ref_type_id)
1833 {
1834 	return btf_add_ref_kind(btf, BTF_KIND_PTR, NULL, ref_type_id);
1835 }
1836 
1837 /*
1838  * Append new BTF_KIND_ARRAY type with:
1839  *   - *index_type_id* - type ID of the type describing array index;
1840  *   - *elem_type_id* - type ID of the type describing array element;
1841  *   - *nr_elems* - the size of the array;
1842  * Returns:
1843  *   - >0, type ID of newly added BTF type;
1844  *   - <0, on error.
1845  */
1846 int btf__add_array(struct btf *btf, int index_type_id, int elem_type_id, __u32 nr_elems)
1847 {
1848 	struct btf_type *t;
1849 	struct btf_array *a;
1850 	int sz;
1851 
1852 	if (validate_type_id(index_type_id) || validate_type_id(elem_type_id))
1853 		return libbpf_err(-EINVAL);
1854 
1855 	if (btf_ensure_modifiable(btf))
1856 		return libbpf_err(-ENOMEM);
1857 
1858 	sz = sizeof(struct btf_type) + sizeof(struct btf_array);
1859 	t = btf_add_type_mem(btf, sz);
1860 	if (!t)
1861 		return libbpf_err(-ENOMEM);
1862 
1863 	t->name_off = 0;
1864 	t->info = btf_type_info(BTF_KIND_ARRAY, 0, 0);
1865 	t->size = 0;
1866 
1867 	a = btf_array(t);
1868 	a->type = elem_type_id;
1869 	a->index_type = index_type_id;
1870 	a->nelems = nr_elems;
1871 
1872 	return btf_commit_type(btf, sz);
1873 }
1874 
1875 /* generic STRUCT/UNION append function */
1876 static int btf_add_composite(struct btf *btf, int kind, const char *name, __u32 bytes_sz)
1877 {
1878 	struct btf_type *t;
1879 	int sz, name_off = 0;
1880 
1881 	if (btf_ensure_modifiable(btf))
1882 		return libbpf_err(-ENOMEM);
1883 
1884 	sz = sizeof(struct btf_type);
1885 	t = btf_add_type_mem(btf, sz);
1886 	if (!t)
1887 		return libbpf_err(-ENOMEM);
1888 
1889 	if (name && name[0]) {
1890 		name_off = btf__add_str(btf, name);
1891 		if (name_off < 0)
1892 			return name_off;
1893 	}
1894 
1895 	/* start out with vlen=0 and no kflag; this will be adjusted when
1896 	 * adding each member
1897 	 */
1898 	t->name_off = name_off;
1899 	t->info = btf_type_info(kind, 0, 0);
1900 	t->size = bytes_sz;
1901 
1902 	return btf_commit_type(btf, sz);
1903 }
1904 
1905 /*
1906  * Append new BTF_KIND_STRUCT type with:
1907  *   - *name* - name of the struct, can be NULL or empty for anonymous structs;
1908  *   - *byte_sz* - size of the struct, in bytes;
1909  *
1910  * Struct initially has no fields in it. Fields can be added by
1911  * btf__add_field() right after btf__add_struct() succeeds.
1912  *
1913  * Returns:
1914  *   - >0, type ID of newly added BTF type;
1915  *   - <0, on error.
1916  */
1917 int btf__add_struct(struct btf *btf, const char *name, __u32 byte_sz)
1918 {
1919 	return btf_add_composite(btf, BTF_KIND_STRUCT, name, byte_sz);
1920 }
1921 
1922 /*
1923  * Append new BTF_KIND_UNION type with:
1924  *   - *name* - name of the union, can be NULL or empty for anonymous union;
1925  *   - *byte_sz* - size of the union, in bytes;
1926  *
1927  * Union initially has no fields in it. Fields can be added by
1928  * btf__add_field() right after btf__add_union() succeeds. All fields
1929  * should have *bit_offset* of 0.
1930  *
1931  * Returns:
1932  *   - >0, type ID of newly added BTF type;
1933  *   - <0, on error.
1934  */
1935 int btf__add_union(struct btf *btf, const char *name, __u32 byte_sz)
1936 {
1937 	return btf_add_composite(btf, BTF_KIND_UNION, name, byte_sz);
1938 }
1939 
1940 static struct btf_type *btf_last_type(struct btf *btf)
1941 {
1942 	return btf_type_by_id(btf, btf__get_nr_types(btf));
1943 }
1944 
1945 /*
1946  * Append new field for the current STRUCT/UNION type with:
1947  *   - *name* - name of the field, can be NULL or empty for anonymous field;
1948  *   - *type_id* - type ID for the type describing field type;
1949  *   - *bit_offset* - bit offset of the start of the field within struct/union;
1950  *   - *bit_size* - bit size of a bitfield, 0 for non-bitfield fields;
1951  * Returns:
1952  *   -  0, on success;
1953  *   - <0, on error.
1954  */
1955 int btf__add_field(struct btf *btf, const char *name, int type_id,
1956 		   __u32 bit_offset, __u32 bit_size)
1957 {
1958 	struct btf_type *t;
1959 	struct btf_member *m;
1960 	bool is_bitfield;
1961 	int sz, name_off = 0;
1962 
1963 	/* last type should be union/struct */
1964 	if (btf->nr_types == 0)
1965 		return libbpf_err(-EINVAL);
1966 	t = btf_last_type(btf);
1967 	if (!btf_is_composite(t))
1968 		return libbpf_err(-EINVAL);
1969 
1970 	if (validate_type_id(type_id))
1971 		return libbpf_err(-EINVAL);
1972 	/* best-effort bit field offset/size enforcement */
1973 	is_bitfield = bit_size || (bit_offset % 8 != 0);
1974 	if (is_bitfield && (bit_size == 0 || bit_size > 255 || bit_offset > 0xffffff))
1975 		return libbpf_err(-EINVAL);
1976 
1977 	/* only offset 0 is allowed for unions */
1978 	if (btf_is_union(t) && bit_offset)
1979 		return libbpf_err(-EINVAL);
1980 
1981 	/* decompose and invalidate raw data */
1982 	if (btf_ensure_modifiable(btf))
1983 		return libbpf_err(-ENOMEM);
1984 
1985 	sz = sizeof(struct btf_member);
1986 	m = btf_add_type_mem(btf, sz);
1987 	if (!m)
1988 		return libbpf_err(-ENOMEM);
1989 
1990 	if (name && name[0]) {
1991 		name_off = btf__add_str(btf, name);
1992 		if (name_off < 0)
1993 			return name_off;
1994 	}
1995 
1996 	m->name_off = name_off;
1997 	m->type = type_id;
1998 	m->offset = bit_offset | (bit_size << 24);
1999 
2000 	/* btf_add_type_mem can invalidate t pointer */
2001 	t = btf_last_type(btf);
2002 	/* update parent type's vlen and kflag */
2003 	t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, is_bitfield || btf_kflag(t));
2004 
2005 	btf->hdr->type_len += sz;
2006 	btf->hdr->str_off += sz;
2007 	return 0;
2008 }
2009 
2010 /*
2011  * Append new BTF_KIND_ENUM type with:
2012  *   - *name* - name of the enum, can be NULL or empty for anonymous enums;
2013  *   - *byte_sz* - size of the enum, in bytes.
2014  *
2015  * Enum initially has no enum values in it (and corresponds to enum forward
2016  * declaration). Enumerator values can be added by btf__add_enum_value()
2017  * immediately after btf__add_enum() succeeds.
2018  *
2019  * Returns:
2020  *   - >0, type ID of newly added BTF type;
2021  *   - <0, on error.
2022  */
2023 int btf__add_enum(struct btf *btf, const char *name, __u32 byte_sz)
2024 {
2025 	struct btf_type *t;
2026 	int sz, name_off = 0;
2027 
2028 	/* byte_sz must be power of 2 */
2029 	if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 8)
2030 		return libbpf_err(-EINVAL);
2031 
2032 	if (btf_ensure_modifiable(btf))
2033 		return libbpf_err(-ENOMEM);
2034 
2035 	sz = sizeof(struct btf_type);
2036 	t = btf_add_type_mem(btf, sz);
2037 	if (!t)
2038 		return libbpf_err(-ENOMEM);
2039 
2040 	if (name && name[0]) {
2041 		name_off = btf__add_str(btf, name);
2042 		if (name_off < 0)
2043 			return name_off;
2044 	}
2045 
2046 	/* start out with vlen=0; it will be adjusted when adding enum values */
2047 	t->name_off = name_off;
2048 	t->info = btf_type_info(BTF_KIND_ENUM, 0, 0);
2049 	t->size = byte_sz;
2050 
2051 	return btf_commit_type(btf, sz);
2052 }
2053 
2054 /*
2055  * Append new enum value for the current ENUM type with:
2056  *   - *name* - name of the enumerator value, can't be NULL or empty;
2057  *   - *value* - integer value corresponding to enum value *name*;
2058  * Returns:
2059  *   -  0, on success;
2060  *   - <0, on error.
2061  */
2062 int btf__add_enum_value(struct btf *btf, const char *name, __s64 value)
2063 {
2064 	struct btf_type *t;
2065 	struct btf_enum *v;
2066 	int sz, name_off;
2067 
2068 	/* last type should be BTF_KIND_ENUM */
2069 	if (btf->nr_types == 0)
2070 		return libbpf_err(-EINVAL);
2071 	t = btf_last_type(btf);
2072 	if (!btf_is_enum(t))
2073 		return libbpf_err(-EINVAL);
2074 
2075 	/* non-empty name */
2076 	if (!name || !name[0])
2077 		return libbpf_err(-EINVAL);
2078 	if (value < INT_MIN || value > UINT_MAX)
2079 		return libbpf_err(-E2BIG);
2080 
2081 	/* decompose and invalidate raw data */
2082 	if (btf_ensure_modifiable(btf))
2083 		return libbpf_err(-ENOMEM);
2084 
2085 	sz = sizeof(struct btf_enum);
2086 	v = btf_add_type_mem(btf, sz);
2087 	if (!v)
2088 		return libbpf_err(-ENOMEM);
2089 
2090 	name_off = btf__add_str(btf, name);
2091 	if (name_off < 0)
2092 		return name_off;
2093 
2094 	v->name_off = name_off;
2095 	v->val = value;
2096 
2097 	/* update parent type's vlen */
2098 	t = btf_last_type(btf);
2099 	btf_type_inc_vlen(t);
2100 
2101 	btf->hdr->type_len += sz;
2102 	btf->hdr->str_off += sz;
2103 	return 0;
2104 }
2105 
2106 /*
2107  * Append new BTF_KIND_FWD type with:
2108  *   - *name*, non-empty/non-NULL name;
2109  *   - *fwd_kind*, kind of forward declaration, one of BTF_FWD_STRUCT,
2110  *     BTF_FWD_UNION, or BTF_FWD_ENUM;
2111  * Returns:
2112  *   - >0, type ID of newly added BTF type;
2113  *   - <0, on error.
2114  */
2115 int btf__add_fwd(struct btf *btf, const char *name, enum btf_fwd_kind fwd_kind)
2116 {
2117 	if (!name || !name[0])
2118 		return libbpf_err(-EINVAL);
2119 
2120 	switch (fwd_kind) {
2121 	case BTF_FWD_STRUCT:
2122 	case BTF_FWD_UNION: {
2123 		struct btf_type *t;
2124 		int id;
2125 
2126 		id = btf_add_ref_kind(btf, BTF_KIND_FWD, name, 0);
2127 		if (id <= 0)
2128 			return id;
2129 		t = btf_type_by_id(btf, id);
2130 		t->info = btf_type_info(BTF_KIND_FWD, 0, fwd_kind == BTF_FWD_UNION);
2131 		return id;
2132 	}
2133 	case BTF_FWD_ENUM:
2134 		/* enum forward in BTF currently is just an enum with no enum
2135 		 * values; we also assume a standard 4-byte size for it
2136 		 */
2137 		return btf__add_enum(btf, name, sizeof(int));
2138 	default:
2139 		return libbpf_err(-EINVAL);
2140 	}
2141 }
2142 
2143 /*
2144  * Append new BTF_KING_TYPEDEF type with:
2145  *   - *name*, non-empty/non-NULL name;
2146  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2147  * Returns:
2148  *   - >0, type ID of newly added BTF type;
2149  *   - <0, on error.
2150  */
2151 int btf__add_typedef(struct btf *btf, const char *name, int ref_type_id)
2152 {
2153 	if (!name || !name[0])
2154 		return libbpf_err(-EINVAL);
2155 
2156 	return btf_add_ref_kind(btf, BTF_KIND_TYPEDEF, name, ref_type_id);
2157 }
2158 
2159 /*
2160  * Append new BTF_KIND_VOLATILE type with:
2161  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2162  * Returns:
2163  *   - >0, type ID of newly added BTF type;
2164  *   - <0, on error.
2165  */
2166 int btf__add_volatile(struct btf *btf, int ref_type_id)
2167 {
2168 	return btf_add_ref_kind(btf, BTF_KIND_VOLATILE, NULL, ref_type_id);
2169 }
2170 
2171 /*
2172  * Append new BTF_KIND_CONST type with:
2173  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2174  * Returns:
2175  *   - >0, type ID of newly added BTF type;
2176  *   - <0, on error.
2177  */
2178 int btf__add_const(struct btf *btf, int ref_type_id)
2179 {
2180 	return btf_add_ref_kind(btf, BTF_KIND_CONST, NULL, ref_type_id);
2181 }
2182 
2183 /*
2184  * Append new BTF_KIND_RESTRICT type with:
2185  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2186  * Returns:
2187  *   - >0, type ID of newly added BTF type;
2188  *   - <0, on error.
2189  */
2190 int btf__add_restrict(struct btf *btf, int ref_type_id)
2191 {
2192 	return btf_add_ref_kind(btf, BTF_KIND_RESTRICT, NULL, ref_type_id);
2193 }
2194 
2195 /*
2196  * Append new BTF_KIND_FUNC type with:
2197  *   - *name*, non-empty/non-NULL name;
2198  *   - *proto_type_id* - FUNC_PROTO's type ID, it might not exist yet;
2199  * Returns:
2200  *   - >0, type ID of newly added BTF type;
2201  *   - <0, on error.
2202  */
2203 int btf__add_func(struct btf *btf, const char *name,
2204 		  enum btf_func_linkage linkage, int proto_type_id)
2205 {
2206 	int id;
2207 
2208 	if (!name || !name[0])
2209 		return libbpf_err(-EINVAL);
2210 	if (linkage != BTF_FUNC_STATIC && linkage != BTF_FUNC_GLOBAL &&
2211 	    linkage != BTF_FUNC_EXTERN)
2212 		return libbpf_err(-EINVAL);
2213 
2214 	id = btf_add_ref_kind(btf, BTF_KIND_FUNC, name, proto_type_id);
2215 	if (id > 0) {
2216 		struct btf_type *t = btf_type_by_id(btf, id);
2217 
2218 		t->info = btf_type_info(BTF_KIND_FUNC, linkage, 0);
2219 	}
2220 	return libbpf_err(id);
2221 }
2222 
2223 /*
2224  * Append new BTF_KIND_FUNC_PROTO with:
2225  *   - *ret_type_id* - type ID for return result of a function.
2226  *
2227  * Function prototype initially has no arguments, but they can be added by
2228  * btf__add_func_param() one by one, immediately after
2229  * btf__add_func_proto() succeeded.
2230  *
2231  * Returns:
2232  *   - >0, type ID of newly added BTF type;
2233  *   - <0, on error.
2234  */
2235 int btf__add_func_proto(struct btf *btf, int ret_type_id)
2236 {
2237 	struct btf_type *t;
2238 	int sz;
2239 
2240 	if (validate_type_id(ret_type_id))
2241 		return libbpf_err(-EINVAL);
2242 
2243 	if (btf_ensure_modifiable(btf))
2244 		return libbpf_err(-ENOMEM);
2245 
2246 	sz = sizeof(struct btf_type);
2247 	t = btf_add_type_mem(btf, sz);
2248 	if (!t)
2249 		return libbpf_err(-ENOMEM);
2250 
2251 	/* start out with vlen=0; this will be adjusted when adding enum
2252 	 * values, if necessary
2253 	 */
2254 	t->name_off = 0;
2255 	t->info = btf_type_info(BTF_KIND_FUNC_PROTO, 0, 0);
2256 	t->type = ret_type_id;
2257 
2258 	return btf_commit_type(btf, sz);
2259 }
2260 
2261 /*
2262  * Append new function parameter for current FUNC_PROTO type with:
2263  *   - *name* - parameter name, can be NULL or empty;
2264  *   - *type_id* - type ID describing the type of the parameter.
2265  * Returns:
2266  *   -  0, on success;
2267  *   - <0, on error.
2268  */
2269 int btf__add_func_param(struct btf *btf, const char *name, int type_id)
2270 {
2271 	struct btf_type *t;
2272 	struct btf_param *p;
2273 	int sz, name_off = 0;
2274 
2275 	if (validate_type_id(type_id))
2276 		return libbpf_err(-EINVAL);
2277 
2278 	/* last type should be BTF_KIND_FUNC_PROTO */
2279 	if (btf->nr_types == 0)
2280 		return libbpf_err(-EINVAL);
2281 	t = btf_last_type(btf);
2282 	if (!btf_is_func_proto(t))
2283 		return libbpf_err(-EINVAL);
2284 
2285 	/* decompose and invalidate raw data */
2286 	if (btf_ensure_modifiable(btf))
2287 		return libbpf_err(-ENOMEM);
2288 
2289 	sz = sizeof(struct btf_param);
2290 	p = btf_add_type_mem(btf, sz);
2291 	if (!p)
2292 		return libbpf_err(-ENOMEM);
2293 
2294 	if (name && name[0]) {
2295 		name_off = btf__add_str(btf, name);
2296 		if (name_off < 0)
2297 			return name_off;
2298 	}
2299 
2300 	p->name_off = name_off;
2301 	p->type = type_id;
2302 
2303 	/* update parent type's vlen */
2304 	t = btf_last_type(btf);
2305 	btf_type_inc_vlen(t);
2306 
2307 	btf->hdr->type_len += sz;
2308 	btf->hdr->str_off += sz;
2309 	return 0;
2310 }
2311 
2312 /*
2313  * Append new BTF_KIND_VAR type with:
2314  *   - *name* - non-empty/non-NULL name;
2315  *   - *linkage* - variable linkage, one of BTF_VAR_STATIC,
2316  *     BTF_VAR_GLOBAL_ALLOCATED, or BTF_VAR_GLOBAL_EXTERN;
2317  *   - *type_id* - type ID of the type describing the type of the variable.
2318  * Returns:
2319  *   - >0, type ID of newly added BTF type;
2320  *   - <0, on error.
2321  */
2322 int btf__add_var(struct btf *btf, const char *name, int linkage, int type_id)
2323 {
2324 	struct btf_type *t;
2325 	struct btf_var *v;
2326 	int sz, name_off;
2327 
2328 	/* non-empty name */
2329 	if (!name || !name[0])
2330 		return libbpf_err(-EINVAL);
2331 	if (linkage != BTF_VAR_STATIC && linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2332 	    linkage != BTF_VAR_GLOBAL_EXTERN)
2333 		return libbpf_err(-EINVAL);
2334 	if (validate_type_id(type_id))
2335 		return libbpf_err(-EINVAL);
2336 
2337 	/* deconstruct BTF, if necessary, and invalidate raw_data */
2338 	if (btf_ensure_modifiable(btf))
2339 		return libbpf_err(-ENOMEM);
2340 
2341 	sz = sizeof(struct btf_type) + sizeof(struct btf_var);
2342 	t = btf_add_type_mem(btf, sz);
2343 	if (!t)
2344 		return libbpf_err(-ENOMEM);
2345 
2346 	name_off = btf__add_str(btf, name);
2347 	if (name_off < 0)
2348 		return name_off;
2349 
2350 	t->name_off = name_off;
2351 	t->info = btf_type_info(BTF_KIND_VAR, 0, 0);
2352 	t->type = type_id;
2353 
2354 	v = btf_var(t);
2355 	v->linkage = linkage;
2356 
2357 	return btf_commit_type(btf, sz);
2358 }
2359 
2360 /*
2361  * Append new BTF_KIND_DATASEC type with:
2362  *   - *name* - non-empty/non-NULL name;
2363  *   - *byte_sz* - data section size, in bytes.
2364  *
2365  * Data section is initially empty. Variables info can be added with
2366  * btf__add_datasec_var_info() calls, after btf__add_datasec() succeeds.
2367  *
2368  * Returns:
2369  *   - >0, type ID of newly added BTF type;
2370  *   - <0, on error.
2371  */
2372 int btf__add_datasec(struct btf *btf, const char *name, __u32 byte_sz)
2373 {
2374 	struct btf_type *t;
2375 	int sz, name_off;
2376 
2377 	/* non-empty name */
2378 	if (!name || !name[0])
2379 		return libbpf_err(-EINVAL);
2380 
2381 	if (btf_ensure_modifiable(btf))
2382 		return libbpf_err(-ENOMEM);
2383 
2384 	sz = sizeof(struct btf_type);
2385 	t = btf_add_type_mem(btf, sz);
2386 	if (!t)
2387 		return libbpf_err(-ENOMEM);
2388 
2389 	name_off = btf__add_str(btf, name);
2390 	if (name_off < 0)
2391 		return name_off;
2392 
2393 	/* start with vlen=0, which will be update as var_secinfos are added */
2394 	t->name_off = name_off;
2395 	t->info = btf_type_info(BTF_KIND_DATASEC, 0, 0);
2396 	t->size = byte_sz;
2397 
2398 	return btf_commit_type(btf, sz);
2399 }
2400 
2401 /*
2402  * Append new data section variable information entry for current DATASEC type:
2403  *   - *var_type_id* - type ID, describing type of the variable;
2404  *   - *offset* - variable offset within data section, in bytes;
2405  *   - *byte_sz* - variable size, in bytes.
2406  *
2407  * Returns:
2408  *   -  0, on success;
2409  *   - <0, on error.
2410  */
2411 int btf__add_datasec_var_info(struct btf *btf, int var_type_id, __u32 offset, __u32 byte_sz)
2412 {
2413 	struct btf_type *t;
2414 	struct btf_var_secinfo *v;
2415 	int sz;
2416 
2417 	/* last type should be BTF_KIND_DATASEC */
2418 	if (btf->nr_types == 0)
2419 		return libbpf_err(-EINVAL);
2420 	t = btf_last_type(btf);
2421 	if (!btf_is_datasec(t))
2422 		return libbpf_err(-EINVAL);
2423 
2424 	if (validate_type_id(var_type_id))
2425 		return libbpf_err(-EINVAL);
2426 
2427 	/* decompose and invalidate raw data */
2428 	if (btf_ensure_modifiable(btf))
2429 		return libbpf_err(-ENOMEM);
2430 
2431 	sz = sizeof(struct btf_var_secinfo);
2432 	v = btf_add_type_mem(btf, sz);
2433 	if (!v)
2434 		return libbpf_err(-ENOMEM);
2435 
2436 	v->type = var_type_id;
2437 	v->offset = offset;
2438 	v->size = byte_sz;
2439 
2440 	/* update parent type's vlen */
2441 	t = btf_last_type(btf);
2442 	btf_type_inc_vlen(t);
2443 
2444 	btf->hdr->type_len += sz;
2445 	btf->hdr->str_off += sz;
2446 	return 0;
2447 }
2448 
2449 /*
2450  * Append new BTF_KIND_TAG type with:
2451  *   - *value* - non-empty/non-NULL string;
2452  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2453  *   - *component_idx* - -1 for tagging reference type, otherwise struct/union
2454  *     member or function argument index;
2455  * Returns:
2456  *   - >0, type ID of newly added BTF type;
2457  *   - <0, on error.
2458  */
2459 int btf__add_tag(struct btf *btf, const char *value, int ref_type_id,
2460 		 int component_idx)
2461 {
2462 	struct btf_type *t;
2463 	int sz, value_off;
2464 
2465 	if (!value || !value[0] || component_idx < -1)
2466 		return libbpf_err(-EINVAL);
2467 
2468 	if (validate_type_id(ref_type_id))
2469 		return libbpf_err(-EINVAL);
2470 
2471 	if (btf_ensure_modifiable(btf))
2472 		return libbpf_err(-ENOMEM);
2473 
2474 	sz = sizeof(struct btf_type) + sizeof(struct btf_tag);
2475 	t = btf_add_type_mem(btf, sz);
2476 	if (!t)
2477 		return libbpf_err(-ENOMEM);
2478 
2479 	value_off = btf__add_str(btf, value);
2480 	if (value_off < 0)
2481 		return value_off;
2482 
2483 	t->name_off = value_off;
2484 	t->info = btf_type_info(BTF_KIND_TAG, 0, false);
2485 	t->type = ref_type_id;
2486 	btf_tag(t)->component_idx = component_idx;
2487 
2488 	return btf_commit_type(btf, sz);
2489 }
2490 
2491 struct btf_ext_sec_setup_param {
2492 	__u32 off;
2493 	__u32 len;
2494 	__u32 min_rec_size;
2495 	struct btf_ext_info *ext_info;
2496 	const char *desc;
2497 };
2498 
2499 static int btf_ext_setup_info(struct btf_ext *btf_ext,
2500 			      struct btf_ext_sec_setup_param *ext_sec)
2501 {
2502 	const struct btf_ext_info_sec *sinfo;
2503 	struct btf_ext_info *ext_info;
2504 	__u32 info_left, record_size;
2505 	/* The start of the info sec (including the __u32 record_size). */
2506 	void *info;
2507 
2508 	if (ext_sec->len == 0)
2509 		return 0;
2510 
2511 	if (ext_sec->off & 0x03) {
2512 		pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n",
2513 		     ext_sec->desc);
2514 		return -EINVAL;
2515 	}
2516 
2517 	info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off;
2518 	info_left = ext_sec->len;
2519 
2520 	if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) {
2521 		pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n",
2522 			 ext_sec->desc, ext_sec->off, ext_sec->len);
2523 		return -EINVAL;
2524 	}
2525 
2526 	/* At least a record size */
2527 	if (info_left < sizeof(__u32)) {
2528 		pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc);
2529 		return -EINVAL;
2530 	}
2531 
2532 	/* The record size needs to meet the minimum standard */
2533 	record_size = *(__u32 *)info;
2534 	if (record_size < ext_sec->min_rec_size ||
2535 	    record_size & 0x03) {
2536 		pr_debug("%s section in .BTF.ext has invalid record size %u\n",
2537 			 ext_sec->desc, record_size);
2538 		return -EINVAL;
2539 	}
2540 
2541 	sinfo = info + sizeof(__u32);
2542 	info_left -= sizeof(__u32);
2543 
2544 	/* If no records, return failure now so .BTF.ext won't be used. */
2545 	if (!info_left) {
2546 		pr_debug("%s section in .BTF.ext has no records", ext_sec->desc);
2547 		return -EINVAL;
2548 	}
2549 
2550 	while (info_left) {
2551 		unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec);
2552 		__u64 total_record_size;
2553 		__u32 num_records;
2554 
2555 		if (info_left < sec_hdrlen) {
2556 			pr_debug("%s section header is not found in .BTF.ext\n",
2557 			     ext_sec->desc);
2558 			return -EINVAL;
2559 		}
2560 
2561 		num_records = sinfo->num_info;
2562 		if (num_records == 0) {
2563 			pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2564 			     ext_sec->desc);
2565 			return -EINVAL;
2566 		}
2567 
2568 		total_record_size = sec_hdrlen +
2569 				    (__u64)num_records * record_size;
2570 		if (info_left < total_record_size) {
2571 			pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2572 			     ext_sec->desc);
2573 			return -EINVAL;
2574 		}
2575 
2576 		info_left -= total_record_size;
2577 		sinfo = (void *)sinfo + total_record_size;
2578 	}
2579 
2580 	ext_info = ext_sec->ext_info;
2581 	ext_info->len = ext_sec->len - sizeof(__u32);
2582 	ext_info->rec_size = record_size;
2583 	ext_info->info = info + sizeof(__u32);
2584 
2585 	return 0;
2586 }
2587 
2588 static int btf_ext_setup_func_info(struct btf_ext *btf_ext)
2589 {
2590 	struct btf_ext_sec_setup_param param = {
2591 		.off = btf_ext->hdr->func_info_off,
2592 		.len = btf_ext->hdr->func_info_len,
2593 		.min_rec_size = sizeof(struct bpf_func_info_min),
2594 		.ext_info = &btf_ext->func_info,
2595 		.desc = "func_info"
2596 	};
2597 
2598 	return btf_ext_setup_info(btf_ext, &param);
2599 }
2600 
2601 static int btf_ext_setup_line_info(struct btf_ext *btf_ext)
2602 {
2603 	struct btf_ext_sec_setup_param param = {
2604 		.off = btf_ext->hdr->line_info_off,
2605 		.len = btf_ext->hdr->line_info_len,
2606 		.min_rec_size = sizeof(struct bpf_line_info_min),
2607 		.ext_info = &btf_ext->line_info,
2608 		.desc = "line_info",
2609 	};
2610 
2611 	return btf_ext_setup_info(btf_ext, &param);
2612 }
2613 
2614 static int btf_ext_setup_core_relos(struct btf_ext *btf_ext)
2615 {
2616 	struct btf_ext_sec_setup_param param = {
2617 		.off = btf_ext->hdr->core_relo_off,
2618 		.len = btf_ext->hdr->core_relo_len,
2619 		.min_rec_size = sizeof(struct bpf_core_relo),
2620 		.ext_info = &btf_ext->core_relo_info,
2621 		.desc = "core_relo",
2622 	};
2623 
2624 	return btf_ext_setup_info(btf_ext, &param);
2625 }
2626 
2627 static int btf_ext_parse_hdr(__u8 *data, __u32 data_size)
2628 {
2629 	const struct btf_ext_header *hdr = (struct btf_ext_header *)data;
2630 
2631 	if (data_size < offsetofend(struct btf_ext_header, hdr_len) ||
2632 	    data_size < hdr->hdr_len) {
2633 		pr_debug("BTF.ext header not found");
2634 		return -EINVAL;
2635 	}
2636 
2637 	if (hdr->magic == bswap_16(BTF_MAGIC)) {
2638 		pr_warn("BTF.ext in non-native endianness is not supported\n");
2639 		return -ENOTSUP;
2640 	} else if (hdr->magic != BTF_MAGIC) {
2641 		pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic);
2642 		return -EINVAL;
2643 	}
2644 
2645 	if (hdr->version != BTF_VERSION) {
2646 		pr_debug("Unsupported BTF.ext version:%u\n", hdr->version);
2647 		return -ENOTSUP;
2648 	}
2649 
2650 	if (hdr->flags) {
2651 		pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags);
2652 		return -ENOTSUP;
2653 	}
2654 
2655 	if (data_size == hdr->hdr_len) {
2656 		pr_debug("BTF.ext has no data\n");
2657 		return -EINVAL;
2658 	}
2659 
2660 	return 0;
2661 }
2662 
2663 void btf_ext__free(struct btf_ext *btf_ext)
2664 {
2665 	if (IS_ERR_OR_NULL(btf_ext))
2666 		return;
2667 	free(btf_ext->data);
2668 	free(btf_ext);
2669 }
2670 
2671 struct btf_ext *btf_ext__new(__u8 *data, __u32 size)
2672 {
2673 	struct btf_ext *btf_ext;
2674 	int err;
2675 
2676 	err = btf_ext_parse_hdr(data, size);
2677 	if (err)
2678 		return libbpf_err_ptr(err);
2679 
2680 	btf_ext = calloc(1, sizeof(struct btf_ext));
2681 	if (!btf_ext)
2682 		return libbpf_err_ptr(-ENOMEM);
2683 
2684 	btf_ext->data_size = size;
2685 	btf_ext->data = malloc(size);
2686 	if (!btf_ext->data) {
2687 		err = -ENOMEM;
2688 		goto done;
2689 	}
2690 	memcpy(btf_ext->data, data, size);
2691 
2692 	if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, line_info_len)) {
2693 		err = -EINVAL;
2694 		goto done;
2695 	}
2696 
2697 	err = btf_ext_setup_func_info(btf_ext);
2698 	if (err)
2699 		goto done;
2700 
2701 	err = btf_ext_setup_line_info(btf_ext);
2702 	if (err)
2703 		goto done;
2704 
2705 	if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len)) {
2706 		err = -EINVAL;
2707 		goto done;
2708 	}
2709 
2710 	err = btf_ext_setup_core_relos(btf_ext);
2711 	if (err)
2712 		goto done;
2713 
2714 done:
2715 	if (err) {
2716 		btf_ext__free(btf_ext);
2717 		return libbpf_err_ptr(err);
2718 	}
2719 
2720 	return btf_ext;
2721 }
2722 
2723 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size)
2724 {
2725 	*size = btf_ext->data_size;
2726 	return btf_ext->data;
2727 }
2728 
2729 static int btf_ext_reloc_info(const struct btf *btf,
2730 			      const struct btf_ext_info *ext_info,
2731 			      const char *sec_name, __u32 insns_cnt,
2732 			      void **info, __u32 *cnt)
2733 {
2734 	__u32 sec_hdrlen = sizeof(struct btf_ext_info_sec);
2735 	__u32 i, record_size, existing_len, records_len;
2736 	struct btf_ext_info_sec *sinfo;
2737 	const char *info_sec_name;
2738 	__u64 remain_len;
2739 	void *data;
2740 
2741 	record_size = ext_info->rec_size;
2742 	sinfo = ext_info->info;
2743 	remain_len = ext_info->len;
2744 	while (remain_len > 0) {
2745 		records_len = sinfo->num_info * record_size;
2746 		info_sec_name = btf__name_by_offset(btf, sinfo->sec_name_off);
2747 		if (strcmp(info_sec_name, sec_name)) {
2748 			remain_len -= sec_hdrlen + records_len;
2749 			sinfo = (void *)sinfo + sec_hdrlen + records_len;
2750 			continue;
2751 		}
2752 
2753 		existing_len = (*cnt) * record_size;
2754 		data = realloc(*info, existing_len + records_len);
2755 		if (!data)
2756 			return libbpf_err(-ENOMEM);
2757 
2758 		memcpy(data + existing_len, sinfo->data, records_len);
2759 		/* adjust insn_off only, the rest data will be passed
2760 		 * to the kernel.
2761 		 */
2762 		for (i = 0; i < sinfo->num_info; i++) {
2763 			__u32 *insn_off;
2764 
2765 			insn_off = data + existing_len + (i * record_size);
2766 			*insn_off = *insn_off / sizeof(struct bpf_insn) + insns_cnt;
2767 		}
2768 		*info = data;
2769 		*cnt += sinfo->num_info;
2770 		return 0;
2771 	}
2772 
2773 	return libbpf_err(-ENOENT);
2774 }
2775 
2776 int btf_ext__reloc_func_info(const struct btf *btf,
2777 			     const struct btf_ext *btf_ext,
2778 			     const char *sec_name, __u32 insns_cnt,
2779 			     void **func_info, __u32 *cnt)
2780 {
2781 	return btf_ext_reloc_info(btf, &btf_ext->func_info, sec_name,
2782 				  insns_cnt, func_info, cnt);
2783 }
2784 
2785 int btf_ext__reloc_line_info(const struct btf *btf,
2786 			     const struct btf_ext *btf_ext,
2787 			     const char *sec_name, __u32 insns_cnt,
2788 			     void **line_info, __u32 *cnt)
2789 {
2790 	return btf_ext_reloc_info(btf, &btf_ext->line_info, sec_name,
2791 				  insns_cnt, line_info, cnt);
2792 }
2793 
2794 __u32 btf_ext__func_info_rec_size(const struct btf_ext *btf_ext)
2795 {
2796 	return btf_ext->func_info.rec_size;
2797 }
2798 
2799 __u32 btf_ext__line_info_rec_size(const struct btf_ext *btf_ext)
2800 {
2801 	return btf_ext->line_info.rec_size;
2802 }
2803 
2804 struct btf_dedup;
2805 
2806 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
2807 				       const struct btf_dedup_opts *opts);
2808 static void btf_dedup_free(struct btf_dedup *d);
2809 static int btf_dedup_prep(struct btf_dedup *d);
2810 static int btf_dedup_strings(struct btf_dedup *d);
2811 static int btf_dedup_prim_types(struct btf_dedup *d);
2812 static int btf_dedup_struct_types(struct btf_dedup *d);
2813 static int btf_dedup_ref_types(struct btf_dedup *d);
2814 static int btf_dedup_compact_types(struct btf_dedup *d);
2815 static int btf_dedup_remap_types(struct btf_dedup *d);
2816 
2817 /*
2818  * Deduplicate BTF types and strings.
2819  *
2820  * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF
2821  * section with all BTF type descriptors and string data. It overwrites that
2822  * memory in-place with deduplicated types and strings without any loss of
2823  * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section
2824  * is provided, all the strings referenced from .BTF.ext section are honored
2825  * and updated to point to the right offsets after deduplication.
2826  *
2827  * If function returns with error, type/string data might be garbled and should
2828  * be discarded.
2829  *
2830  * More verbose and detailed description of both problem btf_dedup is solving,
2831  * as well as solution could be found at:
2832  * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html
2833  *
2834  * Problem description and justification
2835  * =====================================
2836  *
2837  * BTF type information is typically emitted either as a result of conversion
2838  * from DWARF to BTF or directly by compiler. In both cases, each compilation
2839  * unit contains information about a subset of all the types that are used
2840  * in an application. These subsets are frequently overlapping and contain a lot
2841  * of duplicated information when later concatenated together into a single
2842  * binary. This algorithm ensures that each unique type is represented by single
2843  * BTF type descriptor, greatly reducing resulting size of BTF data.
2844  *
2845  * Compilation unit isolation and subsequent duplication of data is not the only
2846  * problem. The same type hierarchy (e.g., struct and all the type that struct
2847  * references) in different compilation units can be represented in BTF to
2848  * various degrees of completeness (or, rather, incompleteness) due to
2849  * struct/union forward declarations.
2850  *
2851  * Let's take a look at an example, that we'll use to better understand the
2852  * problem (and solution). Suppose we have two compilation units, each using
2853  * same `struct S`, but each of them having incomplete type information about
2854  * struct's fields:
2855  *
2856  * // CU #1:
2857  * struct S;
2858  * struct A {
2859  *	int a;
2860  *	struct A* self;
2861  *	struct S* parent;
2862  * };
2863  * struct B;
2864  * struct S {
2865  *	struct A* a_ptr;
2866  *	struct B* b_ptr;
2867  * };
2868  *
2869  * // CU #2:
2870  * struct S;
2871  * struct A;
2872  * struct B {
2873  *	int b;
2874  *	struct B* self;
2875  *	struct S* parent;
2876  * };
2877  * struct S {
2878  *	struct A* a_ptr;
2879  *	struct B* b_ptr;
2880  * };
2881  *
2882  * In case of CU #1, BTF data will know only that `struct B` exist (but no
2883  * more), but will know the complete type information about `struct A`. While
2884  * for CU #2, it will know full type information about `struct B`, but will
2885  * only know about forward declaration of `struct A` (in BTF terms, it will
2886  * have `BTF_KIND_FWD` type descriptor with name `B`).
2887  *
2888  * This compilation unit isolation means that it's possible that there is no
2889  * single CU with complete type information describing structs `S`, `A`, and
2890  * `B`. Also, we might get tons of duplicated and redundant type information.
2891  *
2892  * Additional complication we need to keep in mind comes from the fact that
2893  * types, in general, can form graphs containing cycles, not just DAGs.
2894  *
2895  * While algorithm does deduplication, it also merges and resolves type
2896  * information (unless disabled throught `struct btf_opts`), whenever possible.
2897  * E.g., in the example above with two compilation units having partial type
2898  * information for structs `A` and `B`, the output of algorithm will emit
2899  * a single copy of each BTF type that describes structs `A`, `B`, and `S`
2900  * (as well as type information for `int` and pointers), as if they were defined
2901  * in a single compilation unit as:
2902  *
2903  * struct A {
2904  *	int a;
2905  *	struct A* self;
2906  *	struct S* parent;
2907  * };
2908  * struct B {
2909  *	int b;
2910  *	struct B* self;
2911  *	struct S* parent;
2912  * };
2913  * struct S {
2914  *	struct A* a_ptr;
2915  *	struct B* b_ptr;
2916  * };
2917  *
2918  * Algorithm summary
2919  * =================
2920  *
2921  * Algorithm completes its work in 6 separate passes:
2922  *
2923  * 1. Strings deduplication.
2924  * 2. Primitive types deduplication (int, enum, fwd).
2925  * 3. Struct/union types deduplication.
2926  * 4. Reference types deduplication (pointers, typedefs, arrays, funcs, func
2927  *    protos, and const/volatile/restrict modifiers).
2928  * 5. Types compaction.
2929  * 6. Types remapping.
2930  *
2931  * Algorithm determines canonical type descriptor, which is a single
2932  * representative type for each truly unique type. This canonical type is the
2933  * one that will go into final deduplicated BTF type information. For
2934  * struct/unions, it is also the type that algorithm will merge additional type
2935  * information into (while resolving FWDs), as it discovers it from data in
2936  * other CUs. Each input BTF type eventually gets either mapped to itself, if
2937  * that type is canonical, or to some other type, if that type is equivalent
2938  * and was chosen as canonical representative. This mapping is stored in
2939  * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that
2940  * FWD type got resolved to.
2941  *
2942  * To facilitate fast discovery of canonical types, we also maintain canonical
2943  * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash
2944  * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types
2945  * that match that signature. With sufficiently good choice of type signature
2946  * hashing function, we can limit number of canonical types for each unique type
2947  * signature to a very small number, allowing to find canonical type for any
2948  * duplicated type very quickly.
2949  *
2950  * Struct/union deduplication is the most critical part and algorithm for
2951  * deduplicating structs/unions is described in greater details in comments for
2952  * `btf_dedup_is_equiv` function.
2953  */
2954 int btf__dedup(struct btf *btf, struct btf_ext *btf_ext,
2955 	       const struct btf_dedup_opts *opts)
2956 {
2957 	struct btf_dedup *d = btf_dedup_new(btf, btf_ext, opts);
2958 	int err;
2959 
2960 	if (IS_ERR(d)) {
2961 		pr_debug("btf_dedup_new failed: %ld", PTR_ERR(d));
2962 		return libbpf_err(-EINVAL);
2963 	}
2964 
2965 	if (btf_ensure_modifiable(btf))
2966 		return libbpf_err(-ENOMEM);
2967 
2968 	err = btf_dedup_prep(d);
2969 	if (err) {
2970 		pr_debug("btf_dedup_prep failed:%d\n", err);
2971 		goto done;
2972 	}
2973 	err = btf_dedup_strings(d);
2974 	if (err < 0) {
2975 		pr_debug("btf_dedup_strings failed:%d\n", err);
2976 		goto done;
2977 	}
2978 	err = btf_dedup_prim_types(d);
2979 	if (err < 0) {
2980 		pr_debug("btf_dedup_prim_types failed:%d\n", err);
2981 		goto done;
2982 	}
2983 	err = btf_dedup_struct_types(d);
2984 	if (err < 0) {
2985 		pr_debug("btf_dedup_struct_types failed:%d\n", err);
2986 		goto done;
2987 	}
2988 	err = btf_dedup_ref_types(d);
2989 	if (err < 0) {
2990 		pr_debug("btf_dedup_ref_types failed:%d\n", err);
2991 		goto done;
2992 	}
2993 	err = btf_dedup_compact_types(d);
2994 	if (err < 0) {
2995 		pr_debug("btf_dedup_compact_types failed:%d\n", err);
2996 		goto done;
2997 	}
2998 	err = btf_dedup_remap_types(d);
2999 	if (err < 0) {
3000 		pr_debug("btf_dedup_remap_types failed:%d\n", err);
3001 		goto done;
3002 	}
3003 
3004 done:
3005 	btf_dedup_free(d);
3006 	return libbpf_err(err);
3007 }
3008 
3009 #define BTF_UNPROCESSED_ID ((__u32)-1)
3010 #define BTF_IN_PROGRESS_ID ((__u32)-2)
3011 
3012 struct btf_dedup {
3013 	/* .BTF section to be deduped in-place */
3014 	struct btf *btf;
3015 	/*
3016 	 * Optional .BTF.ext section. When provided, any strings referenced
3017 	 * from it will be taken into account when deduping strings
3018 	 */
3019 	struct btf_ext *btf_ext;
3020 	/*
3021 	 * This is a map from any type's signature hash to a list of possible
3022 	 * canonical representative type candidates. Hash collisions are
3023 	 * ignored, so even types of various kinds can share same list of
3024 	 * candidates, which is fine because we rely on subsequent
3025 	 * btf_xxx_equal() checks to authoritatively verify type equality.
3026 	 */
3027 	struct hashmap *dedup_table;
3028 	/* Canonical types map */
3029 	__u32 *map;
3030 	/* Hypothetical mapping, used during type graph equivalence checks */
3031 	__u32 *hypot_map;
3032 	__u32 *hypot_list;
3033 	size_t hypot_cnt;
3034 	size_t hypot_cap;
3035 	/* Whether hypothetical mapping, if successful, would need to adjust
3036 	 * already canonicalized types (due to a new forward declaration to
3037 	 * concrete type resolution). In such case, during split BTF dedup
3038 	 * candidate type would still be considered as different, because base
3039 	 * BTF is considered to be immutable.
3040 	 */
3041 	bool hypot_adjust_canon;
3042 	/* Various option modifying behavior of algorithm */
3043 	struct btf_dedup_opts opts;
3044 	/* temporary strings deduplication state */
3045 	struct strset *strs_set;
3046 };
3047 
3048 static long hash_combine(long h, long value)
3049 {
3050 	return h * 31 + value;
3051 }
3052 
3053 #define for_each_dedup_cand(d, node, hash) \
3054 	hashmap__for_each_key_entry(d->dedup_table, node, (void *)hash)
3055 
3056 static int btf_dedup_table_add(struct btf_dedup *d, long hash, __u32 type_id)
3057 {
3058 	return hashmap__append(d->dedup_table,
3059 			       (void *)hash, (void *)(long)type_id);
3060 }
3061 
3062 static int btf_dedup_hypot_map_add(struct btf_dedup *d,
3063 				   __u32 from_id, __u32 to_id)
3064 {
3065 	if (d->hypot_cnt == d->hypot_cap) {
3066 		__u32 *new_list;
3067 
3068 		d->hypot_cap += max((size_t)16, d->hypot_cap / 2);
3069 		new_list = libbpf_reallocarray(d->hypot_list, d->hypot_cap, sizeof(__u32));
3070 		if (!new_list)
3071 			return -ENOMEM;
3072 		d->hypot_list = new_list;
3073 	}
3074 	d->hypot_list[d->hypot_cnt++] = from_id;
3075 	d->hypot_map[from_id] = to_id;
3076 	return 0;
3077 }
3078 
3079 static void btf_dedup_clear_hypot_map(struct btf_dedup *d)
3080 {
3081 	int i;
3082 
3083 	for (i = 0; i < d->hypot_cnt; i++)
3084 		d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID;
3085 	d->hypot_cnt = 0;
3086 	d->hypot_adjust_canon = false;
3087 }
3088 
3089 static void btf_dedup_free(struct btf_dedup *d)
3090 {
3091 	hashmap__free(d->dedup_table);
3092 	d->dedup_table = NULL;
3093 
3094 	free(d->map);
3095 	d->map = NULL;
3096 
3097 	free(d->hypot_map);
3098 	d->hypot_map = NULL;
3099 
3100 	free(d->hypot_list);
3101 	d->hypot_list = NULL;
3102 
3103 	free(d);
3104 }
3105 
3106 static size_t btf_dedup_identity_hash_fn(const void *key, void *ctx)
3107 {
3108 	return (size_t)key;
3109 }
3110 
3111 static size_t btf_dedup_collision_hash_fn(const void *key, void *ctx)
3112 {
3113 	return 0;
3114 }
3115 
3116 static bool btf_dedup_equal_fn(const void *k1, const void *k2, void *ctx)
3117 {
3118 	return k1 == k2;
3119 }
3120 
3121 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
3122 				       const struct btf_dedup_opts *opts)
3123 {
3124 	struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup));
3125 	hashmap_hash_fn hash_fn = btf_dedup_identity_hash_fn;
3126 	int i, err = 0, type_cnt;
3127 
3128 	if (!d)
3129 		return ERR_PTR(-ENOMEM);
3130 
3131 	d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds;
3132 	/* dedup_table_size is now used only to force collisions in tests */
3133 	if (opts && opts->dedup_table_size == 1)
3134 		hash_fn = btf_dedup_collision_hash_fn;
3135 
3136 	d->btf = btf;
3137 	d->btf_ext = btf_ext;
3138 
3139 	d->dedup_table = hashmap__new(hash_fn, btf_dedup_equal_fn, NULL);
3140 	if (IS_ERR(d->dedup_table)) {
3141 		err = PTR_ERR(d->dedup_table);
3142 		d->dedup_table = NULL;
3143 		goto done;
3144 	}
3145 
3146 	type_cnt = btf__get_nr_types(btf) + 1;
3147 	d->map = malloc(sizeof(__u32) * type_cnt);
3148 	if (!d->map) {
3149 		err = -ENOMEM;
3150 		goto done;
3151 	}
3152 	/* special BTF "void" type is made canonical immediately */
3153 	d->map[0] = 0;
3154 	for (i = 1; i < type_cnt; i++) {
3155 		struct btf_type *t = btf_type_by_id(d->btf, i);
3156 
3157 		/* VAR and DATASEC are never deduped and are self-canonical */
3158 		if (btf_is_var(t) || btf_is_datasec(t))
3159 			d->map[i] = i;
3160 		else
3161 			d->map[i] = BTF_UNPROCESSED_ID;
3162 	}
3163 
3164 	d->hypot_map = malloc(sizeof(__u32) * type_cnt);
3165 	if (!d->hypot_map) {
3166 		err = -ENOMEM;
3167 		goto done;
3168 	}
3169 	for (i = 0; i < type_cnt; i++)
3170 		d->hypot_map[i] = BTF_UNPROCESSED_ID;
3171 
3172 done:
3173 	if (err) {
3174 		btf_dedup_free(d);
3175 		return ERR_PTR(err);
3176 	}
3177 
3178 	return d;
3179 }
3180 
3181 /*
3182  * Iterate over all possible places in .BTF and .BTF.ext that can reference
3183  * string and pass pointer to it to a provided callback `fn`.
3184  */
3185 static int btf_for_each_str_off(struct btf_dedup *d, str_off_visit_fn fn, void *ctx)
3186 {
3187 	int i, r;
3188 
3189 	for (i = 0; i < d->btf->nr_types; i++) {
3190 		struct btf_type *t = btf_type_by_id(d->btf, d->btf->start_id + i);
3191 
3192 		r = btf_type_visit_str_offs(t, fn, ctx);
3193 		if (r)
3194 			return r;
3195 	}
3196 
3197 	if (!d->btf_ext)
3198 		return 0;
3199 
3200 	r = btf_ext_visit_str_offs(d->btf_ext, fn, ctx);
3201 	if (r)
3202 		return r;
3203 
3204 	return 0;
3205 }
3206 
3207 static int strs_dedup_remap_str_off(__u32 *str_off_ptr, void *ctx)
3208 {
3209 	struct btf_dedup *d = ctx;
3210 	__u32 str_off = *str_off_ptr;
3211 	const char *s;
3212 	int off, err;
3213 
3214 	/* don't touch empty string or string in main BTF */
3215 	if (str_off == 0 || str_off < d->btf->start_str_off)
3216 		return 0;
3217 
3218 	s = btf__str_by_offset(d->btf, str_off);
3219 	if (d->btf->base_btf) {
3220 		err = btf__find_str(d->btf->base_btf, s);
3221 		if (err >= 0) {
3222 			*str_off_ptr = err;
3223 			return 0;
3224 		}
3225 		if (err != -ENOENT)
3226 			return err;
3227 	}
3228 
3229 	off = strset__add_str(d->strs_set, s);
3230 	if (off < 0)
3231 		return off;
3232 
3233 	*str_off_ptr = d->btf->start_str_off + off;
3234 	return 0;
3235 }
3236 
3237 /*
3238  * Dedup string and filter out those that are not referenced from either .BTF
3239  * or .BTF.ext (if provided) sections.
3240  *
3241  * This is done by building index of all strings in BTF's string section,
3242  * then iterating over all entities that can reference strings (e.g., type
3243  * names, struct field names, .BTF.ext line info, etc) and marking corresponding
3244  * strings as used. After that all used strings are deduped and compacted into
3245  * sequential blob of memory and new offsets are calculated. Then all the string
3246  * references are iterated again and rewritten using new offsets.
3247  */
3248 static int btf_dedup_strings(struct btf_dedup *d)
3249 {
3250 	int err;
3251 
3252 	if (d->btf->strs_deduped)
3253 		return 0;
3254 
3255 	d->strs_set = strset__new(BTF_MAX_STR_OFFSET, NULL, 0);
3256 	if (IS_ERR(d->strs_set)) {
3257 		err = PTR_ERR(d->strs_set);
3258 		goto err_out;
3259 	}
3260 
3261 	if (!d->btf->base_btf) {
3262 		/* insert empty string; we won't be looking it up during strings
3263 		 * dedup, but it's good to have it for generic BTF string lookups
3264 		 */
3265 		err = strset__add_str(d->strs_set, "");
3266 		if (err < 0)
3267 			goto err_out;
3268 	}
3269 
3270 	/* remap string offsets */
3271 	err = btf_for_each_str_off(d, strs_dedup_remap_str_off, d);
3272 	if (err)
3273 		goto err_out;
3274 
3275 	/* replace BTF string data and hash with deduped ones */
3276 	strset__free(d->btf->strs_set);
3277 	d->btf->hdr->str_len = strset__data_size(d->strs_set);
3278 	d->btf->strs_set = d->strs_set;
3279 	d->strs_set = NULL;
3280 	d->btf->strs_deduped = true;
3281 	return 0;
3282 
3283 err_out:
3284 	strset__free(d->strs_set);
3285 	d->strs_set = NULL;
3286 
3287 	return err;
3288 }
3289 
3290 static long btf_hash_common(struct btf_type *t)
3291 {
3292 	long h;
3293 
3294 	h = hash_combine(0, t->name_off);
3295 	h = hash_combine(h, t->info);
3296 	h = hash_combine(h, t->size);
3297 	return h;
3298 }
3299 
3300 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2)
3301 {
3302 	return t1->name_off == t2->name_off &&
3303 	       t1->info == t2->info &&
3304 	       t1->size == t2->size;
3305 }
3306 
3307 /* Calculate type signature hash of INT or TAG. */
3308 static long btf_hash_int_tag(struct btf_type *t)
3309 {
3310 	__u32 info = *(__u32 *)(t + 1);
3311 	long h;
3312 
3313 	h = btf_hash_common(t);
3314 	h = hash_combine(h, info);
3315 	return h;
3316 }
3317 
3318 /* Check structural equality of two INTs or TAGs. */
3319 static bool btf_equal_int_tag(struct btf_type *t1, struct btf_type *t2)
3320 {
3321 	__u32 info1, info2;
3322 
3323 	if (!btf_equal_common(t1, t2))
3324 		return false;
3325 	info1 = *(__u32 *)(t1 + 1);
3326 	info2 = *(__u32 *)(t2 + 1);
3327 	return info1 == info2;
3328 }
3329 
3330 /* Calculate type signature hash of ENUM. */
3331 static long btf_hash_enum(struct btf_type *t)
3332 {
3333 	long h;
3334 
3335 	/* don't hash vlen and enum members to support enum fwd resolving */
3336 	h = hash_combine(0, t->name_off);
3337 	h = hash_combine(h, t->info & ~0xffff);
3338 	h = hash_combine(h, t->size);
3339 	return h;
3340 }
3341 
3342 /* Check structural equality of two ENUMs. */
3343 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2)
3344 {
3345 	const struct btf_enum *m1, *m2;
3346 	__u16 vlen;
3347 	int i;
3348 
3349 	if (!btf_equal_common(t1, t2))
3350 		return false;
3351 
3352 	vlen = btf_vlen(t1);
3353 	m1 = btf_enum(t1);
3354 	m2 = btf_enum(t2);
3355 	for (i = 0; i < vlen; i++) {
3356 		if (m1->name_off != m2->name_off || m1->val != m2->val)
3357 			return false;
3358 		m1++;
3359 		m2++;
3360 	}
3361 	return true;
3362 }
3363 
3364 static inline bool btf_is_enum_fwd(struct btf_type *t)
3365 {
3366 	return btf_is_enum(t) && btf_vlen(t) == 0;
3367 }
3368 
3369 static bool btf_compat_enum(struct btf_type *t1, struct btf_type *t2)
3370 {
3371 	if (!btf_is_enum_fwd(t1) && !btf_is_enum_fwd(t2))
3372 		return btf_equal_enum(t1, t2);
3373 	/* ignore vlen when comparing */
3374 	return t1->name_off == t2->name_off &&
3375 	       (t1->info & ~0xffff) == (t2->info & ~0xffff) &&
3376 	       t1->size == t2->size;
3377 }
3378 
3379 /*
3380  * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs,
3381  * as referenced type IDs equivalence is established separately during type
3382  * graph equivalence check algorithm.
3383  */
3384 static long btf_hash_struct(struct btf_type *t)
3385 {
3386 	const struct btf_member *member = btf_members(t);
3387 	__u32 vlen = btf_vlen(t);
3388 	long h = btf_hash_common(t);
3389 	int i;
3390 
3391 	for (i = 0; i < vlen; i++) {
3392 		h = hash_combine(h, member->name_off);
3393 		h = hash_combine(h, member->offset);
3394 		/* no hashing of referenced type ID, it can be unresolved yet */
3395 		member++;
3396 	}
3397 	return h;
3398 }
3399 
3400 /*
3401  * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
3402  * IDs. This check is performed during type graph equivalence check and
3403  * referenced types equivalence is checked separately.
3404  */
3405 static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2)
3406 {
3407 	const struct btf_member *m1, *m2;
3408 	__u16 vlen;
3409 	int i;
3410 
3411 	if (!btf_equal_common(t1, t2))
3412 		return false;
3413 
3414 	vlen = btf_vlen(t1);
3415 	m1 = btf_members(t1);
3416 	m2 = btf_members(t2);
3417 	for (i = 0; i < vlen; i++) {
3418 		if (m1->name_off != m2->name_off || m1->offset != m2->offset)
3419 			return false;
3420 		m1++;
3421 		m2++;
3422 	}
3423 	return true;
3424 }
3425 
3426 /*
3427  * Calculate type signature hash of ARRAY, including referenced type IDs,
3428  * under assumption that they were already resolved to canonical type IDs and
3429  * are not going to change.
3430  */
3431 static long btf_hash_array(struct btf_type *t)
3432 {
3433 	const struct btf_array *info = btf_array(t);
3434 	long h = btf_hash_common(t);
3435 
3436 	h = hash_combine(h, info->type);
3437 	h = hash_combine(h, info->index_type);
3438 	h = hash_combine(h, info->nelems);
3439 	return h;
3440 }
3441 
3442 /*
3443  * Check exact equality of two ARRAYs, taking into account referenced
3444  * type IDs, under assumption that they were already resolved to canonical
3445  * type IDs and are not going to change.
3446  * This function is called during reference types deduplication to compare
3447  * ARRAY to potential canonical representative.
3448  */
3449 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2)
3450 {
3451 	const struct btf_array *info1, *info2;
3452 
3453 	if (!btf_equal_common(t1, t2))
3454 		return false;
3455 
3456 	info1 = btf_array(t1);
3457 	info2 = btf_array(t2);
3458 	return info1->type == info2->type &&
3459 	       info1->index_type == info2->index_type &&
3460 	       info1->nelems == info2->nelems;
3461 }
3462 
3463 /*
3464  * Check structural compatibility of two ARRAYs, ignoring referenced type
3465  * IDs. This check is performed during type graph equivalence check and
3466  * referenced types equivalence is checked separately.
3467  */
3468 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2)
3469 {
3470 	if (!btf_equal_common(t1, t2))
3471 		return false;
3472 
3473 	return btf_array(t1)->nelems == btf_array(t2)->nelems;
3474 }
3475 
3476 /*
3477  * Calculate type signature hash of FUNC_PROTO, including referenced type IDs,
3478  * under assumption that they were already resolved to canonical type IDs and
3479  * are not going to change.
3480  */
3481 static long btf_hash_fnproto(struct btf_type *t)
3482 {
3483 	const struct btf_param *member = btf_params(t);
3484 	__u16 vlen = btf_vlen(t);
3485 	long h = btf_hash_common(t);
3486 	int i;
3487 
3488 	for (i = 0; i < vlen; i++) {
3489 		h = hash_combine(h, member->name_off);
3490 		h = hash_combine(h, member->type);
3491 		member++;
3492 	}
3493 	return h;
3494 }
3495 
3496 /*
3497  * Check exact equality of two FUNC_PROTOs, taking into account referenced
3498  * type IDs, under assumption that they were already resolved to canonical
3499  * type IDs and are not going to change.
3500  * This function is called during reference types deduplication to compare
3501  * FUNC_PROTO to potential canonical representative.
3502  */
3503 static bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2)
3504 {
3505 	const struct btf_param *m1, *m2;
3506 	__u16 vlen;
3507 	int i;
3508 
3509 	if (!btf_equal_common(t1, t2))
3510 		return false;
3511 
3512 	vlen = btf_vlen(t1);
3513 	m1 = btf_params(t1);
3514 	m2 = btf_params(t2);
3515 	for (i = 0; i < vlen; i++) {
3516 		if (m1->name_off != m2->name_off || m1->type != m2->type)
3517 			return false;
3518 		m1++;
3519 		m2++;
3520 	}
3521 	return true;
3522 }
3523 
3524 /*
3525  * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
3526  * IDs. This check is performed during type graph equivalence check and
3527  * referenced types equivalence is checked separately.
3528  */
3529 static bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2)
3530 {
3531 	const struct btf_param *m1, *m2;
3532 	__u16 vlen;
3533 	int i;
3534 
3535 	/* skip return type ID */
3536 	if (t1->name_off != t2->name_off || t1->info != t2->info)
3537 		return false;
3538 
3539 	vlen = btf_vlen(t1);
3540 	m1 = btf_params(t1);
3541 	m2 = btf_params(t2);
3542 	for (i = 0; i < vlen; i++) {
3543 		if (m1->name_off != m2->name_off)
3544 			return false;
3545 		m1++;
3546 		m2++;
3547 	}
3548 	return true;
3549 }
3550 
3551 /* Prepare split BTF for deduplication by calculating hashes of base BTF's
3552  * types and initializing the rest of the state (canonical type mapping) for
3553  * the fixed base BTF part.
3554  */
3555 static int btf_dedup_prep(struct btf_dedup *d)
3556 {
3557 	struct btf_type *t;
3558 	int type_id;
3559 	long h;
3560 
3561 	if (!d->btf->base_btf)
3562 		return 0;
3563 
3564 	for (type_id = 1; type_id < d->btf->start_id; type_id++) {
3565 		t = btf_type_by_id(d->btf, type_id);
3566 
3567 		/* all base BTF types are self-canonical by definition */
3568 		d->map[type_id] = type_id;
3569 
3570 		switch (btf_kind(t)) {
3571 		case BTF_KIND_VAR:
3572 		case BTF_KIND_DATASEC:
3573 			/* VAR and DATASEC are never hash/deduplicated */
3574 			continue;
3575 		case BTF_KIND_CONST:
3576 		case BTF_KIND_VOLATILE:
3577 		case BTF_KIND_RESTRICT:
3578 		case BTF_KIND_PTR:
3579 		case BTF_KIND_FWD:
3580 		case BTF_KIND_TYPEDEF:
3581 		case BTF_KIND_FUNC:
3582 		case BTF_KIND_FLOAT:
3583 			h = btf_hash_common(t);
3584 			break;
3585 		case BTF_KIND_INT:
3586 		case BTF_KIND_TAG:
3587 			h = btf_hash_int_tag(t);
3588 			break;
3589 		case BTF_KIND_ENUM:
3590 			h = btf_hash_enum(t);
3591 			break;
3592 		case BTF_KIND_STRUCT:
3593 		case BTF_KIND_UNION:
3594 			h = btf_hash_struct(t);
3595 			break;
3596 		case BTF_KIND_ARRAY:
3597 			h = btf_hash_array(t);
3598 			break;
3599 		case BTF_KIND_FUNC_PROTO:
3600 			h = btf_hash_fnproto(t);
3601 			break;
3602 		default:
3603 			pr_debug("unknown kind %d for type [%d]\n", btf_kind(t), type_id);
3604 			return -EINVAL;
3605 		}
3606 		if (btf_dedup_table_add(d, h, type_id))
3607 			return -ENOMEM;
3608 	}
3609 
3610 	return 0;
3611 }
3612 
3613 /*
3614  * Deduplicate primitive types, that can't reference other types, by calculating
3615  * their type signature hash and comparing them with any possible canonical
3616  * candidate. If no canonical candidate matches, type itself is marked as
3617  * canonical and is added into `btf_dedup->dedup_table` as another candidate.
3618  */
3619 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id)
3620 {
3621 	struct btf_type *t = btf_type_by_id(d->btf, type_id);
3622 	struct hashmap_entry *hash_entry;
3623 	struct btf_type *cand;
3624 	/* if we don't find equivalent type, then we are canonical */
3625 	__u32 new_id = type_id;
3626 	__u32 cand_id;
3627 	long h;
3628 
3629 	switch (btf_kind(t)) {
3630 	case BTF_KIND_CONST:
3631 	case BTF_KIND_VOLATILE:
3632 	case BTF_KIND_RESTRICT:
3633 	case BTF_KIND_PTR:
3634 	case BTF_KIND_TYPEDEF:
3635 	case BTF_KIND_ARRAY:
3636 	case BTF_KIND_STRUCT:
3637 	case BTF_KIND_UNION:
3638 	case BTF_KIND_FUNC:
3639 	case BTF_KIND_FUNC_PROTO:
3640 	case BTF_KIND_VAR:
3641 	case BTF_KIND_DATASEC:
3642 	case BTF_KIND_TAG:
3643 		return 0;
3644 
3645 	case BTF_KIND_INT:
3646 		h = btf_hash_int_tag(t);
3647 		for_each_dedup_cand(d, hash_entry, h) {
3648 			cand_id = (__u32)(long)hash_entry->value;
3649 			cand = btf_type_by_id(d->btf, cand_id);
3650 			if (btf_equal_int_tag(t, cand)) {
3651 				new_id = cand_id;
3652 				break;
3653 			}
3654 		}
3655 		break;
3656 
3657 	case BTF_KIND_ENUM:
3658 		h = btf_hash_enum(t);
3659 		for_each_dedup_cand(d, hash_entry, h) {
3660 			cand_id = (__u32)(long)hash_entry->value;
3661 			cand = btf_type_by_id(d->btf, cand_id);
3662 			if (btf_equal_enum(t, cand)) {
3663 				new_id = cand_id;
3664 				break;
3665 			}
3666 			if (d->opts.dont_resolve_fwds)
3667 				continue;
3668 			if (btf_compat_enum(t, cand)) {
3669 				if (btf_is_enum_fwd(t)) {
3670 					/* resolve fwd to full enum */
3671 					new_id = cand_id;
3672 					break;
3673 				}
3674 				/* resolve canonical enum fwd to full enum */
3675 				d->map[cand_id] = type_id;
3676 			}
3677 		}
3678 		break;
3679 
3680 	case BTF_KIND_FWD:
3681 	case BTF_KIND_FLOAT:
3682 		h = btf_hash_common(t);
3683 		for_each_dedup_cand(d, hash_entry, h) {
3684 			cand_id = (__u32)(long)hash_entry->value;
3685 			cand = btf_type_by_id(d->btf, cand_id);
3686 			if (btf_equal_common(t, cand)) {
3687 				new_id = cand_id;
3688 				break;
3689 			}
3690 		}
3691 		break;
3692 
3693 	default:
3694 		return -EINVAL;
3695 	}
3696 
3697 	d->map[type_id] = new_id;
3698 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
3699 		return -ENOMEM;
3700 
3701 	return 0;
3702 }
3703 
3704 static int btf_dedup_prim_types(struct btf_dedup *d)
3705 {
3706 	int i, err;
3707 
3708 	for (i = 0; i < d->btf->nr_types; i++) {
3709 		err = btf_dedup_prim_type(d, d->btf->start_id + i);
3710 		if (err)
3711 			return err;
3712 	}
3713 	return 0;
3714 }
3715 
3716 /*
3717  * Check whether type is already mapped into canonical one (could be to itself).
3718  */
3719 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id)
3720 {
3721 	return d->map[type_id] <= BTF_MAX_NR_TYPES;
3722 }
3723 
3724 /*
3725  * Resolve type ID into its canonical type ID, if any; otherwise return original
3726  * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow
3727  * STRUCT/UNION link and resolve it into canonical type ID as well.
3728  */
3729 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id)
3730 {
3731 	while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3732 		type_id = d->map[type_id];
3733 	return type_id;
3734 }
3735 
3736 /*
3737  * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original
3738  * type ID.
3739  */
3740 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id)
3741 {
3742 	__u32 orig_type_id = type_id;
3743 
3744 	if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3745 		return type_id;
3746 
3747 	while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3748 		type_id = d->map[type_id];
3749 
3750 	if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3751 		return type_id;
3752 
3753 	return orig_type_id;
3754 }
3755 
3756 
3757 static inline __u16 btf_fwd_kind(struct btf_type *t)
3758 {
3759 	return btf_kflag(t) ? BTF_KIND_UNION : BTF_KIND_STRUCT;
3760 }
3761 
3762 /* Check if given two types are identical ARRAY definitions */
3763 static int btf_dedup_identical_arrays(struct btf_dedup *d, __u32 id1, __u32 id2)
3764 {
3765 	struct btf_type *t1, *t2;
3766 
3767 	t1 = btf_type_by_id(d->btf, id1);
3768 	t2 = btf_type_by_id(d->btf, id2);
3769 	if (!btf_is_array(t1) || !btf_is_array(t2))
3770 		return 0;
3771 
3772 	return btf_equal_array(t1, t2);
3773 }
3774 
3775 /*
3776  * Check equivalence of BTF type graph formed by candidate struct/union (we'll
3777  * call it "candidate graph" in this description for brevity) to a type graph
3778  * formed by (potential) canonical struct/union ("canonical graph" for brevity
3779  * here, though keep in mind that not all types in canonical graph are
3780  * necessarily canonical representatives themselves, some of them might be
3781  * duplicates or its uniqueness might not have been established yet).
3782  * Returns:
3783  *  - >0, if type graphs are equivalent;
3784  *  -  0, if not equivalent;
3785  *  - <0, on error.
3786  *
3787  * Algorithm performs side-by-side DFS traversal of both type graphs and checks
3788  * equivalence of BTF types at each step. If at any point BTF types in candidate
3789  * and canonical graphs are not compatible structurally, whole graphs are
3790  * incompatible. If types are structurally equivalent (i.e., all information
3791  * except referenced type IDs is exactly the same), a mapping from `canon_id` to
3792  * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`).
3793  * If a type references other types, then those referenced types are checked
3794  * for equivalence recursively.
3795  *
3796  * During DFS traversal, if we find that for current `canon_id` type we
3797  * already have some mapping in hypothetical map, we check for two possible
3798  * situations:
3799  *   - `canon_id` is mapped to exactly the same type as `cand_id`. This will
3800  *     happen when type graphs have cycles. In this case we assume those two
3801  *     types are equivalent.
3802  *   - `canon_id` is mapped to different type. This is contradiction in our
3803  *     hypothetical mapping, because same graph in canonical graph corresponds
3804  *     to two different types in candidate graph, which for equivalent type
3805  *     graphs shouldn't happen. This condition terminates equivalence check
3806  *     with negative result.
3807  *
3808  * If type graphs traversal exhausts types to check and find no contradiction,
3809  * then type graphs are equivalent.
3810  *
3811  * When checking types for equivalence, there is one special case: FWD types.
3812  * If FWD type resolution is allowed and one of the types (either from canonical
3813  * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind
3814  * flag) and their names match, hypothetical mapping is updated to point from
3815  * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully,
3816  * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently.
3817  *
3818  * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution,
3819  * if there are two exactly named (or anonymous) structs/unions that are
3820  * compatible structurally, one of which has FWD field, while other is concrete
3821  * STRUCT/UNION, but according to C sources they are different structs/unions
3822  * that are referencing different types with the same name. This is extremely
3823  * unlikely to happen, but btf_dedup API allows to disable FWD resolution if
3824  * this logic is causing problems.
3825  *
3826  * Doing FWD resolution means that both candidate and/or canonical graphs can
3827  * consists of portions of the graph that come from multiple compilation units.
3828  * This is due to the fact that types within single compilation unit are always
3829  * deduplicated and FWDs are already resolved, if referenced struct/union
3830  * definiton is available. So, if we had unresolved FWD and found corresponding
3831  * STRUCT/UNION, they will be from different compilation units. This
3832  * consequently means that when we "link" FWD to corresponding STRUCT/UNION,
3833  * type graph will likely have at least two different BTF types that describe
3834  * same type (e.g., most probably there will be two different BTF types for the
3835  * same 'int' primitive type) and could even have "overlapping" parts of type
3836  * graph that describe same subset of types.
3837  *
3838  * This in turn means that our assumption that each type in canonical graph
3839  * must correspond to exactly one type in candidate graph might not hold
3840  * anymore and will make it harder to detect contradictions using hypothetical
3841  * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION
3842  * resolution only in canonical graph. FWDs in candidate graphs are never
3843  * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs
3844  * that can occur:
3845  *   - Both types in canonical and candidate graphs are FWDs. If they are
3846  *     structurally equivalent, then they can either be both resolved to the
3847  *     same STRUCT/UNION or not resolved at all. In both cases they are
3848  *     equivalent and there is no need to resolve FWD on candidate side.
3849  *   - Both types in canonical and candidate graphs are concrete STRUCT/UNION,
3850  *     so nothing to resolve as well, algorithm will check equivalence anyway.
3851  *   - Type in canonical graph is FWD, while type in candidate is concrete
3852  *     STRUCT/UNION. In this case candidate graph comes from single compilation
3853  *     unit, so there is exactly one BTF type for each unique C type. After
3854  *     resolving FWD into STRUCT/UNION, there might be more than one BTF type
3855  *     in canonical graph mapping to single BTF type in candidate graph, but
3856  *     because hypothetical mapping maps from canonical to candidate types, it's
3857  *     alright, and we still maintain the property of having single `canon_id`
3858  *     mapping to single `cand_id` (there could be two different `canon_id`
3859  *     mapped to the same `cand_id`, but it's not contradictory).
3860  *   - Type in canonical graph is concrete STRUCT/UNION, while type in candidate
3861  *     graph is FWD. In this case we are just going to check compatibility of
3862  *     STRUCT/UNION and corresponding FWD, and if they are compatible, we'll
3863  *     assume that whatever STRUCT/UNION FWD resolves to must be equivalent to
3864  *     a concrete STRUCT/UNION from canonical graph. If the rest of type graphs
3865  *     turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from
3866  *     canonical graph.
3867  */
3868 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id,
3869 			      __u32 canon_id)
3870 {
3871 	struct btf_type *cand_type;
3872 	struct btf_type *canon_type;
3873 	__u32 hypot_type_id;
3874 	__u16 cand_kind;
3875 	__u16 canon_kind;
3876 	int i, eq;
3877 
3878 	/* if both resolve to the same canonical, they must be equivalent */
3879 	if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id))
3880 		return 1;
3881 
3882 	canon_id = resolve_fwd_id(d, canon_id);
3883 
3884 	hypot_type_id = d->hypot_map[canon_id];
3885 	if (hypot_type_id <= BTF_MAX_NR_TYPES) {
3886 		/* In some cases compiler will generate different DWARF types
3887 		 * for *identical* array type definitions and use them for
3888 		 * different fields within the *same* struct. This breaks type
3889 		 * equivalence check, which makes an assumption that candidate
3890 		 * types sub-graph has a consistent and deduped-by-compiler
3891 		 * types within a single CU. So work around that by explicitly
3892 		 * allowing identical array types here.
3893 		 */
3894 		return hypot_type_id == cand_id ||
3895 		       btf_dedup_identical_arrays(d, hypot_type_id, cand_id);
3896 	}
3897 
3898 	if (btf_dedup_hypot_map_add(d, canon_id, cand_id))
3899 		return -ENOMEM;
3900 
3901 	cand_type = btf_type_by_id(d->btf, cand_id);
3902 	canon_type = btf_type_by_id(d->btf, canon_id);
3903 	cand_kind = btf_kind(cand_type);
3904 	canon_kind = btf_kind(canon_type);
3905 
3906 	if (cand_type->name_off != canon_type->name_off)
3907 		return 0;
3908 
3909 	/* FWD <--> STRUCT/UNION equivalence check, if enabled */
3910 	if (!d->opts.dont_resolve_fwds
3911 	    && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD)
3912 	    && cand_kind != canon_kind) {
3913 		__u16 real_kind;
3914 		__u16 fwd_kind;
3915 
3916 		if (cand_kind == BTF_KIND_FWD) {
3917 			real_kind = canon_kind;
3918 			fwd_kind = btf_fwd_kind(cand_type);
3919 		} else {
3920 			real_kind = cand_kind;
3921 			fwd_kind = btf_fwd_kind(canon_type);
3922 			/* we'd need to resolve base FWD to STRUCT/UNION */
3923 			if (fwd_kind == real_kind && canon_id < d->btf->start_id)
3924 				d->hypot_adjust_canon = true;
3925 		}
3926 		return fwd_kind == real_kind;
3927 	}
3928 
3929 	if (cand_kind != canon_kind)
3930 		return 0;
3931 
3932 	switch (cand_kind) {
3933 	case BTF_KIND_INT:
3934 		return btf_equal_int_tag(cand_type, canon_type);
3935 
3936 	case BTF_KIND_ENUM:
3937 		if (d->opts.dont_resolve_fwds)
3938 			return btf_equal_enum(cand_type, canon_type);
3939 		else
3940 			return btf_compat_enum(cand_type, canon_type);
3941 
3942 	case BTF_KIND_FWD:
3943 	case BTF_KIND_FLOAT:
3944 		return btf_equal_common(cand_type, canon_type);
3945 
3946 	case BTF_KIND_CONST:
3947 	case BTF_KIND_VOLATILE:
3948 	case BTF_KIND_RESTRICT:
3949 	case BTF_KIND_PTR:
3950 	case BTF_KIND_TYPEDEF:
3951 	case BTF_KIND_FUNC:
3952 		if (cand_type->info != canon_type->info)
3953 			return 0;
3954 		return btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
3955 
3956 	case BTF_KIND_ARRAY: {
3957 		const struct btf_array *cand_arr, *canon_arr;
3958 
3959 		if (!btf_compat_array(cand_type, canon_type))
3960 			return 0;
3961 		cand_arr = btf_array(cand_type);
3962 		canon_arr = btf_array(canon_type);
3963 		eq = btf_dedup_is_equiv(d, cand_arr->index_type, canon_arr->index_type);
3964 		if (eq <= 0)
3965 			return eq;
3966 		return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type);
3967 	}
3968 
3969 	case BTF_KIND_STRUCT:
3970 	case BTF_KIND_UNION: {
3971 		const struct btf_member *cand_m, *canon_m;
3972 		__u16 vlen;
3973 
3974 		if (!btf_shallow_equal_struct(cand_type, canon_type))
3975 			return 0;
3976 		vlen = btf_vlen(cand_type);
3977 		cand_m = btf_members(cand_type);
3978 		canon_m = btf_members(canon_type);
3979 		for (i = 0; i < vlen; i++) {
3980 			eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type);
3981 			if (eq <= 0)
3982 				return eq;
3983 			cand_m++;
3984 			canon_m++;
3985 		}
3986 
3987 		return 1;
3988 	}
3989 
3990 	case BTF_KIND_FUNC_PROTO: {
3991 		const struct btf_param *cand_p, *canon_p;
3992 		__u16 vlen;
3993 
3994 		if (!btf_compat_fnproto(cand_type, canon_type))
3995 			return 0;
3996 		eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
3997 		if (eq <= 0)
3998 			return eq;
3999 		vlen = btf_vlen(cand_type);
4000 		cand_p = btf_params(cand_type);
4001 		canon_p = btf_params(canon_type);
4002 		for (i = 0; i < vlen; i++) {
4003 			eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type);
4004 			if (eq <= 0)
4005 				return eq;
4006 			cand_p++;
4007 			canon_p++;
4008 		}
4009 		return 1;
4010 	}
4011 
4012 	default:
4013 		return -EINVAL;
4014 	}
4015 	return 0;
4016 }
4017 
4018 /*
4019  * Use hypothetical mapping, produced by successful type graph equivalence
4020  * check, to augment existing struct/union canonical mapping, where possible.
4021  *
4022  * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record
4023  * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional:
4024  * it doesn't matter if FWD type was part of canonical graph or candidate one,
4025  * we are recording the mapping anyway. As opposed to carefulness required
4026  * for struct/union correspondence mapping (described below), for FWD resolution
4027  * it's not important, as by the time that FWD type (reference type) will be
4028  * deduplicated all structs/unions will be deduped already anyway.
4029  *
4030  * Recording STRUCT/UNION mapping is purely a performance optimization and is
4031  * not required for correctness. It needs to be done carefully to ensure that
4032  * struct/union from candidate's type graph is not mapped into corresponding
4033  * struct/union from canonical type graph that itself hasn't been resolved into
4034  * canonical representative. The only guarantee we have is that canonical
4035  * struct/union was determined as canonical and that won't change. But any
4036  * types referenced through that struct/union fields could have been not yet
4037  * resolved, so in case like that it's too early to establish any kind of
4038  * correspondence between structs/unions.
4039  *
4040  * No canonical correspondence is derived for primitive types (they are already
4041  * deduplicated completely already anyway) or reference types (they rely on
4042  * stability of struct/union canonical relationship for equivalence checks).
4043  */
4044 static void btf_dedup_merge_hypot_map(struct btf_dedup *d)
4045 {
4046 	__u32 canon_type_id, targ_type_id;
4047 	__u16 t_kind, c_kind;
4048 	__u32 t_id, c_id;
4049 	int i;
4050 
4051 	for (i = 0; i < d->hypot_cnt; i++) {
4052 		canon_type_id = d->hypot_list[i];
4053 		targ_type_id = d->hypot_map[canon_type_id];
4054 		t_id = resolve_type_id(d, targ_type_id);
4055 		c_id = resolve_type_id(d, canon_type_id);
4056 		t_kind = btf_kind(btf__type_by_id(d->btf, t_id));
4057 		c_kind = btf_kind(btf__type_by_id(d->btf, c_id));
4058 		/*
4059 		 * Resolve FWD into STRUCT/UNION.
4060 		 * It's ok to resolve FWD into STRUCT/UNION that's not yet
4061 		 * mapped to canonical representative (as opposed to
4062 		 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because
4063 		 * eventually that struct is going to be mapped and all resolved
4064 		 * FWDs will automatically resolve to correct canonical
4065 		 * representative. This will happen before ref type deduping,
4066 		 * which critically depends on stability of these mapping. This
4067 		 * stability is not a requirement for STRUCT/UNION equivalence
4068 		 * checks, though.
4069 		 */
4070 
4071 		/* if it's the split BTF case, we still need to point base FWD
4072 		 * to STRUCT/UNION in a split BTF, because FWDs from split BTF
4073 		 * will be resolved against base FWD. If we don't point base
4074 		 * canonical FWD to the resolved STRUCT/UNION, then all the
4075 		 * FWDs in split BTF won't be correctly resolved to a proper
4076 		 * STRUCT/UNION.
4077 		 */
4078 		if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD)
4079 			d->map[c_id] = t_id;
4080 
4081 		/* if graph equivalence determined that we'd need to adjust
4082 		 * base canonical types, then we need to only point base FWDs
4083 		 * to STRUCTs/UNIONs and do no more modifications. For all
4084 		 * other purposes the type graphs were not equivalent.
4085 		 */
4086 		if (d->hypot_adjust_canon)
4087 			continue;
4088 
4089 		if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD)
4090 			d->map[t_id] = c_id;
4091 
4092 		if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) &&
4093 		    c_kind != BTF_KIND_FWD &&
4094 		    is_type_mapped(d, c_id) &&
4095 		    !is_type_mapped(d, t_id)) {
4096 			/*
4097 			 * as a perf optimization, we can map struct/union
4098 			 * that's part of type graph we just verified for
4099 			 * equivalence. We can do that for struct/union that has
4100 			 * canonical representative only, though.
4101 			 */
4102 			d->map[t_id] = c_id;
4103 		}
4104 	}
4105 }
4106 
4107 /*
4108  * Deduplicate struct/union types.
4109  *
4110  * For each struct/union type its type signature hash is calculated, taking
4111  * into account type's name, size, number, order and names of fields, but
4112  * ignoring type ID's referenced from fields, because they might not be deduped
4113  * completely until after reference types deduplication phase. This type hash
4114  * is used to iterate over all potential canonical types, sharing same hash.
4115  * For each canonical candidate we check whether type graphs that they form
4116  * (through referenced types in fields and so on) are equivalent using algorithm
4117  * implemented in `btf_dedup_is_equiv`. If such equivalence is found and
4118  * BTF_KIND_FWD resolution is allowed, then hypothetical mapping
4119  * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence
4120  * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to
4121  * potentially map other structs/unions to their canonical representatives,
4122  * if such relationship hasn't yet been established. This speeds up algorithm
4123  * by eliminating some of the duplicate work.
4124  *
4125  * If no matching canonical representative was found, struct/union is marked
4126  * as canonical for itself and is added into btf_dedup->dedup_table hash map
4127  * for further look ups.
4128  */
4129 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id)
4130 {
4131 	struct btf_type *cand_type, *t;
4132 	struct hashmap_entry *hash_entry;
4133 	/* if we don't find equivalent type, then we are canonical */
4134 	__u32 new_id = type_id;
4135 	__u16 kind;
4136 	long h;
4137 
4138 	/* already deduped or is in process of deduping (loop detected) */
4139 	if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4140 		return 0;
4141 
4142 	t = btf_type_by_id(d->btf, type_id);
4143 	kind = btf_kind(t);
4144 
4145 	if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION)
4146 		return 0;
4147 
4148 	h = btf_hash_struct(t);
4149 	for_each_dedup_cand(d, hash_entry, h) {
4150 		__u32 cand_id = (__u32)(long)hash_entry->value;
4151 		int eq;
4152 
4153 		/*
4154 		 * Even though btf_dedup_is_equiv() checks for
4155 		 * btf_shallow_equal_struct() internally when checking two
4156 		 * structs (unions) for equivalence, we need to guard here
4157 		 * from picking matching FWD type as a dedup candidate.
4158 		 * This can happen due to hash collision. In such case just
4159 		 * relying on btf_dedup_is_equiv() would lead to potentially
4160 		 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because
4161 		 * FWD and compatible STRUCT/UNION are considered equivalent.
4162 		 */
4163 		cand_type = btf_type_by_id(d->btf, cand_id);
4164 		if (!btf_shallow_equal_struct(t, cand_type))
4165 			continue;
4166 
4167 		btf_dedup_clear_hypot_map(d);
4168 		eq = btf_dedup_is_equiv(d, type_id, cand_id);
4169 		if (eq < 0)
4170 			return eq;
4171 		if (!eq)
4172 			continue;
4173 		btf_dedup_merge_hypot_map(d);
4174 		if (d->hypot_adjust_canon) /* not really equivalent */
4175 			continue;
4176 		new_id = cand_id;
4177 		break;
4178 	}
4179 
4180 	d->map[type_id] = new_id;
4181 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4182 		return -ENOMEM;
4183 
4184 	return 0;
4185 }
4186 
4187 static int btf_dedup_struct_types(struct btf_dedup *d)
4188 {
4189 	int i, err;
4190 
4191 	for (i = 0; i < d->btf->nr_types; i++) {
4192 		err = btf_dedup_struct_type(d, d->btf->start_id + i);
4193 		if (err)
4194 			return err;
4195 	}
4196 	return 0;
4197 }
4198 
4199 /*
4200  * Deduplicate reference type.
4201  *
4202  * Once all primitive and struct/union types got deduplicated, we can easily
4203  * deduplicate all other (reference) BTF types. This is done in two steps:
4204  *
4205  * 1. Resolve all referenced type IDs into their canonical type IDs. This
4206  * resolution can be done either immediately for primitive or struct/union types
4207  * (because they were deduped in previous two phases) or recursively for
4208  * reference types. Recursion will always terminate at either primitive or
4209  * struct/union type, at which point we can "unwind" chain of reference types
4210  * one by one. There is no danger of encountering cycles because in C type
4211  * system the only way to form type cycle is through struct/union, so any chain
4212  * of reference types, even those taking part in a type cycle, will inevitably
4213  * reach struct/union at some point.
4214  *
4215  * 2. Once all referenced type IDs are resolved into canonical ones, BTF type
4216  * becomes "stable", in the sense that no further deduplication will cause
4217  * any changes to it. With that, it's now possible to calculate type's signature
4218  * hash (this time taking into account referenced type IDs) and loop over all
4219  * potential canonical representatives. If no match was found, current type
4220  * will become canonical representative of itself and will be added into
4221  * btf_dedup->dedup_table as another possible canonical representative.
4222  */
4223 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id)
4224 {
4225 	struct hashmap_entry *hash_entry;
4226 	__u32 new_id = type_id, cand_id;
4227 	struct btf_type *t, *cand;
4228 	/* if we don't find equivalent type, then we are representative type */
4229 	int ref_type_id;
4230 	long h;
4231 
4232 	if (d->map[type_id] == BTF_IN_PROGRESS_ID)
4233 		return -ELOOP;
4234 	if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4235 		return resolve_type_id(d, type_id);
4236 
4237 	t = btf_type_by_id(d->btf, type_id);
4238 	d->map[type_id] = BTF_IN_PROGRESS_ID;
4239 
4240 	switch (btf_kind(t)) {
4241 	case BTF_KIND_CONST:
4242 	case BTF_KIND_VOLATILE:
4243 	case BTF_KIND_RESTRICT:
4244 	case BTF_KIND_PTR:
4245 	case BTF_KIND_TYPEDEF:
4246 	case BTF_KIND_FUNC:
4247 		ref_type_id = btf_dedup_ref_type(d, t->type);
4248 		if (ref_type_id < 0)
4249 			return ref_type_id;
4250 		t->type = ref_type_id;
4251 
4252 		h = btf_hash_common(t);
4253 		for_each_dedup_cand(d, hash_entry, h) {
4254 			cand_id = (__u32)(long)hash_entry->value;
4255 			cand = btf_type_by_id(d->btf, cand_id);
4256 			if (btf_equal_common(t, cand)) {
4257 				new_id = cand_id;
4258 				break;
4259 			}
4260 		}
4261 		break;
4262 
4263 	case BTF_KIND_TAG:
4264 		ref_type_id = btf_dedup_ref_type(d, t->type);
4265 		if (ref_type_id < 0)
4266 			return ref_type_id;
4267 		t->type = ref_type_id;
4268 
4269 		h = btf_hash_int_tag(t);
4270 		for_each_dedup_cand(d, hash_entry, h) {
4271 			cand_id = (__u32)(long)hash_entry->value;
4272 			cand = btf_type_by_id(d->btf, cand_id);
4273 			if (btf_equal_int_tag(t, cand)) {
4274 				new_id = cand_id;
4275 				break;
4276 			}
4277 		}
4278 		break;
4279 
4280 	case BTF_KIND_ARRAY: {
4281 		struct btf_array *info = btf_array(t);
4282 
4283 		ref_type_id = btf_dedup_ref_type(d, info->type);
4284 		if (ref_type_id < 0)
4285 			return ref_type_id;
4286 		info->type = ref_type_id;
4287 
4288 		ref_type_id = btf_dedup_ref_type(d, info->index_type);
4289 		if (ref_type_id < 0)
4290 			return ref_type_id;
4291 		info->index_type = ref_type_id;
4292 
4293 		h = btf_hash_array(t);
4294 		for_each_dedup_cand(d, hash_entry, h) {
4295 			cand_id = (__u32)(long)hash_entry->value;
4296 			cand = btf_type_by_id(d->btf, cand_id);
4297 			if (btf_equal_array(t, cand)) {
4298 				new_id = cand_id;
4299 				break;
4300 			}
4301 		}
4302 		break;
4303 	}
4304 
4305 	case BTF_KIND_FUNC_PROTO: {
4306 		struct btf_param *param;
4307 		__u16 vlen;
4308 		int i;
4309 
4310 		ref_type_id = btf_dedup_ref_type(d, t->type);
4311 		if (ref_type_id < 0)
4312 			return ref_type_id;
4313 		t->type = ref_type_id;
4314 
4315 		vlen = btf_vlen(t);
4316 		param = btf_params(t);
4317 		for (i = 0; i < vlen; i++) {
4318 			ref_type_id = btf_dedup_ref_type(d, param->type);
4319 			if (ref_type_id < 0)
4320 				return ref_type_id;
4321 			param->type = ref_type_id;
4322 			param++;
4323 		}
4324 
4325 		h = btf_hash_fnproto(t);
4326 		for_each_dedup_cand(d, hash_entry, h) {
4327 			cand_id = (__u32)(long)hash_entry->value;
4328 			cand = btf_type_by_id(d->btf, cand_id);
4329 			if (btf_equal_fnproto(t, cand)) {
4330 				new_id = cand_id;
4331 				break;
4332 			}
4333 		}
4334 		break;
4335 	}
4336 
4337 	default:
4338 		return -EINVAL;
4339 	}
4340 
4341 	d->map[type_id] = new_id;
4342 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4343 		return -ENOMEM;
4344 
4345 	return new_id;
4346 }
4347 
4348 static int btf_dedup_ref_types(struct btf_dedup *d)
4349 {
4350 	int i, err;
4351 
4352 	for (i = 0; i < d->btf->nr_types; i++) {
4353 		err = btf_dedup_ref_type(d, d->btf->start_id + i);
4354 		if (err < 0)
4355 			return err;
4356 	}
4357 	/* we won't need d->dedup_table anymore */
4358 	hashmap__free(d->dedup_table);
4359 	d->dedup_table = NULL;
4360 	return 0;
4361 }
4362 
4363 /*
4364  * Compact types.
4365  *
4366  * After we established for each type its corresponding canonical representative
4367  * type, we now can eliminate types that are not canonical and leave only
4368  * canonical ones layed out sequentially in memory by copying them over
4369  * duplicates. During compaction btf_dedup->hypot_map array is reused to store
4370  * a map from original type ID to a new compacted type ID, which will be used
4371  * during next phase to "fix up" type IDs, referenced from struct/union and
4372  * reference types.
4373  */
4374 static int btf_dedup_compact_types(struct btf_dedup *d)
4375 {
4376 	__u32 *new_offs;
4377 	__u32 next_type_id = d->btf->start_id;
4378 	const struct btf_type *t;
4379 	void *p;
4380 	int i, id, len;
4381 
4382 	/* we are going to reuse hypot_map to store compaction remapping */
4383 	d->hypot_map[0] = 0;
4384 	/* base BTF types are not renumbered */
4385 	for (id = 1; id < d->btf->start_id; id++)
4386 		d->hypot_map[id] = id;
4387 	for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++)
4388 		d->hypot_map[id] = BTF_UNPROCESSED_ID;
4389 
4390 	p = d->btf->types_data;
4391 
4392 	for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++) {
4393 		if (d->map[id] != id)
4394 			continue;
4395 
4396 		t = btf__type_by_id(d->btf, id);
4397 		len = btf_type_size(t);
4398 		if (len < 0)
4399 			return len;
4400 
4401 		memmove(p, t, len);
4402 		d->hypot_map[id] = next_type_id;
4403 		d->btf->type_offs[next_type_id - d->btf->start_id] = p - d->btf->types_data;
4404 		p += len;
4405 		next_type_id++;
4406 	}
4407 
4408 	/* shrink struct btf's internal types index and update btf_header */
4409 	d->btf->nr_types = next_type_id - d->btf->start_id;
4410 	d->btf->type_offs_cap = d->btf->nr_types;
4411 	d->btf->hdr->type_len = p - d->btf->types_data;
4412 	new_offs = libbpf_reallocarray(d->btf->type_offs, d->btf->type_offs_cap,
4413 				       sizeof(*new_offs));
4414 	if (d->btf->type_offs_cap && !new_offs)
4415 		return -ENOMEM;
4416 	d->btf->type_offs = new_offs;
4417 	d->btf->hdr->str_off = d->btf->hdr->type_len;
4418 	d->btf->raw_size = d->btf->hdr->hdr_len + d->btf->hdr->type_len + d->btf->hdr->str_len;
4419 	return 0;
4420 }
4421 
4422 /*
4423  * Figure out final (deduplicated and compacted) type ID for provided original
4424  * `type_id` by first resolving it into corresponding canonical type ID and
4425  * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map,
4426  * which is populated during compaction phase.
4427  */
4428 static int btf_dedup_remap_type_id(__u32 *type_id, void *ctx)
4429 {
4430 	struct btf_dedup *d = ctx;
4431 	__u32 resolved_type_id, new_type_id;
4432 
4433 	resolved_type_id = resolve_type_id(d, *type_id);
4434 	new_type_id = d->hypot_map[resolved_type_id];
4435 	if (new_type_id > BTF_MAX_NR_TYPES)
4436 		return -EINVAL;
4437 
4438 	*type_id = new_type_id;
4439 	return 0;
4440 }
4441 
4442 /*
4443  * Remap referenced type IDs into deduped type IDs.
4444  *
4445  * After BTF types are deduplicated and compacted, their final type IDs may
4446  * differ from original ones. The map from original to a corresponding
4447  * deduped type ID is stored in btf_dedup->hypot_map and is populated during
4448  * compaction phase. During remapping phase we are rewriting all type IDs
4449  * referenced from any BTF type (e.g., struct fields, func proto args, etc) to
4450  * their final deduped type IDs.
4451  */
4452 static int btf_dedup_remap_types(struct btf_dedup *d)
4453 {
4454 	int i, r;
4455 
4456 	for (i = 0; i < d->btf->nr_types; i++) {
4457 		struct btf_type *t = btf_type_by_id(d->btf, d->btf->start_id + i);
4458 
4459 		r = btf_type_visit_type_ids(t, btf_dedup_remap_type_id, d);
4460 		if (r)
4461 			return r;
4462 	}
4463 
4464 	if (!d->btf_ext)
4465 		return 0;
4466 
4467 	r = btf_ext_visit_type_ids(d->btf_ext, btf_dedup_remap_type_id, d);
4468 	if (r)
4469 		return r;
4470 
4471 	return 0;
4472 }
4473 
4474 /*
4475  * Probe few well-known locations for vmlinux kernel image and try to load BTF
4476  * data out of it to use for target BTF.
4477  */
4478 struct btf *btf__load_vmlinux_btf(void)
4479 {
4480 	struct {
4481 		const char *path_fmt;
4482 		bool raw_btf;
4483 	} locations[] = {
4484 		/* try canonical vmlinux BTF through sysfs first */
4485 		{ "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
4486 		/* fall back to trying to find vmlinux ELF on disk otherwise */
4487 		{ "/boot/vmlinux-%1$s" },
4488 		{ "/lib/modules/%1$s/vmlinux-%1$s" },
4489 		{ "/lib/modules/%1$s/build/vmlinux" },
4490 		{ "/usr/lib/modules/%1$s/kernel/vmlinux" },
4491 		{ "/usr/lib/debug/boot/vmlinux-%1$s" },
4492 		{ "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
4493 		{ "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
4494 	};
4495 	char path[PATH_MAX + 1];
4496 	struct utsname buf;
4497 	struct btf *btf;
4498 	int i, err;
4499 
4500 	uname(&buf);
4501 
4502 	for (i = 0; i < ARRAY_SIZE(locations); i++) {
4503 		snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
4504 
4505 		if (access(path, R_OK))
4506 			continue;
4507 
4508 		if (locations[i].raw_btf)
4509 			btf = btf__parse_raw(path);
4510 		else
4511 			btf = btf__parse_elf(path, NULL);
4512 		err = libbpf_get_error(btf);
4513 		pr_debug("loading kernel BTF '%s': %d\n", path, err);
4514 		if (err)
4515 			continue;
4516 
4517 		return btf;
4518 	}
4519 
4520 	pr_warn("failed to find valid kernel BTF\n");
4521 	return libbpf_err_ptr(-ESRCH);
4522 }
4523 
4524 struct btf *libbpf_find_kernel_btf(void) __attribute__((alias("btf__load_vmlinux_btf")));
4525 
4526 struct btf *btf__load_module_btf(const char *module_name, struct btf *vmlinux_btf)
4527 {
4528 	char path[80];
4529 
4530 	snprintf(path, sizeof(path), "/sys/kernel/btf/%s", module_name);
4531 	return btf__parse_split(path, vmlinux_btf);
4532 }
4533 
4534 int btf_type_visit_type_ids(struct btf_type *t, type_id_visit_fn visit, void *ctx)
4535 {
4536 	int i, n, err;
4537 
4538 	switch (btf_kind(t)) {
4539 	case BTF_KIND_INT:
4540 	case BTF_KIND_FLOAT:
4541 	case BTF_KIND_ENUM:
4542 		return 0;
4543 
4544 	case BTF_KIND_FWD:
4545 	case BTF_KIND_CONST:
4546 	case BTF_KIND_VOLATILE:
4547 	case BTF_KIND_RESTRICT:
4548 	case BTF_KIND_PTR:
4549 	case BTF_KIND_TYPEDEF:
4550 	case BTF_KIND_FUNC:
4551 	case BTF_KIND_VAR:
4552 	case BTF_KIND_TAG:
4553 		return visit(&t->type, ctx);
4554 
4555 	case BTF_KIND_ARRAY: {
4556 		struct btf_array *a = btf_array(t);
4557 
4558 		err = visit(&a->type, ctx);
4559 		err = err ?: visit(&a->index_type, ctx);
4560 		return err;
4561 	}
4562 
4563 	case BTF_KIND_STRUCT:
4564 	case BTF_KIND_UNION: {
4565 		struct btf_member *m = btf_members(t);
4566 
4567 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4568 			err = visit(&m->type, ctx);
4569 			if (err)
4570 				return err;
4571 		}
4572 		return 0;
4573 	}
4574 
4575 	case BTF_KIND_FUNC_PROTO: {
4576 		struct btf_param *m = btf_params(t);
4577 
4578 		err = visit(&t->type, ctx);
4579 		if (err)
4580 			return err;
4581 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4582 			err = visit(&m->type, ctx);
4583 			if (err)
4584 				return err;
4585 		}
4586 		return 0;
4587 	}
4588 
4589 	case BTF_KIND_DATASEC: {
4590 		struct btf_var_secinfo *m = btf_var_secinfos(t);
4591 
4592 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4593 			err = visit(&m->type, ctx);
4594 			if (err)
4595 				return err;
4596 		}
4597 		return 0;
4598 	}
4599 
4600 	default:
4601 		return -EINVAL;
4602 	}
4603 }
4604 
4605 int btf_type_visit_str_offs(struct btf_type *t, str_off_visit_fn visit, void *ctx)
4606 {
4607 	int i, n, err;
4608 
4609 	err = visit(&t->name_off, ctx);
4610 	if (err)
4611 		return err;
4612 
4613 	switch (btf_kind(t)) {
4614 	case BTF_KIND_STRUCT:
4615 	case BTF_KIND_UNION: {
4616 		struct btf_member *m = btf_members(t);
4617 
4618 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4619 			err = visit(&m->name_off, ctx);
4620 			if (err)
4621 				return err;
4622 		}
4623 		break;
4624 	}
4625 	case BTF_KIND_ENUM: {
4626 		struct btf_enum *m = btf_enum(t);
4627 
4628 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4629 			err = visit(&m->name_off, ctx);
4630 			if (err)
4631 				return err;
4632 		}
4633 		break;
4634 	}
4635 	case BTF_KIND_FUNC_PROTO: {
4636 		struct btf_param *m = btf_params(t);
4637 
4638 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4639 			err = visit(&m->name_off, ctx);
4640 			if (err)
4641 				return err;
4642 		}
4643 		break;
4644 	}
4645 	default:
4646 		break;
4647 	}
4648 
4649 	return 0;
4650 }
4651 
4652 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx)
4653 {
4654 	const struct btf_ext_info *seg;
4655 	struct btf_ext_info_sec *sec;
4656 	int i, err;
4657 
4658 	seg = &btf_ext->func_info;
4659 	for_each_btf_ext_sec(seg, sec) {
4660 		struct bpf_func_info_min *rec;
4661 
4662 		for_each_btf_ext_rec(seg, sec, i, rec) {
4663 			err = visit(&rec->type_id, ctx);
4664 			if (err < 0)
4665 				return err;
4666 		}
4667 	}
4668 
4669 	seg = &btf_ext->core_relo_info;
4670 	for_each_btf_ext_sec(seg, sec) {
4671 		struct bpf_core_relo *rec;
4672 
4673 		for_each_btf_ext_rec(seg, sec, i, rec) {
4674 			err = visit(&rec->type_id, ctx);
4675 			if (err < 0)
4676 				return err;
4677 		}
4678 	}
4679 
4680 	return 0;
4681 }
4682 
4683 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx)
4684 {
4685 	const struct btf_ext_info *seg;
4686 	struct btf_ext_info_sec *sec;
4687 	int i, err;
4688 
4689 	seg = &btf_ext->func_info;
4690 	for_each_btf_ext_sec(seg, sec) {
4691 		err = visit(&sec->sec_name_off, ctx);
4692 		if (err)
4693 			return err;
4694 	}
4695 
4696 	seg = &btf_ext->line_info;
4697 	for_each_btf_ext_sec(seg, sec) {
4698 		struct bpf_line_info_min *rec;
4699 
4700 		err = visit(&sec->sec_name_off, ctx);
4701 		if (err)
4702 			return err;
4703 
4704 		for_each_btf_ext_rec(seg, sec, i, rec) {
4705 			err = visit(&rec->file_name_off, ctx);
4706 			if (err)
4707 				return err;
4708 			err = visit(&rec->line_off, ctx);
4709 			if (err)
4710 				return err;
4711 		}
4712 	}
4713 
4714 	seg = &btf_ext->core_relo_info;
4715 	for_each_btf_ext_sec(seg, sec) {
4716 		struct bpf_core_relo *rec;
4717 
4718 		err = visit(&sec->sec_name_off, ctx);
4719 		if (err)
4720 			return err;
4721 
4722 		for_each_btf_ext_rec(seg, sec, i, rec) {
4723 			err = visit(&rec->access_str_off, ctx);
4724 			if (err)
4725 				return err;
4726 		}
4727 	}
4728 
4729 	return 0;
4730 }
4731