1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * BTF-to-C type converter.
6 * Copyright (c) 2019 Facebook
14 #include <linux/err.h>
15 #include <linux/btf.h>
16 #include <linux/kernel.h>
20 #include "libbpf_internal.h"
22 static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
23 static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
25 static const char *pfx(int lvl)
27 return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
30 enum btf_dump_type_order_state {
36 enum btf_dump_type_emit_state {
42 /* per-type auxiliary state */
43 struct btf_dump_type_aux_state {
44 /* topological sorting state */
45 enum btf_dump_type_order_state order_state: 2;
46 /* emitting state used to determine the need for forward declaration */
47 enum btf_dump_type_emit_state emit_state: 2;
48 /* whether forward declaration was already emitted */
50 /* whether unique non-duplicate name was already assigned */
51 __u8 name_resolved: 1;
52 /* whether type is referenced from any other type */
57 const struct btf *btf;
58 const struct btf_ext *btf_ext;
59 btf_dump_printf_fn_t printf_fn;
60 struct btf_dump_opts opts;
65 /* per-type auxiliary state */
66 struct btf_dump_type_aux_state *type_states;
67 size_t type_states_cap;
68 /* per-type optional cached unique name, must be freed, if present */
69 const char **cached_names;
70 size_t cached_names_cap;
72 /* topo-sorted list of dependent type definitions */
78 * stack of type declarations (e.g., chain of modifiers, arrays,
85 /* maps struct/union/enum name to a number of name occurrences */
86 struct hashmap *type_names;
88 * maps typedef identifiers and enum value names to a number of such
91 struct hashmap *ident_names;
94 static size_t str_hash_fn(const void *key, void *ctx)
99 static bool str_equal_fn(const void *a, const void *b, void *ctx)
101 return strcmp(a, b) == 0;
104 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
106 return btf__name_by_offset(d->btf, name_off);
109 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
114 d->printf_fn(d->opts.ctx, fmt, args);
118 static int btf_dump_mark_referenced(struct btf_dump *d);
119 static int btf_dump_resize(struct btf_dump *d);
121 struct btf_dump *btf_dump__new(const struct btf *btf,
122 const struct btf_ext *btf_ext,
123 const struct btf_dump_opts *opts,
124 btf_dump_printf_fn_t printf_fn)
129 d = calloc(1, sizeof(struct btf_dump));
131 return ERR_PTR(-ENOMEM);
134 d->btf_ext = btf_ext;
135 d->printf_fn = printf_fn;
136 d->opts.ctx = opts ? opts->ctx : NULL;
137 d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
139 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
140 if (IS_ERR(d->type_names)) {
141 err = PTR_ERR(d->type_names);
142 d->type_names = NULL;
145 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
146 if (IS_ERR(d->ident_names)) {
147 err = PTR_ERR(d->ident_names);
148 d->ident_names = NULL;
152 err = btf_dump_resize(d);
162 static int btf_dump_resize(struct btf_dump *d)
164 int err, last_id = btf__get_nr_types(d->btf);
166 if (last_id <= d->last_id)
169 if (btf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
170 sizeof(*d->type_states), last_id + 1))
172 if (btf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
173 sizeof(*d->cached_names), last_id + 1))
176 if (d->last_id == 0) {
177 /* VOID is special */
178 d->type_states[0].order_state = ORDERED;
179 d->type_states[0].emit_state = EMITTED;
182 /* eagerly determine referenced types for anon enums */
183 err = btf_dump_mark_referenced(d);
187 d->last_id = last_id;
191 static void btf_dump_free_names(struct hashmap *map)
194 struct hashmap_entry *cur;
196 hashmap__for_each_entry(map, cur, bkt)
197 free((void *)cur->key);
202 void btf_dump__free(struct btf_dump *d)
206 if (IS_ERR_OR_NULL(d))
209 free(d->type_states);
210 if (d->cached_names) {
211 /* any set cached name is owned by us and should be freed */
212 for (i = 0; i <= d->last_id; i++) {
213 if (d->cached_names[i])
214 free((void *)d->cached_names[i]);
217 free(d->cached_names);
220 btf_dump_free_names(d->type_names);
221 btf_dump_free_names(d->ident_names);
226 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
227 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
230 * Dump BTF type in a compilable C syntax, including all the necessary
231 * dependent types, necessary for compilation. If some of the dependent types
232 * were already emitted as part of previous btf_dump__dump_type() invocation
233 * for another type, they won't be emitted again. This API allows callers to
234 * filter out BTF types according to user-defined criterias and emitted only
235 * minimal subset of types, necessary to compile everything. Full struct/union
236 * definitions will still be emitted, even if the only usage is through
237 * pointer and could be satisfied with just a forward declaration.
239 * Dumping is done in two high-level passes:
240 * 1. Topologically sort type definitions to satisfy C rules of compilation.
241 * 2. Emit type definitions in C syntax.
243 * Returns 0 on success; <0, otherwise.
245 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
249 if (id > btf__get_nr_types(d->btf))
252 err = btf_dump_resize(d);
256 d->emit_queue_cnt = 0;
257 err = btf_dump_order_type(d, id, false);
261 for (i = 0; i < d->emit_queue_cnt; i++)
262 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
268 * Mark all types that are referenced from any other type. This is used to
269 * determine top-level anonymous enums that need to be emitted as an
270 * independent type declarations.
271 * Anonymous enums come in two flavors: either embedded in a struct's field
272 * definition, in which case they have to be declared inline as part of field
273 * type declaration; or as a top-level anonymous enum, typically used for
274 * declaring global constants. It's impossible to distinguish between two
275 * without knowning whether given enum type was referenced from other type:
276 * top-level anonymous enum won't be referenced by anything, while embedded
279 static int btf_dump_mark_referenced(struct btf_dump *d)
281 int i, j, n = btf__get_nr_types(d->btf);
282 const struct btf_type *t;
285 for (i = d->last_id + 1; i <= n; i++) {
286 t = btf__type_by_id(d->btf, i);
289 switch (btf_kind(t)) {
295 case BTF_KIND_VOLATILE:
297 case BTF_KIND_RESTRICT:
299 case BTF_KIND_TYPEDEF:
302 d->type_states[t->type].referenced = 1;
305 case BTF_KIND_ARRAY: {
306 const struct btf_array *a = btf_array(t);
308 d->type_states[a->index_type].referenced = 1;
309 d->type_states[a->type].referenced = 1;
312 case BTF_KIND_STRUCT:
313 case BTF_KIND_UNION: {
314 const struct btf_member *m = btf_members(t);
316 for (j = 0; j < vlen; j++, m++)
317 d->type_states[m->type].referenced = 1;
320 case BTF_KIND_FUNC_PROTO: {
321 const struct btf_param *p = btf_params(t);
323 for (j = 0; j < vlen; j++, p++)
324 d->type_states[p->type].referenced = 1;
327 case BTF_KIND_DATASEC: {
328 const struct btf_var_secinfo *v = btf_var_secinfos(t);
330 for (j = 0; j < vlen; j++, v++)
331 d->type_states[v->type].referenced = 1;
341 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
346 if (d->emit_queue_cnt >= d->emit_queue_cap) {
347 new_cap = max(16, d->emit_queue_cap * 3 / 2);
348 new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
351 d->emit_queue = new_queue;
352 d->emit_queue_cap = new_cap;
355 d->emit_queue[d->emit_queue_cnt++] = id;
360 * Determine order of emitting dependent types and specified type to satisfy
361 * C compilation rules. This is done through topological sorting with an
362 * additional complication which comes from C rules. The main idea for C is
363 * that if some type is "embedded" into a struct/union, it's size needs to be
364 * known at the time of definition of containing type. E.g., for:
367 * struct B { struct A x; }
369 * struct A *HAS* to be defined before struct B, because it's "embedded",
370 * i.e., it is part of struct B layout. But in the following case:
373 * struct B { struct A *x; }
376 * it's enough to just have a forward declaration of struct A at the time of
377 * struct B definition, as struct B has a pointer to struct A, so the size of
378 * field x is known without knowing struct A size: it's sizeof(void *).
380 * Unfortunately, there are some trickier cases we need to handle, e.g.:
382 * struct A {}; // if this was forward-declaration: compilation error
384 * struct { // anonymous struct
389 * In this case, struct B's field x is a pointer, so it's size is known
390 * regardless of the size of (anonymous) struct it points to. But because this
391 * struct is anonymous and thus defined inline inside struct B, *and* it
392 * embeds struct A, compiler requires full definition of struct A to be known
393 * before struct B can be defined. This creates a transitive dependency
394 * between struct A and struct B. If struct A was forward-declared before
395 * struct B definition and fully defined after struct B definition, that would
396 * trigger compilation error.
398 * All this means that while we are doing topological sorting on BTF type
399 * graph, we need to determine relationships between different types (graph
401 * - weak link (relationship) between X and Y, if Y *CAN* be
402 * forward-declared at the point of X definition;
403 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
405 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
406 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
407 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
408 * Weak/strong relationship is determined recursively during DFS traversal and
409 * is returned as a result from btf_dump_order_type().
411 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
412 * but it is not guaranteeing that no extraneous forward declarations will be
415 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
416 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
417 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
418 * entire graph path, so depending where from one came to that BTF type, it
419 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
420 * once they are processed, there is no need to do it again, so they are
421 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
422 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
423 * in any case, once those are processed, no need to do it again, as the
424 * result won't change.
427 * - 1, if type is part of strong link (so there is strong topological
428 * ordering requirements);
429 * - 0, if type is part of weak link (so can be satisfied through forward
431 * - <0, on error (e.g., unsatisfiable type loop detected).
433 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
436 * Order state is used to detect strong link cycles, but only for BTF
437 * kinds that are or could be an independent definition (i.e.,
438 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
439 * func_protos, modifiers are just means to get to these definitions.
440 * Int/void don't need definitions, they are assumed to be always
441 * properly defined. We also ignore datasec, var, and funcs for now.
442 * So for all non-defining kinds, we never even set ordering state,
443 * for defining kinds we set ORDERING and subsequently ORDERED if it
444 * forms a strong link.
446 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
447 const struct btf_type *t;
451 /* return true, letting typedefs know that it's ok to be emitted */
452 if (tstate->order_state == ORDERED)
455 t = btf__type_by_id(d->btf, id);
457 if (tstate->order_state == ORDERING) {
458 /* type loop, but resolvable through fwd declaration */
459 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
461 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
465 switch (btf_kind(t)) {
467 tstate->order_state = ORDERED;
471 err = btf_dump_order_type(d, t->type, true);
472 tstate->order_state = ORDERED;
476 return btf_dump_order_type(d, btf_array(t)->type, false);
478 case BTF_KIND_STRUCT:
479 case BTF_KIND_UNION: {
480 const struct btf_member *m = btf_members(t);
482 * struct/union is part of strong link, only if it's embedded
483 * (so no ptr in a path) or it's anonymous (so has to be
484 * defined inline, even if declared through ptr)
486 if (through_ptr && t->name_off != 0)
489 tstate->order_state = ORDERING;
492 for (i = 0; i < vlen; i++, m++) {
493 err = btf_dump_order_type(d, m->type, false);
498 if (t->name_off != 0) {
499 err = btf_dump_add_emit_queue_id(d, id);
504 tstate->order_state = ORDERED;
510 * non-anonymous or non-referenced enums are top-level
511 * declarations and should be emitted. Same logic can be
512 * applied to FWDs, it won't hurt anyways.
514 if (t->name_off != 0 || !tstate->referenced) {
515 err = btf_dump_add_emit_queue_id(d, id);
519 tstate->order_state = ORDERED;
522 case BTF_KIND_TYPEDEF: {
525 is_strong = btf_dump_order_type(d, t->type, through_ptr);
529 /* typedef is similar to struct/union w.r.t. fwd-decls */
530 if (through_ptr && !is_strong)
533 /* typedef is always a named definition */
534 err = btf_dump_add_emit_queue_id(d, id);
538 d->type_states[id].order_state = ORDERED;
541 case BTF_KIND_VOLATILE:
543 case BTF_KIND_RESTRICT:
544 return btf_dump_order_type(d, t->type, through_ptr);
546 case BTF_KIND_FUNC_PROTO: {
547 const struct btf_param *p = btf_params(t);
550 err = btf_dump_order_type(d, t->type, through_ptr);
556 for (i = 0; i < vlen; i++, p++) {
557 err = btf_dump_order_type(d, p->type, through_ptr);
567 case BTF_KIND_DATASEC:
568 d->type_states[id].order_state = ORDERED;
576 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
577 const struct btf_type *t);
579 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
580 const struct btf_type *t);
581 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
582 const struct btf_type *t, int lvl);
584 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
585 const struct btf_type *t);
586 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
587 const struct btf_type *t, int lvl);
589 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
590 const struct btf_type *t);
592 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
593 const struct btf_type *t, int lvl);
595 /* a local view into a shared stack */
601 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
602 const char *fname, int lvl);
603 static void btf_dump_emit_type_chain(struct btf_dump *d,
604 struct id_stack *decl_stack,
605 const char *fname, int lvl);
607 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
608 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
609 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
610 const char *orig_name);
612 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
614 const struct btf_type *t = btf__type_by_id(d->btf, id);
616 /* __builtin_va_list is a compiler built-in, which causes compilation
617 * errors, when compiling w/ different compiler, then used to compile
618 * original code (e.g., GCC to compile kernel, Clang to use generated
619 * C header from BTF). As it is built-in, it should be already defined
620 * properly internally in compiler.
622 if (t->name_off == 0)
624 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
628 * Emit C-syntax definitions of types from chains of BTF types.
630 * High-level handling of determining necessary forward declarations are handled
631 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
632 * declarations/definitions in C syntax are handled by a combo of
633 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
634 * corresponding btf_dump_emit_*_{def,fwd}() functions.
636 * We also keep track of "containing struct/union type ID" to determine when
637 * we reference it from inside and thus can avoid emitting unnecessary forward
640 * This algorithm is designed in such a way, that even if some error occurs
641 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
642 * that doesn't comply to C rules completely), algorithm will try to proceed
643 * and produce as much meaningful output as possible.
645 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
647 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
648 bool top_level_def = cont_id == 0;
649 const struct btf_type *t;
652 if (tstate->emit_state == EMITTED)
655 t = btf__type_by_id(d->btf, id);
658 if (tstate->emit_state == EMITTING) {
659 if (tstate->fwd_emitted)
663 case BTF_KIND_STRUCT:
666 * if we are referencing a struct/union that we are
667 * part of - then no need for fwd declaration
671 if (t->name_off == 0) {
672 pr_warn("anonymous struct/union loop, id:[%u]\n",
676 btf_dump_emit_struct_fwd(d, id, t);
677 btf_dump_printf(d, ";\n\n");
678 tstate->fwd_emitted = 1;
680 case BTF_KIND_TYPEDEF:
682 * for typedef fwd_emitted means typedef definition
683 * was emitted, but it can be used only for "weak"
684 * references through pointer only, not for embedding
686 if (!btf_dump_is_blacklisted(d, id)) {
687 btf_dump_emit_typedef_def(d, id, t, 0);
688 btf_dump_printf(d, ";\n\n");
690 tstate->fwd_emitted = 1;
701 /* Emit type alias definitions if necessary */
702 btf_dump_emit_missing_aliases(d, id, t);
704 tstate->emit_state = EMITTED;
708 btf_dump_emit_enum_def(d, id, t, 0);
709 btf_dump_printf(d, ";\n\n");
711 tstate->emit_state = EMITTED;
714 case BTF_KIND_VOLATILE:
716 case BTF_KIND_RESTRICT:
717 btf_dump_emit_type(d, t->type, cont_id);
720 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
723 btf_dump_emit_fwd_def(d, id, t);
724 btf_dump_printf(d, ";\n\n");
725 tstate->emit_state = EMITTED;
727 case BTF_KIND_TYPEDEF:
728 tstate->emit_state = EMITTING;
729 btf_dump_emit_type(d, t->type, id);
731 * typedef can server as both definition and forward
732 * declaration; at this stage someone depends on
733 * typedef as a forward declaration (refers to it
734 * through pointer), so unless we already did it,
735 * emit typedef as a forward declaration
737 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
738 btf_dump_emit_typedef_def(d, id, t, 0);
739 btf_dump_printf(d, ";\n\n");
741 tstate->emit_state = EMITTED;
743 case BTF_KIND_STRUCT:
745 tstate->emit_state = EMITTING;
746 /* if it's a top-level struct/union definition or struct/union
747 * is anonymous, then in C we'll be emitting all fields and
748 * their types (as opposed to just `struct X`), so we need to
749 * make sure that all types, referenced from struct/union
750 * members have necessary forward-declarations, where
753 if (top_level_def || t->name_off == 0) {
754 const struct btf_member *m = btf_members(t);
755 __u16 vlen = btf_vlen(t);
758 new_cont_id = t->name_off == 0 ? cont_id : id;
759 for (i = 0; i < vlen; i++, m++)
760 btf_dump_emit_type(d, m->type, new_cont_id);
761 } else if (!tstate->fwd_emitted && id != cont_id) {
762 btf_dump_emit_struct_fwd(d, id, t);
763 btf_dump_printf(d, ";\n\n");
764 tstate->fwd_emitted = 1;
768 btf_dump_emit_struct_def(d, id, t, 0);
769 btf_dump_printf(d, ";\n\n");
770 tstate->emit_state = EMITTED;
772 tstate->emit_state = NOT_EMITTED;
775 case BTF_KIND_FUNC_PROTO: {
776 const struct btf_param *p = btf_params(t);
777 __u16 vlen = btf_vlen(t);
780 btf_dump_emit_type(d, t->type, cont_id);
781 for (i = 0; i < vlen; i++, p++)
782 btf_dump_emit_type(d, p->type, cont_id);
791 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
792 const struct btf_type *t)
794 const struct btf_member *m;
795 int max_align = 1, align, i, bit_sz;
800 /* all non-bitfield fields have to be naturally aligned */
801 for (i = 0; i < vlen; i++, m++) {
802 align = btf__align_of(btf, m->type);
803 bit_sz = btf_member_bitfield_size(t, i);
804 if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
806 max_align = max(align, max_align);
808 /* size of a non-packed struct has to be a multiple of its alignment */
809 if (t->size % max_align != 0)
812 * if original struct was marked as packed, but its layout is
813 * naturally aligned, we'll detect that it's not packed
818 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
819 int cur_off, int next_off, int next_align,
820 bool in_bitfield, int lvl)
826 {"long", d->ptr_sz * 8}, {"int", 32}, {"short", 16}, {"char", 8}
828 int new_off, pad_bits, bits, i;
829 const char *pad_type;
831 if (cur_off >= next_off)
834 /* For filling out padding we want to take advantage of
835 * natural alignment rules to minimize unnecessary explicit
836 * padding. First, we find the largest type (among long, int,
837 * short, or char) that can be used to force naturally aligned
838 * boundary. Once determined, we'll use such type to fill in
839 * the remaining padding gap. In some cases we can rely on
840 * compiler filling some gaps, but sometimes we need to force
841 * alignment to close natural alignment with markers like
842 * `long: 0` (this is always the case for bitfields). Note
843 * that even if struct itself has, let's say 4-byte alignment
844 * (i.e., it only uses up to int-aligned types), using `long:
845 * X;` explicit padding doesn't actually change struct's
846 * overall alignment requirements, but compiler does take into
847 * account that type's (long, in this example) natural
848 * alignment requirements when adding implicit padding. We use
849 * this fact heavily and don't worry about ruining correct
850 * struct alignment requirement.
852 for (i = 0; i < ARRAY_SIZE(pads); i++) {
853 pad_bits = pads[i].bits;
854 pad_type = pads[i].name;
856 new_off = roundup(cur_off, pad_bits);
857 if (new_off <= next_off)
861 if (new_off > cur_off && new_off <= next_off) {
862 /* We need explicit `<type>: 0` aligning mark if next
863 * field is right on alignment offset and its
864 * alignment requirement is less strict than <type>'s
865 * alignment (so compiler won't naturally align to the
866 * offset we expect), or if subsequent `<type>: X`,
867 * will actually completely fit in the remaining hole,
868 * making compiler basically ignore `<type>: X`
872 (new_off == next_off && roundup(cur_off, next_align * 8) != new_off) ||
873 (new_off != next_off && next_off - new_off <= new_off - cur_off))
874 /* but for bitfields we'll emit explicit bit count */
875 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type,
876 in_bitfield ? new_off - cur_off : 0);
880 /* Now we know we start at naturally aligned offset for a chosen
881 * padding type (long, int, short, or char), and so the rest is just
882 * a straightforward filling of remaining padding gap with full
883 * `<type>: sizeof(<type>);` markers, except for the last one, which
884 * might need smaller than sizeof(<type>) padding.
886 while (cur_off != next_off) {
887 bits = min(next_off - cur_off, pad_bits);
888 if (bits == pad_bits) {
889 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
893 /* For the remainder padding that doesn't cover entire
894 * pad_type bit length, we pick the smallest necessary type.
895 * This is pure aesthetics, we could have just used `long`,
896 * but having smallest necessary one communicates better the
897 * scale of the padding gap.
899 for (i = ARRAY_SIZE(pads) - 1; i >= 0; i--) {
900 pad_type = pads[i].name;
901 pad_bits = pads[i].bits;
905 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, bits);
912 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
913 const struct btf_type *t)
915 btf_dump_printf(d, "%s %s",
916 btf_is_struct(t) ? "struct" : "union",
917 btf_dump_type_name(d, id));
920 static void btf_dump_emit_struct_def(struct btf_dump *d,
922 const struct btf_type *t,
925 const struct btf_member *m = btf_members(t);
926 bool is_struct = btf_is_struct(t);
927 bool packed, prev_bitfield = false;
928 int align, i, off = 0;
929 __u16 vlen = btf_vlen(t);
931 align = btf__align_of(d->btf, id);
932 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
934 btf_dump_printf(d, "%s%s%s {",
935 is_struct ? "struct" : "union",
936 t->name_off ? " " : "",
937 btf_dump_type_name(d, id));
939 for (i = 0; i < vlen; i++, m++) {
941 int m_off, m_sz, m_align;
944 fname = btf_name_of(d, m->name_off);
945 m_sz = btf_member_bitfield_size(t, i);
946 m_off = btf_member_bit_offset(t, i);
947 m_align = packed ? 1 : btf__align_of(d->btf, m->type);
949 in_bitfield = prev_bitfield && m_sz != 0;
951 btf_dump_emit_bit_padding(d, off, m_off, m_align, in_bitfield, lvl + 1);
952 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
953 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
956 btf_dump_printf(d, ": %d", m_sz);
958 prev_bitfield = true;
960 m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
961 off = m_off + m_sz * 8;
962 prev_bitfield = false;
965 btf_dump_printf(d, ";");
968 /* pad at the end, if necessary */
970 btf_dump_emit_bit_padding(d, off, t->size * 8, align, false, lvl + 1);
973 * Keep `struct empty {}` on a single line,
974 * only print newline when there are regular or padding fields.
976 if (vlen || t->size) {
977 btf_dump_printf(d, "\n");
978 btf_dump_printf(d, "%s}", pfx(lvl));
980 btf_dump_printf(d, "}");
983 btf_dump_printf(d, " __attribute__((packed))");
986 static const char *missing_base_types[][2] = {
988 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
989 * SIMD intrinsics. Alias them to standard base types.
991 { "__Poly8_t", "unsigned char" },
992 { "__Poly16_t", "unsigned short" },
993 { "__Poly64_t", "unsigned long long" },
994 { "__Poly128_t", "unsigned __int128" },
997 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
998 const struct btf_type *t)
1000 const char *name = btf_dump_type_name(d, id);
1003 for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
1004 if (strcmp(name, missing_base_types[i][0]) == 0) {
1005 btf_dump_printf(d, "typedef %s %s;\n\n",
1006 missing_base_types[i][1], name);
1012 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
1013 const struct btf_type *t)
1015 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
1018 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
1019 const struct btf_type *t,
1022 const struct btf_enum *v = btf_enum(t);
1023 __u16 vlen = btf_vlen(t);
1028 btf_dump_printf(d, "enum%s%s",
1029 t->name_off ? " " : "",
1030 btf_dump_type_name(d, id));
1033 btf_dump_printf(d, " {");
1034 for (i = 0; i < vlen; i++, v++) {
1035 name = btf_name_of(d, v->name_off);
1036 /* enumerators share namespace with typedef idents */
1037 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1039 btf_dump_printf(d, "\n%s%s___%zu = %u,",
1040 pfx(lvl + 1), name, dup_cnt,
1043 btf_dump_printf(d, "\n%s%s = %u,",
1048 btf_dump_printf(d, "\n%s}", pfx(lvl));
1052 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1053 const struct btf_type *t)
1055 const char *name = btf_dump_type_name(d, id);
1058 btf_dump_printf(d, "union %s", name);
1060 btf_dump_printf(d, "struct %s", name);
1063 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1064 const struct btf_type *t, int lvl)
1066 const char *name = btf_dump_ident_name(d, id);
1069 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
1070 * pointing to VOID. This generates warnings from btf_dump() and
1071 * results in uncompilable header file, so we are fixing it up here
1072 * with valid typedef into __builtin_va_list.
1074 if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1075 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1079 btf_dump_printf(d, "typedef ");
1080 btf_dump_emit_type_decl(d, t->type, name, lvl);
1083 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1088 if (d->decl_stack_cnt >= d->decl_stack_cap) {
1089 new_cap = max(16, d->decl_stack_cap * 3 / 2);
1090 new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
1093 d->decl_stack = new_stack;
1094 d->decl_stack_cap = new_cap;
1097 d->decl_stack[d->decl_stack_cnt++] = id;
1103 * Emit type declaration (e.g., field type declaration in a struct or argument
1104 * declaration in function prototype) in correct C syntax.
1106 * For most types it's trivial, but there are few quirky type declaration
1107 * cases worth mentioning:
1108 * - function prototypes (especially nesting of function prototypes);
1110 * - const/volatile/restrict for pointers vs other types.
1112 * For a good discussion of *PARSING* C syntax (as a human), see
1113 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1114 * Ch.3 "Unscrambling Declarations in C".
1116 * It won't help with BTF to C conversion much, though, as it's an opposite
1117 * problem. So we came up with this algorithm in reverse to van der Linden's
1118 * parsing algorithm. It goes from structured BTF representation of type
1119 * declaration to a valid compilable C syntax.
1121 * For instance, consider this C typedef:
1122 * typedef const int * const * arr[10] arr_t;
1123 * It will be represented in BTF with this chain of BTF types:
1124 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1126 * Notice how [const] modifier always goes before type it modifies in BTF type
1127 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1128 * the right of pointers, but to the left of other types. There are also other
1129 * quirks, like function pointers, arrays of them, functions returning other
1132 * We handle that by pushing all the types to a stack, until we hit "terminal"
1133 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1134 * top of a stack, modifiers are handled differently. Array/function pointers
1135 * have also wildly different syntax and how nesting of them are done. See
1136 * code for authoritative definition.
1138 * To avoid allocating new stack for each independent chain of BTF types, we
1139 * share one bigger stack, with each chain working only on its own local view
1140 * of a stack frame. Some care is required to "pop" stack frames after
1141 * processing type declaration chain.
1143 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1144 const struct btf_dump_emit_type_decl_opts *opts)
1149 if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1152 err = btf_dump_resize(d);
1156 fname = OPTS_GET(opts, field_name, "");
1157 lvl = OPTS_GET(opts, indent_level, 0);
1158 d->strip_mods = OPTS_GET(opts, strip_mods, false);
1159 btf_dump_emit_type_decl(d, id, fname, lvl);
1160 d->strip_mods = false;
1164 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1165 const char *fname, int lvl)
1167 struct id_stack decl_stack;
1168 const struct btf_type *t;
1169 int err, stack_start;
1171 stack_start = d->decl_stack_cnt;
1173 t = btf__type_by_id(d->btf, id);
1174 if (d->strip_mods && btf_is_mod(t))
1177 err = btf_dump_push_decl_stack_id(d, id);
1180 * if we don't have enough memory for entire type decl
1181 * chain, restore stack, emit warning, and try to
1182 * proceed nevertheless
1184 pr_warn("not enough memory for decl stack:%d", err);
1185 d->decl_stack_cnt = stack_start;
1193 switch (btf_kind(t)) {
1195 case BTF_KIND_VOLATILE:
1196 case BTF_KIND_CONST:
1197 case BTF_KIND_RESTRICT:
1198 case BTF_KIND_FUNC_PROTO:
1201 case BTF_KIND_ARRAY:
1202 id = btf_array(t)->type;
1207 case BTF_KIND_STRUCT:
1208 case BTF_KIND_UNION:
1209 case BTF_KIND_TYPEDEF:
1212 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1219 * We might be inside a chain of declarations (e.g., array of function
1220 * pointers returning anonymous (so inlined) structs, having another
1221 * array field). Each of those needs its own "stack frame" to handle
1222 * emitting of declarations. Those stack frames are non-overlapping
1223 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1224 * handle this set of nested stacks, we create a view corresponding to
1225 * our own "stack frame" and work with it as an independent stack.
1226 * We'll need to clean up after emit_type_chain() returns, though.
1228 decl_stack.ids = d->decl_stack + stack_start;
1229 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1230 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1232 * emit_type_chain() guarantees that it will pop its entire decl_stack
1233 * frame before returning. But it works with a read-only view into
1234 * decl_stack, so it doesn't actually pop anything from the
1235 * perspective of shared btf_dump->decl_stack, per se. We need to
1236 * reset decl_stack state to how it was before us to avoid it growing
1239 d->decl_stack_cnt = stack_start;
1242 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1244 const struct btf_type *t;
1247 while (decl_stack->cnt) {
1248 id = decl_stack->ids[decl_stack->cnt - 1];
1249 t = btf__type_by_id(d->btf, id);
1251 switch (btf_kind(t)) {
1252 case BTF_KIND_VOLATILE:
1253 btf_dump_printf(d, "volatile ");
1255 case BTF_KIND_CONST:
1256 btf_dump_printf(d, "const ");
1258 case BTF_KIND_RESTRICT:
1259 btf_dump_printf(d, "restrict ");
1268 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1270 const struct btf_type *t;
1273 while (decl_stack->cnt) {
1274 id = decl_stack->ids[decl_stack->cnt - 1];
1275 t = btf__type_by_id(d->btf, id);
1282 static void btf_dump_emit_name(const struct btf_dump *d,
1283 const char *name, bool last_was_ptr)
1285 bool separate = name[0] && !last_was_ptr;
1287 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1290 static void btf_dump_emit_type_chain(struct btf_dump *d,
1291 struct id_stack *decls,
1292 const char *fname, int lvl)
1295 * last_was_ptr is used to determine if we need to separate pointer
1296 * asterisk (*) from previous part of type signature with space, so
1297 * that we get `int ***`, instead of `int * * *`. We default to true
1298 * for cases where we have single pointer in a chain. E.g., in ptr ->
1299 * func_proto case. func_proto will start a new emit_type_chain call
1300 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1301 * don't want to prepend space for that last pointer.
1303 bool last_was_ptr = true;
1304 const struct btf_type *t;
1309 while (decls->cnt) {
1310 id = decls->ids[--decls->cnt];
1312 /* VOID is a special snowflake */
1313 btf_dump_emit_mods(d, decls);
1314 btf_dump_printf(d, "void");
1315 last_was_ptr = false;
1319 t = btf__type_by_id(d->btf, id);
1324 btf_dump_emit_mods(d, decls);
1325 name = btf_name_of(d, t->name_off);
1326 btf_dump_printf(d, "%s", name);
1328 case BTF_KIND_STRUCT:
1329 case BTF_KIND_UNION:
1330 btf_dump_emit_mods(d, decls);
1331 /* inline anonymous struct/union */
1332 if (t->name_off == 0)
1333 btf_dump_emit_struct_def(d, id, t, lvl);
1335 btf_dump_emit_struct_fwd(d, id, t);
1338 btf_dump_emit_mods(d, decls);
1339 /* inline anonymous enum */
1340 if (t->name_off == 0)
1341 btf_dump_emit_enum_def(d, id, t, lvl);
1343 btf_dump_emit_enum_fwd(d, id, t);
1346 btf_dump_emit_mods(d, decls);
1347 btf_dump_emit_fwd_def(d, id, t);
1349 case BTF_KIND_TYPEDEF:
1350 btf_dump_emit_mods(d, decls);
1351 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1354 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1356 case BTF_KIND_VOLATILE:
1357 btf_dump_printf(d, " volatile");
1359 case BTF_KIND_CONST:
1360 btf_dump_printf(d, " const");
1362 case BTF_KIND_RESTRICT:
1363 btf_dump_printf(d, " restrict");
1365 case BTF_KIND_ARRAY: {
1366 const struct btf_array *a = btf_array(t);
1367 const struct btf_type *next_t;
1372 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1373 * which causes it to emit extra const/volatile
1374 * modifiers for an array, if array's element type has
1375 * const/volatile modifiers. Clang doesn't do that.
1376 * In general, it doesn't seem very meaningful to have
1377 * a const/volatile modifier for array, so we are
1378 * going to silently skip them here.
1380 btf_dump_drop_mods(d, decls);
1382 if (decls->cnt == 0) {
1383 btf_dump_emit_name(d, fname, last_was_ptr);
1384 btf_dump_printf(d, "[%u]", a->nelems);
1388 next_id = decls->ids[decls->cnt - 1];
1389 next_t = btf__type_by_id(d->btf, next_id);
1390 multidim = btf_is_array(next_t);
1391 /* we need space if we have named non-pointer */
1392 if (fname[0] && !last_was_ptr)
1393 btf_dump_printf(d, " ");
1394 /* no parentheses for multi-dimensional array */
1396 btf_dump_printf(d, "(");
1397 btf_dump_emit_type_chain(d, decls, fname, lvl);
1399 btf_dump_printf(d, ")");
1400 btf_dump_printf(d, "[%u]", a->nelems);
1403 case BTF_KIND_FUNC_PROTO: {
1404 const struct btf_param *p = btf_params(t);
1405 __u16 vlen = btf_vlen(t);
1409 * GCC emits extra volatile qualifier for
1410 * __attribute__((noreturn)) function pointers. Clang
1411 * doesn't do it. It's a GCC quirk for backwards
1412 * compatibility with code written for GCC <2.5. So,
1413 * similarly to extra qualifiers for array, just drop
1414 * them, instead of handling them.
1416 btf_dump_drop_mods(d, decls);
1418 btf_dump_printf(d, " (");
1419 btf_dump_emit_type_chain(d, decls, fname, lvl);
1420 btf_dump_printf(d, ")");
1422 btf_dump_emit_name(d, fname, last_was_ptr);
1424 btf_dump_printf(d, "(");
1426 * Clang for BPF target generates func_proto with no
1427 * args as a func_proto with a single void arg (e.g.,
1428 * `int (*f)(void)` vs just `int (*f)()`). We are
1429 * going to pretend there are no args for such case.
1431 if (vlen == 1 && p->type == 0) {
1432 btf_dump_printf(d, ")");
1436 for (i = 0; i < vlen; i++, p++) {
1438 btf_dump_printf(d, ", ");
1440 /* last arg of type void is vararg */
1441 if (i == vlen - 1 && p->type == 0) {
1442 btf_dump_printf(d, "...");
1446 name = btf_name_of(d, p->name_off);
1447 btf_dump_emit_type_decl(d, p->type, name, lvl);
1450 btf_dump_printf(d, ")");
1454 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1459 last_was_ptr = kind == BTF_KIND_PTR;
1462 btf_dump_emit_name(d, fname, last_was_ptr);
1465 /* return number of duplicates (occurrences) of a given name */
1466 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1467 const char *orig_name)
1469 char *old_name, *new_name;
1473 new_name = strdup(orig_name);
1477 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1480 err = hashmap__set(name_map, new_name, (void *)dup_cnt,
1481 (const void **)&old_name, NULL);
1490 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1491 struct hashmap *name_map)
1493 struct btf_dump_type_aux_state *s = &d->type_states[id];
1494 const struct btf_type *t = btf__type_by_id(d->btf, id);
1495 const char *orig_name = btf_name_of(d, t->name_off);
1496 const char **cached_name = &d->cached_names[id];
1499 if (t->name_off == 0)
1502 if (s->name_resolved)
1503 return *cached_name ? *cached_name : orig_name;
1505 if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1506 s->name_resolved = 1;
1510 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1512 const size_t max_len = 256;
1513 char new_name[max_len];
1515 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1516 *cached_name = strdup(new_name);
1519 s->name_resolved = 1;
1520 return *cached_name ? *cached_name : orig_name;
1523 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1525 return btf_dump_resolve_name(d, id, d->type_names);
1528 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1530 return btf_dump_resolve_name(d, id, d->ident_names);