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 #define min(x, y) ((x) < (y) ? (x) : (y))
22 #define max(x, y) ((x) < (y) ? (y) : (x))
24 static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
25 static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
27 static const char *pfx(int lvl)
29 return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
32 enum btf_dump_type_order_state {
38 enum btf_dump_type_emit_state {
44 /* per-type auxiliary state */
45 struct btf_dump_type_aux_state {
46 /* topological sorting state */
47 enum btf_dump_type_order_state order_state: 2;
48 /* emitting state used to determine the need for forward declaration */
49 enum btf_dump_type_emit_state emit_state: 2;
50 /* whether forward declaration was already emitted */
52 /* whether unique non-duplicate name was already assigned */
53 __u8 name_resolved: 1;
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;
62 /* per-type auxiliary state */
63 struct btf_dump_type_aux_state *type_states;
64 /* per-type optional cached unique name, must be freed, if present */
65 const char **cached_names;
67 /* topo-sorted list of dependent type definitions */
73 * stack of type declarations (e.g., chain of modifiers, arrays,
80 /* maps struct/union/enum name to a number of name occurrences */
81 struct hashmap *type_names;
83 * maps typedef identifiers and enum value names to a number of such
86 struct hashmap *ident_names;
89 static size_t str_hash_fn(const void *key, void *ctx)
101 static bool str_equal_fn(const void *a, const void *b, void *ctx)
103 return strcmp(a, b) == 0;
106 static __u16 btf_kind_of(const struct btf_type *t)
108 return BTF_INFO_KIND(t->info);
111 static __u16 btf_vlen_of(const struct btf_type *t)
113 return BTF_INFO_VLEN(t->info);
116 static bool btf_kflag_of(const struct btf_type *t)
118 return BTF_INFO_KFLAG(t->info);
121 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
123 return btf__name_by_offset(d->btf, name_off);
126 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
131 d->printf_fn(d->opts.ctx, fmt, args);
135 struct btf_dump *btf_dump__new(const struct btf *btf,
136 const struct btf_ext *btf_ext,
137 const struct btf_dump_opts *opts,
138 btf_dump_printf_fn_t printf_fn)
143 d = calloc(1, sizeof(struct btf_dump));
145 return ERR_PTR(-ENOMEM);
148 d->btf_ext = btf_ext;
149 d->printf_fn = printf_fn;
150 d->opts.ctx = opts ? opts->ctx : NULL;
152 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
153 if (IS_ERR(d->type_names)) {
154 err = PTR_ERR(d->type_names);
155 d->type_names = NULL;
159 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
160 if (IS_ERR(d->ident_names)) {
161 err = PTR_ERR(d->ident_names);
162 d->ident_names = NULL;
170 void btf_dump__free(struct btf_dump *d)
177 free(d->type_states);
178 if (d->cached_names) {
179 /* any set cached name is owned by us and should be freed */
180 for (i = 0, cnt = btf__get_nr_types(d->btf); i <= cnt; i++) {
181 if (d->cached_names[i])
182 free((void *)d->cached_names[i]);
185 free(d->cached_names);
188 hashmap__free(d->type_names);
189 hashmap__free(d->ident_names);
194 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
195 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
198 * Dump BTF type in a compilable C syntax, including all the necessary
199 * dependent types, necessary for compilation. If some of the dependent types
200 * were already emitted as part of previous btf_dump__dump_type() invocation
201 * for another type, they won't be emitted again. This API allows callers to
202 * filter out BTF types according to user-defined criterias and emitted only
203 * minimal subset of types, necessary to compile everything. Full struct/union
204 * definitions will still be emitted, even if the only usage is through
205 * pointer and could be satisfied with just a forward declaration.
207 * Dumping is done in two high-level passes:
208 * 1. Topologically sort type definitions to satisfy C rules of compilation.
209 * 2. Emit type definitions in C syntax.
211 * Returns 0 on success; <0, otherwise.
213 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
217 if (id > btf__get_nr_types(d->btf))
220 /* type states are lazily allocated, as they might not be needed */
221 if (!d->type_states) {
222 d->type_states = calloc(1 + btf__get_nr_types(d->btf),
223 sizeof(d->type_states[0]));
226 d->cached_names = calloc(1 + btf__get_nr_types(d->btf),
227 sizeof(d->cached_names[0]));
228 if (!d->cached_names)
231 /* VOID is special */
232 d->type_states[0].order_state = ORDERED;
233 d->type_states[0].emit_state = EMITTED;
236 d->emit_queue_cnt = 0;
237 err = btf_dump_order_type(d, id, false);
241 for (i = 0; i < d->emit_queue_cnt; i++)
242 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
247 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
252 if (d->emit_queue_cnt >= d->emit_queue_cap) {
253 new_cap = max(16, d->emit_queue_cap * 3 / 2);
254 new_queue = realloc(d->emit_queue,
255 new_cap * sizeof(new_queue[0]));
258 d->emit_queue = new_queue;
259 d->emit_queue_cap = new_cap;
262 d->emit_queue[d->emit_queue_cnt++] = id;
267 * Determine order of emitting dependent types and specified type to satisfy
268 * C compilation rules. This is done through topological sorting with an
269 * additional complication which comes from C rules. The main idea for C is
270 * that if some type is "embedded" into a struct/union, it's size needs to be
271 * known at the time of definition of containing type. E.g., for:
274 * struct B { struct A x; }
276 * struct A *HAS* to be defined before struct B, because it's "embedded",
277 * i.e., it is part of struct B layout. But in the following case:
280 * struct B { struct A *x; }
283 * it's enough to just have a forward declaration of struct A at the time of
284 * struct B definition, as struct B has a pointer to struct A, so the size of
285 * field x is known without knowing struct A size: it's sizeof(void *).
287 * Unfortunately, there are some trickier cases we need to handle, e.g.:
289 * struct A {}; // if this was forward-declaration: compilation error
291 * struct { // anonymous struct
296 * In this case, struct B's field x is a pointer, so it's size is known
297 * regardless of the size of (anonymous) struct it points to. But because this
298 * struct is anonymous and thus defined inline inside struct B, *and* it
299 * embeds struct A, compiler requires full definition of struct A to be known
300 * before struct B can be defined. This creates a transitive dependency
301 * between struct A and struct B. If struct A was forward-declared before
302 * struct B definition and fully defined after struct B definition, that would
303 * trigger compilation error.
305 * All this means that while we are doing topological sorting on BTF type
306 * graph, we need to determine relationships between different types (graph
308 * - weak link (relationship) between X and Y, if Y *CAN* be
309 * forward-declared at the point of X definition;
310 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
312 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
313 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
314 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
315 * Weak/strong relationship is determined recursively during DFS traversal and
316 * is returned as a result from btf_dump_order_type().
318 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
319 * but it is not guaranteeing that no extraneous forward declarations will be
322 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
323 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
324 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
325 * entire graph path, so depending where from one came to that BTF type, it
326 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
327 * once they are processed, there is no need to do it again, so they are
328 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
329 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
330 * in any case, once those are processed, no need to do it again, as the
331 * result won't change.
334 * - 1, if type is part of strong link (so there is strong topological
335 * ordering requirements);
336 * - 0, if type is part of weak link (so can be satisfied through forward
338 * - <0, on error (e.g., unsatisfiable type loop detected).
340 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
343 * Order state is used to detect strong link cycles, but only for BTF
344 * kinds that are or could be an independent definition (i.e.,
345 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
346 * func_protos, modifiers are just means to get to these definitions.
347 * Int/void don't need definitions, they are assumed to be always
348 * properly defined. We also ignore datasec, var, and funcs for now.
349 * So for all non-defining kinds, we never even set ordering state,
350 * for defining kinds we set ORDERING and subsequently ORDERED if it
351 * forms a strong link.
353 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
354 const struct btf_type *t;
358 /* return true, letting typedefs know that it's ok to be emitted */
359 if (tstate->order_state == ORDERED)
362 t = btf__type_by_id(d->btf, id);
363 kind = btf_kind_of(t);
365 if (tstate->order_state == ORDERING) {
366 /* type loop, but resolvable through fwd declaration */
367 if ((kind == BTF_KIND_STRUCT || kind == BTF_KIND_UNION) &&
368 through_ptr && t->name_off != 0)
370 pr_warning("unsatisfiable type cycle, id:[%u]\n", id);
376 tstate->order_state = ORDERED;
380 err = btf_dump_order_type(d, t->type, true);
381 tstate->order_state = ORDERED;
384 case BTF_KIND_ARRAY: {
385 const struct btf_array *a = (void *)(t + 1);
387 return btf_dump_order_type(d, a->type, through_ptr);
389 case BTF_KIND_STRUCT:
390 case BTF_KIND_UNION: {
391 const struct btf_member *m = (void *)(t + 1);
393 * struct/union is part of strong link, only if it's embedded
394 * (so no ptr in a path) or it's anonymous (so has to be
395 * defined inline, even if declared through ptr)
397 if (through_ptr && t->name_off != 0)
400 tstate->order_state = ORDERING;
402 vlen = btf_vlen_of(t);
403 for (i = 0; i < vlen; i++, m++) {
404 err = btf_dump_order_type(d, m->type, false);
409 if (t->name_off != 0) {
410 err = btf_dump_add_emit_queue_id(d, id);
415 tstate->order_state = ORDERED;
420 if (t->name_off != 0) {
421 err = btf_dump_add_emit_queue_id(d, id);
425 tstate->order_state = ORDERED;
428 case BTF_KIND_TYPEDEF: {
431 is_strong = btf_dump_order_type(d, t->type, through_ptr);
435 /* typedef is similar to struct/union w.r.t. fwd-decls */
436 if (through_ptr && !is_strong)
439 /* typedef is always a named definition */
440 err = btf_dump_add_emit_queue_id(d, id);
444 d->type_states[id].order_state = ORDERED;
447 case BTF_KIND_VOLATILE:
449 case BTF_KIND_RESTRICT:
450 return btf_dump_order_type(d, t->type, through_ptr);
452 case BTF_KIND_FUNC_PROTO: {
453 const struct btf_param *p = (void *)(t + 1);
456 err = btf_dump_order_type(d, t->type, through_ptr);
461 vlen = btf_vlen_of(t);
462 for (i = 0; i < vlen; i++, p++) {
463 err = btf_dump_order_type(d, p->type, through_ptr);
473 case BTF_KIND_DATASEC:
474 d->type_states[id].order_state = ORDERED;
482 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
483 const struct btf_type *t);
484 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
485 const struct btf_type *t, int lvl);
487 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
488 const struct btf_type *t);
489 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
490 const struct btf_type *t, int lvl);
492 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
493 const struct btf_type *t);
495 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
496 const struct btf_type *t, int lvl);
498 /* a local view into a shared stack */
504 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
505 const char *fname, int lvl);
506 static void btf_dump_emit_type_chain(struct btf_dump *d,
507 struct id_stack *decl_stack,
508 const char *fname, int lvl);
510 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
511 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
512 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
513 const char *orig_name);
515 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
517 const struct btf_type *t = btf__type_by_id(d->btf, id);
519 /* __builtin_va_list is a compiler built-in, which causes compilation
520 * errors, when compiling w/ different compiler, then used to compile
521 * original code (e.g., GCC to compile kernel, Clang to use generated
522 * C header from BTF). As it is built-in, it should be already defined
523 * properly internally in compiler.
525 if (t->name_off == 0)
527 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
531 * Emit C-syntax definitions of types from chains of BTF types.
533 * High-level handling of determining necessary forward declarations are handled
534 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
535 * declarations/definitions in C syntax are handled by a combo of
536 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
537 * corresponding btf_dump_emit_*_{def,fwd}() functions.
539 * We also keep track of "containing struct/union type ID" to determine when
540 * we reference it from inside and thus can avoid emitting unnecessary forward
543 * This algorithm is designed in such a way, that even if some error occurs
544 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
545 * that doesn't comply to C rules completely), algorithm will try to proceed
546 * and produce as much meaningful output as possible.
548 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
550 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
551 bool top_level_def = cont_id == 0;
552 const struct btf_type *t;
555 if (tstate->emit_state == EMITTED)
558 t = btf__type_by_id(d->btf, id);
559 kind = btf_kind_of(t);
561 if (top_level_def && t->name_off == 0) {
562 pr_warning("unexpected nameless definition, id:[%u]\n", id);
566 if (tstate->emit_state == EMITTING) {
567 if (tstate->fwd_emitted)
571 case BTF_KIND_STRUCT:
574 * if we are referencing a struct/union that we are
575 * part of - then no need for fwd declaration
579 if (t->name_off == 0) {
580 pr_warning("anonymous struct/union loop, id:[%u]\n",
584 btf_dump_emit_struct_fwd(d, id, t);
585 btf_dump_printf(d, ";\n\n");
586 tstate->fwd_emitted = 1;
588 case BTF_KIND_TYPEDEF:
590 * for typedef fwd_emitted means typedef definition
591 * was emitted, but it can be used only for "weak"
592 * references through pointer only, not for embedding
594 if (!btf_dump_is_blacklisted(d, id)) {
595 btf_dump_emit_typedef_def(d, id, t, 0);
596 btf_dump_printf(d, ";\n\n");
598 tstate->fwd_emitted = 1;
609 tstate->emit_state = EMITTED;
613 btf_dump_emit_enum_def(d, id, t, 0);
614 btf_dump_printf(d, ";\n\n");
616 tstate->emit_state = EMITTED;
619 case BTF_KIND_VOLATILE:
621 case BTF_KIND_RESTRICT:
622 btf_dump_emit_type(d, t->type, cont_id);
624 case BTF_KIND_ARRAY: {
625 const struct btf_array *a = (void *)(t + 1);
627 btf_dump_emit_type(d, a->type, cont_id);
631 btf_dump_emit_fwd_def(d, id, t);
632 btf_dump_printf(d, ";\n\n");
633 tstate->emit_state = EMITTED;
635 case BTF_KIND_TYPEDEF:
636 tstate->emit_state = EMITTING;
637 btf_dump_emit_type(d, t->type, id);
639 * typedef can server as both definition and forward
640 * declaration; at this stage someone depends on
641 * typedef as a forward declaration (refers to it
642 * through pointer), so unless we already did it,
643 * emit typedef as a forward declaration
645 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
646 btf_dump_emit_typedef_def(d, id, t, 0);
647 btf_dump_printf(d, ";\n\n");
649 tstate->emit_state = EMITTED;
651 case BTF_KIND_STRUCT:
653 tstate->emit_state = EMITTING;
654 /* if it's a top-level struct/union definition or struct/union
655 * is anonymous, then in C we'll be emitting all fields and
656 * their types (as opposed to just `struct X`), so we need to
657 * make sure that all types, referenced from struct/union
658 * members have necessary forward-declarations, where
661 if (top_level_def || t->name_off == 0) {
662 const struct btf_member *m = (void *)(t + 1);
663 __u16 vlen = btf_vlen_of(t);
666 new_cont_id = t->name_off == 0 ? cont_id : id;
667 for (i = 0; i < vlen; i++, m++)
668 btf_dump_emit_type(d, m->type, new_cont_id);
669 } else if (!tstate->fwd_emitted && id != cont_id) {
670 btf_dump_emit_struct_fwd(d, id, t);
671 btf_dump_printf(d, ";\n\n");
672 tstate->fwd_emitted = 1;
676 btf_dump_emit_struct_def(d, id, t, 0);
677 btf_dump_printf(d, ";\n\n");
678 tstate->emit_state = EMITTED;
680 tstate->emit_state = NOT_EMITTED;
683 case BTF_KIND_FUNC_PROTO: {
684 const struct btf_param *p = (void *)(t + 1);
685 __u16 vlen = btf_vlen_of(t);
688 btf_dump_emit_type(d, t->type, cont_id);
689 for (i = 0; i < vlen; i++, p++)
690 btf_dump_emit_type(d, p->type, cont_id);
699 static int btf_align_of(const struct btf *btf, __u32 id)
701 const struct btf_type *t = btf__type_by_id(btf, id);
702 __u16 kind = btf_kind_of(t);
707 return min(sizeof(void *), t->size);
709 return sizeof(void *);
710 case BTF_KIND_TYPEDEF:
711 case BTF_KIND_VOLATILE:
713 case BTF_KIND_RESTRICT:
714 return btf_align_of(btf, t->type);
715 case BTF_KIND_ARRAY: {
716 const struct btf_array *a = (void *)(t + 1);
718 return btf_align_of(btf, a->type);
720 case BTF_KIND_STRUCT:
721 case BTF_KIND_UNION: {
722 const struct btf_member *m = (void *)(t + 1);
723 __u16 vlen = btf_vlen_of(t);
726 for (i = 0; i < vlen; i++, m++)
727 align = max(align, btf_align_of(btf, m->type));
732 pr_warning("unsupported BTF_KIND:%u\n", btf_kind_of(t));
737 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
738 const struct btf_type *t)
740 const struct btf_member *m;
741 int align, i, bit_sz;
745 align = btf_align_of(btf, id);
746 /* size of a non-packed struct has to be a multiple of its alignment*/
751 kflag = btf_kflag_of(t);
752 vlen = btf_vlen_of(t);
753 /* all non-bitfield fields have to be naturally aligned */
754 for (i = 0; i < vlen; i++, m++) {
755 align = btf_align_of(btf, m->type);
756 bit_sz = kflag ? BTF_MEMBER_BITFIELD_SIZE(m->offset) : 0;
757 if (bit_sz == 0 && m->offset % (8 * align) != 0)
762 * if original struct was marked as packed, but its layout is
763 * naturally aligned, we'll detect that it's not packed
768 static int chip_away_bits(int total, int at_most)
770 return total % at_most ? : at_most;
773 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
774 int cur_off, int m_off, int m_bit_sz,
777 int off_diff = m_off - cur_off;
778 int ptr_bits = sizeof(void *) * 8;
783 if (m_bit_sz == 0 && off_diff < align * 8)
784 /* natural padding will take care of a gap */
787 while (off_diff > 0) {
788 const char *pad_type;
791 if (ptr_bits > 32 && off_diff > 32) {
793 pad_bits = chip_away_bits(off_diff, ptr_bits);
794 } else if (off_diff > 16) {
796 pad_bits = chip_away_bits(off_diff, 32);
797 } else if (off_diff > 8) {
799 pad_bits = chip_away_bits(off_diff, 16);
802 pad_bits = chip_away_bits(off_diff, 8);
804 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
805 off_diff -= pad_bits;
809 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
810 const struct btf_type *t)
812 btf_dump_printf(d, "%s %s",
813 btf_kind_of(t) == BTF_KIND_STRUCT ? "struct" : "union",
814 btf_dump_type_name(d, id));
817 static void btf_dump_emit_struct_def(struct btf_dump *d,
819 const struct btf_type *t,
822 const struct btf_member *m = (void *)(t + 1);
823 bool kflag = btf_kflag_of(t), is_struct;
824 int align, i, packed, off = 0;
825 __u16 vlen = btf_vlen_of(t);
827 is_struct = btf_kind_of(t) == BTF_KIND_STRUCT;
828 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
829 align = packed ? 1 : btf_align_of(d->btf, id);
831 btf_dump_printf(d, "%s%s%s {",
832 is_struct ? "struct" : "union",
833 t->name_off ? " " : "",
834 btf_dump_type_name(d, id));
836 for (i = 0; i < vlen; i++, m++) {
840 fname = btf_name_of(d, m->name_off);
841 m_sz = kflag ? BTF_MEMBER_BITFIELD_SIZE(m->offset) : 0;
842 m_off = kflag ? BTF_MEMBER_BIT_OFFSET(m->offset) : m->offset;
843 align = packed ? 1 : btf_align_of(d->btf, m->type);
845 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
846 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
847 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
850 btf_dump_printf(d, ": %d", m_sz);
853 m_sz = max(0, btf__resolve_size(d->btf, m->type));
854 off = m_off + m_sz * 8;
856 btf_dump_printf(d, ";");
860 btf_dump_printf(d, "\n");
861 btf_dump_printf(d, "%s}", pfx(lvl));
863 btf_dump_printf(d, " __attribute__((packed))");
866 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
867 const struct btf_type *t)
869 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
872 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
873 const struct btf_type *t,
876 const struct btf_enum *v = (void *)(t+1);
877 __u16 vlen = btf_vlen_of(t);
882 btf_dump_printf(d, "enum%s%s",
883 t->name_off ? " " : "",
884 btf_dump_type_name(d, id));
887 btf_dump_printf(d, " {");
888 for (i = 0; i < vlen; i++, v++) {
889 name = btf_name_of(d, v->name_off);
890 /* enumerators share namespace with typedef idents */
891 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
893 btf_dump_printf(d, "\n%s%s___%zu = %d,",
894 pfx(lvl + 1), name, dup_cnt,
897 btf_dump_printf(d, "\n%s%s = %d,",
902 btf_dump_printf(d, "\n%s}", pfx(lvl));
906 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
907 const struct btf_type *t)
909 const char *name = btf_dump_type_name(d, id);
912 btf_dump_printf(d, "union %s", name);
914 btf_dump_printf(d, "struct %s", name);
917 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
918 const struct btf_type *t, int lvl)
920 const char *name = btf_dump_ident_name(d, id);
922 btf_dump_printf(d, "typedef ");
923 btf_dump_emit_type_decl(d, t->type, name, lvl);
926 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
931 if (d->decl_stack_cnt >= d->decl_stack_cap) {
932 new_cap = max(16, d->decl_stack_cap * 3 / 2);
933 new_stack = realloc(d->decl_stack,
934 new_cap * sizeof(new_stack[0]));
937 d->decl_stack = new_stack;
938 d->decl_stack_cap = new_cap;
941 d->decl_stack[d->decl_stack_cnt++] = id;
947 * Emit type declaration (e.g., field type declaration in a struct or argument
948 * declaration in function prototype) in correct C syntax.
950 * For most types it's trivial, but there are few quirky type declaration
951 * cases worth mentioning:
952 * - function prototypes (especially nesting of function prototypes);
954 * - const/volatile/restrict for pointers vs other types.
956 * For a good discussion of *PARSING* C syntax (as a human), see
957 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
958 * Ch.3 "Unscrambling Declarations in C".
960 * It won't help with BTF to C conversion much, though, as it's an opposite
961 * problem. So we came up with this algorithm in reverse to van der Linden's
962 * parsing algorithm. It goes from structured BTF representation of type
963 * declaration to a valid compilable C syntax.
965 * For instance, consider this C typedef:
966 * typedef const int * const * arr[10] arr_t;
967 * It will be represented in BTF with this chain of BTF types:
968 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
970 * Notice how [const] modifier always goes before type it modifies in BTF type
971 * graph, but in C syntax, const/volatile/restrict modifiers are written to
972 * the right of pointers, but to the left of other types. There are also other
973 * quirks, like function pointers, arrays of them, functions returning other
976 * We handle that by pushing all the types to a stack, until we hit "terminal"
977 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
978 * top of a stack, modifiers are handled differently. Array/function pointers
979 * have also wildly different syntax and how nesting of them are done. See
980 * code for authoritative definition.
982 * To avoid allocating new stack for each independent chain of BTF types, we
983 * share one bigger stack, with each chain working only on its own local view
984 * of a stack frame. Some care is required to "pop" stack frames after
985 * processing type declaration chain.
987 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
988 const char *fname, int lvl)
990 struct id_stack decl_stack;
991 const struct btf_type *t;
992 int err, stack_start;
995 stack_start = d->decl_stack_cnt;
997 err = btf_dump_push_decl_stack_id(d, id);
1000 * if we don't have enough memory for entire type decl
1001 * chain, restore stack, emit warning, and try to
1002 * proceed nevertheless
1004 pr_warning("not enough memory for decl stack:%d", err);
1005 d->decl_stack_cnt = stack_start;
1013 t = btf__type_by_id(d->btf, id);
1014 kind = btf_kind_of(t);
1017 case BTF_KIND_VOLATILE:
1018 case BTF_KIND_CONST:
1019 case BTF_KIND_RESTRICT:
1020 case BTF_KIND_FUNC_PROTO:
1023 case BTF_KIND_ARRAY: {
1024 const struct btf_array *a = (void *)(t + 1);
1032 case BTF_KIND_STRUCT:
1033 case BTF_KIND_UNION:
1034 case BTF_KIND_TYPEDEF:
1037 pr_warning("unexpected type in decl chain, kind:%u, id:[%u]\n",
1044 * We might be inside a chain of declarations (e.g., array of function
1045 * pointers returning anonymous (so inlined) structs, having another
1046 * array field). Each of those needs its own "stack frame" to handle
1047 * emitting of declarations. Those stack frames are non-overlapping
1048 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1049 * handle this set of nested stacks, we create a view corresponding to
1050 * our own "stack frame" and work with it as an independent stack.
1051 * We'll need to clean up after emit_type_chain() returns, though.
1053 decl_stack.ids = d->decl_stack + stack_start;
1054 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1055 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1057 * emit_type_chain() guarantees that it will pop its entire decl_stack
1058 * frame before returning. But it works with a read-only view into
1059 * decl_stack, so it doesn't actually pop anything from the
1060 * perspective of shared btf_dump->decl_stack, per se. We need to
1061 * reset decl_stack state to how it was before us to avoid it growing
1064 d->decl_stack_cnt = stack_start;
1067 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1069 const struct btf_type *t;
1072 while (decl_stack->cnt) {
1073 id = decl_stack->ids[decl_stack->cnt - 1];
1074 t = btf__type_by_id(d->btf, id);
1076 switch (btf_kind_of(t)) {
1077 case BTF_KIND_VOLATILE:
1078 btf_dump_printf(d, "volatile ");
1080 case BTF_KIND_CONST:
1081 btf_dump_printf(d, "const ");
1083 case BTF_KIND_RESTRICT:
1084 btf_dump_printf(d, "restrict ");
1093 static bool btf_is_mod_kind(const struct btf *btf, __u32 id)
1095 const struct btf_type *t = btf__type_by_id(btf, id);
1097 switch (btf_kind_of(t)) {
1098 case BTF_KIND_VOLATILE:
1099 case BTF_KIND_CONST:
1100 case BTF_KIND_RESTRICT:
1107 static void btf_dump_emit_name(const struct btf_dump *d,
1108 const char *name, bool last_was_ptr)
1110 bool separate = name[0] && !last_was_ptr;
1112 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1115 static void btf_dump_emit_type_chain(struct btf_dump *d,
1116 struct id_stack *decls,
1117 const char *fname, int lvl)
1120 * last_was_ptr is used to determine if we need to separate pointer
1121 * asterisk (*) from previous part of type signature with space, so
1122 * that we get `int ***`, instead of `int * * *`. We default to true
1123 * for cases where we have single pointer in a chain. E.g., in ptr ->
1124 * func_proto case. func_proto will start a new emit_type_chain call
1125 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1126 * don't want to prepend space for that last pointer.
1128 bool last_was_ptr = true;
1129 const struct btf_type *t;
1134 while (decls->cnt) {
1135 id = decls->ids[--decls->cnt];
1137 /* VOID is a special snowflake */
1138 btf_dump_emit_mods(d, decls);
1139 btf_dump_printf(d, "void");
1140 last_was_ptr = false;
1144 t = btf__type_by_id(d->btf, id);
1145 kind = btf_kind_of(t);
1149 btf_dump_emit_mods(d, decls);
1150 name = btf_name_of(d, t->name_off);
1151 btf_dump_printf(d, "%s", name);
1153 case BTF_KIND_STRUCT:
1154 case BTF_KIND_UNION:
1155 btf_dump_emit_mods(d, decls);
1156 /* inline anonymous struct/union */
1157 if (t->name_off == 0)
1158 btf_dump_emit_struct_def(d, id, t, lvl);
1160 btf_dump_emit_struct_fwd(d, id, t);
1163 btf_dump_emit_mods(d, decls);
1164 /* inline anonymous enum */
1165 if (t->name_off == 0)
1166 btf_dump_emit_enum_def(d, id, t, lvl);
1168 btf_dump_emit_enum_fwd(d, id, t);
1171 btf_dump_emit_mods(d, decls);
1172 btf_dump_emit_fwd_def(d, id, t);
1174 case BTF_KIND_TYPEDEF:
1175 btf_dump_emit_mods(d, decls);
1176 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1179 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1181 case BTF_KIND_VOLATILE:
1182 btf_dump_printf(d, " volatile");
1184 case BTF_KIND_CONST:
1185 btf_dump_printf(d, " const");
1187 case BTF_KIND_RESTRICT:
1188 btf_dump_printf(d, " restrict");
1190 case BTF_KIND_ARRAY: {
1191 const struct btf_array *a = (void *)(t + 1);
1192 const struct btf_type *next_t;
1197 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1198 * which causes it to emit extra const/volatile
1199 * modifiers for an array, if array's element type has
1200 * const/volatile modifiers. Clang doesn't do that.
1201 * In general, it doesn't seem very meaningful to have
1202 * a const/volatile modifier for array, so we are
1203 * going to silently skip them here.
1205 while (decls->cnt) {
1206 next_id = decls->ids[decls->cnt - 1];
1207 if (btf_is_mod_kind(d->btf, next_id))
1213 if (decls->cnt == 0) {
1214 btf_dump_emit_name(d, fname, last_was_ptr);
1215 btf_dump_printf(d, "[%u]", a->nelems);
1219 next_t = btf__type_by_id(d->btf, next_id);
1220 multidim = btf_kind_of(next_t) == BTF_KIND_ARRAY;
1221 /* we need space if we have named non-pointer */
1222 if (fname[0] && !last_was_ptr)
1223 btf_dump_printf(d, " ");
1224 /* no parentheses for multi-dimensional array */
1226 btf_dump_printf(d, "(");
1227 btf_dump_emit_type_chain(d, decls, fname, lvl);
1229 btf_dump_printf(d, ")");
1230 btf_dump_printf(d, "[%u]", a->nelems);
1233 case BTF_KIND_FUNC_PROTO: {
1234 const struct btf_param *p = (void *)(t + 1);
1235 __u16 vlen = btf_vlen_of(t);
1238 btf_dump_emit_mods(d, decls);
1240 btf_dump_printf(d, " (");
1241 btf_dump_emit_type_chain(d, decls, fname, lvl);
1242 btf_dump_printf(d, ")");
1244 btf_dump_emit_name(d, fname, last_was_ptr);
1246 btf_dump_printf(d, "(");
1248 * Clang for BPF target generates func_proto with no
1249 * args as a func_proto with a single void arg (e.g.,
1250 * `int (*f)(void)` vs just `int (*f)()`). We are
1251 * going to pretend there are no args for such case.
1253 if (vlen == 1 && p->type == 0) {
1254 btf_dump_printf(d, ")");
1258 for (i = 0; i < vlen; i++, p++) {
1260 btf_dump_printf(d, ", ");
1262 /* last arg of type void is vararg */
1263 if (i == vlen - 1 && p->type == 0) {
1264 btf_dump_printf(d, "...");
1268 name = btf_name_of(d, p->name_off);
1269 btf_dump_emit_type_decl(d, p->type, name, lvl);
1272 btf_dump_printf(d, ")");
1276 pr_warning("unexpected type in decl chain, kind:%u, id:[%u]\n",
1281 last_was_ptr = kind == BTF_KIND_PTR;
1284 btf_dump_emit_name(d, fname, last_was_ptr);
1287 /* return number of duplicates (occurrences) of a given name */
1288 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1289 const char *orig_name)
1293 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1295 hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1300 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1301 struct hashmap *name_map)
1303 struct btf_dump_type_aux_state *s = &d->type_states[id];
1304 const struct btf_type *t = btf__type_by_id(d->btf, id);
1305 const char *orig_name = btf_name_of(d, t->name_off);
1306 const char **cached_name = &d->cached_names[id];
1309 if (t->name_off == 0)
1312 if (s->name_resolved)
1313 return *cached_name ? *cached_name : orig_name;
1315 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1317 const size_t max_len = 256;
1318 char new_name[max_len];
1320 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1321 *cached_name = strdup(new_name);
1324 s->name_resolved = 1;
1325 return *cached_name ? *cached_name : orig_name;
1328 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1330 return btf_dump_resolve_name(d, id, d->type_names);
1333 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1335 return btf_dump_resolve_name(d, id, d->ident_names);