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