xref: /linux/tools/lib/bpf/btf.c (revision 5876080366ae3967a3aad5e193ea0e7704fa022d)
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 <sys/mman.h>
16 #include <linux/kernel.h>
17 #include <linux/err.h>
18 #include <linux/btf.h>
19 #include <gelf.h>
20 #include "btf.h"
21 #include "bpf.h"
22 #include "libbpf.h"
23 #include "libbpf_internal.h"
24 #include "hashmap.h"
25 #include "strset.h"
26 
27 #define BTF_MAX_NR_TYPES 0x7fffffffU
28 #define BTF_MAX_STR_OFFSET 0x7fffffffU
29 
30 static struct btf_type btf_void;
31 
32 /*
33  * Describe how kinds are laid out; some have a singular element following the "struct btf_type",
34  * some have BTF_INFO_VLEN(t->info) elements.  Specify sizes for both.  Flags are currently unused.
35  * Kind layout can be optionally added to the BTF representation in a dedicated section to
36  * facilitate parsing.  New kinds must be added here.
37  */
38 static struct btf_layout layouts[NR_BTF_KINDS] = {
39 /*				singular element size		vlen element(s) size		flags */
40 [BTF_KIND_UNKN] =	{	0,				0,				0 },
41 [BTF_KIND_INT] =	{	sizeof(__u32),			0,				0 },
42 [BTF_KIND_PTR] =	{	0,				0,				0 },
43 [BTF_KIND_ARRAY] =	{	sizeof(struct btf_array),	0,				0 },
44 [BTF_KIND_STRUCT] =	{	0,				sizeof(struct btf_member),	0 },
45 [BTF_KIND_UNION] =	{	0,				sizeof(struct btf_member),	0 },
46 [BTF_KIND_ENUM] =	{	0,				sizeof(struct btf_enum),	0 },
47 [BTF_KIND_FWD] =	{	0,				0,				0 },
48 [BTF_KIND_TYPEDEF] =	{	0,				0,				0 },
49 [BTF_KIND_VOLATILE] =	{	0,				0,				0 },
50 [BTF_KIND_CONST] =	{	0,				0,				0 },
51 [BTF_KIND_RESTRICT] =	{	0,				0,				0 },
52 [BTF_KIND_FUNC] =	{	0,				0,				0 },
53 [BTF_KIND_FUNC_PROTO] =	{	0,				sizeof(struct btf_param),	0 },
54 [BTF_KIND_VAR] =	{	sizeof(struct btf_var),		0,				0 },
55 [BTF_KIND_DATASEC] =	{	0,				sizeof(struct btf_var_secinfo),	0 },
56 [BTF_KIND_FLOAT] =	{	0,				0,				0 },
57 [BTF_KIND_DECL_TAG] =	{	sizeof(struct btf_decl_tag),	0,				0 },
58 [BTF_KIND_TYPE_TAG] =	{	0,				0,				0 },
59 [BTF_KIND_ENUM64] =	{	0,				sizeof(struct btf_enum64),	0 },
60 [BTF_KIND_LOC_PARAM] =	{	sizeof(struct btf_loc_param),	sizeof(__u32),			0 },
61 [BTF_KIND_LOC_PROTO] =	{	0,				sizeof(__u32),			0 },
62 [BTF_KIND_LOCSEC] =	{	0,				sizeof(struct btf_loc),		0 },
63 };
64 
65 struct btf {
66 	/* raw BTF data in native endianness */
67 	void *raw_data;
68 	/* raw BTF data in non-native endianness */
69 	void *raw_data_swapped;
70 	__u32 raw_size;
71 	/* whether target endianness differs from the native one */
72 	bool swapped_endian;
73 
74 	/*
75 	 * When BTF is loaded from an ELF or raw memory it is stored
76 	 * in a contiguous memory block. The type_data, layout and strs_data
77 	 * point inside that memory region to their respective parts of BTF
78 	 * representation:
79 	 *
80 	 * +----------------------------------------+---------------+
81 	 * |  Header  |  Types  |  Optional layout  |  Strings      |
82 	 * +--------------------------------------------------------+
83 	 * ^          ^         ^                   ^
84 	 * |          |         |                   |
85 	 * raw_data   |         |                   |
86 	 * types_data-+         |                   |
87 	 * layout---------------+                   |
88 	 * strs_data--------------------------------+
89 	 *
90 	 * A separate struct btf_header is embedded as btf->hdr,
91 	 * and header information is copied into it.  This allows us
92 	 * to handle header data for various header formats; the original,
93 	 * the extended header with layout info, etc.
94 	 *
95 	 * If BTF data is later modified, e.g., due to types added or
96 	 * removed, BTF deduplication performed, etc, this contiguous
97 	 * representation is broken up into four independent memory
98 	 * regions.
99 	 *
100 	 * raw_data is nulled out at that point, but can be later allocated
101 	 * and cached again if user calls btf__raw_data(), at which point
102 	 * raw_data will contain a contiguous copy of header, types, optional
103 	 * layout and strings.  layout optionally points to a
104 	 * btf_layout array - this allows us to encode information about
105 	 * the kinds known at encoding time.  If layout is NULL no
106 	 * layout information is encoded.
107 	 *
108 	 * +----------+  +---------+  +-----------+   +-----------+
109 	 * |  Header  |  |  Types  |  |  Layout   |   |  Strings  |
110 	 * +----------+  +---------+  +-----------+   +-----------+
111 	 * ^             ^            ^               ^
112 	 * |             |            |               |
113 	 * hdr           |            |               |
114 	 * types_data----+            |               |
115 	 * layout---------------------+               |
116 	 * strset__data(strs_set)---------------------+
117 	 *
118 	 *               +----------+---------+-------------------+-----------+
119 	 *               |  Header  |  Types  |  Optional Layout  |  Strings  |
120 	 * raw_data----->+----------+---------+-------------------+-----------+
121 	 */
122 	struct btf_header hdr;
123 
124 	void *types_data;
125 	size_t types_data_cap; /* used size stored in hdr->type_len */
126 
127 	/* type ID to `struct btf_type *` lookup index
128 	 * type_offs[0] corresponds to the first non-VOID type:
129 	 *   - for base BTF it's type [1];
130 	 *   - for split BTF it's the first non-base BTF type.
131 	 */
132 	__u32 *type_offs;
133 	size_t type_offs_cap;
134 	/* number of types in this BTF instance:
135 	 *   - doesn't include special [0] void type;
136 	 *   - for split BTF counts number of types added on top of base BTF.
137 	 */
138 	__u32 nr_types;
139 	/* the start IDs of named types in sorted BTF */
140 	int named_start_id;
141 	/* if not NULL, points to the base BTF on top of which the current
142 	 * split BTF is based
143 	 */
144 	struct btf *base_btf;
145 	/* BTF type ID of the first type in this BTF instance:
146 	 *   - for base BTF it's equal to 1;
147 	 *   - for split BTF it's equal to biggest type ID of base BTF plus 1.
148 	 */
149 	int start_id;
150 	/* logical string offset of this BTF instance:
151 	 *   - for base BTF it's equal to 0;
152 	 *   - for split BTF it's equal to total size of base BTF's string section size.
153 	 */
154 	int start_str_off;
155 
156 	/* only one of strs_data or strs_set can be non-NULL, depending on
157 	 * whether BTF is in a modifiable state (strs_set is used) or not
158 	 * (strs_data points inside raw_data)
159 	 */
160 	void *strs_data;
161 	/* a set of unique strings */
162 	struct strset *strs_set;
163 	/* whether strings are already deduplicated */
164 	bool strs_deduped;
165 
166 	/* whether base_btf should be freed in btf_free for this instance */
167 	bool owns_base;
168 
169 	/* whether raw_data is a (read-only) mmap */
170 	bool raw_data_is_mmap;
171 
172 	/* is BTF modifiable? i.e. is it split into separate sections as described above? */
173 	bool modifiable;
174 	/* does BTF have header information we do not support?  If so, disallow
175 	 * modification.
176 	 */
177 	bool has_hdr_extra;
178 	/* Points either at raw kind layout data in parsed BTF (if present), or
179 	 * at an allocated kind layout array when BTF is modifiable.
180 	 */
181 	void *layout;
182 
183 	/* BTF object FD, if loaded into kernel */
184 	int fd;
185 
186 	/* Pointer size (in bytes) for a target architecture of this BTF */
187 	int ptr_sz;
188 };
189 
190 static inline __u64 ptr_to_u64(const void *ptr)
191 {
192 	return (__u64) (unsigned long) ptr;
193 }
194 
195 /* Ensure given dynamically allocated memory region pointed to by *data* with
196  * capacity of *cap_cnt* elements each taking *elem_sz* bytes has enough
197  * memory to accommodate *add_cnt* new elements, assuming *cur_cnt* elements
198  * are already used. At most *max_cnt* elements can be ever allocated.
199  * If necessary, memory is reallocated and all existing data is copied over,
200  * new pointer to the memory region is stored at *data, new memory region
201  * capacity (in number of elements) is stored in *cap.
202  * On success, memory pointer to the beginning of unused memory is returned.
203  * On error, NULL is returned.
204  */
205 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
206 		     size_t cur_cnt, size_t max_cnt, size_t add_cnt)
207 {
208 	size_t new_cnt;
209 	void *new_data;
210 
211 	if (cur_cnt + add_cnt <= *cap_cnt)
212 		return *data + cur_cnt * elem_sz;
213 
214 	/* requested more than the set limit */
215 	if (cur_cnt + add_cnt > max_cnt)
216 		return NULL;
217 
218 	new_cnt = *cap_cnt;
219 	new_cnt += new_cnt / 4;		  /* expand by 25% */
220 	if (new_cnt < 16)		  /* but at least 16 elements */
221 		new_cnt = 16;
222 	if (new_cnt > max_cnt)		  /* but not exceeding a set limit */
223 		new_cnt = max_cnt;
224 	if (new_cnt < cur_cnt + add_cnt)  /* also ensure we have enough memory */
225 		new_cnt = cur_cnt + add_cnt;
226 
227 	new_data = libbpf_reallocarray(*data, new_cnt, elem_sz);
228 	if (!new_data)
229 		return NULL;
230 
231 	/* zero out newly allocated portion of memory */
232 	memset(new_data + (*cap_cnt) * elem_sz, 0, (new_cnt - *cap_cnt) * elem_sz);
233 
234 	*data = new_data;
235 	*cap_cnt = new_cnt;
236 	return new_data + cur_cnt * elem_sz;
237 }
238 
239 /* Ensure given dynamically allocated memory region has enough allocated space
240  * to accommodate *need_cnt* elements of size *elem_sz* bytes each
241  */
242 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt)
243 {
244 	void *p;
245 
246 	if (need_cnt <= *cap_cnt)
247 		return 0;
248 
249 	p = libbpf_add_mem(data, cap_cnt, elem_sz, *cap_cnt, SIZE_MAX, need_cnt - *cap_cnt);
250 	if (!p)
251 		return -ENOMEM;
252 
253 	return 0;
254 }
255 
256 static void *btf_add_type_offs_mem(struct btf *btf, size_t add_cnt)
257 {
258 	return libbpf_add_mem((void **)&btf->type_offs, &btf->type_offs_cap, sizeof(__u32),
259 			      btf->nr_types, BTF_MAX_NR_TYPES, add_cnt);
260 }
261 
262 static int btf_add_type_idx_entry(struct btf *btf, __u32 type_off)
263 {
264 	__u32 *p;
265 
266 	p = btf_add_type_offs_mem(btf, 1);
267 	if (!p)
268 		return -ENOMEM;
269 
270 	*p = type_off;
271 	return 0;
272 }
273 
274 static void btf_bswap_hdr(struct btf_header *h, __u32 hdr_len)
275 {
276 	h->magic = bswap_16(h->magic);
277 	h->hdr_len = bswap_32(h->hdr_len);
278 	h->type_off = bswap_32(h->type_off);
279 	h->type_len = bswap_32(h->type_len);
280 	h->str_off = bswap_32(h->str_off);
281 	h->str_len = bswap_32(h->str_len);
282 	/* May be operating on raw data with hdr_len that does not include below fields */
283 	if (hdr_len >= sizeof(struct btf_header)) {
284 		h->layout_off = bswap_32(h->layout_off);
285 		h->layout_len = bswap_32(h->layout_len);
286 	}
287 }
288 
289 static int btf_parse_hdr(struct btf *btf)
290 {
291 	struct btf_header *hdr = btf->raw_data;
292 	__u32 hdr_len, meta_left;
293 
294 	if (btf->raw_size < offsetofend(struct btf_header, str_len)) {
295 		pr_debug("BTF header not found\n");
296 		return -EINVAL;
297 	}
298 
299 	hdr_len = hdr->hdr_len;
300 
301 	if (hdr->magic == bswap_16(BTF_MAGIC)) {
302 		btf->swapped_endian = true;
303 		hdr_len = bswap_32(hdr->hdr_len);
304 		if (hdr_len < offsetofend(struct btf_header, str_len)) {
305 			pr_warn("Can't load BTF with non-native endianness due to unsupported header length %u\n",
306 				hdr_len);
307 			return -ENOTSUP;
308 		}
309 	} else if (hdr->magic != BTF_MAGIC) {
310 		pr_debug("Invalid BTF magic: %x\n", hdr->magic);
311 		return -EINVAL;
312 	}
313 
314 	if (btf->raw_size < hdr_len) {
315 		pr_debug("BTF header len %u larger than data size %u\n",
316 			 hdr_len, btf->raw_size);
317 		return -EINVAL;
318 	}
319 
320 	if (btf->swapped_endian)
321 		btf_bswap_hdr(hdr, hdr_len);
322 
323 	memcpy(&btf->hdr, hdr, min((size_t)hdr_len, sizeof(struct btf_header)));
324 
325 	/* If unknown header data is found, modification is prohibited in
326 	 * btf_ensure_modifiable().
327 	 */
328 	if (hdr_len > sizeof(struct btf_header)) {
329 		__u8 *h = (__u8 *)hdr;
330 		__u32 i;
331 
332 		for (i = sizeof(struct btf_header); i < hdr_len; i++) {
333 			if (!h[i])
334 				continue;
335 			btf->has_hdr_extra = true;
336 			pr_debug("Unknown BTF header data at offset %u; modification is disallowed\n",
337 				 i);
338 			break;
339 		}
340 	}
341 
342 	meta_left = btf->raw_size - hdr_len;
343 	if (meta_left < (long long)btf->hdr.str_off + btf->hdr.str_len) {
344 		pr_debug("Invalid BTF total size: %u\n", btf->raw_size);
345 		return -EINVAL;
346 	}
347 
348 	if ((long long)btf->hdr.type_off + btf->hdr.type_len > btf->hdr.str_off) {
349 		pr_debug("Invalid BTF data sections layout: type data at %u + %u, strings data at %u + %u\n",
350 			 btf->hdr.type_off, btf->hdr.type_len, btf->hdr.str_off,
351 			 btf->hdr.str_len);
352 		return -EINVAL;
353 	}
354 
355 	if (btf->hdr.type_off % 4) {
356 		pr_debug("BTF type section is not aligned to 4 bytes\n");
357 		return -EINVAL;
358 	}
359 
360 	if (btf->hdr.layout_len == 0)
361 		return 0;
362 
363 	/* optional layout section sits between types and strings */
364 	if (btf->hdr.layout_off % 4) {
365 		pr_debug("BTF layout section is not aligned to 4 bytes\n");
366 		return -EINVAL;
367 	}
368 	if (btf->hdr.layout_off < (long long)btf->hdr.type_off + btf->hdr.type_len) {
369 		pr_debug("Invalid BTF data sections layout: type data at %u + %u,  layout data at %u + %u\n",
370 			 btf->hdr.type_off, btf->hdr.type_len,
371 			 btf->hdr.layout_off, btf->hdr.layout_len);
372 		return -EINVAL;
373 	}
374 	if ((long long)btf->hdr.layout_off + btf->hdr.layout_len > btf->hdr.str_off ||
375 	    btf->hdr.layout_off > btf->hdr.str_off) {
376 		pr_debug("Invalid BTF data sections layout: layout data at %u + %u, strings data at %u\n",
377 			 btf->hdr.layout_off, btf->hdr.layout_len, btf->hdr.str_off);
378 		return -EINVAL;
379 	}
380 	return 0;
381 }
382 
383 static int btf_parse_str_sec(struct btf *btf)
384 {
385 	const char *start = btf->strs_data;
386 	const char *end = start + btf->hdr.str_len;
387 
388 	if (btf->base_btf && btf->hdr.str_len == 0)
389 		return 0;
390 	if (!btf->hdr.str_len || btf->hdr.str_len - 1 > BTF_MAX_STR_OFFSET || end[-1]) {
391 		pr_debug("Invalid BTF string section\n");
392 		return -EINVAL;
393 	}
394 	if (!btf->base_btf && start[0]) {
395 		pr_debug("Malformed BTF string section, did you forget to provide base BTF?\n");
396 		return -EINVAL;
397 	}
398 	return 0;
399 }
400 
401 static int btf_parse_layout_sec(struct btf *btf)
402 {
403 	if (!btf->hdr.layout_len)
404 		return 0;
405 
406 	if (btf->hdr.layout_len % sizeof(struct btf_layout) != 0) {
407 		pr_debug("Invalid BTF kind layout section\n");
408 		return -EINVAL;
409 	}
410 	btf->layout = btf->raw_data + btf->hdr.hdr_len + btf->hdr.layout_off;
411 
412 	if (btf->swapped_endian) {
413 		struct btf_layout *l, *end = btf->layout + btf->hdr.layout_len;
414 
415 		for (l = btf->layout; l < end; l++)
416 			l->flags = bswap_16(l->flags);
417 	}
418 
419 	return 0;
420 }
421 
422 /* for unknown kinds, consult kind layout. */
423 static int btf_type_size_unknown(const struct btf *btf, const struct btf_type *t)
424 {
425 	__u32 l_cnt = btf->hdr.layout_len / sizeof(struct btf_layout);
426 	struct btf_layout *l = btf->layout;
427 	__u32 vlen = btf_vlen(t);
428 	__u32 kind = btf_kind(t);
429 
430 	/* Fall back to base BTF if needed as they share layout information */
431 	if (!l) {
432 		struct btf *base_btf = btf->base_btf;
433 
434 		if (base_btf) {
435 			l = base_btf->layout;
436 			l_cnt = base_btf->hdr.layout_len / sizeof(struct btf_layout);
437 		}
438 	}
439 	if (!l || kind >= l_cnt) {
440 		pr_debug("Unsupported BTF_KIND: %u\n", btf_kind(t));
441 		return -EINVAL;
442 	}
443 	if (l[kind].info_sz % 4) {
444 		pr_debug("Unsupported info_sz %u for kind %u\n",
445 			  l[kind].info_sz, kind);
446 		return -EINVAL;
447 	}
448 	if (l[kind].elem_sz % 4) {
449 		pr_debug("Unsupported elem_sz %u for kind %u\n",
450 			 l[kind].elem_sz, kind);
451 		return -EINVAL;
452 	}
453 
454 	return sizeof(struct btf_type) + l[kind].info_sz + vlen * l[kind].elem_sz;
455 }
456 
457 static int btf_type_size(const struct btf *btf, const struct btf_type *t)
458 {
459 	const int base_size = sizeof(struct btf_type);
460 	__u32 vlen = btf_vlen(t);
461 
462 	switch (btf_kind(t)) {
463 	case BTF_KIND_FWD:
464 	case BTF_KIND_CONST:
465 	case BTF_KIND_VOLATILE:
466 	case BTF_KIND_RESTRICT:
467 	case BTF_KIND_PTR:
468 	case BTF_KIND_TYPEDEF:
469 	case BTF_KIND_FUNC:
470 	case BTF_KIND_FLOAT:
471 	case BTF_KIND_TYPE_TAG:
472 		return base_size;
473 	case BTF_KIND_INT:
474 		return base_size + sizeof(__u32);
475 	case BTF_KIND_ENUM:
476 		return base_size + vlen * sizeof(struct btf_enum);
477 	case BTF_KIND_ENUM64:
478 		return base_size + vlen * sizeof(struct btf_enum64);
479 	case BTF_KIND_ARRAY:
480 		return base_size + sizeof(struct btf_array);
481 	case BTF_KIND_STRUCT:
482 	case BTF_KIND_UNION:
483 		return base_size + vlen * sizeof(struct btf_member);
484 	case BTF_KIND_FUNC_PROTO:
485 		return base_size + vlen * sizeof(struct btf_param);
486 	case BTF_KIND_VAR:
487 		return base_size + sizeof(struct btf_var);
488 	case BTF_KIND_DATASEC:
489 		return base_size + vlen * sizeof(struct btf_var_secinfo);
490 	case BTF_KIND_DECL_TAG:
491 		return base_size + sizeof(struct btf_decl_tag);
492 	case BTF_KIND_LOC_PARAM:
493 		return base_size + sizeof(struct btf_loc_param) + vlen * sizeof(__u32);
494 	case BTF_KIND_LOC_PROTO:
495 		return base_size + vlen * sizeof(__u32);
496 	case BTF_KIND_LOCSEC:
497 		return base_size + vlen * sizeof(struct btf_loc);
498 	default:
499 		return btf_type_size_unknown(btf, t);
500 	}
501 }
502 
503 static void btf_bswap_type_base(struct btf_type *t)
504 {
505 	t->name_off = bswap_32(t->name_off);
506 	t->info = bswap_32(t->info);
507 	t->type = bswap_32(t->type);
508 }
509 
510 static int btf_bswap_type_rest(struct btf_type *t)
511 {
512 	struct btf_var_secinfo *v;
513 	struct btf_loc_param *lp;
514 	struct btf_enum64 *e64;
515 	struct btf_member *m;
516 	struct btf_array *a;
517 	struct btf_param *p;
518 	struct btf_enum *e;
519 	struct btf_loc *l;
520 	__u32 vlen = btf_vlen(t);
521 	__u32 *d;
522 	int i;
523 
524 	switch (btf_kind(t)) {
525 	case BTF_KIND_FWD:
526 	case BTF_KIND_CONST:
527 	case BTF_KIND_VOLATILE:
528 	case BTF_KIND_RESTRICT:
529 	case BTF_KIND_PTR:
530 	case BTF_KIND_TYPEDEF:
531 	case BTF_KIND_FUNC:
532 	case BTF_KIND_FLOAT:
533 	case BTF_KIND_TYPE_TAG:
534 		return 0;
535 	case BTF_KIND_INT:
536 		*(__u32 *)(t + 1) = bswap_32(*(__u32 *)(t + 1));
537 		return 0;
538 	case BTF_KIND_ENUM:
539 		for (i = 0, e = btf_enum(t); i < vlen; i++, e++) {
540 			e->name_off = bswap_32(e->name_off);
541 			e->val = bswap_32(e->val);
542 		}
543 		return 0;
544 	case BTF_KIND_ENUM64:
545 		for (i = 0, e64 = btf_enum64(t); i < vlen; i++, e64++) {
546 			e64->name_off = bswap_32(e64->name_off);
547 			e64->val_lo32 = bswap_32(e64->val_lo32);
548 			e64->val_hi32 = bswap_32(e64->val_hi32);
549 		}
550 		return 0;
551 	case BTF_KIND_ARRAY:
552 		a = btf_array(t);
553 		a->type = bswap_32(a->type);
554 		a->index_type = bswap_32(a->index_type);
555 		a->nelems = bswap_32(a->nelems);
556 		return 0;
557 	case BTF_KIND_STRUCT:
558 	case BTF_KIND_UNION:
559 		for (i = 0, m = btf_members(t); i < vlen; i++, m++) {
560 			m->name_off = bswap_32(m->name_off);
561 			m->type = bswap_32(m->type);
562 			m->offset = bswap_32(m->offset);
563 		}
564 		return 0;
565 	case BTF_KIND_FUNC_PROTO:
566 		for (i = 0, p = btf_params(t); i < vlen; i++, p++) {
567 			p->name_off = bswap_32(p->name_off);
568 			p->type = bswap_32(p->type);
569 		}
570 		return 0;
571 	case BTF_KIND_VAR:
572 		btf_var(t)->linkage = bswap_32(btf_var(t)->linkage);
573 		return 0;
574 	case BTF_KIND_DATASEC:
575 		for (i = 0, v = btf_var_secinfos(t); i < vlen; i++, v++) {
576 			v->type = bswap_32(v->type);
577 			v->offset = bswap_32(v->offset);
578 			v->size = bswap_32(v->size);
579 		}
580 		return 0;
581 	case BTF_KIND_DECL_TAG:
582 		btf_decl_tag(t)->component_idx = bswap_32(btf_decl_tag(t)->component_idx);
583 		return 0;
584 	case BTF_KIND_LOC_PARAM:
585 		lp = btf_loc_param(t);
586 		lp->flags = bswap_32(lp->flags);
587 		for (i = 0, d = (__u32 *)(lp + 1); i < vlen; i++, d++)
588 			*d = bswap_32(*d);
589 		return 0;
590 	case BTF_KIND_LOC_PROTO:
591 		for (i = 0, d = btf_loc_proto_params(t); i < vlen; i++, d++)
592 			*d = bswap_32(*d);
593 		return 0;
594 	case BTF_KIND_LOCSEC:
595 		for (i = 0, l = btf_locsec_locs(t); i < vlen; i++, l++) {
596 			l->func = bswap_32(l->func);
597 			l->loc_proto = bswap_32(l->loc_proto);
598 			l->offset = bswap_32(l->offset);
599 		}
600 		return 0;
601 	default:
602 		pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
603 		return -EINVAL;
604 	}
605 }
606 
607 static int btf_parse_type_sec(struct btf *btf)
608 {
609 	void *next_type = btf->types_data;
610 	void *end_type = next_type + btf->hdr.type_len;
611 	int err, type_size;
612 
613 	while (next_type + sizeof(struct btf_type) <= end_type) {
614 		if (btf->swapped_endian)
615 			btf_bswap_type_base(next_type);
616 
617 		type_size = btf_type_size(btf, next_type);
618 		if (type_size < 0)
619 			return type_size;
620 		if (next_type + type_size > end_type) {
621 			pr_warn("BTF type [%u] is malformed\n", btf->start_id + btf->nr_types);
622 			return -EINVAL;
623 		}
624 
625 		if (btf->swapped_endian && btf_bswap_type_rest(next_type))
626 			return -EINVAL;
627 
628 		err = btf_add_type_idx_entry(btf, next_type - btf->types_data);
629 		if (err)
630 			return err;
631 
632 		next_type += type_size;
633 		btf->nr_types++;
634 	}
635 
636 	if (next_type != end_type) {
637 		pr_warn("BTF types data is malformed\n");
638 		return -EINVAL;
639 	}
640 
641 	return 0;
642 }
643 
644 static int btf_validate_str(const struct btf *btf, __u32 str_off, const char *what, __u32 type_id)
645 {
646 	const char *s;
647 
648 	s = btf__str_by_offset(btf, str_off);
649 	if (!s) {
650 		pr_warn("btf: type [%u]: invalid %s (string offset %u)\n", type_id, what, str_off);
651 		return -EINVAL;
652 	}
653 
654 	return 0;
655 }
656 
657 static int btf_validate_id(const struct btf *btf, __u32 id, __u32 ctx_id)
658 {
659 	const struct btf_type *t;
660 
661 	t = btf__type_by_id(btf, id);
662 	if (!t) {
663 		pr_warn("btf: type [%u]: invalid referenced type ID %u\n", ctx_id, id);
664 		return -EINVAL;
665 	}
666 
667 	return 0;
668 }
669 
670 static int btf_validate_type(const struct btf *btf, const struct btf_type *t, __u32 id)
671 {
672 	__u32 kind = btf_kind(t);
673 	int err, i, n;
674 
675 	err = btf_validate_str(btf, t->name_off, "type name", id);
676 	if (err)
677 		return err;
678 
679 	switch (kind) {
680 	case BTF_KIND_UNKN:
681 	case BTF_KIND_INT:
682 	case BTF_KIND_FWD:
683 	case BTF_KIND_FLOAT:
684 		break;
685 	case BTF_KIND_PTR:
686 	case BTF_KIND_TYPEDEF:
687 	case BTF_KIND_VOLATILE:
688 	case BTF_KIND_CONST:
689 	case BTF_KIND_RESTRICT:
690 	case BTF_KIND_VAR:
691 	case BTF_KIND_DECL_TAG:
692 	case BTF_KIND_TYPE_TAG:
693 		err = btf_validate_id(btf, t->type, id);
694 		if (err)
695 			return err;
696 		break;
697 	case BTF_KIND_ARRAY: {
698 		const struct btf_array *a = btf_array(t);
699 
700 		err = btf_validate_id(btf, a->type, id);
701 		err = err ?: btf_validate_id(btf, a->index_type, id);
702 		if (err)
703 			return err;
704 		break;
705 	}
706 	case BTF_KIND_STRUCT:
707 	case BTF_KIND_UNION: {
708 		const struct btf_member *m = btf_members(t);
709 
710 		n = btf_vlen(t);
711 		for (i = 0; i < n; i++, m++) {
712 			err = btf_validate_str(btf, m->name_off, "field name", id);
713 			err = err ?: btf_validate_id(btf, m->type, id);
714 			if (err)
715 				return err;
716 		}
717 		break;
718 	}
719 	case BTF_KIND_ENUM: {
720 		const struct btf_enum *m = btf_enum(t);
721 
722 		n = btf_vlen(t);
723 		for (i = 0; i < n; i++, m++) {
724 			err = btf_validate_str(btf, m->name_off, "enum name", id);
725 			if (err)
726 				return err;
727 		}
728 		break;
729 	}
730 	case BTF_KIND_ENUM64: {
731 		const struct btf_enum64 *m = btf_enum64(t);
732 
733 		n = btf_vlen(t);
734 		for (i = 0; i < n; i++, m++) {
735 			err = btf_validate_str(btf, m->name_off, "enum name", id);
736 			if (err)
737 				return err;
738 		}
739 		break;
740 	}
741 	case BTF_KIND_FUNC: {
742 		const struct btf_type *ft;
743 
744 		err = btf_validate_id(btf, t->type, id);
745 		if (err)
746 			return err;
747 		ft = btf__type_by_id(btf, t->type);
748 		if (btf_kind(ft) != BTF_KIND_FUNC_PROTO) {
749 			pr_warn("btf: type [%u]: referenced type [%u] is not FUNC_PROTO\n", id, t->type);
750 			return -EINVAL;
751 		}
752 		break;
753 	}
754 	case BTF_KIND_FUNC_PROTO: {
755 		const struct btf_param *m = btf_params(t);
756 
757 		n = btf_vlen(t);
758 		for (i = 0; i < n; i++, m++) {
759 			err = btf_validate_str(btf, m->name_off, "param name", id);
760 			err = err ?: btf_validate_id(btf, m->type, id);
761 			if (err)
762 				return err;
763 		}
764 		break;
765 	}
766 	case BTF_KIND_DATASEC: {
767 		const struct btf_var_secinfo *m = btf_var_secinfos(t);
768 
769 		n = btf_vlen(t);
770 		for (i = 0; i < n; i++, m++) {
771 			err = btf_validate_id(btf, m->type, id);
772 			if (err)
773 				return err;
774 		}
775 		break;
776 	}
777 	case BTF_KIND_LOC_PARAM:
778 		break;
779 	case BTF_KIND_LOC_PROTO: {
780 		__u32 *p = btf_loc_proto_params(t);
781 
782 		n = btf_vlen(t);
783 		for (i = 0; i < n; i++, p++) {
784 			err = btf_validate_id(btf, *p, id);
785 			if (err)
786 				return err;
787 		}
788 		break;
789 	}
790 	case BTF_KIND_LOCSEC: {
791 		const struct btf_loc *l = btf_locsec_locs(t);
792 
793 		n = btf_vlen(t);
794 		for (i = 0; i < n; i++, l++) {
795 			if (!err)
796 				err = btf_validate_id(btf, l->func, id);
797 			if (!err)
798 				err = btf_validate_id(btf, l->loc_proto, id);
799 			if (err)
800 				return err;
801 		}
802 		break;
803 	}
804 	default:
805 		/* Kind may be represented in kind layout information. */
806 		if (btf_type_size_unknown(btf, t) < 0) {
807 			pr_warn("btf: type [%u]: unrecognized kind %u\n", id, kind);
808 			return -EINVAL;
809 		}
810 		break;
811 	}
812 	return 0;
813 }
814 
815 /* Validate basic sanity of BTF. It's intentionally less thorough than
816  * kernel's validation and validates only properties of BTF that libbpf relies
817  * on to be correct (e.g., valid type IDs, valid string offsets, etc)
818  */
819 static int btf_sanity_check(const struct btf *btf)
820 {
821 	const struct btf_type *t;
822 	__u32 i, n = btf__type_cnt(btf);
823 	int err;
824 
825 	for (i = btf->start_id; i < n; i++) {
826 		t = btf_type_by_id(btf, i);
827 		err = btf_validate_type(btf, t, i);
828 		if (err)
829 			return err;
830 	}
831 	return 0;
832 }
833 
834 __u32 btf__type_cnt(const struct btf *btf)
835 {
836 	return btf->start_id + btf->nr_types;
837 }
838 
839 const struct btf *btf__base_btf(const struct btf *btf)
840 {
841 	return btf->base_btf;
842 }
843 
844 /* internal helper returning non-const pointer to a type */
845 struct btf_type *btf_type_by_id(const struct btf *btf, __u32 type_id)
846 {
847 	if (type_id == 0)
848 		return &btf_void;
849 	if (type_id < btf->start_id)
850 		return btf_type_by_id(btf->base_btf, type_id);
851 	return btf->types_data + btf->type_offs[type_id - btf->start_id];
852 }
853 
854 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id)
855 {
856 	if (type_id >= btf->start_id + btf->nr_types)
857 		return errno = EINVAL, NULL;
858 	return btf_type_by_id((struct btf *)btf, type_id);
859 }
860 
861 static int determine_ptr_size(const struct btf *btf)
862 {
863 	static const char * const long_aliases[] = {
864 		"long",
865 		"long int",
866 		"int long",
867 		"unsigned long",
868 		"long unsigned",
869 		"unsigned long int",
870 		"unsigned int long",
871 		"long unsigned int",
872 		"long int unsigned",
873 		"int unsigned long",
874 		"int long unsigned",
875 	};
876 	const struct btf_type *t;
877 	const char *name;
878 	int i, j, n;
879 
880 	if (btf->base_btf && btf->base_btf->ptr_sz > 0)
881 		return btf->base_btf->ptr_sz;
882 
883 	n = btf__type_cnt(btf);
884 	for (i = 1; i < n; i++) {
885 		t = btf__type_by_id(btf, i);
886 		if (!btf_is_int(t))
887 			continue;
888 
889 		if (t->size != 4 && t->size != 8)
890 			continue;
891 
892 		name = btf__name_by_offset(btf, t->name_off);
893 		if (!name)
894 			continue;
895 
896 		for (j = 0; j < ARRAY_SIZE(long_aliases); j++) {
897 			if (strcmp(name, long_aliases[j]) == 0)
898 				return t->size;
899 		}
900 	}
901 
902 	return -1;
903 }
904 
905 static size_t btf_ptr_sz(const struct btf *btf)
906 {
907 	if (!btf->ptr_sz)
908 		((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
909 	return btf->ptr_sz < 0 ? sizeof(void *) : btf->ptr_sz;
910 }
911 
912 /* Return pointer size this BTF instance assumes. The size is heuristically
913  * determined by looking for 'long' or 'unsigned long' integer type and
914  * recording its size in bytes. If BTF type information doesn't have any such
915  * type, this function returns 0. In the latter case, native architecture's
916  * pointer size is assumed, so will be either 4 or 8, depending on
917  * architecture that libbpf was compiled for. It's possible to override
918  * guessed value by using btf__set_pointer_size() API.
919  */
920 size_t btf__pointer_size(const struct btf *btf)
921 {
922 	if (!btf->ptr_sz)
923 		((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
924 
925 	if (btf->ptr_sz < 0)
926 		/* not enough BTF type info to guess */
927 		return 0;
928 
929 	return btf->ptr_sz;
930 }
931 
932 /* Override or set pointer size in bytes. Only values of 4 and 8 are
933  * supported.
934  */
935 int btf__set_pointer_size(struct btf *btf, size_t ptr_sz)
936 {
937 	if (ptr_sz != 4 && ptr_sz != 8)
938 		return libbpf_err(-EINVAL);
939 	btf->ptr_sz = ptr_sz;
940 	return 0;
941 }
942 
943 static bool is_host_big_endian(void)
944 {
945 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
946 	return false;
947 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
948 	return true;
949 #else
950 # error "Unrecognized __BYTE_ORDER__"
951 #endif
952 }
953 
954 enum btf_endianness btf__endianness(const struct btf *btf)
955 {
956 	if (is_host_big_endian())
957 		return btf->swapped_endian ? BTF_LITTLE_ENDIAN : BTF_BIG_ENDIAN;
958 	else
959 		return btf->swapped_endian ? BTF_BIG_ENDIAN : BTF_LITTLE_ENDIAN;
960 }
961 
962 int btf__set_endianness(struct btf *btf, enum btf_endianness endian)
963 {
964 	if (endian != BTF_LITTLE_ENDIAN && endian != BTF_BIG_ENDIAN)
965 		return libbpf_err(-EINVAL);
966 
967 	btf->swapped_endian = is_host_big_endian() != (endian == BTF_BIG_ENDIAN);
968 	if (!btf->swapped_endian) {
969 		free(btf->raw_data_swapped);
970 		btf->raw_data_swapped = NULL;
971 	}
972 	return 0;
973 }
974 
975 static bool btf_type_is_void(const struct btf_type *t)
976 {
977 	return t == &btf_void || btf_is_fwd(t);
978 }
979 
980 static bool btf_type_is_void_or_null(const struct btf_type *t)
981 {
982 	return !t || btf_type_is_void(t);
983 }
984 
985 #define MAX_RESOLVE_DEPTH 32
986 
987 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id)
988 {
989 	const struct btf_array *array;
990 	const struct btf_type *t;
991 	__u32 nelems = 1;
992 	__s64 size = -1;
993 	int i;
994 
995 	t = btf__type_by_id(btf, type_id);
996 	for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t); i++) {
997 		switch (btf_kind(t)) {
998 		case BTF_KIND_INT:
999 		case BTF_KIND_STRUCT:
1000 		case BTF_KIND_UNION:
1001 		case BTF_KIND_ENUM:
1002 		case BTF_KIND_ENUM64:
1003 		case BTF_KIND_DATASEC:
1004 		case BTF_KIND_FLOAT:
1005 			size = t->size;
1006 			goto done;
1007 		case BTF_KIND_PTR:
1008 			size = btf_ptr_sz(btf);
1009 			goto done;
1010 		case BTF_KIND_TYPEDEF:
1011 		case BTF_KIND_VOLATILE:
1012 		case BTF_KIND_CONST:
1013 		case BTF_KIND_RESTRICT:
1014 		case BTF_KIND_VAR:
1015 		case BTF_KIND_DECL_TAG:
1016 		case BTF_KIND_TYPE_TAG:
1017 			type_id = t->type;
1018 			break;
1019 		case BTF_KIND_ARRAY:
1020 			array = btf_array(t);
1021 			if (nelems && array->nelems > UINT32_MAX / nelems)
1022 				return libbpf_err(-E2BIG);
1023 			nelems *= array->nelems;
1024 			type_id = array->type;
1025 			break;
1026 		default:
1027 			return libbpf_err(-EINVAL);
1028 		}
1029 
1030 		t = btf__type_by_id(btf, type_id);
1031 	}
1032 
1033 done:
1034 	if (size < 0)
1035 		return libbpf_err(-EINVAL);
1036 	if (nelems && size > UINT32_MAX / nelems)
1037 		return libbpf_err(-E2BIG);
1038 
1039 	return nelems * size;
1040 }
1041 
1042 int btf__align_of(const struct btf *btf, __u32 id)
1043 {
1044 	const struct btf_type *t = btf__type_by_id(btf, id);
1045 	__u16 kind = btf_kind(t);
1046 
1047 	switch (kind) {
1048 	case BTF_KIND_INT:
1049 	case BTF_KIND_ENUM:
1050 	case BTF_KIND_ENUM64:
1051 	case BTF_KIND_FLOAT:
1052 		return min(btf_ptr_sz(btf), (size_t)t->size);
1053 	case BTF_KIND_PTR:
1054 		return btf_ptr_sz(btf);
1055 	case BTF_KIND_TYPEDEF:
1056 	case BTF_KIND_VOLATILE:
1057 	case BTF_KIND_CONST:
1058 	case BTF_KIND_RESTRICT:
1059 	case BTF_KIND_TYPE_TAG:
1060 		return btf__align_of(btf, t->type);
1061 	case BTF_KIND_ARRAY:
1062 		return btf__align_of(btf, btf_array(t)->type);
1063 	case BTF_KIND_STRUCT:
1064 	case BTF_KIND_UNION: {
1065 		const struct btf_member *m = btf_members(t);
1066 		__u32 vlen = btf_vlen(t);
1067 		int i, max_align = 1, align;
1068 
1069 		for (i = 0; i < vlen; i++, m++) {
1070 			align = btf__align_of(btf, m->type);
1071 			if (align <= 0)
1072 				return libbpf_err(align);
1073 			max_align = max(max_align, align);
1074 
1075 			/* if field offset isn't aligned according to field
1076 			 * type's alignment, then struct must be packed
1077 			 */
1078 			if (btf_member_bitfield_size(t, i) == 0 &&
1079 			    (m->offset % (8 * align)) != 0)
1080 				return 1;
1081 		}
1082 
1083 		/* if struct/union size isn't a multiple of its alignment,
1084 		 * then struct must be packed
1085 		 */
1086 		if ((t->size % max_align) != 0)
1087 			return 1;
1088 
1089 		return max_align;
1090 	}
1091 	default:
1092 		pr_warn("unsupported BTF_KIND:%u\n", btf_kind(t));
1093 		return errno = EINVAL, 0;
1094 	}
1095 }
1096 
1097 int btf__resolve_type(const struct btf *btf, __u32 type_id)
1098 {
1099 	const struct btf_type *t;
1100 	int depth = 0;
1101 
1102 	t = btf__type_by_id(btf, type_id);
1103 	while (depth < MAX_RESOLVE_DEPTH &&
1104 	       !btf_type_is_void_or_null(t) &&
1105 	       (btf_is_mod(t) || btf_is_typedef(t) || btf_is_var(t))) {
1106 		type_id = t->type;
1107 		t = btf__type_by_id(btf, type_id);
1108 		depth++;
1109 	}
1110 
1111 	if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t))
1112 		return libbpf_err(-EINVAL);
1113 
1114 	return type_id;
1115 }
1116 
1117 static void btf_check_sorted(struct btf *btf)
1118 {
1119 	__u32 i, n, named_start_id = 0;
1120 
1121 	n = btf__type_cnt(btf);
1122 	for (i = btf->start_id + 1; i < n; i++) {
1123 		struct btf_type *ta = btf_type_by_id(btf, i - 1);
1124 		struct btf_type *tb = btf_type_by_id(btf, i);
1125 		const char *na = btf__str_by_offset(btf, ta->name_off);
1126 		const char *nb = btf__str_by_offset(btf, tb->name_off);
1127 
1128 		if (strcmp(na, nb) > 0)
1129 			return;
1130 
1131 		if (named_start_id == 0 && na[0] != '\0')
1132 			named_start_id = i - 1;
1133 		if (named_start_id == 0 && nb[0] != '\0')
1134 			named_start_id = i;
1135 	}
1136 
1137 	if (named_start_id)
1138 		btf->named_start_id = named_start_id;
1139 }
1140 
1141 static __s32 btf_find_type_by_name_bsearch(const struct btf *btf, const char *name,
1142 					   __s32 start_id)
1143 {
1144 	const struct btf_type *t;
1145 	const char *tname;
1146 	__s32 l, r, m;
1147 
1148 	l = start_id;
1149 	r = btf__type_cnt(btf) - 1;
1150 	while (l <= r) {
1151 		m = l + (r - l) / 2;
1152 		t = btf_type_by_id(btf, m);
1153 		tname = btf__str_by_offset(btf, t->name_off);
1154 		if (strcmp(tname, name) >= 0) {
1155 			if (l == r)
1156 				return r;
1157 			r = m;
1158 		} else {
1159 			l = m + 1;
1160 		}
1161 	}
1162 
1163 	return btf__type_cnt(btf);
1164 }
1165 
1166 static __s32 btf_find_by_name_kind(const struct btf *btf, int start_id,
1167 				   const char *type_name, __s32 kind)
1168 {
1169 	__u32 nr_types = btf__type_cnt(btf);
1170 	const struct btf_type *t;
1171 	const char *tname;
1172 	__s32 id;
1173 
1174 	if (start_id < btf->start_id) {
1175 		id = btf_find_by_name_kind(btf->base_btf, start_id,
1176 					   type_name, kind);
1177 		if (id >= 0)
1178 			return id;
1179 		start_id = btf->start_id;
1180 	}
1181 
1182 	if (kind == BTF_KIND_UNKN || strcmp(type_name, "void") == 0)
1183 		return 0;
1184 
1185 	if (btf->named_start_id > 0 && type_name[0]) {
1186 		start_id = max(start_id, btf->named_start_id);
1187 		id = btf_find_type_by_name_bsearch(btf, type_name, start_id);
1188 		for (; id < nr_types; id++) {
1189 			t = btf__type_by_id(btf, id);
1190 			tname = btf__str_by_offset(btf, t->name_off);
1191 			if (strcmp(tname, type_name) != 0)
1192 				return libbpf_err(-ENOENT);
1193 			if (kind < 0 || btf_kind(t) == kind)
1194 				return id;
1195 		}
1196 	} else {
1197 		for (id = start_id; id < nr_types; id++) {
1198 			t = btf_type_by_id(btf, id);
1199 			if (kind > 0 && btf_kind(t) != kind)
1200 				continue;
1201 			tname = btf__str_by_offset(btf, t->name_off);
1202 			if (strcmp(tname, type_name) == 0)
1203 				return id;
1204 		}
1205 	}
1206 
1207 	return libbpf_err(-ENOENT);
1208 }
1209 
1210 /* the kind value of -1 indicates that kind matching should be skipped */
1211 __s32 btf__find_by_name(const struct btf *btf, const char *type_name)
1212 {
1213 	return btf_find_by_name_kind(btf, 1, type_name, -1);
1214 }
1215 
1216 __s32 btf__find_by_name_kind_own(const struct btf *btf, const char *type_name,
1217 				 __u32 kind)
1218 {
1219 	return btf_find_by_name_kind(btf, btf->start_id, type_name, kind);
1220 }
1221 
1222 __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,
1223 			     __u32 kind)
1224 {
1225 	return btf_find_by_name_kind(btf, 1, type_name, kind);
1226 }
1227 
1228 static bool btf_is_modifiable(const struct btf *btf)
1229 {
1230 	/* BTF is modifiable if split into multiple sections */
1231 	return btf->modifiable;
1232 }
1233 
1234 static void btf_free_raw_data(struct btf *btf)
1235 {
1236 	if (btf->raw_data_is_mmap) {
1237 		munmap(btf->raw_data, btf->raw_size);
1238 		btf->raw_data_is_mmap = false;
1239 	} else {
1240 		free(btf->raw_data);
1241 	}
1242 	btf->raw_data = NULL;
1243 }
1244 
1245 void btf__free(struct btf *btf)
1246 {
1247 	if (IS_ERR_OR_NULL(btf))
1248 		return;
1249 
1250 	if (btf->fd >= 0)
1251 		close(btf->fd);
1252 
1253 	if (btf_is_modifiable(btf)) {
1254 		/* if BTF was modified after loading, it will have a split
1255 		 * in-memory representation for types, strings and layout
1256 		 * sections, so we need to free all of them individually. It
1257 		 * might still have a cached contiguous raw data present,
1258 		 * which will be unconditionally freed below.
1259 		 */
1260 		free(btf->types_data);
1261 		strset__free(btf->strs_set);
1262 		free(btf->layout);
1263 	}
1264 	btf_free_raw_data(btf);
1265 	free(btf->raw_data_swapped);
1266 	free(btf->type_offs);
1267 	if (btf->owns_base)
1268 		btf__free(btf->base_btf);
1269 	free(btf);
1270 }
1271 
1272 static struct btf *btf_new_empty(struct btf_new_opts *opts)
1273 {
1274 	bool add_layout = OPTS_GET(opts, add_layout, false);
1275 	struct btf *base_btf = OPTS_GET(opts, base_btf, NULL);
1276 	struct btf_header *hdr;
1277 	struct btf *btf;
1278 
1279 	btf = calloc(1, sizeof(*btf));
1280 	if (!btf)
1281 		return ERR_PTR(-ENOMEM);
1282 
1283 	btf->nr_types = 0;
1284 	btf->start_id = 1;
1285 	btf->start_str_off = 0;
1286 	btf->fd = -1;
1287 	btf->ptr_sz = sizeof(void *);
1288 	btf->swapped_endian = false;
1289 	btf->named_start_id = 0;
1290 
1291 	if (base_btf) {
1292 		btf->base_btf = base_btf;
1293 		btf->start_id = btf__type_cnt(base_btf);
1294 		btf->start_str_off = base_btf->hdr.str_len + base_btf->start_str_off;
1295 		btf->swapped_endian = base_btf->swapped_endian;
1296 	}
1297 
1298 	/* +1 for empty string at offset 0 */
1299 	btf->raw_size = sizeof(struct btf_header) + (base_btf ? 0 : 1);
1300 	if (add_layout)
1301 		btf->raw_size += sizeof(layouts);
1302 	btf->raw_data = calloc(1, btf->raw_size);
1303 	if (!btf->raw_data) {
1304 		free(btf);
1305 		return ERR_PTR(-ENOMEM);
1306 	}
1307 
1308 	hdr = btf->raw_data;
1309 	hdr->hdr_len = sizeof(struct btf_header);
1310 	hdr->magic = BTF_MAGIC;
1311 	hdr->version = BTF_VERSION;
1312 
1313 	btf->types_data = btf->raw_data + hdr->hdr_len;
1314 	btf->strs_data = btf->raw_data + hdr->hdr_len;
1315 	hdr->str_len = base_btf ? 0 : 1; /* empty string at offset 0 */
1316 
1317 	if (add_layout) {
1318 		hdr->layout_len = sizeof(layouts);
1319 		btf->layout = layouts;
1320 		/*
1321 		 * No need to swap endianness here as btf_get_raw_data()
1322 		 * will do this for us if btf->swapped_endian is true.
1323 		 */
1324 		memcpy(btf->raw_data + hdr->hdr_len, layouts, sizeof(layouts));
1325 		btf->strs_data += sizeof(layouts);
1326 		hdr->str_off += sizeof(layouts);
1327 	}
1328 
1329 	memcpy(&btf->hdr, hdr, sizeof(*hdr));
1330 
1331 	return btf;
1332 }
1333 
1334 struct btf *btf__new_empty(void)
1335 {
1336 	return libbpf_ptr(btf_new_empty(NULL));
1337 }
1338 
1339 struct btf *btf__new_empty_split(struct btf *base_btf)
1340 {
1341 	LIBBPF_OPTS(btf_new_opts, opts);
1342 
1343 	opts.base_btf = base_btf;
1344 
1345 	return libbpf_ptr(btf_new_empty(&opts));
1346 }
1347 
1348 struct btf *btf__new_empty_opts(struct btf_new_opts *opts)
1349 {
1350 	if (!OPTS_VALID(opts, btf_new_opts))
1351 		return libbpf_err_ptr(-EINVAL);
1352 
1353 	return libbpf_ptr(btf_new_empty(opts));
1354 }
1355 
1356 static struct btf *btf_new(const void *data, __u32 size, struct btf *base_btf, bool is_mmap)
1357 {
1358 	struct btf *btf;
1359 	int err;
1360 
1361 	btf = calloc(1, sizeof(struct btf));
1362 	if (!btf)
1363 		return ERR_PTR(-ENOMEM);
1364 
1365 	btf->nr_types = 0;
1366 	btf->start_id = 1;
1367 	btf->start_str_off = 0;
1368 	btf->fd = -1;
1369 	btf->named_start_id = 0;
1370 
1371 	if (base_btf) {
1372 		btf->base_btf = base_btf;
1373 		btf->start_id = btf__type_cnt(base_btf);
1374 		btf->start_str_off = base_btf->hdr.str_len + base_btf->start_str_off;
1375 	}
1376 
1377 	if (is_mmap) {
1378 		btf->raw_data = (void *)data;
1379 		btf->raw_data_is_mmap = true;
1380 	} else {
1381 		btf->raw_data = malloc(size);
1382 		if (!btf->raw_data) {
1383 			err = -ENOMEM;
1384 			goto done;
1385 		}
1386 		memcpy(btf->raw_data, data, size);
1387 	}
1388 
1389 	btf->raw_size = size;
1390 
1391 	err = btf_parse_hdr(btf);
1392 	if (err)
1393 		goto done;
1394 
1395 	btf->strs_data = btf->raw_data + btf->hdr.hdr_len + btf->hdr.str_off;
1396 	btf->types_data = btf->raw_data + btf->hdr.hdr_len + btf->hdr.type_off;
1397 
1398 	err = btf_parse_str_sec(btf);
1399 	err = err ?: btf_parse_layout_sec(btf);
1400 	err = err ?: btf_parse_type_sec(btf);
1401 	err = err ?: btf_sanity_check(btf);
1402 	if (err)
1403 		goto done;
1404 	btf_check_sorted(btf);
1405 
1406 done:
1407 	if (err) {
1408 		btf__free(btf);
1409 		return ERR_PTR(err);
1410 	}
1411 
1412 	return btf;
1413 }
1414 
1415 struct btf *btf__new(const void *data, __u32 size)
1416 {
1417 	return libbpf_ptr(btf_new(data, size, NULL, false));
1418 }
1419 
1420 struct btf *btf__new_split(const void *data, __u32 size, struct btf *base_btf)
1421 {
1422 	return libbpf_ptr(btf_new(data, size, base_btf, false));
1423 }
1424 
1425 struct btf_elf_secs {
1426 	Elf_Data *btf_data;
1427 	Elf_Data *btf_ext_data;
1428 	Elf_Data *btf_base_data;
1429 };
1430 
1431 static int btf_find_elf_sections(Elf *elf, const char *path, struct btf_elf_secs *secs)
1432 {
1433 	Elf_Scn *scn = NULL;
1434 	Elf_Data *data;
1435 	GElf_Ehdr ehdr;
1436 	size_t shstrndx;
1437 	int idx = 0;
1438 
1439 	if (!gelf_getehdr(elf, &ehdr)) {
1440 		pr_warn("failed to get EHDR from %s\n", path);
1441 		goto err;
1442 	}
1443 
1444 	if (elf_getshdrstrndx(elf, &shstrndx)) {
1445 		pr_warn("failed to get section names section index for %s\n",
1446 			path);
1447 		goto err;
1448 	}
1449 
1450 	if (!elf_rawdata(elf_getscn(elf, shstrndx), NULL)) {
1451 		pr_warn("failed to get e_shstrndx from %s\n", path);
1452 		goto err;
1453 	}
1454 
1455 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
1456 		Elf_Data **field;
1457 		GElf_Shdr sh;
1458 		char *name;
1459 
1460 		idx++;
1461 		if (gelf_getshdr(scn, &sh) != &sh) {
1462 			pr_warn("failed to get section(%d) header from %s\n",
1463 				idx, path);
1464 			goto err;
1465 		}
1466 		name = elf_strptr(elf, shstrndx, sh.sh_name);
1467 		if (!name) {
1468 			pr_warn("failed to get section(%d) name from %s\n",
1469 				idx, path);
1470 			goto err;
1471 		}
1472 
1473 		if (strcmp(name, BTF_ELF_SEC) == 0)
1474 			field = &secs->btf_data;
1475 		else if (strcmp(name, BTF_EXT_ELF_SEC) == 0)
1476 			field = &secs->btf_ext_data;
1477 		else if (strcmp(name, BTF_BASE_ELF_SEC) == 0)
1478 			field = &secs->btf_base_data;
1479 		else
1480 			continue;
1481 
1482 		if (sh.sh_type != SHT_PROGBITS) {
1483 			pr_warn("unexpected section type (%u) of section(%d, %s) from %s\n",
1484 				sh.sh_type, idx, name, path);
1485 			goto err;
1486 		}
1487 
1488 		data = elf_getdata(scn, 0);
1489 		if (!data) {
1490 			pr_warn("failed to get section(%d, %s) data from %s\n",
1491 				idx, name, path);
1492 			goto err;
1493 		}
1494 		*field = data;
1495 	}
1496 
1497 	return 0;
1498 
1499 err:
1500 	return -LIBBPF_ERRNO__FORMAT;
1501 }
1502 
1503 static struct btf *btf_parse_elf(const char *path, struct btf *base_btf,
1504 				 struct btf_ext **btf_ext)
1505 {
1506 	struct btf_elf_secs secs = {};
1507 	struct btf *dist_base_btf = NULL;
1508 	struct btf *btf = NULL;
1509 	int err = 0, fd = -1;
1510 	Elf *elf = NULL;
1511 
1512 	if (elf_version(EV_CURRENT) == EV_NONE) {
1513 		pr_warn("failed to init libelf for %s\n", path);
1514 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1515 	}
1516 
1517 	fd = open(path, O_RDONLY | O_CLOEXEC);
1518 	if (fd < 0) {
1519 		err = -errno;
1520 		pr_warn("failed to open %s: %s\n", path, errstr(err));
1521 		return ERR_PTR(err);
1522 	}
1523 
1524 	elf = elf_begin(fd, ELF_C_READ, NULL);
1525 	if (!elf) {
1526 		err = -LIBBPF_ERRNO__FORMAT;
1527 		pr_warn("failed to open %s as ELF file\n", path);
1528 		goto done;
1529 	}
1530 
1531 	err = btf_find_elf_sections(elf, path, &secs);
1532 	if (err)
1533 		goto done;
1534 
1535 	if (!secs.btf_data) {
1536 		pr_warn("failed to find '%s' ELF section in %s\n", BTF_ELF_SEC, path);
1537 		err = -ENODATA;
1538 		goto done;
1539 	}
1540 
1541 	if (secs.btf_base_data) {
1542 		dist_base_btf = btf_new(secs.btf_base_data->d_buf, secs.btf_base_data->d_size,
1543 					NULL, false);
1544 		if (IS_ERR(dist_base_btf)) {
1545 			err = PTR_ERR(dist_base_btf);
1546 			dist_base_btf = NULL;
1547 			goto done;
1548 		}
1549 	}
1550 
1551 	btf = btf_new(secs.btf_data->d_buf, secs.btf_data->d_size,
1552 		      dist_base_btf ?: base_btf, false);
1553 	if (IS_ERR(btf)) {
1554 		err = PTR_ERR(btf);
1555 		goto done;
1556 	}
1557 	if (dist_base_btf && base_btf) {
1558 		err = btf__relocate(btf, base_btf);
1559 		if (err)
1560 			goto done;
1561 		btf__free(dist_base_btf);
1562 		dist_base_btf = NULL;
1563 	}
1564 
1565 	switch (gelf_getclass(elf)) {
1566 	case ELFCLASS32:
1567 		btf__set_pointer_size(btf, 4);
1568 		break;
1569 	case ELFCLASS64:
1570 		btf__set_pointer_size(btf, 8);
1571 		break;
1572 	default:
1573 		pr_warn("failed to get ELF class (bitness) for %s\n", path);
1574 		break;
1575 	}
1576 
1577 	if (btf_ext && secs.btf_ext_data) {
1578 		*btf_ext = btf_ext__new(secs.btf_ext_data->d_buf, secs.btf_ext_data->d_size);
1579 		if (!*btf_ext) {
1580 			err = -errno;
1581 			goto done;
1582 		}
1583 	} else if (btf_ext) {
1584 		*btf_ext = NULL;
1585 	}
1586 
1587 	if (dist_base_btf)
1588 		btf->owns_base = true;
1589 done:
1590 	if (elf)
1591 		elf_end(elf);
1592 	close(fd);
1593 
1594 	if (!err)
1595 		return btf;
1596 
1597 	if (btf_ext)
1598 		btf_ext__free(*btf_ext);
1599 	btf__free(dist_base_btf);
1600 	btf__free(btf);
1601 
1602 	return ERR_PTR(err);
1603 }
1604 
1605 struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext)
1606 {
1607 	return libbpf_ptr(btf_parse_elf(path, NULL, btf_ext));
1608 }
1609 
1610 struct btf *btf__parse_elf_split(const char *path, struct btf *base_btf)
1611 {
1612 	return libbpf_ptr(btf_parse_elf(path, base_btf, NULL));
1613 }
1614 
1615 static struct btf *btf_parse_raw(const char *path, struct btf *base_btf)
1616 {
1617 	struct btf *btf = NULL;
1618 	void *data = NULL;
1619 	FILE *f = NULL;
1620 	__u16 magic;
1621 	int err = 0;
1622 	long sz;
1623 
1624 	f = fopen(path, "rbe");
1625 	if (!f) {
1626 		err = -errno;
1627 		goto err_out;
1628 	}
1629 
1630 	/* check BTF magic */
1631 	if (fread(&magic, 1, sizeof(magic), f) < sizeof(magic)) {
1632 		err = -EIO;
1633 		goto err_out;
1634 	}
1635 	if (magic != BTF_MAGIC && magic != bswap_16(BTF_MAGIC)) {
1636 		/* definitely not a raw BTF */
1637 		err = -EPROTO;
1638 		goto err_out;
1639 	}
1640 
1641 	/* get file size */
1642 	if (fseek(f, 0, SEEK_END)) {
1643 		err = -errno;
1644 		goto err_out;
1645 	}
1646 	sz = ftell(f);
1647 	if (sz < 0) {
1648 		err = -errno;
1649 		goto err_out;
1650 	}
1651 	/* rewind to the start */
1652 	if (fseek(f, 0, SEEK_SET)) {
1653 		err = -errno;
1654 		goto err_out;
1655 	}
1656 
1657 	/* pre-alloc memory and read all of BTF data */
1658 	data = malloc(sz);
1659 	if (!data) {
1660 		err = -ENOMEM;
1661 		goto err_out;
1662 	}
1663 	if (fread(data, 1, sz, f) < sz) {
1664 		err = -EIO;
1665 		goto err_out;
1666 	}
1667 
1668 	/* finally parse BTF data */
1669 	btf = btf_new(data, sz, base_btf, false);
1670 
1671 err_out:
1672 	free(data);
1673 	if (f)
1674 		fclose(f);
1675 	return err ? ERR_PTR(err) : btf;
1676 }
1677 
1678 struct btf *btf__parse_raw(const char *path)
1679 {
1680 	return libbpf_ptr(btf_parse_raw(path, NULL));
1681 }
1682 
1683 struct btf *btf__parse_raw_split(const char *path, struct btf *base_btf)
1684 {
1685 	return libbpf_ptr(btf_parse_raw(path, base_btf));
1686 }
1687 
1688 static struct btf *btf_parse_raw_mmap(const char *path, struct btf *base_btf)
1689 {
1690 	struct stat st;
1691 	void *data;
1692 	struct btf *btf;
1693 	int fd, err;
1694 
1695 	fd = open(path, O_RDONLY);
1696 	if (fd < 0)
1697 		return ERR_PTR(-errno);
1698 
1699 	if (fstat(fd, &st) < 0) {
1700 		err = -errno;
1701 		close(fd);
1702 		return ERR_PTR(err);
1703 	}
1704 
1705 	data = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1706 	err = -errno;
1707 	close(fd);
1708 
1709 	if (data == MAP_FAILED)
1710 		return ERR_PTR(err);
1711 
1712 	btf = btf_new(data, st.st_size, base_btf, true);
1713 	if (IS_ERR(btf))
1714 		munmap(data, st.st_size);
1715 
1716 	return btf;
1717 }
1718 
1719 static struct btf *btf_parse(const char *path, struct btf *base_btf, struct btf_ext **btf_ext)
1720 {
1721 	struct btf *btf;
1722 	int err;
1723 
1724 	if (btf_ext)
1725 		*btf_ext = NULL;
1726 
1727 	btf = btf_parse_raw(path, base_btf);
1728 	err = libbpf_get_error(btf);
1729 	if (!err)
1730 		return btf;
1731 	if (err != -EPROTO)
1732 		return ERR_PTR(err);
1733 	return btf_parse_elf(path, base_btf, btf_ext);
1734 }
1735 
1736 struct btf *btf__parse(const char *path, struct btf_ext **btf_ext)
1737 {
1738 	return libbpf_ptr(btf_parse(path, NULL, btf_ext));
1739 }
1740 
1741 struct btf *btf__parse_split(const char *path, struct btf *base_btf)
1742 {
1743 	return libbpf_ptr(btf_parse(path, base_btf, NULL));
1744 }
1745 
1746 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian);
1747 
1748 int btf_load_into_kernel(struct btf *btf,
1749 			 char *log_buf, size_t log_sz, __u32 log_level,
1750 			 int token_fd)
1751 {
1752 	LIBBPF_OPTS(bpf_btf_load_opts, opts);
1753 	__u32 buf_sz = 0, raw_size;
1754 	char *buf = NULL, *tmp;
1755 	void *raw_data;
1756 	int err = 0;
1757 
1758 	if (btf->fd >= 0)
1759 		return libbpf_err(-EEXIST);
1760 	if (log_sz && !log_buf)
1761 		return libbpf_err(-EINVAL);
1762 
1763 	/* cache native raw data representation */
1764 	raw_data = btf_get_raw_data(btf, &raw_size, false);
1765 	if (!raw_data) {
1766 		err = -ENOMEM;
1767 		goto done;
1768 	}
1769 	btf->raw_size = raw_size;
1770 	btf->raw_data = raw_data;
1771 
1772 retry_load:
1773 	/* if log_level is 0, we won't provide log_buf/log_size to the kernel,
1774 	 * initially. Only if BTF loading fails, we bump log_level to 1 and
1775 	 * retry, using either auto-allocated or custom log_buf. This way
1776 	 * non-NULL custom log_buf provides a buffer just in case, but hopes
1777 	 * for successful load and no need for log_buf.
1778 	 */
1779 	if (log_level) {
1780 		/* if caller didn't provide custom log_buf, we'll keep
1781 		 * allocating our own progressively bigger buffers for BTF
1782 		 * verification log
1783 		 */
1784 		if (!log_buf) {
1785 			buf_sz = max((__u32)BPF_LOG_BUF_SIZE, buf_sz * 2);
1786 			tmp = realloc(buf, buf_sz);
1787 			if (!tmp) {
1788 				err = -ENOMEM;
1789 				goto done;
1790 			}
1791 			buf = tmp;
1792 			buf[0] = '\0';
1793 		}
1794 
1795 		opts.log_buf = log_buf ? log_buf : buf;
1796 		opts.log_size = log_buf ? log_sz : buf_sz;
1797 		opts.log_level = log_level;
1798 	}
1799 
1800 	opts.token_fd = token_fd;
1801 	if (token_fd)
1802 		opts.btf_flags |= BPF_F_TOKEN_FD;
1803 
1804 	btf->fd = bpf_btf_load(raw_data, raw_size, &opts);
1805 	if (btf->fd < 0) {
1806 		/* time to turn on verbose mode and try again */
1807 		if (log_level == 0) {
1808 			log_level = 1;
1809 			goto retry_load;
1810 		}
1811 		/* only retry if caller didn't provide custom log_buf, but
1812 		 * make sure we can never overflow buf_sz
1813 		 */
1814 		if (!log_buf && errno == ENOSPC && buf_sz <= UINT_MAX / 2)
1815 			goto retry_load;
1816 
1817 		err = -errno;
1818 		pr_warn("BTF loading error: %s\n", errstr(err));
1819 		/* don't print out contents of custom log_buf */
1820 		if (!log_buf && buf[0])
1821 			pr_warn("-- BEGIN BTF LOAD LOG ---\n%s\n-- END BTF LOAD LOG --\n", buf);
1822 	}
1823 
1824 done:
1825 	free(buf);
1826 	return libbpf_err(err);
1827 }
1828 
1829 int btf__load_into_kernel(struct btf *btf)
1830 {
1831 	return btf_load_into_kernel(btf, NULL, 0, 0, 0);
1832 }
1833 
1834 int btf__fd(const struct btf *btf)
1835 {
1836 	return btf->fd;
1837 }
1838 
1839 void btf__set_fd(struct btf *btf, int fd)
1840 {
1841 	btf->fd = fd;
1842 }
1843 
1844 static const void *btf_strs_data(const struct btf *btf)
1845 {
1846 	return btf->strs_data ? btf->strs_data : strset__data(btf->strs_set);
1847 }
1848 
1849 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian)
1850 {
1851 	const struct btf_header *hdr = &btf->hdr;
1852 	struct btf_type *t;
1853 	void *data, *p;
1854 	__u32 data_sz;
1855 	int i;
1856 
1857 	data = swap_endian ? btf->raw_data_swapped : btf->raw_data;
1858 	if (data) {
1859 		*size = btf->raw_size;
1860 		return data;
1861 	}
1862 
1863 	data_sz = hdr->hdr_len + hdr->type_len + hdr->str_len;
1864 	if (btf->layout)
1865 		data_sz += hdr->layout_len;
1866 
1867 	data = calloc(1, data_sz);
1868 	if (!data)
1869 		return NULL;
1870 	p = data;
1871 
1872 	memcpy(p, hdr, min((__u32)sizeof(struct btf_header), hdr->hdr_len));
1873 	if (swap_endian)
1874 		btf_bswap_hdr(p, hdr->hdr_len);
1875 	p += hdr->hdr_len;
1876 
1877 	memcpy(p, btf->types_data, hdr->type_len);
1878 	if (swap_endian) {
1879 		for (i = 0; i < btf->nr_types; i++) {
1880 			t = p + btf->type_offs[i];
1881 			/* btf_bswap_type_rest() relies on native t->info, so
1882 			 * we swap base type info after we swapped all the
1883 			 * additional information
1884 			 */
1885 			if (btf_bswap_type_rest(t))
1886 				goto err_out;
1887 			btf_bswap_type_base(t);
1888 		}
1889 	}
1890 	p += hdr->type_len;
1891 
1892 	if (btf->layout) {
1893 		memcpy(p, btf->layout, hdr->layout_len);
1894 		if (swap_endian) {
1895 			struct btf_layout *l, *end = p + hdr->layout_len;
1896 
1897 			for (l = p; l < end ; l++)
1898 				l->flags = bswap_16(l->flags);
1899 		}
1900 		p += hdr->layout_len;
1901 	}
1902 
1903 	memcpy(p, btf_strs_data(btf), hdr->str_len);
1904 
1905 	*size = data_sz;
1906 	return data;
1907 err_out:
1908 	free(data);
1909 	return NULL;
1910 }
1911 
1912 const void *btf__raw_data(const struct btf *btf_ro, __u32 *size)
1913 {
1914 	struct btf *btf = (struct btf *)btf_ro;
1915 	__u32 data_sz;
1916 	void *data;
1917 
1918 	data = btf_get_raw_data(btf, &data_sz, btf->swapped_endian);
1919 	if (!data)
1920 		return errno = ENOMEM, NULL;
1921 
1922 	btf->raw_size = data_sz;
1923 	if (btf->swapped_endian)
1924 		btf->raw_data_swapped = data;
1925 	else
1926 		btf->raw_data = data;
1927 	*size = data_sz;
1928 	return data;
1929 }
1930 
1931 __attribute__((alias("btf__raw_data")))
1932 const void *btf__get_raw_data(const struct btf *btf, __u32 *size);
1933 
1934 const char *btf__str_by_offset(const struct btf *btf, __u32 offset)
1935 {
1936 	if (offset < btf->start_str_off)
1937 		return btf__str_by_offset(btf->base_btf, offset);
1938 	else if (offset - btf->start_str_off < btf->hdr.str_len)
1939 		return btf_strs_data(btf) + (offset - btf->start_str_off);
1940 	else
1941 		return errno = EINVAL, NULL;
1942 }
1943 
1944 const char *btf__name_by_offset(const struct btf *btf, __u32 offset)
1945 {
1946 	return btf__str_by_offset(btf, offset);
1947 }
1948 
1949 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf)
1950 {
1951 	struct bpf_btf_info btf_info;
1952 	__u32 len = sizeof(btf_info);
1953 	__u32 last_size;
1954 	struct btf *btf;
1955 	void *ptr;
1956 	int err;
1957 
1958 	/* we won't know btf_size until we call bpf_btf_get_info_by_fd(). so
1959 	 * let's start with a sane default - 4KiB here - and resize it only if
1960 	 * bpf_btf_get_info_by_fd() needs a bigger buffer.
1961 	 */
1962 	last_size = 4096;
1963 	ptr = malloc(last_size);
1964 	if (!ptr)
1965 		return ERR_PTR(-ENOMEM);
1966 
1967 	memset(&btf_info, 0, sizeof(btf_info));
1968 	btf_info.btf = ptr_to_u64(ptr);
1969 	btf_info.btf_size = last_size;
1970 	err = bpf_btf_get_info_by_fd(btf_fd, &btf_info, &len);
1971 
1972 	if (!err && btf_info.btf_size > last_size) {
1973 		void *temp_ptr;
1974 
1975 		last_size = btf_info.btf_size;
1976 		temp_ptr = realloc(ptr, last_size);
1977 		if (!temp_ptr) {
1978 			btf = ERR_PTR(-ENOMEM);
1979 			goto exit_free;
1980 		}
1981 		ptr = temp_ptr;
1982 
1983 		len = sizeof(btf_info);
1984 		memset(&btf_info, 0, sizeof(btf_info));
1985 		btf_info.btf = ptr_to_u64(ptr);
1986 		btf_info.btf_size = last_size;
1987 
1988 		err = bpf_btf_get_info_by_fd(btf_fd, &btf_info, &len);
1989 	}
1990 
1991 	if (err || btf_info.btf_size > last_size) {
1992 		btf = err ? ERR_PTR(-errno) : ERR_PTR(-E2BIG);
1993 		goto exit_free;
1994 	}
1995 
1996 	btf = btf_new(ptr, btf_info.btf_size, base_btf, false);
1997 
1998 exit_free:
1999 	free(ptr);
2000 	return btf;
2001 }
2002 
2003 struct btf *btf_load_from_kernel(__u32 id, struct btf *base_btf, int token_fd)
2004 {
2005 	struct btf *btf;
2006 	int btf_fd;
2007 	LIBBPF_OPTS(bpf_get_fd_by_id_opts, opts);
2008 
2009 	if (token_fd) {
2010 		opts.open_flags |= BPF_F_TOKEN_FD;
2011 		opts.token_fd = token_fd;
2012 	}
2013 
2014 	btf_fd = bpf_btf_get_fd_by_id_opts(id, &opts);
2015 	if (btf_fd < 0)
2016 		return libbpf_err_ptr(-errno);
2017 
2018 	btf = btf_get_from_fd(btf_fd, base_btf);
2019 	close(btf_fd);
2020 
2021 	return libbpf_ptr(btf);
2022 }
2023 
2024 struct btf *btf__load_from_kernel_by_id_split(__u32 id, struct btf *base_btf)
2025 {
2026 	return btf_load_from_kernel(id, base_btf, 0);
2027 }
2028 
2029 struct btf *btf__load_from_kernel_by_id(__u32 id)
2030 {
2031 	return btf__load_from_kernel_by_id_split(id, NULL);
2032 }
2033 
2034 static void btf_invalidate_raw_data(struct btf *btf)
2035 {
2036 	if (btf->raw_data)
2037 		btf_free_raw_data(btf);
2038 	if (btf->raw_data_swapped) {
2039 		free(btf->raw_data_swapped);
2040 		btf->raw_data_swapped = NULL;
2041 	}
2042 	btf->named_start_id = 0;
2043 }
2044 
2045 /* Ensure BTF is ready to be modified (by splitting into a three memory
2046  * regions for types, strings and layout. Also invalidate cached
2047  * raw_data, if any.
2048  */
2049 static int btf_ensure_modifiable(struct btf *btf)
2050 {
2051 	void *types, *layout = NULL;
2052 	struct strset *set = NULL;
2053 	int err = -ENOMEM;
2054 
2055 	if (btf_is_modifiable(btf)) {
2056 		/* any BTF modification invalidates raw_data */
2057 		btf_invalidate_raw_data(btf);
2058 		return 0;
2059 	}
2060 
2061 	if (btf->has_hdr_extra) {
2062 		/* Additional BTF header data was found; not safe to modify. */
2063 		return -EOPNOTSUPP;
2064 	}
2065 
2066 	/* split raw data into memory regions; btf->hdr is done already. */
2067 	types = malloc(btf->hdr.type_len);
2068 	if (!types)
2069 		goto err_out;
2070 	memcpy(types, btf->types_data, btf->hdr.type_len);
2071 
2072 	if (btf->hdr.layout_len) {
2073 		layout = malloc(btf->hdr.layout_len);
2074 		if (!layout)
2075 			goto err_out;
2076 		memcpy(layout, btf->raw_data + btf->hdr.hdr_len + btf->hdr.layout_off,
2077 		       btf->hdr.layout_len);
2078 	}
2079 
2080 	/* build lookup index for all strings */
2081 	set = strset__new(BTF_MAX_STR_OFFSET, btf->strs_data, btf->hdr.str_len);
2082 	if (IS_ERR(set)) {
2083 		err = PTR_ERR(set);
2084 		goto err_out;
2085 	}
2086 
2087 	/* only when everything was successful, update internal state */
2088 	btf->types_data = types;
2089 	btf->types_data_cap = btf->hdr.type_len;
2090 	btf->strs_data = NULL;
2091 	btf->strs_set = set;
2092 	if (layout)
2093 		btf->layout = layout;
2094 	/* if BTF was created from scratch, all strings are guaranteed to be
2095 	 * unique and deduplicated
2096 	 */
2097 	if (btf->hdr.str_len == 0)
2098 		btf->strs_deduped = true;
2099 	if (!btf->base_btf && btf->hdr.str_len == 1)
2100 		btf->strs_deduped = true;
2101 
2102 	/* invalidate raw_data representation */
2103 	btf_invalidate_raw_data(btf);
2104 
2105 	btf->modifiable = true;
2106 
2107 	return 0;
2108 
2109 err_out:
2110 	strset__free(set);
2111 	free(types);
2112 	free(layout);
2113 	return err;
2114 }
2115 
2116 /* Find an offset in BTF string section that corresponds to a given string *s*.
2117  * Returns:
2118  *   - >0 offset into string section, if string is found;
2119  *   - -ENOENT, if string is not in the string section;
2120  *   - <0, on any other error.
2121  */
2122 int btf__find_str(struct btf *btf, const char *s)
2123 {
2124 	int off;
2125 	int err;
2126 
2127 	if (btf->base_btf) {
2128 		off = btf__find_str(btf->base_btf, s);
2129 		if (off != -ENOENT)
2130 			return off;
2131 	}
2132 
2133 	/* BTF needs to be in a modifiable state to build string lookup index */
2134 	err = btf_ensure_modifiable(btf);
2135 	if (err)
2136 		return libbpf_err(err);
2137 
2138 	off = strset__find_str(btf->strs_set, s);
2139 	if (off < 0)
2140 		return libbpf_err(off);
2141 
2142 	return btf->start_str_off + off;
2143 }
2144 
2145 /* Add a string s to the BTF string section.
2146  * Returns:
2147  *   - > 0 offset into string section, on success;
2148  *   - < 0, on error.
2149  */
2150 int btf__add_str(struct btf *btf, const char *s)
2151 {
2152 	int off;
2153 	int err;
2154 
2155 	if (btf->base_btf) {
2156 		off = btf__find_str(btf->base_btf, s);
2157 		if (off != -ENOENT)
2158 			return off;
2159 	}
2160 
2161 	err = btf_ensure_modifiable(btf);
2162 	if (err)
2163 		return libbpf_err(err);
2164 
2165 	off = strset__add_str(btf->strs_set, s);
2166 	if (off < 0)
2167 		return libbpf_err(off);
2168 
2169 	btf->hdr.str_len = strset__data_size(btf->strs_set);
2170 
2171 	return btf->start_str_off + off;
2172 }
2173 
2174 static void *btf_add_type_mem(struct btf *btf, size_t add_sz)
2175 {
2176 	return libbpf_add_mem(&btf->types_data, &btf->types_data_cap, 1,
2177 			      btf->hdr.type_len, UINT_MAX, add_sz);
2178 }
2179 
2180 static int btf_type_inc_vlen(struct btf_type *t)
2181 {
2182 	if (btf_vlen(t) == BTF_MAX_VLEN)
2183 		return -ENOSPC;
2184 	t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, btf_kflag(t));
2185 	return 0;
2186 }
2187 
2188 static void btf_hdr_update_type_len(struct btf *btf, int new_len)
2189 {
2190 	btf->hdr.type_len = new_len;
2191 	if (btf->layout) {
2192 		btf->hdr.layout_off = btf->hdr.type_off + new_len;
2193 		btf->hdr.str_off = btf->hdr.layout_off + btf->hdr.layout_len;
2194 	} else {
2195 		btf->hdr.str_off = btf->hdr.type_off + new_len;
2196 	}
2197 }
2198 
2199 static void btf_hdr_update_str_len(struct btf *btf, int new_len)
2200 {
2201 	btf->hdr.str_len = new_len;
2202 }
2203 
2204 static int btf_commit_type(struct btf *btf, int data_sz)
2205 {
2206 	int err;
2207 
2208 	err = btf_add_type_idx_entry(btf, btf->hdr.type_len);
2209 	if (err)
2210 		return libbpf_err(err);
2211 
2212 	btf_hdr_update_type_len(btf, btf->hdr.type_len + data_sz);
2213 	btf->nr_types++;
2214 	return btf->start_id + btf->nr_types - 1;
2215 }
2216 
2217 struct btf_pipe {
2218 	const struct btf *src;
2219 	struct btf *dst;
2220 	struct hashmap *str_off_map; /* map string offsets from src to dst */
2221 };
2222 
2223 static int btf_rewrite_str(struct btf_pipe *p, __u32 *str_off)
2224 {
2225 	long mapped_off;
2226 	int off, err;
2227 
2228 	if (!*str_off) /* nothing to do for empty strings */
2229 		return 0;
2230 
2231 	if (p->str_off_map &&
2232 	    hashmap__find(p->str_off_map, *str_off, &mapped_off)) {
2233 		*str_off = mapped_off;
2234 		return 0;
2235 	}
2236 
2237 	off = btf__add_str(p->dst, btf__str_by_offset(p->src, *str_off));
2238 	if (off < 0)
2239 		return off;
2240 
2241 	/* Remember string mapping from src to dst.  It avoids
2242 	 * performing expensive string comparisons.
2243 	 */
2244 	if (p->str_off_map) {
2245 		err = hashmap__append(p->str_off_map, *str_off, off);
2246 		if (err)
2247 			return err;
2248 	}
2249 
2250 	*str_off = off;
2251 	return 0;
2252 }
2253 
2254 static int btf_add_type(struct btf_pipe *p, const struct btf_type *src_type)
2255 {
2256 	struct btf_field_iter it;
2257 	struct btf_type *t;
2258 	__u32 *str_off;
2259 	int sz, err;
2260 
2261 	sz = btf_type_size(p->src, src_type);
2262 	if (sz < 0)
2263 		return libbpf_err(sz);
2264 
2265 	/* deconstruct BTF, if necessary, and invalidate raw_data */
2266 	err = btf_ensure_modifiable(p->dst);
2267 	if (err)
2268 		return libbpf_err(err);
2269 
2270 	t = btf_add_type_mem(p->dst, sz);
2271 	if (!t)
2272 		return libbpf_err(-ENOMEM);
2273 
2274 	memcpy(t, src_type, sz);
2275 
2276 	err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_STRS);
2277 	if (err)
2278 		return libbpf_err(err);
2279 
2280 	while ((str_off = btf_field_iter_next(&it))) {
2281 		err = btf_rewrite_str(p, str_off);
2282 		if (err)
2283 			return libbpf_err(err);
2284 	}
2285 
2286 	return btf_commit_type(p->dst, sz);
2287 }
2288 
2289 int btf__add_type(struct btf *btf, const struct btf *src_btf, const struct btf_type *src_type)
2290 {
2291 	struct btf_pipe p = { .src = src_btf, .dst = btf };
2292 
2293 	return btf_add_type(&p, src_type);
2294 }
2295 
2296 static size_t btf_dedup_identity_hash_fn(long key, void *ctx);
2297 static bool btf_dedup_equal_fn(long k1, long k2, void *ctx);
2298 
2299 int btf__add_btf(struct btf *btf, const struct btf *src_btf)
2300 {
2301 	struct btf_pipe p = { .src = src_btf, .dst = btf };
2302 	int data_sz, sz, cnt, i, err, old_strs_len;
2303 	__u32 src_start_id;
2304 	__u32 *off;
2305 	void *t;
2306 
2307 	/*
2308 	 * When appending split BTF, the destination must share the same base
2309 	 * BTF so that base type ID references remain valid.
2310 	 */
2311 	if (src_btf->base_btf && src_btf->base_btf != btf->base_btf)
2312 		return libbpf_err(-EOPNOTSUPP);
2313 
2314 	src_start_id = src_btf->base_btf ? btf__type_cnt(src_btf->base_btf) : 1;
2315 
2316 	/* deconstruct BTF, if necessary, and invalidate raw_data */
2317 	err = btf_ensure_modifiable(btf);
2318 	if (err)
2319 		return libbpf_err(err);
2320 
2321 	/* remember original strings section size if we have to roll back
2322 	 * partial strings section changes
2323 	 */
2324 	old_strs_len = btf->hdr.str_len;
2325 
2326 	data_sz = src_btf->hdr.type_len;
2327 	cnt = src_btf->nr_types;
2328 
2329 	/* pre-allocate enough memory for new types */
2330 	t = btf_add_type_mem(btf, data_sz);
2331 	if (!t)
2332 		return libbpf_err(-ENOMEM);
2333 
2334 	/* pre-allocate enough memory for type offset index for new types */
2335 	off = btf_add_type_offs_mem(btf, cnt);
2336 	if (!off)
2337 		return libbpf_err(-ENOMEM);
2338 
2339 	/* Map the string offsets from src_btf to the offsets from btf to improve performance */
2340 	p.str_off_map = hashmap__new(btf_dedup_identity_hash_fn, btf_dedup_equal_fn, NULL);
2341 	if (IS_ERR(p.str_off_map))
2342 		return libbpf_err(-ENOMEM);
2343 
2344 	/* bulk copy types data for all types from src_btf */
2345 	memcpy(t, src_btf->types_data, data_sz);
2346 
2347 	for (i = 0; i < cnt; i++) {
2348 		struct btf_field_iter it;
2349 		__u32 *type_id, *str_off;
2350 
2351 		sz = btf_type_size(src_btf, t);
2352 		if (sz < 0) {
2353 			/* unlikely, has to be corrupted src_btf */
2354 			err = sz;
2355 			goto err_out;
2356 		}
2357 
2358 		/* fill out type ID to type offset mapping for lookups by type ID */
2359 		*off = t - btf->types_data;
2360 
2361 		/* add, dedup, and remap strings referenced by this BTF type */
2362 		err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_STRS);
2363 		if (err)
2364 			goto err_out;
2365 		while ((str_off = btf_field_iter_next(&it))) {
2366 			/* don't remap strings from shared base BTF */
2367 			if (*str_off < src_btf->start_str_off)
2368 				continue;
2369 			err = btf_rewrite_str(&p, str_off);
2370 			if (err)
2371 				goto err_out;
2372 		}
2373 
2374 		/* remap all type IDs referenced from this BTF type */
2375 		err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_IDS);
2376 		if (err)
2377 			goto err_out;
2378 
2379 		while ((type_id = btf_field_iter_next(&it))) {
2380 			if (!*type_id) /* nothing to do for VOID references */
2381 				continue;
2382 
2383 			/* don't remap types from shared base BTF */
2384 			if (*type_id < src_start_id)
2385 				continue;
2386 
2387 			*type_id += btf->start_id + btf->nr_types - src_start_id;
2388 		}
2389 
2390 		/* go to next type data and type offset index entry */
2391 		t += sz;
2392 		off++;
2393 	}
2394 
2395 	/* Up until now any of the copied type data was effectively invisible,
2396 	 * so if we exited early before this point due to error, BTF would be
2397 	 * effectively unmodified. There would be extra internal memory
2398 	 * pre-allocated, but it would not be available for querying.  But now
2399 	 * that we've copied and rewritten all the data successfully, we can
2400 	 * update type count and various internal offsets and sizes to
2401 	 * "commit" the changes and made them visible to the outside world.
2402 	 */
2403 	btf_hdr_update_type_len(btf, btf->hdr.type_len + data_sz);
2404 	btf->nr_types += cnt;
2405 
2406 	hashmap__free(p.str_off_map);
2407 
2408 	/* return type ID of the first added BTF type */
2409 	return btf->start_id + btf->nr_types - cnt;
2410 err_out:
2411 	/* zero out preallocated memory as if it was just allocated with
2412 	 * libbpf_add_mem()
2413 	 */
2414 	memset(btf->types_data + btf->hdr.type_len, 0, data_sz);
2415 	if (btf->strs_data)
2416 		memset(btf->strs_data + old_strs_len, 0, btf->hdr.str_len - old_strs_len);
2417 
2418 	/* and now restore original strings section size; types data size
2419 	 * wasn't modified, so doesn't need restoring, see big comment above
2420 	 */
2421 	btf_hdr_update_str_len(btf, old_strs_len);
2422 
2423 	hashmap__free(p.str_off_map);
2424 
2425 	return libbpf_err(err);
2426 }
2427 
2428 /*
2429  * Append new BTF_KIND_INT type with:
2430  *   - *name* - non-empty, non-NULL type name;
2431  *   - *sz* - power-of-2 (1, 2, 4, ..) size of the type, in bytes;
2432  *   - encoding is a combination of BTF_INT_SIGNED, BTF_INT_CHAR, BTF_INT_BOOL.
2433  * Returns:
2434  *   - >0, type ID of newly added BTF type;
2435  *   - <0, on error.
2436  */
2437 int btf__add_int(struct btf *btf, const char *name, size_t byte_sz, int encoding)
2438 {
2439 	struct btf_type *t;
2440 	int sz, name_off;
2441 	int err;
2442 
2443 	/* non-empty name */
2444 	if (str_is_empty(name))
2445 		return libbpf_err(-EINVAL);
2446 	/* byte_sz must be power of 2 */
2447 	if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 16)
2448 		return libbpf_err(-EINVAL);
2449 	if (encoding & ~(BTF_INT_SIGNED | BTF_INT_CHAR | BTF_INT_BOOL))
2450 		return libbpf_err(-EINVAL);
2451 
2452 	/* deconstruct BTF, if necessary, and invalidate raw_data */
2453 	err = btf_ensure_modifiable(btf);
2454 	if (err)
2455 		return libbpf_err(err);
2456 
2457 	sz = sizeof(struct btf_type) + sizeof(int);
2458 	t = btf_add_type_mem(btf, sz);
2459 	if (!t)
2460 		return libbpf_err(-ENOMEM);
2461 
2462 	/* if something goes wrong later, we might end up with an extra string,
2463 	 * but that shouldn't be a problem, because BTF can't be constructed
2464 	 * completely anyway and will most probably be just discarded
2465 	 */
2466 	name_off = btf__add_str(btf, name);
2467 	if (name_off < 0)
2468 		return name_off;
2469 
2470 	t->name_off = name_off;
2471 	t->info = btf_type_info(BTF_KIND_INT, 0, 0);
2472 	t->size = byte_sz;
2473 	/* set INT info, we don't allow setting legacy bit offset/size */
2474 	*(__u32 *)(t + 1) = (encoding << 24) | (byte_sz * 8);
2475 
2476 	return btf_commit_type(btf, sz);
2477 }
2478 
2479 /*
2480  * Append new BTF_KIND_FLOAT type with:
2481  *   - *name* - non-empty, non-NULL type name;
2482  *   - *sz* - size of the type, in bytes;
2483  * Returns:
2484  *   - >0, type ID of newly added BTF type;
2485  *   - <0, on error.
2486  */
2487 int btf__add_float(struct btf *btf, const char *name, size_t byte_sz)
2488 {
2489 	struct btf_type *t;
2490 	int sz, name_off;
2491 	int err;
2492 
2493 	/* non-empty name */
2494 	if (str_is_empty(name))
2495 		return libbpf_err(-EINVAL);
2496 
2497 	/* byte_sz must be one of the explicitly allowed values */
2498 	if (byte_sz != 2 && byte_sz != 4 && byte_sz != 8 && byte_sz != 12 &&
2499 	    byte_sz != 16)
2500 		return libbpf_err(-EINVAL);
2501 
2502 	err = btf_ensure_modifiable(btf);
2503 	if (err)
2504 		return libbpf_err(err);
2505 
2506 	sz = sizeof(struct btf_type);
2507 	t = btf_add_type_mem(btf, sz);
2508 	if (!t)
2509 		return libbpf_err(-ENOMEM);
2510 
2511 	name_off = btf__add_str(btf, name);
2512 	if (name_off < 0)
2513 		return name_off;
2514 
2515 	t->name_off = name_off;
2516 	t->info = btf_type_info(BTF_KIND_FLOAT, 0, 0);
2517 	t->size = byte_sz;
2518 
2519 	return btf_commit_type(btf, sz);
2520 }
2521 
2522 /* it's completely legal to append BTF types with type IDs pointing forward to
2523  * types that haven't been appended yet, so we only make sure that id looks
2524  * sane, we can't guarantee that ID will always be valid
2525  */
2526 static int validate_type_id(int id)
2527 {
2528 	if (id < 0 || id > BTF_MAX_NR_TYPES)
2529 		return -EINVAL;
2530 	return 0;
2531 }
2532 
2533 /* generic append function for PTR, TYPEDEF, CONST/VOLATILE/RESTRICT */
2534 static int btf_add_ref_kind(struct btf *btf, int kind, const char *name, int ref_type_id, int kflag)
2535 {
2536 	struct btf_type *t;
2537 	int sz, name_off = 0;
2538 	int err;
2539 
2540 	if (validate_type_id(ref_type_id))
2541 		return libbpf_err(-EINVAL);
2542 
2543 	err = btf_ensure_modifiable(btf);
2544 	if (err)
2545 		return libbpf_err(err);
2546 
2547 	sz = sizeof(struct btf_type);
2548 	t = btf_add_type_mem(btf, sz);
2549 	if (!t)
2550 		return libbpf_err(-ENOMEM);
2551 
2552 	if (!str_is_empty(name)) {
2553 		name_off = btf__add_str(btf, name);
2554 		if (name_off < 0)
2555 			return name_off;
2556 	}
2557 
2558 	t->name_off = name_off;
2559 	t->info = btf_type_info(kind, 0, kflag);
2560 	t->type = ref_type_id;
2561 
2562 	return btf_commit_type(btf, sz);
2563 }
2564 
2565 /*
2566  * Append new BTF_KIND_PTR type with:
2567  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2568  * Returns:
2569  *   - >0, type ID of newly added BTF type;
2570  *   - <0, on error.
2571  */
2572 int btf__add_ptr(struct btf *btf, int ref_type_id)
2573 {
2574 	return btf_add_ref_kind(btf, BTF_KIND_PTR, NULL, ref_type_id, 0);
2575 }
2576 
2577 /*
2578  * Append new BTF_KIND_ARRAY type with:
2579  *   - *index_type_id* - type ID of the type describing array index;
2580  *   - *elem_type_id* - type ID of the type describing array element;
2581  *   - *nr_elems* - the size of the array;
2582  * Returns:
2583  *   - >0, type ID of newly added BTF type;
2584  *   - <0, on error.
2585  */
2586 int btf__add_array(struct btf *btf, int index_type_id, int elem_type_id, __u32 nr_elems)
2587 {
2588 	struct btf_type *t;
2589 	struct btf_array *a;
2590 	int err;
2591 	int sz;
2592 
2593 	if (validate_type_id(index_type_id) || validate_type_id(elem_type_id))
2594 		return libbpf_err(-EINVAL);
2595 
2596 	err = btf_ensure_modifiable(btf);
2597 	if (err)
2598 		return libbpf_err(err);
2599 
2600 	sz = sizeof(struct btf_type) + sizeof(struct btf_array);
2601 	t = btf_add_type_mem(btf, sz);
2602 	if (!t)
2603 		return libbpf_err(-ENOMEM);
2604 
2605 	t->name_off = 0;
2606 	t->info = btf_type_info(BTF_KIND_ARRAY, 0, 0);
2607 	t->size = 0;
2608 
2609 	a = btf_array(t);
2610 	a->type = elem_type_id;
2611 	a->index_type = index_type_id;
2612 	a->nelems = nr_elems;
2613 
2614 	return btf_commit_type(btf, sz);
2615 }
2616 
2617 /* generic STRUCT/UNION append function */
2618 static int btf_add_composite(struct btf *btf, int kind, const char *name, __u32 bytes_sz)
2619 {
2620 	struct btf_type *t;
2621 	int sz, name_off = 0;
2622 	int err;
2623 
2624 	err = btf_ensure_modifiable(btf);
2625 	if (err)
2626 		return libbpf_err(err);
2627 
2628 	sz = sizeof(struct btf_type);
2629 	t = btf_add_type_mem(btf, sz);
2630 	if (!t)
2631 		return libbpf_err(-ENOMEM);
2632 
2633 	if (!str_is_empty(name)) {
2634 		name_off = btf__add_str(btf, name);
2635 		if (name_off < 0)
2636 			return name_off;
2637 	}
2638 
2639 	/* start out with vlen=0 and no kflag; this will be adjusted when
2640 	 * adding each member
2641 	 */
2642 	t->name_off = name_off;
2643 	t->info = btf_type_info(kind, 0, 0);
2644 	t->size = bytes_sz;
2645 
2646 	return btf_commit_type(btf, sz);
2647 }
2648 
2649 /*
2650  * Append new BTF_KIND_STRUCT type with:
2651  *   - *name* - name of the struct, can be NULL or empty for anonymous structs;
2652  *   - *byte_sz* - size of the struct, in bytes;
2653  *
2654  * Struct initially has no fields in it. Fields can be added by
2655  * btf__add_field() right after btf__add_struct() succeeds.
2656  *
2657  * Returns:
2658  *   - >0, type ID of newly added BTF type;
2659  *   - <0, on error.
2660  */
2661 int btf__add_struct(struct btf *btf, const char *name, __u32 byte_sz)
2662 {
2663 	return btf_add_composite(btf, BTF_KIND_STRUCT, name, byte_sz);
2664 }
2665 
2666 /*
2667  * Append new BTF_KIND_UNION type with:
2668  *   - *name* - name of the union, can be NULL or empty for anonymous union;
2669  *   - *byte_sz* - size of the union, in bytes;
2670  *
2671  * Union initially has no fields in it. Fields can be added by
2672  * btf__add_field() right after btf__add_union() succeeds. All fields
2673  * should have *bit_offset* of 0.
2674  *
2675  * Returns:
2676  *   - >0, type ID of newly added BTF type;
2677  *   - <0, on error.
2678  */
2679 int btf__add_union(struct btf *btf, const char *name, __u32 byte_sz)
2680 {
2681 	return btf_add_composite(btf, BTF_KIND_UNION, name, byte_sz);
2682 }
2683 
2684 static struct btf_type *btf_last_type(struct btf *btf)
2685 {
2686 	return btf_type_by_id(btf, btf__type_cnt(btf) - 1);
2687 }
2688 
2689 /*
2690  * Append new field for the current STRUCT/UNION type with:
2691  *   - *name* - name of the field, can be NULL or empty for anonymous field;
2692  *   - *type_id* - type ID for the type describing field type;
2693  *   - *bit_offset* - bit offset of the start of the field within struct/union;
2694  *   - *bit_size* - bit size of a bitfield, 0 for non-bitfield fields;
2695  * Returns:
2696  *   -  0, on success;
2697  *   - <0, on error.
2698  */
2699 int btf__add_field(struct btf *btf, const char *name, int type_id,
2700 		   __u32 bit_offset, __u32 bit_size)
2701 {
2702 	struct btf_type *t;
2703 	struct btf_member *m;
2704 	bool is_bitfield;
2705 	int sz, name_off = 0;
2706 	int err;
2707 
2708 	/* last type should be union/struct */
2709 	if (btf->nr_types == 0)
2710 		return libbpf_err(-EINVAL);
2711 	t = btf_last_type(btf);
2712 	if (!btf_is_composite(t))
2713 		return libbpf_err(-EINVAL);
2714 	if (btf_vlen(t) == BTF_MAX_VLEN)
2715 		return libbpf_err(-ENOSPC);
2716 
2717 	if (validate_type_id(type_id))
2718 		return libbpf_err(-EINVAL);
2719 	/* best-effort bit field offset/size enforcement */
2720 	is_bitfield = bit_size || (bit_offset % 8 != 0);
2721 	if (is_bitfield && (bit_size == 0 || bit_size > 255 || bit_offset > 0xffffff))
2722 		return libbpf_err(-EINVAL);
2723 
2724 	/* only offset 0 is allowed for unions */
2725 	if (btf_is_union(t) && bit_offset)
2726 		return libbpf_err(-EINVAL);
2727 
2728 	/* decompose and invalidate raw data */
2729 	err = btf_ensure_modifiable(btf);
2730 	if (err)
2731 		return libbpf_err(err);
2732 
2733 	sz = sizeof(struct btf_member);
2734 	m = btf_add_type_mem(btf, sz);
2735 	if (!m)
2736 		return libbpf_err(-ENOMEM);
2737 
2738 	if (!str_is_empty(name)) {
2739 		name_off = btf__add_str(btf, name);
2740 		if (name_off < 0)
2741 			return name_off;
2742 	}
2743 
2744 	m->name_off = name_off;
2745 	m->type = type_id;
2746 	m->offset = bit_offset | (bit_size << 24);
2747 
2748 	/* btf_add_type_mem can invalidate t pointer */
2749 	t = btf_last_type(btf);
2750 
2751 	/* update parent type's vlen and kflag */
2752 	t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, is_bitfield || btf_kflag(t));
2753 
2754 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
2755 	return 0;
2756 }
2757 
2758 static int btf_add_enum_common(struct btf *btf, const char *name, __u32 byte_sz,
2759 			       bool is_signed, __u8 kind)
2760 {
2761 	struct btf_type *t;
2762 	int sz, name_off = 0;
2763 	int err;
2764 
2765 	/* byte_sz must be power of 2 */
2766 	if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 8)
2767 		return libbpf_err(-EINVAL);
2768 
2769 	err = btf_ensure_modifiable(btf);
2770 	if (err)
2771 		return libbpf_err(err);
2772 
2773 	sz = sizeof(struct btf_type);
2774 	t = btf_add_type_mem(btf, sz);
2775 	if (!t)
2776 		return libbpf_err(-ENOMEM);
2777 
2778 	if (!str_is_empty(name)) {
2779 		name_off = btf__add_str(btf, name);
2780 		if (name_off < 0)
2781 			return name_off;
2782 	}
2783 
2784 	/* start out with vlen=0; it will be adjusted when adding enum values */
2785 	t->name_off = name_off;
2786 	t->info = btf_type_info(kind, 0, is_signed);
2787 	t->size = byte_sz;
2788 
2789 	return btf_commit_type(btf, sz);
2790 }
2791 
2792 /*
2793  * Append new BTF_KIND_ENUM type with:
2794  *   - *name* - name of the enum, can be NULL or empty for anonymous enums;
2795  *   - *byte_sz* - size of the enum, in bytes.
2796  *
2797  * Enum initially has no enum values in it (and corresponds to enum forward
2798  * declaration). Enumerator values can be added by btf__add_enum_value()
2799  * immediately after btf__add_enum() succeeds.
2800  *
2801  * Returns:
2802  *   - >0, type ID of newly added BTF type;
2803  *   - <0, on error.
2804  */
2805 int btf__add_enum(struct btf *btf, const char *name, __u32 byte_sz)
2806 {
2807 	/*
2808 	 * set the signedness to be unsigned, it will change to signed
2809 	 * if any later enumerator is negative.
2810 	 */
2811 	return btf_add_enum_common(btf, name, byte_sz, false, BTF_KIND_ENUM);
2812 }
2813 
2814 /*
2815  * Append new enum value for the current ENUM type with:
2816  *   - *name* - name of the enumerator value, can't be NULL or empty;
2817  *   - *value* - integer value corresponding to enum value *name*;
2818  * Returns:
2819  *   -  0, on success;
2820  *   - <0, on error.
2821  */
2822 int btf__add_enum_value(struct btf *btf, const char *name, __s64 value)
2823 {
2824 	struct btf_type *t;
2825 	struct btf_enum *v;
2826 	int sz, name_off;
2827 	int err;
2828 
2829 	/* last type should be BTF_KIND_ENUM */
2830 	if (btf->nr_types == 0)
2831 		return libbpf_err(-EINVAL);
2832 	t = btf_last_type(btf);
2833 	if (!btf_is_enum(t))
2834 		return libbpf_err(-EINVAL);
2835 
2836 	/* non-empty name */
2837 	if (str_is_empty(name))
2838 		return libbpf_err(-EINVAL);
2839 	if (value < INT_MIN || value > UINT_MAX)
2840 		return libbpf_err(-E2BIG);
2841 
2842 	/* decompose and invalidate raw data */
2843 	err = btf_ensure_modifiable(btf);
2844 	if (err)
2845 		return libbpf_err(err);
2846 
2847 	sz = sizeof(struct btf_enum);
2848 	v = btf_add_type_mem(btf, sz);
2849 	if (!v)
2850 		return libbpf_err(-ENOMEM);
2851 
2852 	name_off = btf__add_str(btf, name);
2853 	if (name_off < 0)
2854 		return name_off;
2855 
2856 	v->name_off = name_off;
2857 	v->val = value;
2858 
2859 	/* update parent type's vlen */
2860 	t = btf_last_type(btf);
2861 	err = btf_type_inc_vlen(t);
2862 	if (err)
2863 		return libbpf_err(err);
2864 
2865 	/* if negative value, set signedness to signed */
2866 	if (value < 0)
2867 		t->info = btf_type_info(btf_kind(t), btf_vlen(t), true);
2868 
2869 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
2870 	return 0;
2871 }
2872 
2873 /*
2874  * Append new BTF_KIND_ENUM64 type with:
2875  *   - *name* - name of the enum, can be NULL or empty for anonymous enums;
2876  *   - *byte_sz* - size of the enum, in bytes.
2877  *   - *is_signed* - whether the enum values are signed or not;
2878  *
2879  * Enum initially has no enum values in it (and corresponds to enum forward
2880  * declaration). Enumerator values can be added by btf__add_enum64_value()
2881  * immediately after btf__add_enum64() succeeds.
2882  *
2883  * Returns:
2884  *   - >0, type ID of newly added BTF type;
2885  *   - <0, on error.
2886  */
2887 int btf__add_enum64(struct btf *btf, const char *name, __u32 byte_sz,
2888 		    bool is_signed)
2889 {
2890 	return btf_add_enum_common(btf, name, byte_sz, is_signed,
2891 				   BTF_KIND_ENUM64);
2892 }
2893 
2894 /*
2895  * Append new enum value for the current ENUM64 type with:
2896  *   - *name* - name of the enumerator value, can't be NULL or empty;
2897  *   - *value* - integer value corresponding to enum value *name*;
2898  * Returns:
2899  *   -  0, on success;
2900  *   - <0, on error.
2901  */
2902 int btf__add_enum64_value(struct btf *btf, const char *name, __u64 value)
2903 {
2904 	struct btf_enum64 *v;
2905 	struct btf_type *t;
2906 	int sz, name_off;
2907 	int err;
2908 
2909 	/* last type should be BTF_KIND_ENUM64 */
2910 	if (btf->nr_types == 0)
2911 		return libbpf_err(-EINVAL);
2912 	t = btf_last_type(btf);
2913 	if (!btf_is_enum64(t))
2914 		return libbpf_err(-EINVAL);
2915 
2916 	/* non-empty name */
2917 	if (str_is_empty(name))
2918 		return libbpf_err(-EINVAL);
2919 
2920 	/* decompose and invalidate raw data */
2921 	err = btf_ensure_modifiable(btf);
2922 	if (err)
2923 		return libbpf_err(err);
2924 
2925 	sz = sizeof(struct btf_enum64);
2926 	v = btf_add_type_mem(btf, sz);
2927 	if (!v)
2928 		return libbpf_err(-ENOMEM);
2929 
2930 	name_off = btf__add_str(btf, name);
2931 	if (name_off < 0)
2932 		return name_off;
2933 
2934 	v->name_off = name_off;
2935 	v->val_lo32 = (__u32)value;
2936 	v->val_hi32 = value >> 32;
2937 
2938 	/* update parent type's vlen */
2939 	t = btf_last_type(btf);
2940 	err = btf_type_inc_vlen(t);
2941 	if (err)
2942 		return libbpf_err(err);
2943 
2944 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
2945 	return 0;
2946 }
2947 
2948 /*
2949  * Append new BTF_KIND_FWD type with:
2950  *   - *name*, non-empty/non-NULL name;
2951  *   - *fwd_kind*, kind of forward declaration, one of BTF_FWD_STRUCT,
2952  *     BTF_FWD_UNION, or BTF_FWD_ENUM;
2953  * Returns:
2954  *   - >0, type ID of newly added BTF type;
2955  *   - <0, on error.
2956  */
2957 int btf__add_fwd(struct btf *btf, const char *name, enum btf_fwd_kind fwd_kind)
2958 {
2959 	if (str_is_empty(name))
2960 		return libbpf_err(-EINVAL);
2961 
2962 	switch (fwd_kind) {
2963 	case BTF_FWD_STRUCT:
2964 	case BTF_FWD_UNION: {
2965 		struct btf_type *t;
2966 		int id;
2967 
2968 		id = btf_add_ref_kind(btf, BTF_KIND_FWD, name, 0, 0);
2969 		if (id <= 0)
2970 			return id;
2971 		t = btf_type_by_id(btf, id);
2972 		t->info = btf_type_info(BTF_KIND_FWD, 0, fwd_kind == BTF_FWD_UNION);
2973 		return id;
2974 	}
2975 	case BTF_FWD_ENUM:
2976 		/* enum forward in BTF currently is just an enum with no enum
2977 		 * values; we also assume a standard 4-byte size for it
2978 		 */
2979 		return btf__add_enum(btf, name, sizeof(int));
2980 	default:
2981 		return libbpf_err(-EINVAL);
2982 	}
2983 }
2984 
2985 /*
2986  * Append new BTF_KING_TYPEDEF type with:
2987  *   - *name*, non-empty/non-NULL name;
2988  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2989  * Returns:
2990  *   - >0, type ID of newly added BTF type;
2991  *   - <0, on error.
2992  */
2993 int btf__add_typedef(struct btf *btf, const char *name, int ref_type_id)
2994 {
2995 	if (str_is_empty(name))
2996 		return libbpf_err(-EINVAL);
2997 
2998 	return btf_add_ref_kind(btf, BTF_KIND_TYPEDEF, name, ref_type_id, 0);
2999 }
3000 
3001 /*
3002  * Append new BTF_KIND_VOLATILE type with:
3003  *   - *ref_type_id* - referenced type ID, it might not exist yet;
3004  * Returns:
3005  *   - >0, type ID of newly added BTF type;
3006  *   - <0, on error.
3007  */
3008 int btf__add_volatile(struct btf *btf, int ref_type_id)
3009 {
3010 	return btf_add_ref_kind(btf, BTF_KIND_VOLATILE, NULL, ref_type_id, 0);
3011 }
3012 
3013 /*
3014  * Append new BTF_KIND_CONST type with:
3015  *   - *ref_type_id* - referenced type ID, it might not exist yet;
3016  * Returns:
3017  *   - >0, type ID of newly added BTF type;
3018  *   - <0, on error.
3019  */
3020 int btf__add_const(struct btf *btf, int ref_type_id)
3021 {
3022 	return btf_add_ref_kind(btf, BTF_KIND_CONST, NULL, ref_type_id, 0);
3023 }
3024 
3025 /*
3026  * Append new BTF_KIND_RESTRICT type with:
3027  *   - *ref_type_id* - referenced type ID, it might not exist yet;
3028  * Returns:
3029  *   - >0, type ID of newly added BTF type;
3030  *   - <0, on error.
3031  */
3032 int btf__add_restrict(struct btf *btf, int ref_type_id)
3033 {
3034 	return btf_add_ref_kind(btf, BTF_KIND_RESTRICT, NULL, ref_type_id, 0);
3035 }
3036 
3037 /*
3038  * Append new BTF_KIND_TYPE_TAG type with:
3039  *   - *value*, non-empty/non-NULL tag value;
3040  *   - *ref_type_id* - referenced type ID, it might not exist yet;
3041  * Returns:
3042  *   - >0, type ID of newly added BTF type;
3043  *   - <0, on error.
3044  */
3045 int btf__add_type_tag(struct btf *btf, const char *value, int ref_type_id)
3046 {
3047 	if (str_is_empty(value))
3048 		return libbpf_err(-EINVAL);
3049 
3050 	return btf_add_ref_kind(btf, BTF_KIND_TYPE_TAG, value, ref_type_id, 0);
3051 }
3052 
3053 /*
3054  * Append new BTF_KIND_TYPE_TAG type with:
3055  *   - *value*, non-empty/non-NULL tag value;
3056  *   - *ref_type_id* - referenced type ID, it might not exist yet;
3057  * Set info->kflag to 1, indicating this tag is an __attribute__
3058  * Returns:
3059  *   - >0, type ID of newly added BTF type;
3060  *   - <0, on error.
3061  */
3062 int btf__add_type_attr(struct btf *btf, const char *value, int ref_type_id)
3063 {
3064 	if (str_is_empty(value))
3065 		return libbpf_err(-EINVAL);
3066 
3067 	return btf_add_ref_kind(btf, BTF_KIND_TYPE_TAG, value, ref_type_id, 1);
3068 }
3069 
3070 /*
3071  * Append new BTF_KIND_FUNC type with:
3072  *   - *name*, non-empty/non-NULL name;
3073  *   - *proto_type_id* - FUNC_PROTO's type ID, it might not exist yet;
3074  * Returns:
3075  *   - >0, type ID of newly added BTF type;
3076  *   - <0, on error.
3077  */
3078 int btf__add_func(struct btf *btf, const char *name,
3079 		  enum btf_func_linkage linkage, int proto_type_id)
3080 {
3081 	int id;
3082 
3083 	if (str_is_empty(name))
3084 		return libbpf_err(-EINVAL);
3085 	if (linkage != BTF_FUNC_STATIC && linkage != BTF_FUNC_GLOBAL &&
3086 	    linkage != BTF_FUNC_EXTERN)
3087 		return libbpf_err(-EINVAL);
3088 
3089 	id = btf_add_ref_kind(btf, BTF_KIND_FUNC, name, proto_type_id, 0);
3090 	if (id > 0) {
3091 		struct btf_type *t = btf_type_by_id(btf, id);
3092 
3093 		t->info = btf_type_info(BTF_KIND_FUNC, linkage, 0);
3094 	}
3095 	return libbpf_err(id);
3096 }
3097 
3098 /*
3099  * Append new BTF_KIND_FUNC_PROTO with:
3100  *   - *ret_type_id* - type ID for return result of a function.
3101  *
3102  * Function prototype initially has no arguments, but they can be added by
3103  * btf__add_func_param() one by one, immediately after
3104  * btf__add_func_proto() succeeded.
3105  *
3106  * Returns:
3107  *   - >0, type ID of newly added BTF type;
3108  *   - <0, on error.
3109  */
3110 int btf__add_func_proto(struct btf *btf, int ret_type_id)
3111 {
3112 	struct btf_type *t;
3113 	int err;
3114 	int sz;
3115 
3116 	if (validate_type_id(ret_type_id))
3117 		return libbpf_err(-EINVAL);
3118 
3119 	err = btf_ensure_modifiable(btf);
3120 	if (err)
3121 		return libbpf_err(err);
3122 
3123 	sz = sizeof(struct btf_type);
3124 	t = btf_add_type_mem(btf, sz);
3125 	if (!t)
3126 		return libbpf_err(-ENOMEM);
3127 
3128 	/* start out with vlen=0; this will be adjusted when adding enum
3129 	 * values, if necessary
3130 	 */
3131 	t->name_off = 0;
3132 	t->info = btf_type_info(BTF_KIND_FUNC_PROTO, 0, 0);
3133 	t->type = ret_type_id;
3134 
3135 	return btf_commit_type(btf, sz);
3136 }
3137 
3138 /*
3139  * Append new function parameter for current FUNC_PROTO type with:
3140  *   - *name* - parameter name, can be NULL or empty;
3141  *   - *type_id* - type ID describing the type of the parameter.
3142  * Returns:
3143  *   -  0, on success;
3144  *   - <0, on error.
3145  */
3146 int btf__add_func_param(struct btf *btf, const char *name, int type_id)
3147 {
3148 	struct btf_type *t;
3149 	struct btf_param *p;
3150 	int sz, name_off = 0;
3151 	int err;
3152 
3153 	if (validate_type_id(type_id))
3154 		return libbpf_err(-EINVAL);
3155 
3156 	/* last type should be BTF_KIND_FUNC_PROTO */
3157 	if (btf->nr_types == 0)
3158 		return libbpf_err(-EINVAL);
3159 	t = btf_last_type(btf);
3160 	if (!btf_is_func_proto(t))
3161 		return libbpf_err(-EINVAL);
3162 
3163 	/* decompose and invalidate raw data */
3164 	err = btf_ensure_modifiable(btf);
3165 	if (err)
3166 		return libbpf_err(err);
3167 
3168 	sz = sizeof(struct btf_param);
3169 	p = btf_add_type_mem(btf, sz);
3170 	if (!p)
3171 		return libbpf_err(-ENOMEM);
3172 
3173 	if (!str_is_empty(name)) {
3174 		name_off = btf__add_str(btf, name);
3175 		if (name_off < 0)
3176 			return name_off;
3177 	}
3178 
3179 	p->name_off = name_off;
3180 	p->type = type_id;
3181 
3182 	/* update parent type's vlen */
3183 	t = btf_last_type(btf);
3184 	err = btf_type_inc_vlen(t);
3185 	if (err)
3186 		return libbpf_err(err);
3187 
3188 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
3189 	return 0;
3190 }
3191 
3192 /*
3193  * Append new BTF_KIND_VAR type with:
3194  *   - *name* - non-empty/non-NULL name;
3195  *   - *linkage* - variable linkage, one of BTF_VAR_STATIC,
3196  *     BTF_VAR_GLOBAL_ALLOCATED, or BTF_VAR_GLOBAL_EXTERN;
3197  *   - *type_id* - type ID of the type describing the type of the variable.
3198  * Returns:
3199  *   - >0, type ID of newly added BTF type;
3200  *   - <0, on error.
3201  */
3202 int btf__add_var(struct btf *btf, const char *name, int linkage, int type_id)
3203 {
3204 	struct btf_type *t;
3205 	struct btf_var *v;
3206 	int sz, name_off;
3207 	int err;
3208 
3209 	/* non-empty name */
3210 	if (str_is_empty(name))
3211 		return libbpf_err(-EINVAL);
3212 	if (linkage != BTF_VAR_STATIC && linkage != BTF_VAR_GLOBAL_ALLOCATED &&
3213 	    linkage != BTF_VAR_GLOBAL_EXTERN)
3214 		return libbpf_err(-EINVAL);
3215 	if (validate_type_id(type_id))
3216 		return libbpf_err(-EINVAL);
3217 
3218 	/* deconstruct BTF, if necessary, and invalidate raw_data */
3219 	err = btf_ensure_modifiable(btf);
3220 	if (err)
3221 		return libbpf_err(err);
3222 
3223 	sz = sizeof(struct btf_type) + sizeof(struct btf_var);
3224 	t = btf_add_type_mem(btf, sz);
3225 	if (!t)
3226 		return libbpf_err(-ENOMEM);
3227 
3228 	name_off = btf__add_str(btf, name);
3229 	if (name_off < 0)
3230 		return name_off;
3231 
3232 	t->name_off = name_off;
3233 	t->info = btf_type_info(BTF_KIND_VAR, 0, 0);
3234 	t->type = type_id;
3235 
3236 	v = btf_var(t);
3237 	v->linkage = linkage;
3238 
3239 	return btf_commit_type(btf, sz);
3240 }
3241 
3242 /*
3243  * Append new BTF_KIND_DATASEC type with:
3244  *   - *name* - non-empty/non-NULL name;
3245  *   - *byte_sz* - data section size, in bytes.
3246  *
3247  * Data section is initially empty. Variables info can be added with
3248  * btf__add_datasec_var_info() calls, after btf__add_datasec() succeeds.
3249  *
3250  * Returns:
3251  *   - >0, type ID of newly added BTF type;
3252  *   - <0, on error.
3253  */
3254 int btf__add_datasec(struct btf *btf, const char *name, __u32 byte_sz)
3255 {
3256 	struct btf_type *t;
3257 	int sz, name_off;
3258 	int err;
3259 
3260 	/* non-empty name */
3261 	if (str_is_empty(name))
3262 		return libbpf_err(-EINVAL);
3263 
3264 	err = btf_ensure_modifiable(btf);
3265 	if (err)
3266 		return libbpf_err(err);
3267 
3268 	sz = sizeof(struct btf_type);
3269 	t = btf_add_type_mem(btf, sz);
3270 	if (!t)
3271 		return libbpf_err(-ENOMEM);
3272 
3273 	name_off = btf__add_str(btf, name);
3274 	if (name_off < 0)
3275 		return name_off;
3276 
3277 	/* start with vlen=0, which will be update as var_secinfos are added */
3278 	t->name_off = name_off;
3279 	t->info = btf_type_info(BTF_KIND_DATASEC, 0, 0);
3280 	t->size = byte_sz;
3281 
3282 	return btf_commit_type(btf, sz);
3283 }
3284 
3285 /*
3286  * Append new data section variable information entry for current DATASEC type:
3287  *   - *var_type_id* - type ID, describing type of the variable;
3288  *   - *offset* - variable offset within data section, in bytes;
3289  *   - *byte_sz* - variable size, in bytes.
3290  *
3291  * Returns:
3292  *   -  0, on success;
3293  *   - <0, on error.
3294  */
3295 int btf__add_datasec_var_info(struct btf *btf, int var_type_id, __u32 offset, __u32 byte_sz)
3296 {
3297 	struct btf_type *t;
3298 	struct btf_var_secinfo *v;
3299 	int err;
3300 	int sz;
3301 
3302 	/* last type should be BTF_KIND_DATASEC */
3303 	if (btf->nr_types == 0)
3304 		return libbpf_err(-EINVAL);
3305 	t = btf_last_type(btf);
3306 	if (!btf_is_datasec(t))
3307 		return libbpf_err(-EINVAL);
3308 
3309 	if (validate_type_id(var_type_id))
3310 		return libbpf_err(-EINVAL);
3311 
3312 	/* decompose and invalidate raw data */
3313 	err = btf_ensure_modifiable(btf);
3314 	if (err)
3315 		return libbpf_err(err);
3316 
3317 	sz = sizeof(struct btf_var_secinfo);
3318 	v = btf_add_type_mem(btf, sz);
3319 	if (!v)
3320 		return libbpf_err(-ENOMEM);
3321 
3322 	v->type = var_type_id;
3323 	v->offset = offset;
3324 	v->size = byte_sz;
3325 
3326 	/* update parent type's vlen */
3327 	t = btf_last_type(btf);
3328 	err = btf_type_inc_vlen(t);
3329 	if (err)
3330 		return libbpf_err(err);
3331 
3332 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
3333 	return 0;
3334 }
3335 
3336 static int btf_add_decl_tag(struct btf *btf, const char *value, int ref_type_id,
3337 			    int component_idx, int kflag)
3338 {
3339 	struct btf_type *t;
3340 	int sz, value_off;
3341 	int err;
3342 
3343 	if (str_is_empty(value) || component_idx < -1)
3344 		return libbpf_err(-EINVAL);
3345 
3346 	if (validate_type_id(ref_type_id))
3347 		return libbpf_err(-EINVAL);
3348 
3349 	err = btf_ensure_modifiable(btf);
3350 	if (err)
3351 		return libbpf_err(err);
3352 
3353 	sz = sizeof(struct btf_type) + sizeof(struct btf_decl_tag);
3354 	t = btf_add_type_mem(btf, sz);
3355 	if (!t)
3356 		return libbpf_err(-ENOMEM);
3357 
3358 	value_off = btf__add_str(btf, value);
3359 	if (value_off < 0)
3360 		return value_off;
3361 
3362 	t->name_off = value_off;
3363 	t->info = btf_type_info(BTF_KIND_DECL_TAG, 0, kflag);
3364 	t->type = ref_type_id;
3365 	btf_decl_tag(t)->component_idx = component_idx;
3366 
3367 	return btf_commit_type(btf, sz);
3368 }
3369 
3370 /*
3371  * Append new BTF_KIND_DECL_TAG type with:
3372  *   - *value* - non-empty/non-NULL string;
3373  *   - *ref_type_id* - referenced type ID, it might not exist yet;
3374  *   - *component_idx* - -1 for tagging reference type, otherwise struct/union
3375  *     member or function argument index;
3376  * Returns:
3377  *   - >0, type ID of newly added BTF type;
3378  *   - <0, on error.
3379  */
3380 int btf__add_decl_tag(struct btf *btf, const char *value, int ref_type_id,
3381 		      int component_idx)
3382 {
3383 	return btf_add_decl_tag(btf, value, ref_type_id, component_idx, 0);
3384 }
3385 
3386 /*
3387  * Append new BTF_KIND_DECL_TAG type with:
3388  *   - *value* - non-empty/non-NULL string;
3389  *   - *ref_type_id* - referenced type ID, it might not exist yet;
3390  *   - *component_idx* - -1 for tagging reference type, otherwise struct/union
3391  *     member or function argument index;
3392  * Set info->kflag to 1, indicating this tag is an __attribute__
3393  * Returns:
3394  *   - >0, type ID of newly added BTF type;
3395  *   - <0, on error.
3396  */
3397 int btf__add_decl_attr(struct btf *btf, const char *value, int ref_type_id,
3398 		       int component_idx)
3399 {
3400 	return btf_add_decl_tag(btf, value, ref_type_id, component_idx, 1);
3401 }
3402 
3403 /*
3404  * Append new BTF_KIND_LOC_PARAM with specified size and flags.  Values are
3405  * added via btf__add_loc_param_value().
3406  *
3407  * - *byte_sz* - size of the type, in bytes (1 through 16);
3408  * - *flags* - combination of enum btf_loc_param_flags values
3409  *
3410  * Returns:
3411  *   -  >0, type ID of newly added BTF type;
3412  *   - <0, on error.
3413  */
3414 int btf__add_loc_param(struct btf *btf, __u32 byte_sz, __u32 flags)
3415 {
3416 	struct btf_loc_param *p;
3417 	struct btf_type *t;
3418 	int sz, err;
3419 
3420 	if (!byte_sz || byte_sz > 16)
3421 		return libbpf_err(-EINVAL);
3422 
3423 	err = btf_ensure_modifiable(btf);
3424 	if (err)
3425 		return libbpf_err(err);
3426 
3427 	sz = sizeof(struct btf_type) + sizeof(*p);
3428 	t = btf_add_type_mem(btf, sz);
3429 	if (!t)
3430 		return libbpf_err(-ENOMEM);
3431 
3432 	t->name_off = 0;
3433 	t->info = btf_type_info(BTF_KIND_LOC_PARAM, 0, 0);
3434 	t->size = byte_sz;
3435 
3436 	p = btf_loc_param(t);
3437 	p->flags = flags;
3438 
3439 	return btf_commit_type(btf, sz);
3440 }
3441 
3442 /*
3443  * Append *value* to existing BTF_KIND_LOC_PARAM.
3444  *
3445  * Returns:
3446  *   - 0 on success
3447  *   - <0, on error.
3448  */
3449 int btf__add_loc_param_value(struct btf *btf, __u32 value)
3450 {
3451 	struct btf_type *t;
3452 	int sz, err;
3453 	__u32 *v;
3454 
3455 	/* last type should be BTF_KIND_LOC_PARAM */
3456 	if (btf->nr_types == 0)
3457 		return libbpf_err(-EINVAL);
3458 	t = btf_last_type(btf);
3459 	if (!btf_is_loc_param(t))
3460 		return libbpf_err(-EINVAL);
3461 
3462 	/* decompose and invalidate raw data */
3463 	err = btf_ensure_modifiable(btf);
3464 	if (err)
3465 		return libbpf_err(err);
3466 
3467 	sz = sizeof(value);
3468 	v = btf_add_type_mem(btf, sz);
3469 	if (!v)
3470 		return libbpf_err(-ENOMEM);
3471 	*v = value;
3472 
3473 	/* update parent type's vlen */
3474 	t = btf_last_type(btf);
3475 	err = btf_type_inc_vlen(t);
3476 	if (err)
3477 		return libbpf_err(err);
3478 
3479 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
3480 	return 0;
3481 }
3482 
3483 /*
3484  * Append new BTF_KIND_LOC_PROTO
3485  *
3486  * The prototype is then populated with 0 or more BTF_KIND_LOC_PARAMs via
3487  * btf__add_loc_proto_param(); similar to how btf__add_func_param() adds
3488  * parameters to a FUNC_PROTO.
3489  *
3490  * Returns:
3491  *   -  >0, type ID of newly added BTF type;
3492  *   - <0, on error.
3493  */
3494 int btf__add_loc_proto(struct btf *btf)
3495 {
3496 	struct btf_type *t;
3497 	int err;
3498 
3499 	err = btf_ensure_modifiable(btf);
3500 	if (err)
3501 		return libbpf_err(err);
3502 
3503 	t = btf_add_type_mem(btf, sizeof(struct btf_type));
3504 	if (!t)
3505 		return libbpf_err(-ENOMEM);
3506 
3507 	t->name_off = 0;
3508 	t->info = btf_type_info(BTF_KIND_LOC_PROTO, 0, 0);
3509 	t->size = 0;
3510 
3511 	return btf_commit_type(btf, sizeof(struct btf_type));
3512 }
3513 
3514 /*
3515  * Append a BTF_KIND_LOC_PARAM id/0 to BTF_KIND_LOC_PROTO.
3516  *
3517  * Returns:
3518  *   - 0 on success;
3519  *   - <0, on error.
3520 
3521  */
3522 int btf__add_loc_proto_param(struct btf *btf, __u32 id)
3523 {
3524 	struct btf_type *t;
3525 	int sz, err;
3526 	__u32 *p;
3527 
3528 	if (validate_type_id(id))
3529 		return libbpf_err(-EINVAL);
3530 
3531 	/* last type should be BTF_KIND_LOC_PROTO */
3532 	if (btf->nr_types == 0)
3533 		return libbpf_err(-EINVAL);
3534 	t = btf_last_type(btf);
3535 	if (!btf_is_loc_proto(t))
3536 		return libbpf_err(-EINVAL);
3537 
3538 	/* decompose and invalidate raw data */
3539 	err = btf_ensure_modifiable(btf);
3540 	if (err)
3541 		return libbpf_err(err);
3542 
3543 	sz = sizeof(__u32);
3544 	p = btf_add_type_mem(btf, sz);
3545 	if (!p)
3546 		return libbpf_err(-ENOMEM);
3547 	*p = id;
3548 
3549 	/* update parent type's vlen */
3550 	t = btf_last_type(btf);
3551 	err = btf_type_inc_vlen(t);
3552 	if (err)
3553 		return libbpf_err(err);
3554 
3555 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
3556 	return 0;
3557 }
3558 
3559 /*
3560  * Append new BTF_KIND_LOCSEC type with:
3561  *   - *name* - non-empty/non-NULL name;
3562  *
3563  * Location section is initially empty. Location info can be added with
3564  * btf__add_locsec_loc() calls, after btf__add_locsec() succeeds.
3565  *
3566  * Returns:
3567  *   - >0, type ID of newly added BTF type;
3568  *   - <0, on error.
3569  */
3570 
3571 int btf__add_locsec(struct btf *btf, const char *name)
3572 {
3573 	struct btf_type *t;
3574 	int name_off = 0;
3575 	int err;
3576 
3577 	/* non-empty name */
3578 	if (str_is_empty(name))
3579 		return libbpf_err(-EINVAL);
3580 
3581 	err = btf_ensure_modifiable(btf);
3582 	if (err)
3583 		return libbpf_err(err);
3584 
3585 	t = btf_add_type_mem(btf, sizeof(struct btf_type));
3586 	if (!t)
3587 		return libbpf_err(-ENOMEM);
3588 
3589 	name_off = btf__add_str(btf, name);
3590 	if (name_off < 0)
3591 		return libbpf_err(name_off);
3592 	t->name_off = name_off;
3593 	t->info = btf_type_info(BTF_KIND_LOCSEC, 0, 0);
3594 	t->size = 0;
3595 
3596 	return btf_commit_type(btf, sizeof(struct btf_type));
3597 }
3598 
3599 int btf__add_locsec_loc(struct btf *btf, __u32 func, __u32 loc_proto,
3600 			__u32 offset)
3601 {
3602 	struct btf_type *t;
3603 	struct btf_loc *l;
3604 	int sz, err;
3605 
3606 	if (validate_type_id(func) || validate_type_id(loc_proto))
3607 		return libbpf_err(-EINVAL);
3608 
3609 	/* last type should be BTF_KIND_LOCSEC */
3610 	if (btf->nr_types == 0)
3611 		return libbpf_err(-EINVAL);
3612 	t = btf_last_type(btf);
3613 	if (!btf_is_locsec(t))
3614 		return libbpf_err(-EINVAL);
3615 
3616 	/* decompose and invalidate raw data */
3617 	err = btf_ensure_modifiable(btf);
3618 	if (err)
3619 		return libbpf_err(err);
3620 
3621 	sz = sizeof(*l);
3622 	l = btf_add_type_mem(btf, sz);
3623 	if (!l)
3624 		return libbpf_err(-ENOMEM);
3625 
3626 	l->func = func;
3627 	l->loc_proto = loc_proto;
3628 	l->offset = offset;
3629 
3630 	/* update parent type's vlen */
3631 	t = btf_last_type(btf);
3632 	err = btf_type_inc_vlen(t);
3633 	if (err)
3634 		return libbpf_err(err);
3635 
3636 	btf_hdr_update_type_len(btf, btf->hdr.type_len + sz);
3637 	return 0;
3638 }
3639 
3640 struct btf_ext_sec_info_param {
3641 	__u32 off;
3642 	__u32 len;
3643 	__u32 min_rec_size;
3644 	struct btf_ext_info *ext_info;
3645 	const char *desc;
3646 };
3647 
3648 /*
3649  * Parse a single info subsection of the BTF.ext info data:
3650  *  - validate subsection structure and elements
3651  *  - save info subsection start and sizing details in struct btf_ext
3652  *  - endian-independent operation, for calling before byte-swapping
3653  */
3654 static int btf_ext_parse_sec_info(struct btf_ext *btf_ext,
3655 				  struct btf_ext_sec_info_param *ext_sec,
3656 				  bool is_native)
3657 {
3658 	const struct btf_ext_info_sec *sinfo;
3659 	struct btf_ext_info *ext_info;
3660 	__u32 data_left, info_left, record_size;
3661 	size_t sec_cnt = 0;
3662 	void *info;
3663 
3664 	if (ext_sec->len == 0)
3665 		return 0;
3666 
3667 	if (ext_sec->off & 0x03) {
3668 		pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n",
3669 		     ext_sec->desc);
3670 		return -EINVAL;
3671 	}
3672 
3673 	if (btf_ext->hdr->hdr_len > btf_ext->data_size)
3674 		return -EINVAL;
3675 
3676 	data_left = btf_ext->data_size - btf_ext->hdr->hdr_len;
3677 	if (ext_sec->off > data_left || ext_sec->len > data_left - ext_sec->off) {
3678 		pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n",
3679 			 ext_sec->desc, ext_sec->off, ext_sec->len);
3680 		return -EINVAL;
3681 	}
3682 
3683 	/* The start of the info sec (including the __u32 record_size). */
3684 	info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off;
3685 	info_left = ext_sec->len;
3686 
3687 	/* At least a record size */
3688 	if (info_left < sizeof(__u32)) {
3689 		pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc);
3690 		return -EINVAL;
3691 	}
3692 
3693 	/* The record size needs to meet either the minimum standard or, when
3694 	 * handling non-native endianness data, the exact standard so as
3695 	 * to allow safe byte-swapping.
3696 	 */
3697 	record_size = is_native ? *(__u32 *)info : bswap_32(*(__u32 *)info);
3698 	if (record_size < ext_sec->min_rec_size ||
3699 	    (!is_native && record_size != ext_sec->min_rec_size) ||
3700 	    record_size & 0x03) {
3701 		pr_debug("%s section in .BTF.ext has invalid record size %u\n",
3702 			 ext_sec->desc, record_size);
3703 		return -EINVAL;
3704 	}
3705 
3706 	sinfo = info + sizeof(__u32);
3707 	info_left -= sizeof(__u32);
3708 
3709 	/* If no records, return failure now so .BTF.ext won't be used. */
3710 	if (!info_left) {
3711 		pr_debug("%s section in .BTF.ext has no records\n", ext_sec->desc);
3712 		return -EINVAL;
3713 	}
3714 
3715 	while (info_left) {
3716 		unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec);
3717 		__u64 total_record_size;
3718 		__u32 num_records;
3719 
3720 		if (info_left < sec_hdrlen) {
3721 			pr_debug("%s section header is not found in .BTF.ext\n",
3722 			     ext_sec->desc);
3723 			return -EINVAL;
3724 		}
3725 
3726 		num_records = is_native ? sinfo->num_info : bswap_32(sinfo->num_info);
3727 		if (num_records == 0) {
3728 			pr_debug("%s section has incorrect num_records in .BTF.ext\n",
3729 			     ext_sec->desc);
3730 			return -EINVAL;
3731 		}
3732 
3733 		total_record_size = sec_hdrlen + (__u64)num_records * record_size;
3734 		if (info_left < total_record_size) {
3735 			pr_debug("%s section has incorrect num_records in .BTF.ext\n",
3736 			     ext_sec->desc);
3737 			return -EINVAL;
3738 		}
3739 
3740 		info_left -= total_record_size;
3741 		sinfo = (void *)sinfo + total_record_size;
3742 		sec_cnt++;
3743 	}
3744 
3745 	ext_info = ext_sec->ext_info;
3746 	ext_info->len = ext_sec->len - sizeof(__u32);
3747 	ext_info->rec_size = record_size;
3748 	ext_info->info = info + sizeof(__u32);
3749 	ext_info->sec_cnt = sec_cnt;
3750 
3751 	return 0;
3752 }
3753 
3754 /* Parse all info secs in the BTF.ext info data */
3755 static int btf_ext_parse_info(struct btf_ext *btf_ext, bool is_native)
3756 {
3757 	struct btf_ext_sec_info_param func_info = {
3758 		.off = btf_ext->hdr->func_info_off,
3759 		.len = btf_ext->hdr->func_info_len,
3760 		.min_rec_size = sizeof(struct bpf_func_info_min),
3761 		.ext_info = &btf_ext->func_info,
3762 		.desc = "func_info"
3763 	};
3764 	struct btf_ext_sec_info_param line_info = {
3765 		.off = btf_ext->hdr->line_info_off,
3766 		.len = btf_ext->hdr->line_info_len,
3767 		.min_rec_size = sizeof(struct bpf_line_info_min),
3768 		.ext_info = &btf_ext->line_info,
3769 		.desc = "line_info",
3770 	};
3771 	struct btf_ext_sec_info_param core_relo = {
3772 		.min_rec_size = sizeof(struct bpf_core_relo),
3773 		.ext_info = &btf_ext->core_relo_info,
3774 		.desc = "core_relo",
3775 	};
3776 	int err;
3777 
3778 	err = btf_ext_parse_sec_info(btf_ext, &func_info, is_native);
3779 	if (err)
3780 		return err;
3781 
3782 	err = btf_ext_parse_sec_info(btf_ext, &line_info, is_native);
3783 	if (err)
3784 		return err;
3785 
3786 	if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len))
3787 		return 0; /* skip core relos parsing */
3788 
3789 	core_relo.off = btf_ext->hdr->core_relo_off;
3790 	core_relo.len = btf_ext->hdr->core_relo_len;
3791 	err = btf_ext_parse_sec_info(btf_ext, &core_relo, is_native);
3792 	if (err)
3793 		return err;
3794 
3795 	return 0;
3796 }
3797 
3798 /* Swap byte-order of BTF.ext header with any endianness */
3799 static void btf_ext_bswap_hdr(struct btf_ext_header *h)
3800 {
3801 	bool is_native = h->magic == BTF_MAGIC;
3802 	__u32 hdr_len;
3803 
3804 	hdr_len = is_native ? h->hdr_len : bswap_32(h->hdr_len);
3805 
3806 	h->magic = bswap_16(h->magic);
3807 	h->hdr_len = bswap_32(h->hdr_len);
3808 	h->func_info_off = bswap_32(h->func_info_off);
3809 	h->func_info_len = bswap_32(h->func_info_len);
3810 	h->line_info_off = bswap_32(h->line_info_off);
3811 	h->line_info_len = bswap_32(h->line_info_len);
3812 
3813 	if (hdr_len < offsetofend(struct btf_ext_header, core_relo_len))
3814 		return;
3815 
3816 	h->core_relo_off = bswap_32(h->core_relo_off);
3817 	h->core_relo_len = bswap_32(h->core_relo_len);
3818 }
3819 
3820 /* Swap byte-order of generic info subsection */
3821 static void btf_ext_bswap_info_sec(void *info, __u32 len, bool is_native,
3822 				   info_rec_bswap_fn bswap_fn)
3823 {
3824 	struct btf_ext_info_sec *sec;
3825 	__u32 info_left, rec_size, *rs;
3826 
3827 	if (len == 0)
3828 		return;
3829 
3830 	rs = info;				/* info record size */
3831 	rec_size = is_native ? *rs : bswap_32(*rs);
3832 	*rs = bswap_32(*rs);
3833 
3834 	sec = info + sizeof(__u32);		/* info sec #1 */
3835 	info_left = len - sizeof(__u32);
3836 	while (info_left) {
3837 		unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec);
3838 		__u32 i, num_recs;
3839 		void *p;
3840 
3841 		num_recs = is_native ? sec->num_info : bswap_32(sec->num_info);
3842 		sec->sec_name_off = bswap_32(sec->sec_name_off);
3843 		sec->num_info = bswap_32(sec->num_info);
3844 		p = sec->data;			/* info rec #1 */
3845 		for (i = 0; i < num_recs; i++, p += rec_size)
3846 			bswap_fn(p);
3847 		sec = p;
3848 		info_left -= sec_hdrlen + (__u64)rec_size * num_recs;
3849 	}
3850 }
3851 
3852 /*
3853  * Swap byte-order of all info data in a BTF.ext section
3854  *  - requires BTF.ext hdr in native endianness
3855  */
3856 static void btf_ext_bswap_info(struct btf_ext *btf_ext, void *data)
3857 {
3858 	const bool is_native = btf_ext->swapped_endian;
3859 	const struct btf_ext_header *h = data;
3860 	void *info;
3861 
3862 	/* Swap func_info subsection byte-order */
3863 	info = data + h->hdr_len + h->func_info_off;
3864 	btf_ext_bswap_info_sec(info, h->func_info_len, is_native,
3865 			       (info_rec_bswap_fn)bpf_func_info_bswap);
3866 
3867 	/* Swap line_info subsection byte-order */
3868 	info = data + h->hdr_len + h->line_info_off;
3869 	btf_ext_bswap_info_sec(info, h->line_info_len, is_native,
3870 			       (info_rec_bswap_fn)bpf_line_info_bswap);
3871 
3872 	/* Swap core_relo subsection byte-order (if present) */
3873 	if (h->hdr_len < offsetofend(struct btf_ext_header, core_relo_len))
3874 		return;
3875 
3876 	info = data + h->hdr_len + h->core_relo_off;
3877 	btf_ext_bswap_info_sec(info, h->core_relo_len, is_native,
3878 			       (info_rec_bswap_fn)bpf_core_relo_bswap);
3879 }
3880 
3881 /* Parse hdr data and info sections: check and convert to native endianness */
3882 static int btf_ext_parse(struct btf_ext *btf_ext)
3883 {
3884 	__u32 hdr_len, data_size = btf_ext->data_size;
3885 	struct btf_ext_header *hdr = btf_ext->hdr;
3886 	bool swapped_endian = false;
3887 	int err;
3888 
3889 	if (data_size < offsetofend(struct btf_ext_header, hdr_len)) {
3890 		pr_debug("BTF.ext header too short\n");
3891 		return -EINVAL;
3892 	}
3893 
3894 	hdr_len = hdr->hdr_len;
3895 	if (hdr->magic == bswap_16(BTF_MAGIC)) {
3896 		swapped_endian = true;
3897 		hdr_len = bswap_32(hdr_len);
3898 	} else if (hdr->magic != BTF_MAGIC) {
3899 		pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic);
3900 		return -EINVAL;
3901 	}
3902 
3903 	/* Ensure known version of structs, current BTF_VERSION == 1 */
3904 	if (hdr->version != 1) {
3905 		pr_debug("Unsupported BTF.ext version:%u\n", hdr->version);
3906 		return -ENOTSUP;
3907 	}
3908 
3909 	if (hdr->flags) {
3910 		pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags);
3911 		return -ENOTSUP;
3912 	}
3913 
3914 	if (data_size < hdr_len) {
3915 		pr_debug("BTF.ext header not found\n");
3916 		return -EINVAL;
3917 	} else if (data_size == hdr_len) {
3918 		pr_debug("BTF.ext has no data\n");
3919 		return -EINVAL;
3920 	}
3921 
3922 	/* Verify mandatory hdr info details present */
3923 	if (hdr_len < offsetofend(struct btf_ext_header, line_info_len)) {
3924 		pr_warn("BTF.ext header missing func_info, line_info\n");
3925 		return -EINVAL;
3926 	}
3927 
3928 	/* Keep hdr native byte-order in memory for introspection */
3929 	if (swapped_endian)
3930 		btf_ext_bswap_hdr(btf_ext->hdr);
3931 
3932 	/* Validate info subsections and cache key metadata */
3933 	err = btf_ext_parse_info(btf_ext, !swapped_endian);
3934 	if (err)
3935 		return err;
3936 
3937 	/* Keep infos native byte-order in memory for introspection */
3938 	if (swapped_endian)
3939 		btf_ext_bswap_info(btf_ext, btf_ext->data);
3940 
3941 	/*
3942 	 * Set btf_ext->swapped_endian only after all header and info data has
3943 	 * been swapped, helping bswap functions determine if their data are
3944 	 * in native byte-order when called.
3945 	 */
3946 	btf_ext->swapped_endian = swapped_endian;
3947 	return 0;
3948 }
3949 
3950 void btf_ext__free(struct btf_ext *btf_ext)
3951 {
3952 	if (IS_ERR_OR_NULL(btf_ext))
3953 		return;
3954 	free(btf_ext->func_info.sec_idxs);
3955 	free(btf_ext->line_info.sec_idxs);
3956 	free(btf_ext->core_relo_info.sec_idxs);
3957 	free(btf_ext->data);
3958 	free(btf_ext->data_swapped);
3959 	free(btf_ext);
3960 }
3961 
3962 struct btf_ext *btf_ext__new(const __u8 *data, __u32 size)
3963 {
3964 	struct btf_ext *btf_ext;
3965 	int err;
3966 
3967 	btf_ext = calloc(1, sizeof(struct btf_ext));
3968 	if (!btf_ext)
3969 		return libbpf_err_ptr(-ENOMEM);
3970 
3971 	btf_ext->data_size = size;
3972 	btf_ext->data = malloc(size);
3973 	if (!btf_ext->data) {
3974 		err = -ENOMEM;
3975 		goto done;
3976 	}
3977 	memcpy(btf_ext->data, data, size);
3978 
3979 	err = btf_ext_parse(btf_ext);
3980 
3981 done:
3982 	if (err) {
3983 		btf_ext__free(btf_ext);
3984 		return libbpf_err_ptr(err);
3985 	}
3986 
3987 	return btf_ext;
3988 }
3989 
3990 static void *btf_ext_raw_data(const struct btf_ext *btf_ext_ro, bool swap_endian)
3991 {
3992 	struct btf_ext *btf_ext = (struct btf_ext *)btf_ext_ro;
3993 	const __u32 data_sz = btf_ext->data_size;
3994 	void *data;
3995 
3996 	/* Return native data (always present) or swapped data if present */
3997 	if (!swap_endian)
3998 		return btf_ext->data;
3999 	else if (btf_ext->data_swapped)
4000 		return btf_ext->data_swapped;
4001 
4002 	/* Recreate missing swapped data, then cache and return */
4003 	data = calloc(1, data_sz);
4004 	if (!data)
4005 		return NULL;
4006 	memcpy(data, btf_ext->data, data_sz);
4007 
4008 	btf_ext_bswap_info(btf_ext, data);
4009 	btf_ext_bswap_hdr(data);
4010 	btf_ext->data_swapped = data;
4011 	return data;
4012 }
4013 
4014 const void *btf_ext__raw_data(const struct btf_ext *btf_ext, __u32 *size)
4015 {
4016 	void *data;
4017 
4018 	data = btf_ext_raw_data(btf_ext, btf_ext->swapped_endian);
4019 	if (!data)
4020 		return errno = ENOMEM, NULL;
4021 
4022 	*size = btf_ext->data_size;
4023 	return data;
4024 }
4025 
4026 __attribute__((alias("btf_ext__raw_data")))
4027 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size);
4028 
4029 enum btf_endianness btf_ext__endianness(const struct btf_ext *btf_ext)
4030 {
4031 	if (is_host_big_endian())
4032 		return btf_ext->swapped_endian ? BTF_LITTLE_ENDIAN : BTF_BIG_ENDIAN;
4033 	else
4034 		return btf_ext->swapped_endian ? BTF_BIG_ENDIAN : BTF_LITTLE_ENDIAN;
4035 }
4036 
4037 int btf_ext__set_endianness(struct btf_ext *btf_ext, enum btf_endianness endian)
4038 {
4039 	if (endian != BTF_LITTLE_ENDIAN && endian != BTF_BIG_ENDIAN)
4040 		return libbpf_err(-EINVAL);
4041 
4042 	btf_ext->swapped_endian = is_host_big_endian() != (endian == BTF_BIG_ENDIAN);
4043 
4044 	if (!btf_ext->swapped_endian) {
4045 		free(btf_ext->data_swapped);
4046 		btf_ext->data_swapped = NULL;
4047 	}
4048 	return 0;
4049 }
4050 
4051 struct btf_dedup;
4052 
4053 static struct btf_dedup *btf_dedup_new(struct btf *btf, const struct btf_dedup_opts *opts);
4054 static void btf_dedup_free(struct btf_dedup *d);
4055 static int btf_dedup_prep(struct btf_dedup *d);
4056 static int btf_dedup_strings(struct btf_dedup *d);
4057 static int btf_dedup_prim_types(struct btf_dedup *d);
4058 static int btf_dedup_struct_types(struct btf_dedup *d);
4059 static int btf_dedup_ref_types(struct btf_dedup *d);
4060 static int btf_dedup_resolve_fwds(struct btf_dedup *d);
4061 static int btf_dedup_compact_types(struct btf_dedup *d);
4062 static int btf_dedup_remap_types(struct btf_dedup *d);
4063 
4064 /*
4065  * Deduplicate BTF types and strings.
4066  *
4067  * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF
4068  * section with all BTF type descriptors and string data. It overwrites that
4069  * memory in-place with deduplicated types and strings without any loss of
4070  * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section
4071  * is provided, all the strings referenced from .BTF.ext section are honored
4072  * and updated to point to the right offsets after deduplication.
4073  *
4074  * If function returns with error, type/string data might be garbled and should
4075  * be discarded.
4076  *
4077  * More verbose and detailed description of both problem btf_dedup is solving,
4078  * as well as solution could be found at:
4079  * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html
4080  *
4081  * Problem description and justification
4082  * =====================================
4083  *
4084  * BTF type information is typically emitted either as a result of conversion
4085  * from DWARF to BTF or directly by compiler. In both cases, each compilation
4086  * unit contains information about a subset of all the types that are used
4087  * in an application. These subsets are frequently overlapping and contain a lot
4088  * of duplicated information when later concatenated together into a single
4089  * binary. This algorithm ensures that each unique type is represented by single
4090  * BTF type descriptor, greatly reducing resulting size of BTF data.
4091  *
4092  * Compilation unit isolation and subsequent duplication of data is not the only
4093  * problem. The same type hierarchy (e.g., struct and all the type that struct
4094  * references) in different compilation units can be represented in BTF to
4095  * various degrees of completeness (or, rather, incompleteness) due to
4096  * struct/union forward declarations.
4097  *
4098  * Let's take a look at an example, that we'll use to better understand the
4099  * problem (and solution). Suppose we have two compilation units, each using
4100  * same `struct S`, but each of them having incomplete type information about
4101  * struct's fields:
4102  *
4103  * // CU #1:
4104  * struct S;
4105  * struct A {
4106  *	int a;
4107  *	struct A* self;
4108  *	struct S* parent;
4109  * };
4110  * struct B;
4111  * struct S {
4112  *	struct A* a_ptr;
4113  *	struct B* b_ptr;
4114  * };
4115  *
4116  * // CU #2:
4117  * struct S;
4118  * struct A;
4119  * struct B {
4120  *	int b;
4121  *	struct B* self;
4122  *	struct S* parent;
4123  * };
4124  * struct S {
4125  *	struct A* a_ptr;
4126  *	struct B* b_ptr;
4127  * };
4128  *
4129  * In case of CU #1, BTF data will know only that `struct B` exist (but no
4130  * more), but will know the complete type information about `struct A`. While
4131  * for CU #2, it will know full type information about `struct B`, but will
4132  * only know about forward declaration of `struct A` (in BTF terms, it will
4133  * have `BTF_KIND_FWD` type descriptor with name `B`).
4134  *
4135  * This compilation unit isolation means that it's possible that there is no
4136  * single CU with complete type information describing structs `S`, `A`, and
4137  * `B`. Also, we might get tons of duplicated and redundant type information.
4138  *
4139  * Additional complication we need to keep in mind comes from the fact that
4140  * types, in general, can form graphs containing cycles, not just DAGs.
4141  *
4142  * While algorithm does deduplication, it also merges and resolves type
4143  * information (unless disabled throught `struct btf_opts`), whenever possible.
4144  * E.g., in the example above with two compilation units having partial type
4145  * information for structs `A` and `B`, the output of algorithm will emit
4146  * a single copy of each BTF type that describes structs `A`, `B`, and `S`
4147  * (as well as type information for `int` and pointers), as if they were defined
4148  * in a single compilation unit as:
4149  *
4150  * struct A {
4151  *	int a;
4152  *	struct A* self;
4153  *	struct S* parent;
4154  * };
4155  * struct B {
4156  *	int b;
4157  *	struct B* self;
4158  *	struct S* parent;
4159  * };
4160  * struct S {
4161  *	struct A* a_ptr;
4162  *	struct B* b_ptr;
4163  * };
4164  *
4165  * Algorithm summary
4166  * =================
4167  *
4168  * Algorithm completes its work in 7 separate passes:
4169  *
4170  * 1. Strings deduplication.
4171  * 2. Primitive types deduplication (int, enum, fwd).
4172  * 3. Struct/union types deduplication.
4173  * 4. Resolve unambiguous forward declarations.
4174  * 5. Reference types deduplication (pointers, typedefs, arrays, funcs, func
4175  *    protos, and const/volatile/restrict modifiers).
4176  * 6. Types compaction.
4177  * 7. Types remapping.
4178  *
4179  * Algorithm determines canonical type descriptor, which is a single
4180  * representative type for each truly unique type. This canonical type is the
4181  * one that will go into final deduplicated BTF type information. For
4182  * struct/unions, it is also the type that algorithm will merge additional type
4183  * information into (while resolving FWDs), as it discovers it from data in
4184  * other CUs. Each input BTF type eventually gets either mapped to itself, if
4185  * that type is canonical, or to some other type, if that type is equivalent
4186  * and was chosen as canonical representative. This mapping is stored in
4187  * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that
4188  * FWD type got resolved to.
4189  *
4190  * To facilitate fast discovery of canonical types, we also maintain canonical
4191  * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash
4192  * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types
4193  * that match that signature. With sufficiently good choice of type signature
4194  * hashing function, we can limit number of canonical types for each unique type
4195  * signature to a very small number, allowing to find canonical type for any
4196  * duplicated type very quickly.
4197  *
4198  * Struct/union deduplication is the most critical part and algorithm for
4199  * deduplicating structs/unions is described in greater details in comments for
4200  * `btf_dedup_is_equiv` function.
4201  */
4202 int btf__dedup(struct btf *btf, const struct btf_dedup_opts *opts)
4203 {
4204 	struct btf_dedup *d;
4205 	int err;
4206 
4207 	if (!OPTS_VALID(opts, btf_dedup_opts))
4208 		return libbpf_err(-EINVAL);
4209 
4210 	d = btf_dedup_new(btf, opts);
4211 	if (IS_ERR(d)) {
4212 		pr_debug("btf_dedup_new failed: %ld\n", PTR_ERR(d));
4213 		return libbpf_err(-EINVAL);
4214 	}
4215 
4216 	err = btf_ensure_modifiable(btf);
4217 	if (err)
4218 		goto done;
4219 
4220 	err = btf_dedup_prep(d);
4221 	if (err) {
4222 		pr_debug("btf_dedup_prep failed: %s\n", errstr(err));
4223 		goto done;
4224 	}
4225 	err = btf_dedup_strings(d);
4226 	if (err < 0) {
4227 		pr_debug("btf_dedup_strings failed: %s\n", errstr(err));
4228 		goto done;
4229 	}
4230 	err = btf_dedup_prim_types(d);
4231 	if (err < 0) {
4232 		pr_debug("btf_dedup_prim_types failed: %s\n", errstr(err));
4233 		goto done;
4234 	}
4235 	err = btf_dedup_struct_types(d);
4236 	if (err < 0) {
4237 		pr_debug("btf_dedup_struct_types failed: %s\n", errstr(err));
4238 		goto done;
4239 	}
4240 	err = btf_dedup_resolve_fwds(d);
4241 	if (err < 0) {
4242 		pr_debug("btf_dedup_resolve_fwds failed: %s\n", errstr(err));
4243 		goto done;
4244 	}
4245 	err = btf_dedup_ref_types(d);
4246 	if (err < 0) {
4247 		pr_debug("btf_dedup_ref_types failed: %s\n", errstr(err));
4248 		goto done;
4249 	}
4250 	err = btf_dedup_compact_types(d);
4251 	if (err < 0) {
4252 		pr_debug("btf_dedup_compact_types failed: %s\n", errstr(err));
4253 		goto done;
4254 	}
4255 	err = btf_dedup_remap_types(d);
4256 	if (err < 0) {
4257 		pr_debug("btf_dedup_remap_types failed: %s\n", errstr(err));
4258 		goto done;
4259 	}
4260 
4261 done:
4262 	btf_dedup_free(d);
4263 	return libbpf_err(err);
4264 }
4265 
4266 #define BTF_UNPROCESSED_ID ((__u32)-1)
4267 #define BTF_IN_PROGRESS_ID ((__u32)-2)
4268 
4269 struct btf_dedup {
4270 	/* .BTF section to be deduped in-place */
4271 	struct btf *btf;
4272 	/*
4273 	 * Optional .BTF.ext section. When provided, any strings referenced
4274 	 * from it will be taken into account when deduping strings
4275 	 */
4276 	struct btf_ext *btf_ext;
4277 	/*
4278 	 * This is a map from any type's signature hash to a list of possible
4279 	 * canonical representative type candidates. Hash collisions are
4280 	 * ignored, so even types of various kinds can share same list of
4281 	 * candidates, which is fine because we rely on subsequent
4282 	 * btf_xxx_equal() checks to authoritatively verify type equality.
4283 	 */
4284 	struct hashmap *dedup_table;
4285 	/* Canonical types map */
4286 	__u32 *map;
4287 	/* Hypothetical mapping, used during type graph equivalence checks */
4288 	__u32 *hypot_map;
4289 	__u32 *hypot_list;
4290 	size_t hypot_cnt;
4291 	size_t hypot_cap;
4292 	/* Whether hypothetical mapping, if successful, would need to adjust
4293 	 * already canonicalized types (due to a new forward declaration to
4294 	 * concrete type resolution). In such case, during split BTF dedup
4295 	 * candidate type would still be considered as different, because base
4296 	 * BTF is considered to be immutable.
4297 	 */
4298 	bool hypot_adjust_canon;
4299 	/* Various option modifying behavior of algorithm */
4300 	struct btf_dedup_opts opts;
4301 	/* temporary strings deduplication state */
4302 	struct strset *strs_set;
4303 };
4304 
4305 static unsigned long hash_combine(unsigned long h, unsigned long value)
4306 {
4307 	return h * 31 + value;
4308 }
4309 
4310 #define for_each_dedup_cand(d, node, hash) \
4311 	hashmap__for_each_key_entry(d->dedup_table, node, hash)
4312 
4313 static int btf_dedup_table_add(struct btf_dedup *d, long hash, __u32 type_id)
4314 {
4315 	return hashmap__append(d->dedup_table, hash, type_id);
4316 }
4317 
4318 static int btf_dedup_hypot_map_add(struct btf_dedup *d,
4319 				   __u32 from_id, __u32 to_id)
4320 {
4321 	if (d->hypot_cnt == d->hypot_cap) {
4322 		__u32 *new_list;
4323 
4324 		d->hypot_cap += max((size_t)16, d->hypot_cap / 2);
4325 		new_list = libbpf_reallocarray(d->hypot_list, d->hypot_cap, sizeof(__u32));
4326 		if (!new_list)
4327 			return -ENOMEM;
4328 		d->hypot_list = new_list;
4329 	}
4330 	d->hypot_list[d->hypot_cnt++] = from_id;
4331 	d->hypot_map[from_id] = to_id;
4332 	return 0;
4333 }
4334 
4335 static void btf_dedup_clear_hypot_map(struct btf_dedup *d)
4336 {
4337 	int i;
4338 
4339 	for (i = 0; i < d->hypot_cnt; i++)
4340 		d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID;
4341 	d->hypot_cnt = 0;
4342 	d->hypot_adjust_canon = false;
4343 }
4344 
4345 static void btf_dedup_free(struct btf_dedup *d)
4346 {
4347 	hashmap__free(d->dedup_table);
4348 	d->dedup_table = NULL;
4349 
4350 	free(d->map);
4351 	d->map = NULL;
4352 
4353 	free(d->hypot_map);
4354 	d->hypot_map = NULL;
4355 
4356 	free(d->hypot_list);
4357 	d->hypot_list = NULL;
4358 
4359 	free(d);
4360 }
4361 
4362 static size_t btf_dedup_identity_hash_fn(long key, void *ctx)
4363 {
4364 	return key;
4365 }
4366 
4367 static size_t btf_dedup_collision_hash_fn(long key, void *ctx)
4368 {
4369 	return 0;
4370 }
4371 
4372 static bool btf_dedup_equal_fn(long k1, long k2, void *ctx)
4373 {
4374 	return k1 == k2;
4375 }
4376 
4377 static struct btf_dedup *btf_dedup_new(struct btf *btf, const struct btf_dedup_opts *opts)
4378 {
4379 	struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup));
4380 	hashmap_hash_fn hash_fn = btf_dedup_identity_hash_fn;
4381 	int i, err = 0, type_cnt;
4382 
4383 	if (!d)
4384 		return ERR_PTR(-ENOMEM);
4385 
4386 	if (OPTS_GET(opts, force_collisions, false))
4387 		hash_fn = btf_dedup_collision_hash_fn;
4388 
4389 	d->btf = btf;
4390 	d->btf_ext = OPTS_GET(opts, btf_ext, NULL);
4391 
4392 	d->dedup_table = hashmap__new(hash_fn, btf_dedup_equal_fn, NULL);
4393 	if (IS_ERR(d->dedup_table)) {
4394 		err = PTR_ERR(d->dedup_table);
4395 		d->dedup_table = NULL;
4396 		goto done;
4397 	}
4398 
4399 	type_cnt = btf__type_cnt(btf);
4400 	d->map = malloc(sizeof(__u32) * type_cnt);
4401 	if (!d->map) {
4402 		err = -ENOMEM;
4403 		goto done;
4404 	}
4405 	/* special BTF "void" type is made canonical immediately */
4406 	d->map[0] = 0;
4407 	for (i = 1; i < type_cnt; i++) {
4408 		struct btf_type *t = btf_type_by_id(d->btf, i);
4409 
4410 		/* VAR, DATASEC and LOCSEC are never deduped and are self-canonical */
4411 		if (btf_is_var(t) || btf_is_datasec(t) || btf_is_locsec(t))
4412 			d->map[i] = i;
4413 		else
4414 			d->map[i] = BTF_UNPROCESSED_ID;
4415 	}
4416 
4417 	d->hypot_map = malloc(sizeof(__u32) * type_cnt);
4418 	if (!d->hypot_map) {
4419 		err = -ENOMEM;
4420 		goto done;
4421 	}
4422 	for (i = 0; i < type_cnt; i++)
4423 		d->hypot_map[i] = BTF_UNPROCESSED_ID;
4424 
4425 done:
4426 	if (err) {
4427 		btf_dedup_free(d);
4428 		return ERR_PTR(err);
4429 	}
4430 
4431 	return d;
4432 }
4433 
4434 /*
4435  * Iterate over all possible places in .BTF and .BTF.ext that can reference
4436  * string and pass pointer to it to a provided callback `fn`.
4437  */
4438 static int btf_for_each_str_off(struct btf_dedup *d, str_off_visit_fn fn, void *ctx)
4439 {
4440 	int i, r;
4441 
4442 	for (i = 0; i < d->btf->nr_types; i++) {
4443 		struct btf_field_iter it;
4444 		struct btf_type *t = btf_type_by_id(d->btf, d->btf->start_id + i);
4445 		__u32 *str_off;
4446 
4447 		r = btf_field_iter_init(&it, t, BTF_FIELD_ITER_STRS);
4448 		if (r)
4449 			return r;
4450 
4451 		while ((str_off = btf_field_iter_next(&it))) {
4452 			r = fn(str_off, ctx);
4453 			if (r)
4454 				return r;
4455 		}
4456 	}
4457 
4458 	if (!d->btf_ext)
4459 		return 0;
4460 
4461 	r = btf_ext_visit_str_offs(d->btf_ext, fn, ctx);
4462 	if (r)
4463 		return r;
4464 
4465 	return 0;
4466 }
4467 
4468 static int strs_dedup_remap_str_off(__u32 *str_off_ptr, void *ctx)
4469 {
4470 	struct btf_dedup *d = ctx;
4471 	__u32 str_off = *str_off_ptr;
4472 	const char *s;
4473 	int off, err;
4474 
4475 	/* don't touch empty string or string in main BTF */
4476 	if (str_off == 0 || str_off < d->btf->start_str_off)
4477 		return 0;
4478 
4479 	s = btf__str_by_offset(d->btf, str_off);
4480 	if (d->btf->base_btf) {
4481 		err = btf__find_str(d->btf->base_btf, s);
4482 		if (err >= 0) {
4483 			*str_off_ptr = err;
4484 			return 0;
4485 		}
4486 		if (err != -ENOENT)
4487 			return err;
4488 	}
4489 
4490 	off = strset__add_str(d->strs_set, s);
4491 	if (off < 0)
4492 		return off;
4493 
4494 	*str_off_ptr = d->btf->start_str_off + off;
4495 	return 0;
4496 }
4497 
4498 /*
4499  * Dedup string and filter out those that are not referenced from either .BTF
4500  * or .BTF.ext (if provided) sections.
4501  *
4502  * This is done by building index of all strings in BTF's string section,
4503  * then iterating over all entities that can reference strings (e.g., type
4504  * names, struct field names, .BTF.ext line info, etc) and marking corresponding
4505  * strings as used. After that all used strings are deduped and compacted into
4506  * sequential blob of memory and new offsets are calculated. Then all the string
4507  * references are iterated again and rewritten using new offsets.
4508  */
4509 static int btf_dedup_strings(struct btf_dedup *d)
4510 {
4511 	int err;
4512 
4513 	if (d->btf->strs_deduped)
4514 		return 0;
4515 
4516 	d->strs_set = strset__new(BTF_MAX_STR_OFFSET, NULL, 0);
4517 	if (IS_ERR(d->strs_set)) {
4518 		err = PTR_ERR(d->strs_set);
4519 		goto err_out;
4520 	}
4521 
4522 	if (!d->btf->base_btf) {
4523 		/* insert empty string; we won't be looking it up during strings
4524 		 * dedup, but it's good to have it for generic BTF string lookups
4525 		 */
4526 		err = strset__add_str(d->strs_set, "");
4527 		if (err < 0)
4528 			goto err_out;
4529 	}
4530 
4531 	/* remap string offsets */
4532 	err = btf_for_each_str_off(d, strs_dedup_remap_str_off, d);
4533 	if (err)
4534 		goto err_out;
4535 
4536 	/* replace BTF string data and hash with deduped ones */
4537 	strset__free(d->btf->strs_set);
4538 	btf_hdr_update_str_len(d->btf, strset__data_size(d->strs_set));
4539 	d->btf->strs_set = d->strs_set;
4540 	d->strs_set = NULL;
4541 	d->btf->strs_deduped = true;
4542 	return 0;
4543 
4544 err_out:
4545 	strset__free(d->strs_set);
4546 	d->strs_set = NULL;
4547 
4548 	return err;
4549 }
4550 
4551 /*
4552  * Calculate type signature hash of TYPEDEF, ignoring referenced type IDs,
4553  * as referenced type IDs equivalence is established separately during type
4554  * graph equivalence check algorithm.
4555  */
4556 static long btf_hash_typedef(struct btf_type *t)
4557 {
4558 	long h;
4559 
4560 	h = hash_combine(0, t->name_off);
4561 	h = hash_combine(h, t->info);
4562 	return h;
4563 }
4564 
4565 static long btf_hash_common(struct btf_type *t)
4566 {
4567 	long h;
4568 
4569 	h = hash_combine(0, t->name_off);
4570 	h = hash_combine(h, t->info);
4571 	h = hash_combine(h, t->size);
4572 	return h;
4573 }
4574 
4575 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2)
4576 {
4577 	return t1->name_off == t2->name_off &&
4578 	       t1->info == t2->info &&
4579 	       t1->size == t2->size;
4580 }
4581 
4582 /* Check structural compatibility of two TYPEDEF. */
4583 static bool btf_equal_typedef(struct btf_type *t1, struct btf_type *t2)
4584 {
4585 	return t1->name_off == t2->name_off &&
4586 	       t1->info == t2->info;
4587 }
4588 
4589 /* Calculate type signature hash of INT or TAG. */
4590 static long btf_hash_int_decl_tag(struct btf_type *t)
4591 {
4592 	__u32 info = *(__u32 *)(t + 1);
4593 	long h;
4594 
4595 	h = btf_hash_common(t);
4596 	h = hash_combine(h, info);
4597 	return h;
4598 }
4599 
4600 /* Check structural equality of two INTs or TAGs. */
4601 static bool btf_equal_int_tag(struct btf_type *t1, struct btf_type *t2)
4602 {
4603 	__u32 info1, info2;
4604 
4605 	if (!btf_equal_common(t1, t2))
4606 		return false;
4607 	info1 = *(__u32 *)(t1 + 1);
4608 	info2 = *(__u32 *)(t2 + 1);
4609 	return info1 == info2;
4610 }
4611 
4612 /* Calculate type signature hash of ENUM/ENUM64. */
4613 static long btf_hash_enum(struct btf_type *t)
4614 {
4615 	long h;
4616 
4617 	/* don't hash vlen, enum members and size to support enum fwd resolving */
4618 	h = hash_combine(0, t->name_off);
4619 	return h;
4620 }
4621 
4622 static bool btf_equal_enum_members(struct btf_type *t1, struct btf_type *t2)
4623 {
4624 	const struct btf_enum *m1, *m2;
4625 	__u32 vlen;
4626 	int i;
4627 
4628 	vlen = btf_vlen(t1);
4629 	m1 = btf_enum(t1);
4630 	m2 = btf_enum(t2);
4631 	for (i = 0; i < vlen; i++) {
4632 		if (m1->name_off != m2->name_off || m1->val != m2->val)
4633 			return false;
4634 		m1++;
4635 		m2++;
4636 	}
4637 	return true;
4638 }
4639 
4640 static bool btf_equal_enum64_members(struct btf_type *t1, struct btf_type *t2)
4641 {
4642 	const struct btf_enum64 *m1, *m2;
4643 	__u32 vlen;
4644 	int i;
4645 
4646 	vlen = btf_vlen(t1);
4647 	m1 = btf_enum64(t1);
4648 	m2 = btf_enum64(t2);
4649 	for (i = 0; i < vlen; i++) {
4650 		if (m1->name_off != m2->name_off || m1->val_lo32 != m2->val_lo32 ||
4651 		    m1->val_hi32 != m2->val_hi32)
4652 			return false;
4653 		m1++;
4654 		m2++;
4655 	}
4656 	return true;
4657 }
4658 
4659 /* Check structural equality of two ENUMs or ENUM64s. */
4660 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2)
4661 {
4662 	if (!btf_equal_common(t1, t2))
4663 		return false;
4664 
4665 	/* t1 & t2 kinds are identical because of btf_equal_common */
4666 	if (btf_kind(t1) == BTF_KIND_ENUM)
4667 		return btf_equal_enum_members(t1, t2);
4668 	else
4669 		return btf_equal_enum64_members(t1, t2);
4670 }
4671 
4672 static inline bool btf_is_enum_fwd(struct btf_type *t)
4673 {
4674 	return btf_is_any_enum(t) && btf_vlen(t) == 0;
4675 }
4676 
4677 static bool btf_compat_enum(struct btf_type *t1, struct btf_type *t2)
4678 {
4679 	if (!btf_is_enum_fwd(t1) && !btf_is_enum_fwd(t2))
4680 		return btf_equal_enum(t1, t2);
4681 	/* At this point either t1 or t2 or both are forward declarations, thus:
4682 	 * - skip comparing vlen because it is zero for forward declarations;
4683 	 * - skip comparing size to allow enum forward declarations
4684 	 *   to be compatible with enum64 full declarations;
4685 	 * - skip comparing kind for the same reason.
4686 	 */
4687 	return t1->name_off == t2->name_off &&
4688 	       btf_is_any_enum(t1) && btf_is_any_enum(t2);
4689 }
4690 
4691 static long btf_hash_loc_param(struct btf_type *t)
4692 {
4693 	struct btf_loc_param *p = btf_loc_param(t);
4694 	long h = btf_hash_common(t);
4695 	int i, vlen = btf_vlen(t);
4696 
4697 	h = hash_combine(h, p->flags);
4698 
4699 	for (i = 0; i < vlen; i++)
4700 		h = hash_combine(h, p->values[i]);
4701 	return h;
4702 }
4703 
4704 static long btf_hash_loc_proto(struct btf_type *t)
4705 {
4706 	__u32 *p = btf_loc_proto_params(t);
4707 	long h = btf_hash_common(t);
4708 	int i, vlen = btf_vlen(t);
4709 
4710 	for (i = 0; i < vlen; i++, p++)
4711 		h = hash_combine(h, *p);
4712 	return h;
4713 }
4714 
4715 static bool btf_equal_loc_param(struct btf_type *t1, struct btf_type *t2)
4716 {
4717 	struct btf_loc_param *p1 = btf_loc_param(t1);
4718 	struct btf_loc_param *p2 = btf_loc_param(t2);
4719 	int i, vlen = btf_vlen(t1);
4720 
4721 	if (!btf_equal_common(t1, t2))
4722 		return false;
4723 	if (p1->flags != p2->flags)
4724 		return false;
4725 	for (i = 0; i < vlen; i++) {
4726 		if (p1->values[i] != p2->values[i])
4727 			return false;
4728 	}
4729 	return true;
4730 }
4731 
4732 /*
4733  * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs,
4734  * as referenced type IDs equivalence is established separately during type
4735  * graph equivalence check algorithm.
4736  */
4737 static long btf_hash_struct(struct btf_type *t)
4738 {
4739 	const struct btf_member *member = btf_members(t);
4740 	__u32 vlen = btf_vlen(t);
4741 	long h = btf_hash_common(t);
4742 	int i;
4743 
4744 	for (i = 0; i < vlen; i++) {
4745 		h = hash_combine(h, member->name_off);
4746 		h = hash_combine(h, member->offset);
4747 		/* no hashing of referenced type ID, it can be unresolved yet */
4748 		member++;
4749 	}
4750 	return h;
4751 }
4752 
4753 /*
4754  * Check structural compatibility of two STRUCTs/UNIONs, ignoring referenced
4755  * type IDs. This check is performed during type graph equivalence check and
4756  * referenced types equivalence is checked separately.
4757  */
4758 static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2)
4759 {
4760 	const struct btf_member *m1, *m2;
4761 	__u32 vlen;
4762 	int i;
4763 
4764 	if (!btf_equal_common(t1, t2))
4765 		return false;
4766 
4767 	vlen = btf_vlen(t1);
4768 	m1 = btf_members(t1);
4769 	m2 = btf_members(t2);
4770 	for (i = 0; i < vlen; i++) {
4771 		if (m1->name_off != m2->name_off || m1->offset != m2->offset)
4772 			return false;
4773 		m1++;
4774 		m2++;
4775 	}
4776 	return true;
4777 }
4778 
4779 /*
4780  * Calculate type signature hash of ARRAY, including referenced type IDs,
4781  * under assumption that they were already resolved to canonical type IDs and
4782  * are not going to change.
4783  */
4784 static long btf_hash_array(struct btf_type *t)
4785 {
4786 	const struct btf_array *info = btf_array(t);
4787 	long h = btf_hash_common(t);
4788 
4789 	h = hash_combine(h, info->type);
4790 	h = hash_combine(h, info->index_type);
4791 	h = hash_combine(h, info->nelems);
4792 	return h;
4793 }
4794 
4795 /*
4796  * Check exact equality of two ARRAYs, taking into account referenced
4797  * type IDs, under assumption that they were already resolved to canonical
4798  * type IDs and are not going to change.
4799  * This function is called during reference types deduplication to compare
4800  * ARRAY to potential canonical representative.
4801  */
4802 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2)
4803 {
4804 	const struct btf_array *info1, *info2;
4805 
4806 	if (!btf_equal_common(t1, t2))
4807 		return false;
4808 
4809 	info1 = btf_array(t1);
4810 	info2 = btf_array(t2);
4811 	return info1->type == info2->type &&
4812 	       info1->index_type == info2->index_type &&
4813 	       info1->nelems == info2->nelems;
4814 }
4815 
4816 /*
4817  * Check structural compatibility of two ARRAYs, ignoring referenced type
4818  * IDs. This check is performed during type graph equivalence check and
4819  * referenced types equivalence is checked separately.
4820  */
4821 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2)
4822 {
4823 	if (!btf_equal_common(t1, t2))
4824 		return false;
4825 
4826 	return btf_array(t1)->nelems == btf_array(t2)->nelems;
4827 }
4828 
4829 /*
4830  * Calculate type signature hash of FUNC_PROTO, including referenced type IDs,
4831  * under assumption that they were already resolved to canonical type IDs and
4832  * are not going to change.
4833  */
4834 static long btf_hash_fnproto(struct btf_type *t)
4835 {
4836 	const struct btf_param *member = btf_params(t);
4837 	__u32 vlen = btf_vlen(t);
4838 	long h = btf_hash_common(t);
4839 	int i;
4840 
4841 	for (i = 0; i < vlen; i++) {
4842 		h = hash_combine(h, member->name_off);
4843 		h = hash_combine(h, member->type);
4844 		member++;
4845 	}
4846 	return h;
4847 }
4848 
4849 /*
4850  * Check exact equality of two FUNC_PROTOs, taking into account referenced
4851  * type IDs, under assumption that they were already resolved to canonical
4852  * type IDs and are not going to change.
4853  * This function is called during reference types deduplication to compare
4854  * FUNC_PROTO to potential canonical representative.
4855  */
4856 static bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2)
4857 {
4858 	const struct btf_param *m1, *m2;
4859 	__u32 vlen;
4860 	int i;
4861 
4862 	if (!btf_equal_common(t1, t2))
4863 		return false;
4864 
4865 	vlen = btf_vlen(t1);
4866 	m1 = btf_params(t1);
4867 	m2 = btf_params(t2);
4868 	for (i = 0; i < vlen; i++) {
4869 		if (m1->name_off != m2->name_off || m1->type != m2->type)
4870 			return false;
4871 		m1++;
4872 		m2++;
4873 	}
4874 	return true;
4875 }
4876 
4877 /*
4878  * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
4879  * IDs. This check is performed during type graph equivalence check and
4880  * referenced types equivalence is checked separately.
4881  */
4882 static bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2)
4883 {
4884 	const struct btf_param *m1, *m2;
4885 	__u32 vlen;
4886 	int i;
4887 
4888 	/* skip return type ID */
4889 	if (t1->name_off != t2->name_off || t1->info != t2->info)
4890 		return false;
4891 
4892 	vlen = btf_vlen(t1);
4893 	m1 = btf_params(t1);
4894 	m2 = btf_params(t2);
4895 	for (i = 0; i < vlen; i++) {
4896 		if (m1->name_off != m2->name_off)
4897 			return false;
4898 		m1++;
4899 		m2++;
4900 	}
4901 	return true;
4902 }
4903 
4904 /* Prepare split BTF for deduplication by calculating hashes of base BTF's
4905  * types and initializing the rest of the state (canonical type mapping) for
4906  * the fixed base BTF part.
4907  */
4908 static int btf_dedup_prep(struct btf_dedup *d)
4909 {
4910 	struct btf_type *t;
4911 	int type_id;
4912 	long h;
4913 
4914 	if (!d->btf->base_btf)
4915 		return 0;
4916 
4917 	for (type_id = 1; type_id < d->btf->start_id; type_id++) {
4918 		t = btf_type_by_id(d->btf, type_id);
4919 
4920 		/* all base BTF types are self-canonical by definition */
4921 		d->map[type_id] = type_id;
4922 
4923 		switch (btf_kind(t)) {
4924 		case BTF_KIND_VAR:
4925 		case BTF_KIND_DATASEC:
4926 		case BTF_KIND_LOCSEC:
4927 			/* VAR DATASEC and LOCSEC are never hash/deduplicated */
4928 			continue;
4929 		case BTF_KIND_CONST:
4930 		case BTF_KIND_VOLATILE:
4931 		case BTF_KIND_RESTRICT:
4932 		case BTF_KIND_PTR:
4933 		case BTF_KIND_FWD:
4934 		case BTF_KIND_FUNC:
4935 		case BTF_KIND_FLOAT:
4936 		case BTF_KIND_TYPE_TAG:
4937 			h = btf_hash_common(t);
4938 			break;
4939 		case BTF_KIND_TYPEDEF:
4940 			h = btf_hash_typedef(t);
4941 			break;
4942 		case BTF_KIND_INT:
4943 		case BTF_KIND_DECL_TAG:
4944 			h = btf_hash_int_decl_tag(t);
4945 			break;
4946 		case BTF_KIND_ENUM:
4947 		case BTF_KIND_ENUM64:
4948 			h = btf_hash_enum(t);
4949 			break;
4950 		case BTF_KIND_STRUCT:
4951 		case BTF_KIND_UNION:
4952 			h = btf_hash_struct(t);
4953 			break;
4954 		case BTF_KIND_ARRAY:
4955 			h = btf_hash_array(t);
4956 			break;
4957 		case BTF_KIND_FUNC_PROTO:
4958 			h = btf_hash_fnproto(t);
4959 			break;
4960 		case BTF_KIND_LOC_PARAM:
4961 			h = btf_hash_loc_param(t);
4962 			break;
4963 		case BTF_KIND_LOC_PROTO:
4964 			h = btf_hash_loc_proto(t);
4965 			break;
4966 		default:
4967 			pr_debug("unknown kind %d for type [%d]\n", btf_kind(t), type_id);
4968 			return -EINVAL;
4969 		}
4970 		if (btf_dedup_table_add(d, h, type_id))
4971 			return -ENOMEM;
4972 	}
4973 
4974 	return 0;
4975 }
4976 
4977 /*
4978  * Deduplicate primitive types, that can't reference other types, by calculating
4979  * their type signature hash and comparing them with any possible canonical
4980  * candidate. If no canonical candidate matches, type itself is marked as
4981  * canonical and is added into `btf_dedup->dedup_table` as another candidate.
4982  */
4983 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id)
4984 {
4985 	struct btf_type *t = btf_type_by_id(d->btf, type_id);
4986 	struct hashmap_entry *hash_entry;
4987 	struct btf_type *cand;
4988 	/* if we don't find equivalent type, then we are canonical */
4989 	__u32 new_id = type_id;
4990 	__u32 cand_id;
4991 	long h;
4992 
4993 	switch (btf_kind(t)) {
4994 	case BTF_KIND_CONST:
4995 	case BTF_KIND_VOLATILE:
4996 	case BTF_KIND_RESTRICT:
4997 	case BTF_KIND_PTR:
4998 	case BTF_KIND_TYPEDEF:
4999 	case BTF_KIND_ARRAY:
5000 	case BTF_KIND_STRUCT:
5001 	case BTF_KIND_UNION:
5002 	case BTF_KIND_FUNC:
5003 	case BTF_KIND_FUNC_PROTO:
5004 	case BTF_KIND_VAR:
5005 	case BTF_KIND_DATASEC:
5006 	case BTF_KIND_DECL_TAG:
5007 	case BTF_KIND_TYPE_TAG:
5008 	case BTF_KIND_LOC_PROTO:
5009 	case BTF_KIND_LOCSEC:
5010 		return 0;
5011 
5012 	case BTF_KIND_INT:
5013 		h = btf_hash_int_decl_tag(t);
5014 		for_each_dedup_cand(d, hash_entry, h) {
5015 			cand_id = hash_entry->value;
5016 			cand = btf_type_by_id(d->btf, cand_id);
5017 			if (btf_equal_int_tag(t, cand)) {
5018 				new_id = cand_id;
5019 				break;
5020 			}
5021 		}
5022 		break;
5023 
5024 	case BTF_KIND_ENUM:
5025 	case BTF_KIND_ENUM64:
5026 		h = btf_hash_enum(t);
5027 		for_each_dedup_cand(d, hash_entry, h) {
5028 			cand_id = hash_entry->value;
5029 			cand = btf_type_by_id(d->btf, cand_id);
5030 			if (btf_equal_enum(t, cand)) {
5031 				new_id = cand_id;
5032 				break;
5033 			}
5034 			if (btf_compat_enum(t, cand)) {
5035 				if (btf_is_enum_fwd(t)) {
5036 					/* resolve fwd to full enum */
5037 					new_id = cand_id;
5038 					break;
5039 				}
5040 				/* resolve canonical enum fwd to full enum */
5041 				d->map[cand_id] = type_id;
5042 			}
5043 		}
5044 		break;
5045 
5046 	case BTF_KIND_FWD:
5047 	case BTF_KIND_FLOAT:
5048 		h = btf_hash_common(t);
5049 		for_each_dedup_cand(d, hash_entry, h) {
5050 			cand_id = hash_entry->value;
5051 			cand = btf_type_by_id(d->btf, cand_id);
5052 			if (btf_equal_common(t, cand)) {
5053 				new_id = cand_id;
5054 				break;
5055 			}
5056 		}
5057 		break;
5058 
5059 	case BTF_KIND_LOC_PARAM:
5060 		h = btf_hash_loc_param(t);
5061 		for_each_dedup_cand(d, hash_entry, h) {
5062 			cand_id = hash_entry->value;
5063 			cand = btf_type_by_id(d->btf, cand_id);
5064 			if (btf_equal_loc_param(t, cand)) {
5065 				new_id = cand_id;
5066 				break;
5067 			}
5068 		}
5069 		break;
5070 
5071 	default:
5072 		return -EINVAL;
5073 	}
5074 
5075 	d->map[type_id] = new_id;
5076 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
5077 		return -ENOMEM;
5078 
5079 	return 0;
5080 }
5081 
5082 static int btf_dedup_prim_types(struct btf_dedup *d)
5083 {
5084 	int i, err;
5085 
5086 	for (i = 0; i < d->btf->nr_types; i++) {
5087 		err = btf_dedup_prim_type(d, d->btf->start_id + i);
5088 		if (err)
5089 			return err;
5090 	}
5091 	return 0;
5092 }
5093 
5094 /*
5095  * Check whether type is already mapped into canonical one (could be to itself).
5096  */
5097 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id)
5098 {
5099 	return d->map[type_id] <= BTF_MAX_NR_TYPES;
5100 }
5101 
5102 /*
5103  * Resolve type ID into its canonical type ID, if any; otherwise return original
5104  * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow
5105  * STRUCT/UNION link and resolve it into canonical type ID as well.
5106  */
5107 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id)
5108 {
5109 	while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
5110 		type_id = d->map[type_id];
5111 	return type_id;
5112 }
5113 
5114 /*
5115  * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original
5116  * type ID.
5117  */
5118 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id)
5119 {
5120 	__u32 orig_type_id = type_id;
5121 
5122 	if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
5123 		return type_id;
5124 
5125 	while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
5126 		type_id = d->map[type_id];
5127 
5128 	if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
5129 		return type_id;
5130 
5131 	return orig_type_id;
5132 }
5133 
5134 
5135 static inline __u16 btf_fwd_kind(struct btf_type *t)
5136 {
5137 	return btf_kflag(t) ? BTF_KIND_UNION : BTF_KIND_STRUCT;
5138 }
5139 
5140 static bool btf_dedup_identical_types(struct btf_dedup *d, __u32 id1, __u32 id2, int depth)
5141 {
5142 	struct btf_type *t1, *t2;
5143 	int k1, k2;
5144 recur:
5145 	t1 = btf_type_by_id(d->btf, id1);
5146 	t2 = btf_type_by_id(d->btf, id2);
5147 	if (depth <= 0) {
5148 		pr_debug("Reached depth limit for identical type comparison for '%s'/'%s'\n",
5149 			 btf__name_by_offset(d->btf, t1->name_off),
5150 			 btf__name_by_offset(d->btf, t2->name_off));
5151 		return false;
5152 	}
5153 
5154 	k1 = btf_kind(t1);
5155 	k2 = btf_kind(t2);
5156 	if (k1 != k2)
5157 		return false;
5158 
5159 	switch (k1) {
5160 	case BTF_KIND_UNKN: /* VOID */
5161 		return true;
5162 	case BTF_KIND_INT:
5163 		return btf_equal_int_tag(t1, t2);
5164 	case BTF_KIND_ENUM:
5165 	case BTF_KIND_ENUM64:
5166 		return btf_compat_enum(t1, t2);
5167 	case BTF_KIND_FWD:
5168 	case BTF_KIND_FLOAT:
5169 		return btf_equal_common(t1, t2);
5170 	case BTF_KIND_CONST:
5171 	case BTF_KIND_VOLATILE:
5172 	case BTF_KIND_RESTRICT:
5173 	case BTF_KIND_PTR:
5174 	case BTF_KIND_TYPEDEF:
5175 	case BTF_KIND_FUNC:
5176 	case BTF_KIND_TYPE_TAG:
5177 		if (t1->info != t2->info || t1->name_off != t2->name_off)
5178 			return false;
5179 		id1 = t1->type;
5180 		id2 = t2->type;
5181 		goto recur;
5182 	case BTF_KIND_ARRAY: {
5183 		struct btf_array *a1, *a2;
5184 
5185 		if (!btf_compat_array(t1, t2))
5186 			return false;
5187 
5188 		a1 = btf_array(t1);
5189 		a2 = btf_array(t2);
5190 
5191 		if (a1->index_type != a2->index_type &&
5192 		    !btf_dedup_identical_types(d, a1->index_type, a2->index_type, depth - 1))
5193 			return false;
5194 
5195 		if (a1->type != a2->type &&
5196 		    !btf_dedup_identical_types(d, a1->type, a2->type, depth - 1))
5197 			return false;
5198 
5199 		return true;
5200 	}
5201 	case BTF_KIND_STRUCT:
5202 	case BTF_KIND_UNION: {
5203 		const struct btf_member *m1, *m2;
5204 		int i, n;
5205 
5206 		if (!btf_shallow_equal_struct(t1, t2))
5207 			return false;
5208 
5209 		m1 = btf_members(t1);
5210 		m2 = btf_members(t2);
5211 		for (i = 0, n = btf_vlen(t1); i < n; i++, m1++, m2++) {
5212 			if (m1->type == m2->type)
5213 				continue;
5214 			if (!btf_dedup_identical_types(d, m1->type, m2->type, depth - 1)) {
5215 				if (t1->name_off) {
5216 					pr_debug("%s '%s' size=%u vlen=%u id1[%u] id2[%u] shallow-equal but not identical for field#%d '%s'\n",
5217 						 k1 == BTF_KIND_STRUCT ? "STRUCT" : "UNION",
5218 						 btf__name_by_offset(d->btf, t1->name_off),
5219 						 t1->size, btf_vlen(t1), id1, id2, i,
5220 						 btf__name_by_offset(d->btf, m1->name_off));
5221 				}
5222 				return false;
5223 			}
5224 		}
5225 		return true;
5226 	}
5227 	case BTF_KIND_FUNC_PROTO: {
5228 		const struct btf_param *p1, *p2;
5229 		int i, n;
5230 
5231 		if (!btf_compat_fnproto(t1, t2))
5232 			return false;
5233 
5234 		if (t1->type != t2->type &&
5235 		    !btf_dedup_identical_types(d, t1->type, t2->type, depth - 1))
5236 			return false;
5237 
5238 		p1 = btf_params(t1);
5239 		p2 = btf_params(t2);
5240 		for (i = 0, n = btf_vlen(t1); i < n; i++, p1++, p2++) {
5241 			if (p1->type == p2->type)
5242 				continue;
5243 			if (!btf_dedup_identical_types(d, p1->type, p2->type, depth - 1))
5244 				return false;
5245 		}
5246 		return true;
5247 	}
5248 	default:
5249 		return false;
5250 	}
5251 }
5252 
5253 
5254 /*
5255  * Check equivalence of BTF type graph formed by candidate struct/union (we'll
5256  * call it "candidate graph" in this description for brevity) to a type graph
5257  * formed by (potential) canonical struct/union ("canonical graph" for brevity
5258  * here, though keep in mind that not all types in canonical graph are
5259  * necessarily canonical representatives themselves, some of them might be
5260  * duplicates or its uniqueness might not have been established yet).
5261  * Returns:
5262  *  - >0, if type graphs are equivalent;
5263  *  -  0, if not equivalent;
5264  *  - <0, on error.
5265  *
5266  * Algorithm performs side-by-side DFS traversal of both type graphs and checks
5267  * equivalence of BTF types at each step. If at any point BTF types in candidate
5268  * and canonical graphs are not compatible structurally, whole graphs are
5269  * incompatible. If types are structurally equivalent (i.e., all information
5270  * except referenced type IDs is exactly the same), a mapping from `canon_id` to
5271  * a `cand_id` is recoded in hypothetical mapping (`btf_dedup->hypot_map`).
5272  * If a type references other types, then those referenced types are checked
5273  * for equivalence recursively.
5274  *
5275  * During DFS traversal, if we find that for current `canon_id` type we
5276  * already have some mapping in hypothetical map, we check for two possible
5277  * situations:
5278  *   - `canon_id` is mapped to exactly the same type as `cand_id`. This will
5279  *     happen when type graphs have cycles. In this case we assume those two
5280  *     types are equivalent.
5281  *   - `canon_id` is mapped to different type. This is contradiction in our
5282  *     hypothetical mapping, because same graph in canonical graph corresponds
5283  *     to two different types in candidate graph, which for equivalent type
5284  *     graphs shouldn't happen. This condition terminates equivalence check
5285  *     with negative result.
5286  *
5287  * If type graphs traversal exhausts types to check and find no contradiction,
5288  * then type graphs are equivalent.
5289  *
5290  * When checking types for equivalence, there is one special case: FWD types.
5291  * If FWD type resolution is allowed and one of the types (either from canonical
5292  * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind
5293  * flag) and their names match, hypothetical mapping is updated to point from
5294  * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully,
5295  * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently.
5296  *
5297  * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution,
5298  * if there are two exactly named (or anonymous) structs/unions that are
5299  * compatible structurally, one of which has FWD field, while other is concrete
5300  * STRUCT/UNION, but according to C sources they are different structs/unions
5301  * that are referencing different types with the same name. This is extremely
5302  * unlikely to happen, but btf_dedup API allows to disable FWD resolution if
5303  * this logic is causing problems.
5304  *
5305  * Doing FWD resolution means that both candidate and/or canonical graphs can
5306  * consists of portions of the graph that come from multiple compilation units.
5307  * This is due to the fact that types within single compilation unit are always
5308  * deduplicated and FWDs are already resolved, if referenced struct/union
5309  * definition is available. So, if we had unresolved FWD and found corresponding
5310  * STRUCT/UNION, they will be from different compilation units. This
5311  * consequently means that when we "link" FWD to corresponding STRUCT/UNION,
5312  * type graph will likely have at least two different BTF types that describe
5313  * same type (e.g., most probably there will be two different BTF types for the
5314  * same 'int' primitive type) and could even have "overlapping" parts of type
5315  * graph that describe same subset of types.
5316  *
5317  * This in turn means that our assumption that each type in canonical graph
5318  * must correspond to exactly one type in candidate graph might not hold
5319  * anymore and will make it harder to detect contradictions using hypothetical
5320  * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION
5321  * resolution only in canonical graph. FWDs in candidate graphs are never
5322  * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs
5323  * that can occur:
5324  *   - Both types in canonical and candidate graphs are FWDs. If they are
5325  *     structurally equivalent, then they can either be both resolved to the
5326  *     same STRUCT/UNION or not resolved at all. In both cases they are
5327  *     equivalent and there is no need to resolve FWD on candidate side.
5328  *   - Both types in canonical and candidate graphs are concrete STRUCT/UNION,
5329  *     so nothing to resolve as well, algorithm will check equivalence anyway.
5330  *   - Type in canonical graph is FWD, while type in candidate is concrete
5331  *     STRUCT/UNION. In this case candidate graph comes from single compilation
5332  *     unit, so there is exactly one BTF type for each unique C type. After
5333  *     resolving FWD into STRUCT/UNION, there might be more than one BTF type
5334  *     in canonical graph mapping to single BTF type in candidate graph, but
5335  *     because hypothetical mapping maps from canonical to candidate types, it's
5336  *     alright, and we still maintain the property of having single `canon_id`
5337  *     mapping to single `cand_id` (there could be two different `canon_id`
5338  *     mapped to the same `cand_id`, but it's not contradictory).
5339  *   - Type in canonical graph is concrete STRUCT/UNION, while type in candidate
5340  *     graph is FWD. In this case we are just going to check compatibility of
5341  *     STRUCT/UNION and corresponding FWD, and if they are compatible, we'll
5342  *     assume that whatever STRUCT/UNION FWD resolves to must be equivalent to
5343  *     a concrete STRUCT/UNION from canonical graph. If the rest of type graphs
5344  *     turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from
5345  *     canonical graph.
5346  */
5347 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id,
5348 			      __u32 canon_id)
5349 {
5350 	struct btf_type *cand_type;
5351 	struct btf_type *canon_type;
5352 	__u32 hypot_type_id;
5353 	__u16 cand_kind;
5354 	__u16 canon_kind;
5355 	int i, eq;
5356 
5357 	/* if both resolve to the same canonical, they must be equivalent */
5358 	if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id))
5359 		return 1;
5360 
5361 	canon_id = resolve_fwd_id(d, canon_id);
5362 
5363 	hypot_type_id = d->hypot_map[canon_id];
5364 	if (hypot_type_id <= BTF_MAX_NR_TYPES) {
5365 		if (hypot_type_id == cand_id)
5366 			return 1;
5367 		/* In some cases compiler will generate different DWARF types
5368 		 * for *identical* array type definitions and use them for
5369 		 * different fields within the *same* struct. This breaks type
5370 		 * equivalence check, which makes an assumption that candidate
5371 		 * types sub-graph has a consistent and deduped-by-compiler
5372 		 * types within a single CU. And similar situation can happen
5373 		 * with struct/union sometimes, and event with pointers.
5374 		 * So accommodate cases like this doing a structural
5375 		 * comparison recursively, but avoiding being stuck in endless
5376 		 * loops by limiting the depth up to which we check.
5377 		 */
5378 		if (btf_dedup_identical_types(d, hypot_type_id, cand_id, 16))
5379 			return 1;
5380 		return 0;
5381 	}
5382 
5383 	if (btf_dedup_hypot_map_add(d, canon_id, cand_id))
5384 		return -ENOMEM;
5385 
5386 	cand_type = btf_type_by_id(d->btf, cand_id);
5387 	canon_type = btf_type_by_id(d->btf, canon_id);
5388 	cand_kind = btf_kind(cand_type);
5389 	canon_kind = btf_kind(canon_type);
5390 
5391 	if (cand_type->name_off != canon_type->name_off)
5392 		return 0;
5393 
5394 	/* FWD <--> STRUCT/UNION equivalence check, if enabled */
5395 	if ((cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD)
5396 	    && cand_kind != canon_kind) {
5397 		__u16 real_kind;
5398 		__u16 fwd_kind;
5399 
5400 		if (cand_kind == BTF_KIND_FWD) {
5401 			real_kind = canon_kind;
5402 			fwd_kind = btf_fwd_kind(cand_type);
5403 		} else {
5404 			real_kind = cand_kind;
5405 			fwd_kind = btf_fwd_kind(canon_type);
5406 			/* we'd need to resolve base FWD to STRUCT/UNION */
5407 			if (fwd_kind == real_kind && canon_id < d->btf->start_id)
5408 				d->hypot_adjust_canon = true;
5409 		}
5410 		return fwd_kind == real_kind;
5411 	}
5412 
5413 	if (cand_kind != canon_kind)
5414 		return 0;
5415 
5416 	switch (cand_kind) {
5417 	case BTF_KIND_INT:
5418 		return btf_equal_int_tag(cand_type, canon_type);
5419 
5420 	case BTF_KIND_ENUM:
5421 	case BTF_KIND_ENUM64:
5422 		return btf_compat_enum(cand_type, canon_type);
5423 
5424 	case BTF_KIND_FWD:
5425 	case BTF_KIND_FLOAT:
5426 		return btf_equal_common(cand_type, canon_type);
5427 
5428 	case BTF_KIND_CONST:
5429 	case BTF_KIND_VOLATILE:
5430 	case BTF_KIND_RESTRICT:
5431 	case BTF_KIND_PTR:
5432 	case BTF_KIND_TYPEDEF:
5433 	case BTF_KIND_FUNC:
5434 	case BTF_KIND_TYPE_TAG:
5435 		if (cand_type->info != canon_type->info)
5436 			return 0;
5437 		return btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
5438 
5439 	case BTF_KIND_ARRAY: {
5440 		const struct btf_array *cand_arr, *canon_arr;
5441 
5442 		if (!btf_compat_array(cand_type, canon_type))
5443 			return 0;
5444 		cand_arr = btf_array(cand_type);
5445 		canon_arr = btf_array(canon_type);
5446 		eq = btf_dedup_is_equiv(d, cand_arr->index_type, canon_arr->index_type);
5447 		if (eq <= 0)
5448 			return eq;
5449 		return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type);
5450 	}
5451 
5452 	case BTF_KIND_STRUCT:
5453 	case BTF_KIND_UNION: {
5454 		const struct btf_member *cand_m, *canon_m;
5455 		__u32 vlen;
5456 
5457 		if (!btf_shallow_equal_struct(cand_type, canon_type))
5458 			return 0;
5459 		vlen = btf_vlen(cand_type);
5460 		cand_m = btf_members(cand_type);
5461 		canon_m = btf_members(canon_type);
5462 		for (i = 0; i < vlen; i++) {
5463 			eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type);
5464 			if (eq <= 0) {
5465 				if (cand_type->name_off) {
5466 					pr_debug("%s '%s' size=%u vlen=%u cand_id[%u] canon_id[%u] shallow-equal but not equiv for field#%d '%s': %d\n",
5467 						 cand_kind == BTF_KIND_STRUCT ? "STRUCT" : "UNION",
5468 						 btf__name_by_offset(d->btf, cand_type->name_off),
5469 						 cand_type->size, vlen, cand_id, canon_id, i,
5470 						 btf__name_by_offset(d->btf, cand_m->name_off), eq);
5471 				}
5472 				return eq;
5473 			}
5474 			cand_m++;
5475 			canon_m++;
5476 		}
5477 
5478 		return 1;
5479 	}
5480 
5481 	case BTF_KIND_FUNC_PROTO: {
5482 		const struct btf_param *cand_p, *canon_p;
5483 		__u32 vlen;
5484 
5485 		if (!btf_compat_fnproto(cand_type, canon_type))
5486 			return 0;
5487 		eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
5488 		if (eq <= 0)
5489 			return eq;
5490 		vlen = btf_vlen(cand_type);
5491 		cand_p = btf_params(cand_type);
5492 		canon_p = btf_params(canon_type);
5493 		for (i = 0; i < vlen; i++) {
5494 			eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type);
5495 			if (eq <= 0)
5496 				return eq;
5497 			cand_p++;
5498 			canon_p++;
5499 		}
5500 		return 1;
5501 	}
5502 
5503 	case BTF_KIND_LOC_PARAM:
5504 		return btf_equal_loc_param(cand_type, canon_type);
5505 
5506 	case BTF_KIND_LOC_PROTO:
5507 	case BTF_KIND_LOCSEC:
5508 		return 0;
5509 
5510 	default:
5511 		return -EINVAL;
5512 	}
5513 	return 0;
5514 }
5515 
5516 /*
5517  * Use hypothetical mapping, produced by successful type graph equivalence
5518  * check, to augment existing struct/union canonical mapping, where possible.
5519  *
5520  * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record
5521  * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional:
5522  * it doesn't matter if FWD type was part of canonical graph or candidate one,
5523  * we are recording the mapping anyway. As opposed to carefulness required
5524  * for struct/union correspondence mapping (described below), for FWD resolution
5525  * it's not important, as by the time that FWD type (reference type) will be
5526  * deduplicated all structs/unions will be deduped already anyway.
5527  *
5528  * Recording STRUCT/UNION mapping is purely a performance optimization and is
5529  * not required for correctness. It needs to be done carefully to ensure that
5530  * struct/union from candidate's type graph is not mapped into corresponding
5531  * struct/union from canonical type graph that itself hasn't been resolved into
5532  * canonical representative. The only guarantee we have is that canonical
5533  * struct/union was determined as canonical and that won't change. But any
5534  * types referenced through that struct/union fields could have been not yet
5535  * resolved, so in case like that it's too early to establish any kind of
5536  * correspondence between structs/unions.
5537  *
5538  * No canonical correspondence is derived for primitive types (they are already
5539  * deduplicated completely already anyway) or reference types (they rely on
5540  * stability of struct/union canonical relationship for equivalence checks).
5541  */
5542 static void btf_dedup_merge_hypot_map(struct btf_dedup *d)
5543 {
5544 	__u32 canon_type_id, targ_type_id;
5545 	__u16 t_kind, c_kind;
5546 	__u32 t_id, c_id;
5547 	int i;
5548 
5549 	for (i = 0; i < d->hypot_cnt; i++) {
5550 		canon_type_id = d->hypot_list[i];
5551 		targ_type_id = d->hypot_map[canon_type_id];
5552 		t_id = resolve_type_id(d, targ_type_id);
5553 		c_id = resolve_type_id(d, canon_type_id);
5554 		t_kind = btf_kind(btf__type_by_id(d->btf, t_id));
5555 		c_kind = btf_kind(btf__type_by_id(d->btf, c_id));
5556 		/*
5557 		 * Resolve FWD into STRUCT/UNION.
5558 		 * It's ok to resolve FWD into STRUCT/UNION that's not yet
5559 		 * mapped to canonical representative (as opposed to
5560 		 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because
5561 		 * eventually that struct is going to be mapped and all resolved
5562 		 * FWDs will automatically resolve to correct canonical
5563 		 * representative. This will happen before ref type deduping,
5564 		 * which critically depends on stability of these mapping. This
5565 		 * stability is not a requirement for STRUCT/UNION equivalence
5566 		 * checks, though.
5567 		 */
5568 
5569 		/* if it's the split BTF case, we still need to point base FWD
5570 		 * to STRUCT/UNION in a split BTF, because FWDs from split BTF
5571 		 * will be resolved against base FWD. If we don't point base
5572 		 * canonical FWD to the resolved STRUCT/UNION, then all the
5573 		 * FWDs in split BTF won't be correctly resolved to a proper
5574 		 * STRUCT/UNION.
5575 		 */
5576 		if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD)
5577 			d->map[c_id] = t_id;
5578 
5579 		/* if graph equivalence determined that we'd need to adjust
5580 		 * base canonical types, then we need to only point base FWDs
5581 		 * to STRUCTs/UNIONs and do no more modifications. For all
5582 		 * other purposes the type graphs were not equivalent.
5583 		 */
5584 		if (d->hypot_adjust_canon)
5585 			continue;
5586 
5587 		if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD)
5588 			d->map[t_id] = c_id;
5589 
5590 		if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) &&
5591 		    c_kind != BTF_KIND_FWD &&
5592 		    is_type_mapped(d, c_id) &&
5593 		    !is_type_mapped(d, t_id)) {
5594 			/*
5595 			 * as a perf optimization, we can map struct/union
5596 			 * that's part of type graph we just verified for
5597 			 * equivalence. We can do that for struct/union that has
5598 			 * canonical representative only, though.
5599 			 */
5600 			d->map[t_id] = c_id;
5601 		}
5602 	}
5603 }
5604 
5605 static inline long btf_hash_by_kind(struct btf_type *t, __u16 kind)
5606 {
5607 	if (kind == BTF_KIND_TYPEDEF)
5608 		return btf_hash_typedef(t);
5609 	else
5610 		return btf_hash_struct(t);
5611 }
5612 
5613 static inline bool btf_equal_by_kind(struct btf_type *t1, struct btf_type *t2, __u16 kind)
5614 {
5615 	if (kind == BTF_KIND_TYPEDEF)
5616 		return btf_equal_typedef(t1, t2);
5617 	else
5618 		return btf_shallow_equal_struct(t1, t2);
5619 }
5620 
5621 /*
5622  * Deduplicate struct/union and typedef types.
5623  *
5624  * For each struct/union type its type signature hash is calculated, taking
5625  * into account type's name, size, number, order and names of fields, but
5626  * ignoring type ID's referenced from fields, because they might not be deduped
5627  * completely until after reference types deduplication phase. For each typedef
5628  * type, the hash is computed based on the type’s name and size. This type hash
5629  * is used to iterate over all potential canonical types, sharing same hash.
5630  * For each canonical candidate we check whether type graphs that they form
5631  * (through referenced types in fields and so on) are equivalent using algorithm
5632  * implemented in `btf_dedup_is_equiv`. If such equivalence is found and
5633  * BTF_KIND_FWD resolution is allowed, then hypothetical mapping
5634  * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence
5635  * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to
5636  * potentially map other structs/unions to their canonical representatives,
5637  * if such relationship hasn't yet been established. This speeds up algorithm
5638  * by eliminating some of the duplicate work.
5639  *
5640  * If no matching canonical representative was found, struct/union is marked
5641  * as canonical for itself and is added into btf_dedup->dedup_table hash map
5642  * for further look ups.
5643  */
5644 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id)
5645 {
5646 	struct btf_type *cand_type, *t;
5647 	struct hashmap_entry *hash_entry;
5648 	/* if we don't find equivalent type, then we are canonical */
5649 	__u32 new_id = type_id;
5650 	__u16 kind;
5651 	long h;
5652 
5653 	/* already deduped or is in process of deduping (loop detected) */
5654 	if (d->map[type_id] <= BTF_MAX_NR_TYPES)
5655 		return 0;
5656 
5657 	t = btf_type_by_id(d->btf, type_id);
5658 	kind = btf_kind(t);
5659 
5660 	if (kind != BTF_KIND_STRUCT &&
5661 		kind != BTF_KIND_UNION &&
5662 		kind != BTF_KIND_TYPEDEF)
5663 		return 0;
5664 
5665 	h = btf_hash_by_kind(t, kind);
5666 	for_each_dedup_cand(d, hash_entry, h) {
5667 		__u32 cand_id = hash_entry->value;
5668 		int eq;
5669 
5670 		/*
5671 		 * Even though btf_dedup_is_equiv() checks for
5672 		 * btf_equal_by_kind() internally when checking two
5673 		 * structs (unions) or typedefs for equivalence, we need to guard here
5674 		 * from picking matching FWD type as a dedup candidate.
5675 		 * This can happen due to hash collision. In such case just
5676 		 * relying on btf_dedup_is_equiv() would lead to potentially
5677 		 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because
5678 		 * FWD and compatible STRUCT/UNION are considered equivalent.
5679 		 */
5680 		cand_type = btf_type_by_id(d->btf, cand_id);
5681 		if (!btf_equal_by_kind(t, cand_type, kind))
5682 			continue;
5683 
5684 		btf_dedup_clear_hypot_map(d);
5685 		eq = btf_dedup_is_equiv(d, type_id, cand_id);
5686 		if (eq < 0)
5687 			return eq;
5688 		if (!eq)
5689 			continue;
5690 		btf_dedup_merge_hypot_map(d);
5691 		if (d->hypot_adjust_canon) /* not really equivalent */
5692 			continue;
5693 		new_id = cand_id;
5694 		break;
5695 	}
5696 
5697 	d->map[type_id] = new_id;
5698 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
5699 		return -ENOMEM;
5700 
5701 	return 0;
5702 }
5703 
5704 static int btf_dedup_struct_types(struct btf_dedup *d)
5705 {
5706 	int i, err;
5707 
5708 	for (i = 0; i < d->btf->nr_types; i++) {
5709 		err = btf_dedup_struct_type(d, d->btf->start_id + i);
5710 		if (err)
5711 			return err;
5712 	}
5713 	return 0;
5714 }
5715 
5716 /*
5717  * Deduplicate reference type.
5718  *
5719  * Once all primitive, struct/union and typedef types got deduplicated, we can easily
5720  * deduplicate all other (reference) BTF types. This is done in two steps:
5721  *
5722  * 1. Resolve all referenced type IDs into their canonical type IDs. This
5723  * resolution can be done either immediately for primitive, struct/union, and typedef
5724  * types (because they were deduped in previous two phases) or recursively for
5725  * reference types. Recursion will always terminate at either primitive or
5726  * struct/union and typedef types, at which point we can "unwind" chain of reference
5727  * types one by one. There is no danger of encountering cycles in C, as the only way to
5728  * form a type cycle is through struct or union types. Go can form such cycles through
5729  * typedef. Thus, any chain of reference types, even those taking part in a type cycle,
5730  * will inevitably reach a struct/union or typedef type at some point.
5731  *
5732  * 2. Once all referenced type IDs are resolved into canonical ones, BTF type
5733  * becomes "stable", in the sense that no further deduplication will cause
5734  * any changes to it. With that, it's now possible to calculate type's signature
5735  * hash (this time taking into account referenced type IDs) and loop over all
5736  * potential canonical representatives. If no match was found, current type
5737  * will become canonical representative of itself and will be added into
5738  * btf_dedup->dedup_table as another possible canonical representative.
5739  */
5740 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id)
5741 {
5742 	struct hashmap_entry *hash_entry;
5743 	__u32 new_id = type_id, cand_id;
5744 	struct btf_type *t, *cand;
5745 	/* if we don't find equivalent type, then we are representative type */
5746 	int ref_type_id;
5747 	long h;
5748 
5749 	if (d->map[type_id] == BTF_IN_PROGRESS_ID)
5750 		return -ELOOP;
5751 	if (d->map[type_id] <= BTF_MAX_NR_TYPES)
5752 		return resolve_type_id(d, type_id);
5753 
5754 	t = btf_type_by_id(d->btf, type_id);
5755 	d->map[type_id] = BTF_IN_PROGRESS_ID;
5756 
5757 	switch (btf_kind(t)) {
5758 	case BTF_KIND_CONST:
5759 	case BTF_KIND_VOLATILE:
5760 	case BTF_KIND_RESTRICT:
5761 	case BTF_KIND_PTR:
5762 	case BTF_KIND_FUNC:
5763 	case BTF_KIND_TYPE_TAG:
5764 		ref_type_id = btf_dedup_ref_type(d, t->type);
5765 		if (ref_type_id < 0)
5766 			return ref_type_id;
5767 		t->type = ref_type_id;
5768 
5769 		h = btf_hash_common(t);
5770 		for_each_dedup_cand(d, hash_entry, h) {
5771 			cand_id = hash_entry->value;
5772 			cand = btf_type_by_id(d->btf, cand_id);
5773 			if (btf_equal_common(t, cand)) {
5774 				new_id = cand_id;
5775 				break;
5776 			}
5777 		}
5778 		break;
5779 
5780 	case BTF_KIND_DECL_TAG:
5781 		ref_type_id = btf_dedup_ref_type(d, t->type);
5782 		if (ref_type_id < 0)
5783 			return ref_type_id;
5784 		t->type = ref_type_id;
5785 
5786 		h = btf_hash_int_decl_tag(t);
5787 		for_each_dedup_cand(d, hash_entry, h) {
5788 			cand_id = hash_entry->value;
5789 			cand = btf_type_by_id(d->btf, cand_id);
5790 			if (btf_equal_int_tag(t, cand)) {
5791 				new_id = cand_id;
5792 				break;
5793 			}
5794 		}
5795 		break;
5796 
5797 	case BTF_KIND_ARRAY: {
5798 		struct btf_array *info = btf_array(t);
5799 
5800 		ref_type_id = btf_dedup_ref_type(d, info->type);
5801 		if (ref_type_id < 0)
5802 			return ref_type_id;
5803 		info->type = ref_type_id;
5804 
5805 		ref_type_id = btf_dedup_ref_type(d, info->index_type);
5806 		if (ref_type_id < 0)
5807 			return ref_type_id;
5808 		info->index_type = ref_type_id;
5809 
5810 		h = btf_hash_array(t);
5811 		for_each_dedup_cand(d, hash_entry, h) {
5812 			cand_id = hash_entry->value;
5813 			cand = btf_type_by_id(d->btf, cand_id);
5814 			if (btf_equal_array(t, cand)) {
5815 				new_id = cand_id;
5816 				break;
5817 			}
5818 		}
5819 		break;
5820 	}
5821 
5822 	case BTF_KIND_FUNC_PROTO: {
5823 		struct btf_param *param;
5824 		__u32 vlen;
5825 		int i;
5826 
5827 		ref_type_id = btf_dedup_ref_type(d, t->type);
5828 		if (ref_type_id < 0)
5829 			return ref_type_id;
5830 		t->type = ref_type_id;
5831 
5832 		vlen = btf_vlen(t);
5833 		param = btf_params(t);
5834 		for (i = 0; i < vlen; i++) {
5835 			ref_type_id = btf_dedup_ref_type(d, param->type);
5836 			if (ref_type_id < 0)
5837 				return ref_type_id;
5838 			param->type = ref_type_id;
5839 			param++;
5840 		}
5841 
5842 		h = btf_hash_fnproto(t);
5843 		for_each_dedup_cand(d, hash_entry, h) {
5844 			cand_id = hash_entry->value;
5845 			cand = btf_type_by_id(d->btf, cand_id);
5846 			if (btf_equal_fnproto(t, cand)) {
5847 				new_id = cand_id;
5848 				break;
5849 			}
5850 		}
5851 		break;
5852 	}
5853 
5854 	case BTF_KIND_LOC_PROTO: {
5855 		__u32 *p1, *p2;
5856 		__u32 i, vlen;
5857 
5858 		p1 = btf_loc_proto_params(t);
5859 		vlen = btf_vlen(t);
5860 
5861 		for (i = 0; i < vlen; i++, p1++) {
5862 			ref_type_id = btf_dedup_ref_type(d, *p1);
5863 			if (ref_type_id < 0)
5864 				return ref_type_id;
5865 			*p1 = ref_type_id;
5866 		}
5867 
5868 		h = btf_hash_loc_proto(t);
5869 		for_each_dedup_cand(d, hash_entry, h) {
5870 			cand_id = hash_entry->value;
5871 			cand = btf_type_by_id(d->btf, cand_id);
5872 			if (!btf_equal_common(t, cand))
5873 				continue;
5874 			vlen = btf_vlen(cand);
5875 			p1 = btf_loc_proto_params(t);
5876 			p2 = btf_loc_proto_params(cand);
5877 			if (memcmp(p1, p2, vlen * sizeof(__u32)) == 0) {
5878 				new_id = cand_id;
5879 				break;
5880 			}
5881 		}
5882 		break;
5883 	}
5884 
5885 	default:
5886 		return -EINVAL;
5887 	}
5888 
5889 	d->map[type_id] = new_id;
5890 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
5891 		return -ENOMEM;
5892 
5893 	return new_id;
5894 }
5895 
5896 static int btf_dedup_ref_types(struct btf_dedup *d)
5897 {
5898 	int i, err;
5899 
5900 	for (i = 0; i < d->btf->nr_types; i++) {
5901 		err = btf_dedup_ref_type(d, d->btf->start_id + i);
5902 		if (err < 0)
5903 			return err;
5904 	}
5905 	/* we won't need d->dedup_table anymore */
5906 	hashmap__free(d->dedup_table);
5907 	d->dedup_table = NULL;
5908 	return 0;
5909 }
5910 
5911 /*
5912  * Collect a map from type names to type ids for all canonical structs
5913  * and unions. If the same name is shared by several canonical types
5914  * use a special value 0 to indicate this fact.
5915  */
5916 static int btf_dedup_fill_unique_names_map(struct btf_dedup *d, struct hashmap *names_map)
5917 {
5918 	__u32 nr_types = btf__type_cnt(d->btf);
5919 	struct btf_type *t;
5920 	__u32 type_id;
5921 	__u16 kind;
5922 	int err;
5923 
5924 	/*
5925 	 * Iterate over base and split module ids in order to get all
5926 	 * available structs in the map.
5927 	 */
5928 	for (type_id = 1; type_id < nr_types; ++type_id) {
5929 		t = btf_type_by_id(d->btf, type_id);
5930 		kind = btf_kind(t);
5931 
5932 		if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION)
5933 			continue;
5934 
5935 		/* Skip non-canonical types */
5936 		if (type_id != d->map[type_id])
5937 			continue;
5938 
5939 		err = hashmap__add(names_map, t->name_off, type_id);
5940 		if (err == -EEXIST)
5941 			err = hashmap__set(names_map, t->name_off, 0, NULL, NULL);
5942 
5943 		if (err)
5944 			return err;
5945 	}
5946 
5947 	return 0;
5948 }
5949 
5950 static int btf_dedup_resolve_fwd(struct btf_dedup *d, struct hashmap *names_map, __u32 type_id)
5951 {
5952 	struct btf_type *t = btf_type_by_id(d->btf, type_id);
5953 	enum btf_fwd_kind fwd_kind = btf_kflag(t);
5954 	__u16 cand_kind, kind = btf_kind(t);
5955 	struct btf_type *cand_t;
5956 	uintptr_t cand_id;
5957 
5958 	if (kind != BTF_KIND_FWD)
5959 		return 0;
5960 
5961 	/* Skip if this FWD already has a mapping */
5962 	if (type_id != d->map[type_id])
5963 		return 0;
5964 
5965 	if (!hashmap__find(names_map, t->name_off, &cand_id))
5966 		return 0;
5967 
5968 	/* Zero is a special value indicating that name is not unique */
5969 	if (!cand_id)
5970 		return 0;
5971 
5972 	cand_t = btf_type_by_id(d->btf, cand_id);
5973 	cand_kind = btf_kind(cand_t);
5974 	if ((cand_kind == BTF_KIND_STRUCT && fwd_kind != BTF_FWD_STRUCT) ||
5975 	    (cand_kind == BTF_KIND_UNION && fwd_kind != BTF_FWD_UNION))
5976 		return 0;
5977 
5978 	d->map[type_id] = cand_id;
5979 
5980 	return 0;
5981 }
5982 
5983 /*
5984  * Resolve unambiguous forward declarations.
5985  *
5986  * The lion's share of all FWD declarations is resolved during
5987  * `btf_dedup_struct_types` phase when different type graphs are
5988  * compared against each other. However, if in some compilation unit a
5989  * FWD declaration is not a part of a type graph compared against
5990  * another type graph that declaration's canonical type would not be
5991  * changed. Example:
5992  *
5993  * CU #1:
5994  *
5995  * struct foo;
5996  * struct foo *some_global;
5997  *
5998  * CU #2:
5999  *
6000  * struct foo { int u; };
6001  * struct foo *another_global;
6002  *
6003  * After `btf_dedup_struct_types` the BTF looks as follows:
6004  *
6005  * [1] STRUCT 'foo' size=4 vlen=1 ...
6006  * [2] INT 'int' size=4 ...
6007  * [3] PTR '(anon)' type_id=1
6008  * [4] FWD 'foo' fwd_kind=struct
6009  * [5] PTR '(anon)' type_id=4
6010  *
6011  * This pass assumes that such FWD declarations should be mapped to
6012  * structs or unions with identical name in case if the name is not
6013  * ambiguous.
6014  */
6015 static int btf_dedup_resolve_fwds(struct btf_dedup *d)
6016 {
6017 	int i, err;
6018 	struct hashmap *names_map;
6019 
6020 	names_map = hashmap__new(btf_dedup_identity_hash_fn, btf_dedup_equal_fn, NULL);
6021 	if (IS_ERR(names_map))
6022 		return PTR_ERR(names_map);
6023 
6024 	err = btf_dedup_fill_unique_names_map(d, names_map);
6025 	if (err < 0)
6026 		goto exit;
6027 
6028 	for (i = 0; i < d->btf->nr_types; i++) {
6029 		err = btf_dedup_resolve_fwd(d, names_map, d->btf->start_id + i);
6030 		if (err < 0)
6031 			break;
6032 	}
6033 
6034 exit:
6035 	hashmap__free(names_map);
6036 	return err;
6037 }
6038 
6039 /*
6040  * Compact types.
6041  *
6042  * After we established for each type its corresponding canonical representative
6043  * type, we now can eliminate types that are not canonical and leave only
6044  * canonical ones layed out sequentially in memory by copying them over
6045  * duplicates. During compaction btf_dedup->hypot_map array is reused to store
6046  * a map from original type ID to a new compacted type ID, which will be used
6047  * during next phase to "fix up" type IDs, referenced from struct/union and
6048  * reference types.
6049  */
6050 static int btf_dedup_compact_types(struct btf_dedup *d)
6051 {
6052 	__u32 *new_offs;
6053 	__u32 next_type_id = d->btf->start_id;
6054 	const struct btf_type *t;
6055 	void *p;
6056 	int i, id, len;
6057 
6058 	/* we are going to reuse hypot_map to store compaction remapping */
6059 	d->hypot_map[0] = 0;
6060 	/* base BTF types are not renumbered */
6061 	for (id = 1; id < d->btf->start_id; id++)
6062 		d->hypot_map[id] = id;
6063 	for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++)
6064 		d->hypot_map[id] = BTF_UNPROCESSED_ID;
6065 
6066 	p = d->btf->types_data;
6067 
6068 	for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++) {
6069 		if (d->map[id] != id)
6070 			continue;
6071 
6072 		t = btf__type_by_id(d->btf, id);
6073 		len = btf_type_size(d->btf, t);
6074 		if (len < 0)
6075 			return len;
6076 
6077 		memmove(p, t, len);
6078 		d->hypot_map[id] = next_type_id;
6079 		d->btf->type_offs[next_type_id - d->btf->start_id] = p - d->btf->types_data;
6080 		p += len;
6081 		next_type_id++;
6082 	}
6083 
6084 	/* shrink struct btf's internal types index and update btf_header */
6085 	d->btf->nr_types = next_type_id - d->btf->start_id;
6086 	d->btf->type_offs_cap = d->btf->nr_types;
6087 	d->btf->hdr.type_len = p - d->btf->types_data;
6088 	new_offs = libbpf_reallocarray(d->btf->type_offs, d->btf->type_offs_cap,
6089 				       sizeof(*new_offs));
6090 	if (d->btf->type_offs_cap && !new_offs)
6091 		return -ENOMEM;
6092 	d->btf->type_offs = new_offs;
6093 	if (d->btf->layout)
6094 		d->btf->hdr.layout_off = d->btf->hdr.type_off + d->btf->hdr.type_len;
6095 	d->btf->hdr.str_off = d->btf->hdr.type_off + d->btf->hdr.type_len + d->btf->hdr.layout_len;
6096 	d->btf->raw_size = d->btf->hdr.hdr_len + d->btf->hdr.type_off + d->btf->hdr.type_len +
6097 			   d->btf->hdr.layout_len + d->btf->hdr.str_len;
6098 	return 0;
6099 }
6100 
6101 /*
6102  * Figure out final (deduplicated and compacted) type ID for provided original
6103  * `type_id` by first resolving it into corresponding canonical type ID and
6104  * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map,
6105  * which is populated during compaction phase.
6106  */
6107 static int btf_dedup_remap_type_id(__u32 *type_id, void *ctx)
6108 {
6109 	struct btf_dedup *d = ctx;
6110 	__u32 resolved_type_id, new_type_id;
6111 
6112 	resolved_type_id = resolve_type_id(d, *type_id);
6113 	new_type_id = d->hypot_map[resolved_type_id];
6114 	if (new_type_id > BTF_MAX_NR_TYPES)
6115 		return -EINVAL;
6116 
6117 	*type_id = new_type_id;
6118 	return 0;
6119 }
6120 
6121 /*
6122  * Remap referenced type IDs into deduped type IDs.
6123  *
6124  * After BTF types are deduplicated and compacted, their final type IDs may
6125  * differ from original ones. The map from original to a corresponding
6126  * deduped type ID is stored in btf_dedup->hypot_map and is populated during
6127  * compaction phase. During remapping phase we are rewriting all type IDs
6128  * referenced from any BTF type (e.g., struct fields, func proto args, etc) to
6129  * their final deduped type IDs.
6130  */
6131 static int btf_dedup_remap_types(struct btf_dedup *d)
6132 {
6133 	int i, r;
6134 
6135 	for (i = 0; i < d->btf->nr_types; i++) {
6136 		struct btf_type *t = btf_type_by_id(d->btf, d->btf->start_id + i);
6137 		struct btf_field_iter it;
6138 		__u32 *type_id;
6139 
6140 		r = btf_field_iter_init(&it, t, BTF_FIELD_ITER_IDS);
6141 		if (r)
6142 			return r;
6143 
6144 		while ((type_id = btf_field_iter_next(&it))) {
6145 			__u32 resolved_id, new_id;
6146 
6147 			resolved_id = resolve_type_id(d, *type_id);
6148 			new_id = d->hypot_map[resolved_id];
6149 			if (new_id > BTF_MAX_NR_TYPES)
6150 				return -EINVAL;
6151 
6152 			*type_id = new_id;
6153 		}
6154 	}
6155 
6156 	if (!d->btf_ext)
6157 		return 0;
6158 
6159 	r = btf_ext_visit_type_ids(d->btf_ext, btf_dedup_remap_type_id, d);
6160 	if (r)
6161 		return r;
6162 
6163 	return 0;
6164 }
6165 
6166 /*
6167  * Probe few well-known locations for vmlinux kernel image and try to load BTF
6168  * data out of it to use for target BTF.
6169  */
6170 struct btf *btf__load_vmlinux_btf(void)
6171 {
6172 	const char *sysfs_btf_path = "/sys/kernel/btf/vmlinux";
6173 	/* fall back locations, trying to find vmlinux on disk */
6174 	const char *locations[] = {
6175 		"/boot/vmlinux-%1$s",
6176 		"/lib/modules/%1$s/vmlinux-%1$s",
6177 		"/lib/modules/%1$s/build/vmlinux",
6178 		"/usr/lib/modules/%1$s/kernel/vmlinux",
6179 		"/usr/lib/debug/boot/vmlinux-%1$s",
6180 		"/usr/lib/debug/boot/vmlinux-%1$s.debug",
6181 		"/usr/lib/debug/lib/modules/%1$s/vmlinux",
6182 	};
6183 	char path[PATH_MAX + 1];
6184 	struct utsname buf;
6185 	struct btf *btf;
6186 	int i, err;
6187 
6188 	/* is canonical sysfs location accessible? */
6189 	if (faccessat(AT_FDCWD, sysfs_btf_path, F_OK, AT_EACCESS) < 0) {
6190 		pr_warn("kernel BTF is missing at '%s', was CONFIG_DEBUG_INFO_BTF enabled?\n",
6191 			sysfs_btf_path);
6192 	} else {
6193 		btf = btf_parse_raw_mmap(sysfs_btf_path, NULL);
6194 		if (IS_ERR(btf))
6195 			btf = btf__parse(sysfs_btf_path, NULL);
6196 
6197 		if (!btf) {
6198 			err = -errno;
6199 			pr_warn("failed to read kernel BTF from '%s': %s\n",
6200 				sysfs_btf_path, errstr(err));
6201 			return libbpf_err_ptr(err);
6202 		}
6203 		pr_debug("loaded kernel BTF from '%s'\n", sysfs_btf_path);
6204 		return btf;
6205 	}
6206 
6207 	/* try fallback locations */
6208 	uname(&buf);
6209 	for (i = 0; i < ARRAY_SIZE(locations); i++) {
6210 		snprintf(path, PATH_MAX, locations[i], buf.release);
6211 
6212 		if (faccessat(AT_FDCWD, path, R_OK, AT_EACCESS))
6213 			continue;
6214 
6215 		btf = btf__parse(path, NULL);
6216 		err = libbpf_get_error(btf);
6217 		pr_debug("loading kernel BTF '%s': %s\n", path, errstr(err));
6218 		if (err)
6219 			continue;
6220 
6221 		return btf;
6222 	}
6223 
6224 	pr_warn("failed to find valid kernel BTF\n");
6225 	return libbpf_err_ptr(-ESRCH);
6226 }
6227 
6228 struct btf *libbpf_find_kernel_btf(void) __attribute__((alias("btf__load_vmlinux_btf")));
6229 
6230 struct btf *btf__load_module_btf(const char *module_name, struct btf *vmlinux_btf)
6231 {
6232 	char path[80];
6233 
6234 	snprintf(path, sizeof(path), "/sys/kernel/btf/%s", module_name);
6235 	return btf__parse_split(path, vmlinux_btf);
6236 }
6237 
6238 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx)
6239 {
6240 	const struct btf_ext_info *seg;
6241 	struct btf_ext_info_sec *sec;
6242 	int i, err;
6243 
6244 	seg = &btf_ext->func_info;
6245 	for_each_btf_ext_sec(seg, sec) {
6246 		struct bpf_func_info_min *rec;
6247 
6248 		for_each_btf_ext_rec(seg, sec, i, rec) {
6249 			err = visit(&rec->type_id, ctx);
6250 			if (err < 0)
6251 				return err;
6252 		}
6253 	}
6254 
6255 	seg = &btf_ext->core_relo_info;
6256 	for_each_btf_ext_sec(seg, sec) {
6257 		struct bpf_core_relo *rec;
6258 
6259 		for_each_btf_ext_rec(seg, sec, i, rec) {
6260 			err = visit(&rec->type_id, ctx);
6261 			if (err < 0)
6262 				return err;
6263 		}
6264 	}
6265 
6266 	return 0;
6267 }
6268 
6269 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx)
6270 {
6271 	const struct btf_ext_info *seg;
6272 	struct btf_ext_info_sec *sec;
6273 	int i, err;
6274 
6275 	seg = &btf_ext->func_info;
6276 	for_each_btf_ext_sec(seg, sec) {
6277 		err = visit(&sec->sec_name_off, ctx);
6278 		if (err)
6279 			return err;
6280 	}
6281 
6282 	seg = &btf_ext->line_info;
6283 	for_each_btf_ext_sec(seg, sec) {
6284 		struct bpf_line_info_min *rec;
6285 
6286 		err = visit(&sec->sec_name_off, ctx);
6287 		if (err)
6288 			return err;
6289 
6290 		for_each_btf_ext_rec(seg, sec, i, rec) {
6291 			err = visit(&rec->file_name_off, ctx);
6292 			if (err)
6293 				return err;
6294 			err = visit(&rec->line_off, ctx);
6295 			if (err)
6296 				return err;
6297 		}
6298 	}
6299 
6300 	seg = &btf_ext->core_relo_info;
6301 	for_each_btf_ext_sec(seg, sec) {
6302 		struct bpf_core_relo *rec;
6303 
6304 		err = visit(&sec->sec_name_off, ctx);
6305 		if (err)
6306 			return err;
6307 
6308 		for_each_btf_ext_rec(seg, sec, i, rec) {
6309 			err = visit(&rec->access_str_off, ctx);
6310 			if (err)
6311 				return err;
6312 		}
6313 	}
6314 
6315 	return 0;
6316 }
6317 
6318 struct btf_distill {
6319 	struct btf_pipe pipe;
6320 	int *id_map;
6321 	unsigned int split_start_id;
6322 	unsigned int split_start_str;
6323 	int diff_id;
6324 };
6325 
6326 static int btf_add_distilled_type_ids(struct btf_distill *dist, __u32 i)
6327 {
6328 	struct btf_type *split_t = btf_type_by_id(dist->pipe.src, i);
6329 	struct btf_field_iter it;
6330 	__u32 *id;
6331 	int err;
6332 
6333 	err = btf_field_iter_init(&it, split_t, BTF_FIELD_ITER_IDS);
6334 	if (err)
6335 		return err;
6336 	while ((id = btf_field_iter_next(&it))) {
6337 		struct btf_type *base_t;
6338 
6339 		if (!*id)
6340 			continue;
6341 		/* split BTF id, not needed */
6342 		if (*id >= dist->split_start_id)
6343 			continue;
6344 		/* already added ? */
6345 		if (dist->id_map[*id] > 0)
6346 			continue;
6347 
6348 		/* only a subset of base BTF types should be referenced from
6349 		 * split BTF; ensure nothing unexpected is referenced.
6350 		 */
6351 		base_t = btf_type_by_id(dist->pipe.src, *id);
6352 		switch (btf_kind(base_t)) {
6353 		case BTF_KIND_INT:
6354 		case BTF_KIND_FLOAT:
6355 		case BTF_KIND_FWD:
6356 		case BTF_KIND_ARRAY:
6357 		case BTF_KIND_STRUCT:
6358 		case BTF_KIND_UNION:
6359 		case BTF_KIND_TYPEDEF:
6360 		case BTF_KIND_ENUM:
6361 		case BTF_KIND_ENUM64:
6362 		case BTF_KIND_PTR:
6363 		case BTF_KIND_CONST:
6364 		case BTF_KIND_RESTRICT:
6365 		case BTF_KIND_VOLATILE:
6366 		case BTF_KIND_FUNC:
6367 		case BTF_KIND_FUNC_PROTO:
6368 		case BTF_KIND_TYPE_TAG:
6369 		case BTF_KIND_LOC_PARAM:
6370 		case BTF_KIND_LOC_PROTO:
6371 			dist->id_map[*id] = *id;
6372 			break;
6373 		default:
6374 			pr_warn("unexpected reference to base type[%u] of kind [%u] when creating distilled base BTF.\n",
6375 				*id, btf_kind(base_t));
6376 			return -EINVAL;
6377 		}
6378 		/* If a base type is used, ensure types it refers to are
6379 		 * marked as used also; so for example if we find a PTR to INT
6380 		 * we need both the PTR and INT.
6381 		 *
6382 		 * The only exception is named struct/unions, since distilled
6383 		 * base BTF composite types have no members.
6384 		 */
6385 		if (btf_is_composite(base_t) && base_t->name_off)
6386 			continue;
6387 		err = btf_add_distilled_type_ids(dist, *id);
6388 		if (err)
6389 			return err;
6390 	}
6391 	return 0;
6392 }
6393 
6394 static int btf_add_distilled_types(struct btf_distill *dist)
6395 {
6396 	bool adding_to_base = dist->pipe.dst->base_btf == NULL;
6397 	int id = btf__type_cnt(dist->pipe.dst);
6398 	struct btf_type *t;
6399 	int i, err = 0;
6400 
6401 
6402 	/* Add types for each of the required references to either distilled
6403 	 * base or split BTF, depending on type characteristics.
6404 	 */
6405 	for (i = 1; i < dist->split_start_id; i++) {
6406 		const char *name;
6407 		int kind;
6408 
6409 		if (!dist->id_map[i])
6410 			continue;
6411 		t = btf_type_by_id(dist->pipe.src, i);
6412 		kind = btf_kind(t);
6413 		name = btf__name_by_offset(dist->pipe.src, t->name_off);
6414 
6415 		switch (kind) {
6416 		case BTF_KIND_INT:
6417 		case BTF_KIND_FLOAT:
6418 		case BTF_KIND_FWD:
6419 			/* Named int, float, fwd are added to base. */
6420 			if (!adding_to_base)
6421 				continue;
6422 			err = btf_add_type(&dist->pipe, t);
6423 			break;
6424 		case BTF_KIND_STRUCT:
6425 		case BTF_KIND_UNION:
6426 			/* Named struct/union are added to base as 0-vlen
6427 			 * struct/union of same size.  Anonymous struct/unions
6428 			 * are added to split BTF as-is.
6429 			 */
6430 			if (adding_to_base) {
6431 				if (!t->name_off)
6432 					continue;
6433 				err = btf_add_composite(dist->pipe.dst, kind, name, t->size);
6434 			} else {
6435 				if (t->name_off)
6436 					continue;
6437 				err = btf_add_type(&dist->pipe, t);
6438 			}
6439 			break;
6440 		case BTF_KIND_ENUM:
6441 		case BTF_KIND_ENUM64:
6442 			/* Named enum[64]s are added to base as a sized
6443 			 * enum; relocation will match with appropriately-named
6444 			 * and sized enum or enum64.
6445 			 *
6446 			 * Anonymous enums are added to split BTF as-is.
6447 			 */
6448 			if (adding_to_base) {
6449 				if (!t->name_off)
6450 					continue;
6451 				err = btf__add_enum(dist->pipe.dst, name, t->size);
6452 			} else {
6453 				if (t->name_off)
6454 					continue;
6455 				err = btf_add_type(&dist->pipe, t);
6456 			}
6457 			break;
6458 		case BTF_KIND_ARRAY:
6459 		case BTF_KIND_TYPEDEF:
6460 		case BTF_KIND_PTR:
6461 		case BTF_KIND_CONST:
6462 		case BTF_KIND_RESTRICT:
6463 		case BTF_KIND_VOLATILE:
6464 		case BTF_KIND_FUNC:
6465 		case BTF_KIND_FUNC_PROTO:
6466 		case BTF_KIND_TYPE_TAG:
6467 		case BTF_KIND_LOC_PARAM:
6468 		case BTF_KIND_LOC_PROTO:
6469 		case BTF_KIND_LOCSEC:
6470 			/* All other types are added to split BTF. */
6471 			if (adding_to_base)
6472 				continue;
6473 			err = btf_add_type(&dist->pipe, t);
6474 			break;
6475 		default:
6476 			pr_warn("unexpected kind when adding base type '%s'[%d] of kind [%d] to distilled base BTF.\n",
6477 				name, i, kind);
6478 			return -EINVAL;
6479 
6480 		}
6481 		if (err < 0)
6482 			break;
6483 		dist->id_map[i] = id++;
6484 	}
6485 	return err;
6486 }
6487 
6488 /* Split BTF ids without a mapping will be shifted downwards since distilled
6489  * base BTF is smaller than the original base BTF.  For those that have a
6490  * mapping (either to base or updated split BTF), update the id based on
6491  * that mapping.
6492  */
6493 static int btf_update_distilled_type_ids(struct btf_distill *dist, __u32 i)
6494 {
6495 	struct btf_type *t = btf_type_by_id(dist->pipe.dst, i);
6496 	struct btf_field_iter it;
6497 	__u32 *id;
6498 	int err;
6499 
6500 	err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_IDS);
6501 	if (err)
6502 		return err;
6503 	while ((id = btf_field_iter_next(&it))) {
6504 		if (dist->id_map[*id])
6505 			*id = dist->id_map[*id];
6506 		else if (*id >= dist->split_start_id)
6507 			*id -= dist->diff_id;
6508 	}
6509 	return 0;
6510 }
6511 
6512 /* Create updated split BTF with distilled base BTF; distilled base BTF
6513  * consists of BTF information required to clarify the types that split
6514  * BTF refers to, omitting unneeded details.  Specifically it will contain
6515  * base types and memberless definitions of named structs, unions and enumerated
6516  * types. Associated reference types like pointers, arrays and anonymous
6517  * structs, unions and enumerated types will be added to split BTF.
6518  * Size is recorded for named struct/unions to help guide matching to the
6519  * target base BTF during later relocation.
6520  *
6521  * The only case where structs, unions or enumerated types are fully represented
6522  * is when they are anonymous; in such cases, the anonymous type is added to
6523  * split BTF in full.
6524  *
6525  * We return newly-created split BTF where the split BTF refers to a newly-created
6526  * distilled base BTF. Both must be freed separately by the caller.
6527  */
6528 int btf__distill_base(const struct btf *src_btf, struct btf **new_base_btf,
6529 		      struct btf **new_split_btf)
6530 {
6531 	struct btf *new_base = NULL, *new_split = NULL;
6532 	const struct btf *old_base;
6533 	unsigned int n = btf__type_cnt(src_btf);
6534 	struct btf_distill dist = {};
6535 	struct btf_type *t;
6536 	int i, err = 0;
6537 
6538 	/* src BTF must be split BTF. */
6539 	old_base = btf__base_btf(src_btf);
6540 	if (!new_base_btf || !new_split_btf || !old_base)
6541 		return libbpf_err(-EINVAL);
6542 
6543 	new_base = btf__new_empty();
6544 	if (!new_base)
6545 		return libbpf_err(-ENOMEM);
6546 
6547 	btf__set_endianness(new_base, btf__endianness(src_btf));
6548 
6549 	dist.id_map = calloc(n, sizeof(*dist.id_map));
6550 	if (!dist.id_map) {
6551 		err = -ENOMEM;
6552 		goto done;
6553 	}
6554 	dist.pipe.src = src_btf;
6555 	dist.pipe.dst = new_base;
6556 	dist.pipe.str_off_map = hashmap__new(btf_dedup_identity_hash_fn, btf_dedup_equal_fn, NULL);
6557 	if (IS_ERR(dist.pipe.str_off_map)) {
6558 		err = -ENOMEM;
6559 		goto done;
6560 	}
6561 	dist.split_start_id = btf__type_cnt(old_base);
6562 	dist.split_start_str = old_base->hdr.str_len;
6563 
6564 	/* Pass over src split BTF; generate the list of base BTF type ids it
6565 	 * references; these will constitute our distilled BTF set to be
6566 	 * distributed over base and split BTF as appropriate.
6567 	 */
6568 	for (i = src_btf->start_id; i < n; i++) {
6569 		err = btf_add_distilled_type_ids(&dist, i);
6570 		if (err < 0)
6571 			goto done;
6572 	}
6573 	/* Next add types for each of the required references to base BTF and split BTF
6574 	 * in turn.
6575 	 */
6576 	err = btf_add_distilled_types(&dist);
6577 	if (err < 0)
6578 		goto done;
6579 
6580 	/* Create new split BTF with distilled base BTF as its base; the final
6581 	 * state is split BTF with distilled base BTF that represents enough
6582 	 * about its base references to allow it to be relocated with the base
6583 	 * BTF available.
6584 	 */
6585 	new_split = btf__new_empty_split(new_base);
6586 	if (!new_split) {
6587 		err = -errno;
6588 		goto done;
6589 	}
6590 	dist.pipe.dst = new_split;
6591 	/* First add all split types */
6592 	for (i = src_btf->start_id; i < n; i++) {
6593 		t = btf_type_by_id(src_btf, i);
6594 		err = btf_add_type(&dist.pipe, t);
6595 		if (err < 0)
6596 			goto done;
6597 	}
6598 	/* Now add distilled types to split BTF that are not added to base. */
6599 	err = btf_add_distilled_types(&dist);
6600 	if (err < 0)
6601 		goto done;
6602 
6603 	/* All split BTF ids will be shifted downwards since there are less base
6604 	 * BTF ids in distilled base BTF.
6605 	 */
6606 	dist.diff_id = dist.split_start_id - btf__type_cnt(new_base);
6607 
6608 	n = btf__type_cnt(new_split);
6609 	/* Now update base/split BTF ids. */
6610 	for (i = 1; i < n; i++) {
6611 		err = btf_update_distilled_type_ids(&dist, i);
6612 		if (err < 0)
6613 			break;
6614 	}
6615 done:
6616 	free(dist.id_map);
6617 	hashmap__free(dist.pipe.str_off_map);
6618 	if (err) {
6619 		btf__free(new_split);
6620 		btf__free(new_base);
6621 		return libbpf_err(err);
6622 	}
6623 	*new_base_btf = new_base;
6624 	*new_split_btf = new_split;
6625 
6626 	return 0;
6627 }
6628 
6629 const struct btf_header *btf_header(const struct btf *btf)
6630 {
6631 	return &btf->hdr;
6632 }
6633 
6634 void btf_set_base_btf(struct btf *btf, const struct btf *base_btf)
6635 {
6636 	btf->base_btf = (struct btf *)base_btf;
6637 	btf->start_id = btf__type_cnt(base_btf);
6638 	btf->start_str_off = base_btf->hdr.str_len + base_btf->start_str_off;
6639 }
6640 
6641 int btf__relocate(struct btf *btf, const struct btf *base_btf)
6642 {
6643 	int err = btf_relocate(btf, base_btf, NULL, NULL);
6644 
6645 	if (!err)
6646 		btf->owns_base = false;
6647 	return libbpf_err(err);
6648 }
6649 
6650 struct btf_permute {
6651 	struct btf *btf;
6652 	__u32 *id_map;
6653 	__u32 start_offs;
6654 };
6655 
6656 /* Callback function to remap individual type ID references */
6657 static int btf_permute_remap_type_id(__u32 *type_id, void *ctx)
6658 {
6659 	struct btf_permute *p = ctx;
6660 	__u32 new_id = *type_id;
6661 
6662 	/* refer to the base BTF or VOID type */
6663 	if (new_id < p->btf->start_id)
6664 		return 0;
6665 
6666 	if (new_id >= btf__type_cnt(p->btf))
6667 		return -EINVAL;
6668 
6669 	*type_id = p->id_map[new_id - p->btf->start_id + p->start_offs];
6670 	return 0;
6671 }
6672 
6673 int btf__permute(struct btf *btf, __u32 *id_map, __u32 id_map_cnt,
6674 		 const struct btf_permute_opts *opts)
6675 {
6676 	struct btf_permute p;
6677 	struct btf_ext *btf_ext;
6678 	void *nt, *new_types = NULL;
6679 	__u32 *order_map = NULL;
6680 	int err = 0, i;
6681 	__u32 n, id, start_offs = 0;
6682 
6683 	if (!OPTS_VALID(opts, btf_permute_opts))
6684 		return libbpf_err(-EINVAL);
6685 
6686 	if (btf__base_btf(btf)) {
6687 		n = btf->nr_types;
6688 	} else {
6689 		if (id_map[0] != 0)
6690 			return libbpf_err(-EINVAL);
6691 		n = btf__type_cnt(btf);
6692 		start_offs = 1;
6693 	}
6694 
6695 	if (id_map_cnt != n)
6696 		return libbpf_err(-EINVAL);
6697 
6698 	/* record the sequence of types */
6699 	order_map = calloc(id_map_cnt, sizeof(*id_map));
6700 	if (!order_map) {
6701 		err = -ENOMEM;
6702 		goto done;
6703 	}
6704 
6705 	new_types = calloc(btf->hdr.type_len, 1);
6706 	if (!new_types) {
6707 		err = -ENOMEM;
6708 		goto done;
6709 	}
6710 
6711 	err = btf_ensure_modifiable(btf);
6712 	if (err)
6713 		goto done;
6714 
6715 	for (i = start_offs; i < id_map_cnt; i++) {
6716 		id = id_map[i];
6717 		if (id < btf->start_id || id >= btf__type_cnt(btf)) {
6718 			err = -EINVAL;
6719 			goto done;
6720 		}
6721 		id -= btf->start_id - start_offs;
6722 		/* cannot be mapped to the same ID */
6723 		if (order_map[id]) {
6724 			err = -EINVAL;
6725 			goto done;
6726 		}
6727 		order_map[id] = i + btf->start_id - start_offs;
6728 	}
6729 
6730 	p.btf = btf;
6731 	p.id_map = id_map;
6732 	p.start_offs = start_offs;
6733 	nt = new_types;
6734 	for (i = start_offs; i < id_map_cnt; i++) {
6735 		struct btf_field_iter it;
6736 		const struct btf_type *t;
6737 		__u32 *type_id;
6738 		int type_size;
6739 
6740 		id = order_map[i];
6741 		t = btf__type_by_id(btf, id);
6742 		type_size = btf_type_size(btf, t);
6743 		memcpy(nt, t, type_size);
6744 
6745 		/* fix up referenced IDs for BTF */
6746 		err = btf_field_iter_init(&it, nt, BTF_FIELD_ITER_IDS);
6747 		if (err)
6748 			goto done;
6749 		while ((type_id = btf_field_iter_next(&it))) {
6750 			err = btf_permute_remap_type_id(type_id, &p);
6751 			if (err)
6752 				goto done;
6753 		}
6754 
6755 		nt += type_size;
6756 	}
6757 
6758 	/* fix up referenced IDs for btf_ext */
6759 	btf_ext = OPTS_GET(opts, btf_ext, NULL);
6760 	if (btf_ext) {
6761 		err = btf_ext_visit_type_ids(btf_ext, btf_permute_remap_type_id, &p);
6762 		if (err)
6763 			goto done;
6764 	}
6765 
6766 	for (nt = new_types, i = 0; i < id_map_cnt - start_offs; i++) {
6767 		btf->type_offs[i] = nt - new_types;
6768 		nt += btf_type_size(btf, nt);
6769 	}
6770 
6771 	free(order_map);
6772 	free(btf->types_data);
6773 	btf->types_data = new_types;
6774 	return 0;
6775 
6776 done:
6777 	free(order_map);
6778 	free(new_types);
6779 	return libbpf_err(err);
6780 }
6781