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>
19 #include "libbpf_internal.h"
21 static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
22 static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
24 static const char *pfx(int lvl)
26 return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
29 enum btf_dump_type_order_state {
35 enum btf_dump_type_emit_state {
41 /* per-type auxiliary state */
42 struct btf_dump_type_aux_state {
43 /* topological sorting state */
44 enum btf_dump_type_order_state order_state: 2;
45 /* emitting state used to determine the need for forward declaration */
46 enum btf_dump_type_emit_state emit_state: 2;
47 /* whether forward declaration was already emitted */
49 /* whether unique non-duplicate name was already assigned */
50 __u8 name_resolved: 1;
54 const struct btf *btf;
55 const struct btf_ext *btf_ext;
56 btf_dump_printf_fn_t printf_fn;
57 struct btf_dump_opts opts;
59 /* per-type auxiliary state */
60 struct btf_dump_type_aux_state *type_states;
61 /* per-type optional cached unique name, must be freed, if present */
62 const char **cached_names;
64 /* topo-sorted list of dependent type definitions */
70 * stack of type declarations (e.g., chain of modifiers, arrays,
77 /* maps struct/union/enum name to a number of name occurrences */
78 struct hashmap *type_names;
80 * maps typedef identifiers and enum value names to a number of such
83 struct hashmap *ident_names;
86 static size_t str_hash_fn(const void *key, void *ctx)
98 static bool str_equal_fn(const void *a, const void *b, void *ctx)
100 return strcmp(a, b) == 0;
103 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
105 return btf__name_by_offset(d->btf, name_off);
108 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
113 d->printf_fn(d->opts.ctx, fmt, args);
117 struct btf_dump *btf_dump__new(const struct btf *btf,
118 const struct btf_ext *btf_ext,
119 const struct btf_dump_opts *opts,
120 btf_dump_printf_fn_t printf_fn)
125 d = calloc(1, sizeof(struct btf_dump));
127 return ERR_PTR(-ENOMEM);
130 d->btf_ext = btf_ext;
131 d->printf_fn = printf_fn;
132 d->opts.ctx = opts ? opts->ctx : NULL;
134 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
135 if (IS_ERR(d->type_names)) {
136 err = PTR_ERR(d->type_names);
137 d->type_names = NULL;
141 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
142 if (IS_ERR(d->ident_names)) {
143 err = PTR_ERR(d->ident_names);
144 d->ident_names = NULL;
152 void btf_dump__free(struct btf_dump *d)
159 free(d->type_states);
160 if (d->cached_names) {
161 /* any set cached name is owned by us and should be freed */
162 for (i = 0, cnt = btf__get_nr_types(d->btf); i <= cnt; i++) {
163 if (d->cached_names[i])
164 free((void *)d->cached_names[i]);
167 free(d->cached_names);
170 hashmap__free(d->type_names);
171 hashmap__free(d->ident_names);
176 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
177 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
180 * Dump BTF type in a compilable C syntax, including all the necessary
181 * dependent types, necessary for compilation. If some of the dependent types
182 * were already emitted as part of previous btf_dump__dump_type() invocation
183 * for another type, they won't be emitted again. This API allows callers to
184 * filter out BTF types according to user-defined criterias and emitted only
185 * minimal subset of types, necessary to compile everything. Full struct/union
186 * definitions will still be emitted, even if the only usage is through
187 * pointer and could be satisfied with just a forward declaration.
189 * Dumping is done in two high-level passes:
190 * 1. Topologically sort type definitions to satisfy C rules of compilation.
191 * 2. Emit type definitions in C syntax.
193 * Returns 0 on success; <0, otherwise.
195 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
199 if (id > btf__get_nr_types(d->btf))
202 /* type states are lazily allocated, as they might not be needed */
203 if (!d->type_states) {
204 d->type_states = calloc(1 + btf__get_nr_types(d->btf),
205 sizeof(d->type_states[0]));
208 d->cached_names = calloc(1 + btf__get_nr_types(d->btf),
209 sizeof(d->cached_names[0]));
210 if (!d->cached_names)
213 /* VOID is special */
214 d->type_states[0].order_state = ORDERED;
215 d->type_states[0].emit_state = EMITTED;
218 d->emit_queue_cnt = 0;
219 err = btf_dump_order_type(d, id, false);
223 for (i = 0; i < d->emit_queue_cnt; i++)
224 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
229 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
234 if (d->emit_queue_cnt >= d->emit_queue_cap) {
235 new_cap = max(16, d->emit_queue_cap * 3 / 2);
236 new_queue = realloc(d->emit_queue,
237 new_cap * sizeof(new_queue[0]));
240 d->emit_queue = new_queue;
241 d->emit_queue_cap = new_cap;
244 d->emit_queue[d->emit_queue_cnt++] = id;
249 * Determine order of emitting dependent types and specified type to satisfy
250 * C compilation rules. This is done through topological sorting with an
251 * additional complication which comes from C rules. The main idea for C is
252 * that if some type is "embedded" into a struct/union, it's size needs to be
253 * known at the time of definition of containing type. E.g., for:
256 * struct B { struct A x; }
258 * struct A *HAS* to be defined before struct B, because it's "embedded",
259 * i.e., it is part of struct B layout. But in the following case:
262 * struct B { struct A *x; }
265 * it's enough to just have a forward declaration of struct A at the time of
266 * struct B definition, as struct B has a pointer to struct A, so the size of
267 * field x is known without knowing struct A size: it's sizeof(void *).
269 * Unfortunately, there are some trickier cases we need to handle, e.g.:
271 * struct A {}; // if this was forward-declaration: compilation error
273 * struct { // anonymous struct
278 * In this case, struct B's field x is a pointer, so it's size is known
279 * regardless of the size of (anonymous) struct it points to. But because this
280 * struct is anonymous and thus defined inline inside struct B, *and* it
281 * embeds struct A, compiler requires full definition of struct A to be known
282 * before struct B can be defined. This creates a transitive dependency
283 * between struct A and struct B. If struct A was forward-declared before
284 * struct B definition and fully defined after struct B definition, that would
285 * trigger compilation error.
287 * All this means that while we are doing topological sorting on BTF type
288 * graph, we need to determine relationships between different types (graph
290 * - weak link (relationship) between X and Y, if Y *CAN* be
291 * forward-declared at the point of X definition;
292 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
294 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
295 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
296 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
297 * Weak/strong relationship is determined recursively during DFS traversal and
298 * is returned as a result from btf_dump_order_type().
300 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
301 * but it is not guaranteeing that no extraneous forward declarations will be
304 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
305 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
306 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
307 * entire graph path, so depending where from one came to that BTF type, it
308 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
309 * once they are processed, there is no need to do it again, so they are
310 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
311 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
312 * in any case, once those are processed, no need to do it again, as the
313 * result won't change.
316 * - 1, if type is part of strong link (so there is strong topological
317 * ordering requirements);
318 * - 0, if type is part of weak link (so can be satisfied through forward
320 * - <0, on error (e.g., unsatisfiable type loop detected).
322 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
325 * Order state is used to detect strong link cycles, but only for BTF
326 * kinds that are or could be an independent definition (i.e.,
327 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
328 * func_protos, modifiers are just means to get to these definitions.
329 * Int/void don't need definitions, they are assumed to be always
330 * properly defined. We also ignore datasec, var, and funcs for now.
331 * So for all non-defining kinds, we never even set ordering state,
332 * for defining kinds we set ORDERING and subsequently ORDERED if it
333 * forms a strong link.
335 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
336 const struct btf_type *t;
340 /* return true, letting typedefs know that it's ok to be emitted */
341 if (tstate->order_state == ORDERED)
344 t = btf__type_by_id(d->btf, id);
346 if (tstate->order_state == ORDERING) {
347 /* type loop, but resolvable through fwd declaration */
348 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
350 pr_warning("unsatisfiable type cycle, id:[%u]\n", id);
354 switch (btf_kind(t)) {
356 tstate->order_state = ORDERED;
360 err = btf_dump_order_type(d, t->type, true);
361 tstate->order_state = ORDERED;
365 return btf_dump_order_type(d, btf_array(t)->type, through_ptr);
367 case BTF_KIND_STRUCT:
368 case BTF_KIND_UNION: {
369 const struct btf_member *m = btf_members(t);
371 * struct/union is part of strong link, only if it's embedded
372 * (so no ptr in a path) or it's anonymous (so has to be
373 * defined inline, even if declared through ptr)
375 if (through_ptr && t->name_off != 0)
378 tstate->order_state = ORDERING;
381 for (i = 0; i < vlen; i++, m++) {
382 err = btf_dump_order_type(d, m->type, false);
387 if (t->name_off != 0) {
388 err = btf_dump_add_emit_queue_id(d, id);
393 tstate->order_state = ORDERED;
398 if (t->name_off != 0) {
399 err = btf_dump_add_emit_queue_id(d, id);
403 tstate->order_state = ORDERED;
406 case BTF_KIND_TYPEDEF: {
409 is_strong = btf_dump_order_type(d, t->type, through_ptr);
413 /* typedef is similar to struct/union w.r.t. fwd-decls */
414 if (through_ptr && !is_strong)
417 /* typedef is always a named definition */
418 err = btf_dump_add_emit_queue_id(d, id);
422 d->type_states[id].order_state = ORDERED;
425 case BTF_KIND_VOLATILE:
427 case BTF_KIND_RESTRICT:
428 return btf_dump_order_type(d, t->type, through_ptr);
430 case BTF_KIND_FUNC_PROTO: {
431 const struct btf_param *p = btf_params(t);
434 err = btf_dump_order_type(d, t->type, through_ptr);
440 for (i = 0; i < vlen; i++, p++) {
441 err = btf_dump_order_type(d, p->type, through_ptr);
451 case BTF_KIND_DATASEC:
452 d->type_states[id].order_state = ORDERED;
460 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
461 const struct btf_type *t);
462 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
463 const struct btf_type *t, int lvl);
465 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
466 const struct btf_type *t);
467 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
468 const struct btf_type *t, int lvl);
470 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
471 const struct btf_type *t);
473 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
474 const struct btf_type *t, int lvl);
476 /* a local view into a shared stack */
482 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
483 const char *fname, int lvl);
484 static void btf_dump_emit_type_chain(struct btf_dump *d,
485 struct id_stack *decl_stack,
486 const char *fname, int lvl);
488 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
489 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
490 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
491 const char *orig_name);
493 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
495 const struct btf_type *t = btf__type_by_id(d->btf, id);
497 /* __builtin_va_list is a compiler built-in, which causes compilation
498 * errors, when compiling w/ different compiler, then used to compile
499 * original code (e.g., GCC to compile kernel, Clang to use generated
500 * C header from BTF). As it is built-in, it should be already defined
501 * properly internally in compiler.
503 if (t->name_off == 0)
505 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
509 * Emit C-syntax definitions of types from chains of BTF types.
511 * High-level handling of determining necessary forward declarations are handled
512 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
513 * declarations/definitions in C syntax are handled by a combo of
514 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
515 * corresponding btf_dump_emit_*_{def,fwd}() functions.
517 * We also keep track of "containing struct/union type ID" to determine when
518 * we reference it from inside and thus can avoid emitting unnecessary forward
521 * This algorithm is designed in such a way, that even if some error occurs
522 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
523 * that doesn't comply to C rules completely), algorithm will try to proceed
524 * and produce as much meaningful output as possible.
526 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
528 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
529 bool top_level_def = cont_id == 0;
530 const struct btf_type *t;
533 if (tstate->emit_state == EMITTED)
536 t = btf__type_by_id(d->btf, id);
539 if (top_level_def && t->name_off == 0) {
540 pr_warning("unexpected nameless definition, id:[%u]\n", id);
544 if (tstate->emit_state == EMITTING) {
545 if (tstate->fwd_emitted)
549 case BTF_KIND_STRUCT:
552 * if we are referencing a struct/union that we are
553 * part of - then no need for fwd declaration
557 if (t->name_off == 0) {
558 pr_warning("anonymous struct/union loop, id:[%u]\n",
562 btf_dump_emit_struct_fwd(d, id, t);
563 btf_dump_printf(d, ";\n\n");
564 tstate->fwd_emitted = 1;
566 case BTF_KIND_TYPEDEF:
568 * for typedef fwd_emitted means typedef definition
569 * was emitted, but it can be used only for "weak"
570 * references through pointer only, not for embedding
572 if (!btf_dump_is_blacklisted(d, id)) {
573 btf_dump_emit_typedef_def(d, id, t, 0);
574 btf_dump_printf(d, ";\n\n");
576 tstate->fwd_emitted = 1;
587 tstate->emit_state = EMITTED;
591 btf_dump_emit_enum_def(d, id, t, 0);
592 btf_dump_printf(d, ";\n\n");
594 tstate->emit_state = EMITTED;
597 case BTF_KIND_VOLATILE:
599 case BTF_KIND_RESTRICT:
600 btf_dump_emit_type(d, t->type, cont_id);
603 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
606 btf_dump_emit_fwd_def(d, id, t);
607 btf_dump_printf(d, ";\n\n");
608 tstate->emit_state = EMITTED;
610 case BTF_KIND_TYPEDEF:
611 tstate->emit_state = EMITTING;
612 btf_dump_emit_type(d, t->type, id);
614 * typedef can server as both definition and forward
615 * declaration; at this stage someone depends on
616 * typedef as a forward declaration (refers to it
617 * through pointer), so unless we already did it,
618 * emit typedef as a forward declaration
620 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
621 btf_dump_emit_typedef_def(d, id, t, 0);
622 btf_dump_printf(d, ";\n\n");
624 tstate->emit_state = EMITTED;
626 case BTF_KIND_STRUCT:
628 tstate->emit_state = EMITTING;
629 /* if it's a top-level struct/union definition or struct/union
630 * is anonymous, then in C we'll be emitting all fields and
631 * their types (as opposed to just `struct X`), so we need to
632 * make sure that all types, referenced from struct/union
633 * members have necessary forward-declarations, where
636 if (top_level_def || t->name_off == 0) {
637 const struct btf_member *m = btf_members(t);
638 __u16 vlen = btf_vlen(t);
641 new_cont_id = t->name_off == 0 ? cont_id : id;
642 for (i = 0; i < vlen; i++, m++)
643 btf_dump_emit_type(d, m->type, new_cont_id);
644 } else if (!tstate->fwd_emitted && id != cont_id) {
645 btf_dump_emit_struct_fwd(d, id, t);
646 btf_dump_printf(d, ";\n\n");
647 tstate->fwd_emitted = 1;
651 btf_dump_emit_struct_def(d, id, t, 0);
652 btf_dump_printf(d, ";\n\n");
653 tstate->emit_state = EMITTED;
655 tstate->emit_state = NOT_EMITTED;
658 case BTF_KIND_FUNC_PROTO: {
659 const struct btf_param *p = btf_params(t);
660 __u16 vlen = btf_vlen(t);
663 btf_dump_emit_type(d, t->type, cont_id);
664 for (i = 0; i < vlen; i++, p++)
665 btf_dump_emit_type(d, p->type, cont_id);
674 static int btf_align_of(const struct btf *btf, __u32 id)
676 const struct btf_type *t = btf__type_by_id(btf, id);
677 __u16 kind = btf_kind(t);
682 return min(sizeof(void *), t->size);
684 return sizeof(void *);
685 case BTF_KIND_TYPEDEF:
686 case BTF_KIND_VOLATILE:
688 case BTF_KIND_RESTRICT:
689 return btf_align_of(btf, t->type);
691 return btf_align_of(btf, btf_array(t)->type);
692 case BTF_KIND_STRUCT:
693 case BTF_KIND_UNION: {
694 const struct btf_member *m = btf_members(t);
695 __u16 vlen = btf_vlen(t);
698 for (i = 0; i < vlen; i++, m++)
699 align = max(align, btf_align_of(btf, m->type));
704 pr_warning("unsupported BTF_KIND:%u\n", btf_kind(t));
709 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
710 const struct btf_type *t)
712 const struct btf_member *m;
713 int align, i, bit_sz;
716 align = btf_align_of(btf, id);
717 /* size of a non-packed struct has to be a multiple of its alignment*/
723 /* all non-bitfield fields have to be naturally aligned */
724 for (i = 0; i < vlen; i++, m++) {
725 align = btf_align_of(btf, m->type);
726 bit_sz = btf_member_bitfield_size(t, i);
727 if (bit_sz == 0 && m->offset % (8 * align) != 0)
732 * if original struct was marked as packed, but its layout is
733 * naturally aligned, we'll detect that it's not packed
738 static int chip_away_bits(int total, int at_most)
740 return total % at_most ? : at_most;
743 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
744 int cur_off, int m_off, int m_bit_sz,
747 int off_diff = m_off - cur_off;
748 int ptr_bits = sizeof(void *) * 8;
753 if (m_bit_sz == 0 && off_diff < align * 8)
754 /* natural padding will take care of a gap */
757 while (off_diff > 0) {
758 const char *pad_type;
761 if (ptr_bits > 32 && off_diff > 32) {
763 pad_bits = chip_away_bits(off_diff, ptr_bits);
764 } else if (off_diff > 16) {
766 pad_bits = chip_away_bits(off_diff, 32);
767 } else if (off_diff > 8) {
769 pad_bits = chip_away_bits(off_diff, 16);
772 pad_bits = chip_away_bits(off_diff, 8);
774 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
775 off_diff -= pad_bits;
779 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
780 const struct btf_type *t)
782 btf_dump_printf(d, "%s %s",
783 btf_is_struct(t) ? "struct" : "union",
784 btf_dump_type_name(d, id));
787 static void btf_dump_emit_struct_def(struct btf_dump *d,
789 const struct btf_type *t,
792 const struct btf_member *m = btf_members(t);
793 bool is_struct = btf_is_struct(t);
794 int align, i, packed, off = 0;
795 __u16 vlen = btf_vlen(t);
797 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
798 align = packed ? 1 : btf_align_of(d->btf, id);
800 btf_dump_printf(d, "%s%s%s {",
801 is_struct ? "struct" : "union",
802 t->name_off ? " " : "",
803 btf_dump_type_name(d, id));
805 for (i = 0; i < vlen; i++, m++) {
809 fname = btf_name_of(d, m->name_off);
810 m_sz = btf_member_bitfield_size(t, i);
811 m_off = btf_member_bit_offset(t, i);
812 align = packed ? 1 : btf_align_of(d->btf, m->type);
814 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
815 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
816 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
819 btf_dump_printf(d, ": %d", m_sz);
822 m_sz = max(0, btf__resolve_size(d->btf, m->type));
823 off = m_off + m_sz * 8;
825 btf_dump_printf(d, ";");
829 btf_dump_printf(d, "\n");
830 btf_dump_printf(d, "%s}", pfx(lvl));
832 btf_dump_printf(d, " __attribute__((packed))");
835 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
836 const struct btf_type *t)
838 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
841 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
842 const struct btf_type *t,
845 const struct btf_enum *v = btf_enum(t);
846 __u16 vlen = btf_vlen(t);
851 btf_dump_printf(d, "enum%s%s",
852 t->name_off ? " " : "",
853 btf_dump_type_name(d, id));
856 btf_dump_printf(d, " {");
857 for (i = 0; i < vlen; i++, v++) {
858 name = btf_name_of(d, v->name_off);
859 /* enumerators share namespace with typedef idents */
860 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
862 btf_dump_printf(d, "\n%s%s___%zu = %d,",
863 pfx(lvl + 1), name, dup_cnt,
866 btf_dump_printf(d, "\n%s%s = %d,",
871 btf_dump_printf(d, "\n%s}", pfx(lvl));
875 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
876 const struct btf_type *t)
878 const char *name = btf_dump_type_name(d, id);
881 btf_dump_printf(d, "union %s", name);
883 btf_dump_printf(d, "struct %s", name);
886 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
887 const struct btf_type *t, int lvl)
889 const char *name = btf_dump_ident_name(d, id);
891 btf_dump_printf(d, "typedef ");
892 btf_dump_emit_type_decl(d, t->type, name, lvl);
895 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
900 if (d->decl_stack_cnt >= d->decl_stack_cap) {
901 new_cap = max(16, d->decl_stack_cap * 3 / 2);
902 new_stack = realloc(d->decl_stack,
903 new_cap * sizeof(new_stack[0]));
906 d->decl_stack = new_stack;
907 d->decl_stack_cap = new_cap;
910 d->decl_stack[d->decl_stack_cnt++] = id;
916 * Emit type declaration (e.g., field type declaration in a struct or argument
917 * declaration in function prototype) in correct C syntax.
919 * For most types it's trivial, but there are few quirky type declaration
920 * cases worth mentioning:
921 * - function prototypes (especially nesting of function prototypes);
923 * - const/volatile/restrict for pointers vs other types.
925 * For a good discussion of *PARSING* C syntax (as a human), see
926 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
927 * Ch.3 "Unscrambling Declarations in C".
929 * It won't help with BTF to C conversion much, though, as it's an opposite
930 * problem. So we came up with this algorithm in reverse to van der Linden's
931 * parsing algorithm. It goes from structured BTF representation of type
932 * declaration to a valid compilable C syntax.
934 * For instance, consider this C typedef:
935 * typedef const int * const * arr[10] arr_t;
936 * It will be represented in BTF with this chain of BTF types:
937 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
939 * Notice how [const] modifier always goes before type it modifies in BTF type
940 * graph, but in C syntax, const/volatile/restrict modifiers are written to
941 * the right of pointers, but to the left of other types. There are also other
942 * quirks, like function pointers, arrays of them, functions returning other
945 * We handle that by pushing all the types to a stack, until we hit "terminal"
946 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
947 * top of a stack, modifiers are handled differently. Array/function pointers
948 * have also wildly different syntax and how nesting of them are done. See
949 * code for authoritative definition.
951 * To avoid allocating new stack for each independent chain of BTF types, we
952 * share one bigger stack, with each chain working only on its own local view
953 * of a stack frame. Some care is required to "pop" stack frames after
954 * processing type declaration chain.
956 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
957 const char *fname, int lvl)
959 struct id_stack decl_stack;
960 const struct btf_type *t;
961 int err, stack_start;
963 stack_start = d->decl_stack_cnt;
965 err = btf_dump_push_decl_stack_id(d, id);
968 * if we don't have enough memory for entire type decl
969 * chain, restore stack, emit warning, and try to
970 * proceed nevertheless
972 pr_warning("not enough memory for decl stack:%d", err);
973 d->decl_stack_cnt = stack_start;
981 t = btf__type_by_id(d->btf, id);
982 switch (btf_kind(t)) {
984 case BTF_KIND_VOLATILE:
986 case BTF_KIND_RESTRICT:
987 case BTF_KIND_FUNC_PROTO:
991 id = btf_array(t)->type;
996 case BTF_KIND_STRUCT:
998 case BTF_KIND_TYPEDEF:
1001 pr_warning("unexpected type in decl chain, kind:%u, id:[%u]\n",
1008 * We might be inside a chain of declarations (e.g., array of function
1009 * pointers returning anonymous (so inlined) structs, having another
1010 * array field). Each of those needs its own "stack frame" to handle
1011 * emitting of declarations. Those stack frames are non-overlapping
1012 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1013 * handle this set of nested stacks, we create a view corresponding to
1014 * our own "stack frame" and work with it as an independent stack.
1015 * We'll need to clean up after emit_type_chain() returns, though.
1017 decl_stack.ids = d->decl_stack + stack_start;
1018 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1019 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1021 * emit_type_chain() guarantees that it will pop its entire decl_stack
1022 * frame before returning. But it works with a read-only view into
1023 * decl_stack, so it doesn't actually pop anything from the
1024 * perspective of shared btf_dump->decl_stack, per se. We need to
1025 * reset decl_stack state to how it was before us to avoid it growing
1028 d->decl_stack_cnt = stack_start;
1031 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1033 const struct btf_type *t;
1036 while (decl_stack->cnt) {
1037 id = decl_stack->ids[decl_stack->cnt - 1];
1038 t = btf__type_by_id(d->btf, id);
1040 switch (btf_kind(t)) {
1041 case BTF_KIND_VOLATILE:
1042 btf_dump_printf(d, "volatile ");
1044 case BTF_KIND_CONST:
1045 btf_dump_printf(d, "const ");
1047 case BTF_KIND_RESTRICT:
1048 btf_dump_printf(d, "restrict ");
1057 static void btf_dump_emit_name(const struct btf_dump *d,
1058 const char *name, bool last_was_ptr)
1060 bool separate = name[0] && !last_was_ptr;
1062 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1065 static void btf_dump_emit_type_chain(struct btf_dump *d,
1066 struct id_stack *decls,
1067 const char *fname, int lvl)
1070 * last_was_ptr is used to determine if we need to separate pointer
1071 * asterisk (*) from previous part of type signature with space, so
1072 * that we get `int ***`, instead of `int * * *`. We default to true
1073 * for cases where we have single pointer in a chain. E.g., in ptr ->
1074 * func_proto case. func_proto will start a new emit_type_chain call
1075 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1076 * don't want to prepend space for that last pointer.
1078 bool last_was_ptr = true;
1079 const struct btf_type *t;
1084 while (decls->cnt) {
1085 id = decls->ids[--decls->cnt];
1087 /* VOID is a special snowflake */
1088 btf_dump_emit_mods(d, decls);
1089 btf_dump_printf(d, "void");
1090 last_was_ptr = false;
1094 t = btf__type_by_id(d->btf, id);
1099 btf_dump_emit_mods(d, decls);
1100 name = btf_name_of(d, t->name_off);
1101 btf_dump_printf(d, "%s", name);
1103 case BTF_KIND_STRUCT:
1104 case BTF_KIND_UNION:
1105 btf_dump_emit_mods(d, decls);
1106 /* inline anonymous struct/union */
1107 if (t->name_off == 0)
1108 btf_dump_emit_struct_def(d, id, t, lvl);
1110 btf_dump_emit_struct_fwd(d, id, t);
1113 btf_dump_emit_mods(d, decls);
1114 /* inline anonymous enum */
1115 if (t->name_off == 0)
1116 btf_dump_emit_enum_def(d, id, t, lvl);
1118 btf_dump_emit_enum_fwd(d, id, t);
1121 btf_dump_emit_mods(d, decls);
1122 btf_dump_emit_fwd_def(d, id, t);
1124 case BTF_KIND_TYPEDEF:
1125 btf_dump_emit_mods(d, decls);
1126 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1129 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1131 case BTF_KIND_VOLATILE:
1132 btf_dump_printf(d, " volatile");
1134 case BTF_KIND_CONST:
1135 btf_dump_printf(d, " const");
1137 case BTF_KIND_RESTRICT:
1138 btf_dump_printf(d, " restrict");
1140 case BTF_KIND_ARRAY: {
1141 const struct btf_array *a = btf_array(t);
1142 const struct btf_type *next_t;
1147 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1148 * which causes it to emit extra const/volatile
1149 * modifiers for an array, if array's element type has
1150 * const/volatile modifiers. Clang doesn't do that.
1151 * In general, it doesn't seem very meaningful to have
1152 * a const/volatile modifier for array, so we are
1153 * going to silently skip them here.
1155 while (decls->cnt) {
1156 next_id = decls->ids[decls->cnt - 1];
1157 next_t = btf__type_by_id(d->btf, next_id);
1158 if (btf_is_mod(next_t))
1164 if (decls->cnt == 0) {
1165 btf_dump_emit_name(d, fname, last_was_ptr);
1166 btf_dump_printf(d, "[%u]", a->nelems);
1170 next_t = btf__type_by_id(d->btf, next_id);
1171 multidim = btf_is_array(next_t);
1172 /* we need space if we have named non-pointer */
1173 if (fname[0] && !last_was_ptr)
1174 btf_dump_printf(d, " ");
1175 /* no parentheses for multi-dimensional array */
1177 btf_dump_printf(d, "(");
1178 btf_dump_emit_type_chain(d, decls, fname, lvl);
1180 btf_dump_printf(d, ")");
1181 btf_dump_printf(d, "[%u]", a->nelems);
1184 case BTF_KIND_FUNC_PROTO: {
1185 const struct btf_param *p = btf_params(t);
1186 __u16 vlen = btf_vlen(t);
1189 btf_dump_emit_mods(d, decls);
1191 btf_dump_printf(d, " (");
1192 btf_dump_emit_type_chain(d, decls, fname, lvl);
1193 btf_dump_printf(d, ")");
1195 btf_dump_emit_name(d, fname, last_was_ptr);
1197 btf_dump_printf(d, "(");
1199 * Clang for BPF target generates func_proto with no
1200 * args as a func_proto with a single void arg (e.g.,
1201 * `int (*f)(void)` vs just `int (*f)()`). We are
1202 * going to pretend there are no args for such case.
1204 if (vlen == 1 && p->type == 0) {
1205 btf_dump_printf(d, ")");
1209 for (i = 0; i < vlen; i++, p++) {
1211 btf_dump_printf(d, ", ");
1213 /* last arg of type void is vararg */
1214 if (i == vlen - 1 && p->type == 0) {
1215 btf_dump_printf(d, "...");
1219 name = btf_name_of(d, p->name_off);
1220 btf_dump_emit_type_decl(d, p->type, name, lvl);
1223 btf_dump_printf(d, ")");
1227 pr_warning("unexpected type in decl chain, kind:%u, id:[%u]\n",
1232 last_was_ptr = kind == BTF_KIND_PTR;
1235 btf_dump_emit_name(d, fname, last_was_ptr);
1238 /* return number of duplicates (occurrences) of a given name */
1239 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1240 const char *orig_name)
1244 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1246 hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1251 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1252 struct hashmap *name_map)
1254 struct btf_dump_type_aux_state *s = &d->type_states[id];
1255 const struct btf_type *t = btf__type_by_id(d->btf, id);
1256 const char *orig_name = btf_name_of(d, t->name_off);
1257 const char **cached_name = &d->cached_names[id];
1260 if (t->name_off == 0)
1263 if (s->name_resolved)
1264 return *cached_name ? *cached_name : orig_name;
1266 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1268 const size_t max_len = 256;
1269 char new_name[max_len];
1271 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1272 *cached_name = strdup(new_name);
1275 s->name_resolved = 1;
1276 return *cached_name ? *cached_name : orig_name;
1279 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1281 return btf_dump_resolve_name(d, id, d->type_names);
1284 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1286 return btf_dump_resolve_name(d, id, d->ident_names);