Debian Codegraph @

src/btf.c

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