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