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 /* make sure libbpf doesn't use kernel-only integer typedefs */
22 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
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;
54 /* whether type is referenced from any other type */
59 const struct btf *btf;
60 const struct btf_ext *btf_ext;
61 btf_dump_printf_fn_t printf_fn;
62 struct btf_dump_opts opts;
65 /* per-type auxiliary state */
66 struct btf_dump_type_aux_state *type_states;
67 /* per-type optional cached unique name, must be freed, if present */
68 const char **cached_names;
70 /* topo-sorted list of dependent type definitions */
76 * stack of type declarations (e.g., chain of modifiers, arrays,
83 /* maps struct/union/enum name to a number of name occurrences */
84 struct hashmap *type_names;
86 * maps typedef identifiers and enum value names to a number of such
89 struct hashmap *ident_names;
92 static size_t str_hash_fn(const void *key, void *ctx)
104 static bool str_equal_fn(const void *a, const void *b, void *ctx)
106 return strcmp(a, b) == 0;
109 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
111 return btf__name_by_offset(d->btf, name_off);
114 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
119 d->printf_fn(d->opts.ctx, fmt, args);
123 static int btf_dump_mark_referenced(struct btf_dump *d);
125 struct btf_dump *btf_dump__new(const struct btf *btf,
126 const struct btf_ext *btf_ext,
127 const struct btf_dump_opts *opts,
128 btf_dump_printf_fn_t printf_fn)
133 d = calloc(1, sizeof(struct btf_dump));
135 return ERR_PTR(-ENOMEM);
138 d->btf_ext = btf_ext;
139 d->printf_fn = printf_fn;
140 d->opts.ctx = opts ? opts->ctx : NULL;
142 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
143 if (IS_ERR(d->type_names)) {
144 err = PTR_ERR(d->type_names);
145 d->type_names = NULL;
148 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
149 if (IS_ERR(d->ident_names)) {
150 err = PTR_ERR(d->ident_names);
151 d->ident_names = NULL;
154 d->type_states = calloc(1 + btf__get_nr_types(d->btf),
155 sizeof(d->type_states[0]));
156 if (!d->type_states) {
160 d->cached_names = calloc(1 + btf__get_nr_types(d->btf),
161 sizeof(d->cached_names[0]));
162 if (!d->cached_names) {
167 /* VOID is special */
168 d->type_states[0].order_state = ORDERED;
169 d->type_states[0].emit_state = EMITTED;
171 /* eagerly determine referenced types for anon enums */
172 err = btf_dump_mark_referenced(d);
182 void btf_dump__free(struct btf_dump *d)
186 if (IS_ERR_OR_NULL(d))
189 free(d->type_states);
190 if (d->cached_names) {
191 /* any set cached name is owned by us and should be freed */
192 for (i = 0, cnt = btf__get_nr_types(d->btf); i <= cnt; i++) {
193 if (d->cached_names[i])
194 free((void *)d->cached_names[i]);
197 free(d->cached_names);
200 hashmap__free(d->type_names);
201 hashmap__free(d->ident_names);
206 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
207 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
210 * Dump BTF type in a compilable C syntax, including all the necessary
211 * dependent types, necessary for compilation. If some of the dependent types
212 * were already emitted as part of previous btf_dump__dump_type() invocation
213 * for another type, they won't be emitted again. This API allows callers to
214 * filter out BTF types according to user-defined criterias and emitted only
215 * minimal subset of types, necessary to compile everything. Full struct/union
216 * definitions will still be emitted, even if the only usage is through
217 * pointer and could be satisfied with just a forward declaration.
219 * Dumping is done in two high-level passes:
220 * 1. Topologically sort type definitions to satisfy C rules of compilation.
221 * 2. Emit type definitions in C syntax.
223 * Returns 0 on success; <0, otherwise.
225 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
229 if (id > btf__get_nr_types(d->btf))
232 d->emit_queue_cnt = 0;
233 err = btf_dump_order_type(d, id, false);
237 for (i = 0; i < d->emit_queue_cnt; i++)
238 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
244 * Mark all types that are referenced from any other type. This is used to
245 * determine top-level anonymous enums that need to be emitted as an
246 * independent type declarations.
247 * Anonymous enums come in two flavors: either embedded in a struct's field
248 * definition, in which case they have to be declared inline as part of field
249 * type declaration; or as a top-level anonymous enum, typically used for
250 * declaring global constants. It's impossible to distinguish between two
251 * without knowning whether given enum type was referenced from other type:
252 * top-level anonymous enum won't be referenced by anything, while embedded
255 static int btf_dump_mark_referenced(struct btf_dump *d)
257 int i, j, n = btf__get_nr_types(d->btf);
258 const struct btf_type *t;
261 for (i = 1; i <= n; i++) {
262 t = btf__type_by_id(d->btf, i);
265 switch (btf_kind(t)) {
271 case BTF_KIND_VOLATILE:
273 case BTF_KIND_RESTRICT:
275 case BTF_KIND_TYPEDEF:
278 d->type_states[t->type].referenced = 1;
281 case BTF_KIND_ARRAY: {
282 const struct btf_array *a = btf_array(t);
284 d->type_states[a->index_type].referenced = 1;
285 d->type_states[a->type].referenced = 1;
288 case BTF_KIND_STRUCT:
289 case BTF_KIND_UNION: {
290 const struct btf_member *m = btf_members(t);
292 for (j = 0; j < vlen; j++, m++)
293 d->type_states[m->type].referenced = 1;
296 case BTF_KIND_FUNC_PROTO: {
297 const struct btf_param *p = btf_params(t);
299 for (j = 0; j < vlen; j++, p++)
300 d->type_states[p->type].referenced = 1;
303 case BTF_KIND_DATASEC: {
304 const struct btf_var_secinfo *v = btf_var_secinfos(t);
306 for (j = 0; j < vlen; j++, v++)
307 d->type_states[v->type].referenced = 1;
316 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
321 if (d->emit_queue_cnt >= d->emit_queue_cap) {
322 new_cap = max(16, d->emit_queue_cap * 3 / 2);
323 new_queue = realloc(d->emit_queue,
324 new_cap * sizeof(new_queue[0]));
327 d->emit_queue = new_queue;
328 d->emit_queue_cap = new_cap;
331 d->emit_queue[d->emit_queue_cnt++] = id;
336 * Determine order of emitting dependent types and specified type to satisfy
337 * C compilation rules. This is done through topological sorting with an
338 * additional complication which comes from C rules. The main idea for C is
339 * that if some type is "embedded" into a struct/union, it's size needs to be
340 * known at the time of definition of containing type. E.g., for:
343 * struct B { struct A x; }
345 * struct A *HAS* to be defined before struct B, because it's "embedded",
346 * i.e., it is part of struct B layout. But in the following case:
349 * struct B { struct A *x; }
352 * it's enough to just have a forward declaration of struct A at the time of
353 * struct B definition, as struct B has a pointer to struct A, so the size of
354 * field x is known without knowing struct A size: it's sizeof(void *).
356 * Unfortunately, there are some trickier cases we need to handle, e.g.:
358 * struct A {}; // if this was forward-declaration: compilation error
360 * struct { // anonymous struct
365 * In this case, struct B's field x is a pointer, so it's size is known
366 * regardless of the size of (anonymous) struct it points to. But because this
367 * struct is anonymous and thus defined inline inside struct B, *and* it
368 * embeds struct A, compiler requires full definition of struct A to be known
369 * before struct B can be defined. This creates a transitive dependency
370 * between struct A and struct B. If struct A was forward-declared before
371 * struct B definition and fully defined after struct B definition, that would
372 * trigger compilation error.
374 * All this means that while we are doing topological sorting on BTF type
375 * graph, we need to determine relationships between different types (graph
377 * - weak link (relationship) between X and Y, if Y *CAN* be
378 * forward-declared at the point of X definition;
379 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
381 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
382 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
383 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
384 * Weak/strong relationship is determined recursively during DFS traversal and
385 * is returned as a result from btf_dump_order_type().
387 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
388 * but it is not guaranteeing that no extraneous forward declarations will be
391 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
392 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
393 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
394 * entire graph path, so depending where from one came to that BTF type, it
395 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
396 * once they are processed, there is no need to do it again, so they are
397 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
398 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
399 * in any case, once those are processed, no need to do it again, as the
400 * result won't change.
403 * - 1, if type is part of strong link (so there is strong topological
404 * ordering requirements);
405 * - 0, if type is part of weak link (so can be satisfied through forward
407 * - <0, on error (e.g., unsatisfiable type loop detected).
409 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
412 * Order state is used to detect strong link cycles, but only for BTF
413 * kinds that are or could be an independent definition (i.e.,
414 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
415 * func_protos, modifiers are just means to get to these definitions.
416 * Int/void don't need definitions, they are assumed to be always
417 * properly defined. We also ignore datasec, var, and funcs for now.
418 * So for all non-defining kinds, we never even set ordering state,
419 * for defining kinds we set ORDERING and subsequently ORDERED if it
420 * forms a strong link.
422 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
423 const struct btf_type *t;
427 /* return true, letting typedefs know that it's ok to be emitted */
428 if (tstate->order_state == ORDERED)
431 t = btf__type_by_id(d->btf, id);
433 if (tstate->order_state == ORDERING) {
434 /* type loop, but resolvable through fwd declaration */
435 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
437 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
441 switch (btf_kind(t)) {
443 tstate->order_state = ORDERED;
447 err = btf_dump_order_type(d, t->type, true);
448 tstate->order_state = ORDERED;
452 return btf_dump_order_type(d, btf_array(t)->type, through_ptr);
454 case BTF_KIND_STRUCT:
455 case BTF_KIND_UNION: {
456 const struct btf_member *m = btf_members(t);
458 * struct/union is part of strong link, only if it's embedded
459 * (so no ptr in a path) or it's anonymous (so has to be
460 * defined inline, even if declared through ptr)
462 if (through_ptr && t->name_off != 0)
465 tstate->order_state = ORDERING;
468 for (i = 0; i < vlen; i++, m++) {
469 err = btf_dump_order_type(d, m->type, false);
474 if (t->name_off != 0) {
475 err = btf_dump_add_emit_queue_id(d, id);
480 tstate->order_state = ORDERED;
486 * non-anonymous or non-referenced enums are top-level
487 * declarations and should be emitted. Same logic can be
488 * applied to FWDs, it won't hurt anyways.
490 if (t->name_off != 0 || !tstate->referenced) {
491 err = btf_dump_add_emit_queue_id(d, id);
495 tstate->order_state = ORDERED;
498 case BTF_KIND_TYPEDEF: {
501 is_strong = btf_dump_order_type(d, t->type, through_ptr);
505 /* typedef is similar to struct/union w.r.t. fwd-decls */
506 if (through_ptr && !is_strong)
509 /* typedef is always a named definition */
510 err = btf_dump_add_emit_queue_id(d, id);
514 d->type_states[id].order_state = ORDERED;
517 case BTF_KIND_VOLATILE:
519 case BTF_KIND_RESTRICT:
520 return btf_dump_order_type(d, t->type, through_ptr);
522 case BTF_KIND_FUNC_PROTO: {
523 const struct btf_param *p = btf_params(t);
526 err = btf_dump_order_type(d, t->type, through_ptr);
532 for (i = 0; i < vlen; i++, p++) {
533 err = btf_dump_order_type(d, p->type, through_ptr);
543 case BTF_KIND_DATASEC:
544 d->type_states[id].order_state = ORDERED;
552 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
553 const struct btf_type *t);
554 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
555 const struct btf_type *t, int lvl);
557 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
558 const struct btf_type *t);
559 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
560 const struct btf_type *t, int lvl);
562 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
563 const struct btf_type *t);
565 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
566 const struct btf_type *t, int lvl);
568 /* a local view into a shared stack */
574 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
575 const char *fname, int lvl);
576 static void btf_dump_emit_type_chain(struct btf_dump *d,
577 struct id_stack *decl_stack,
578 const char *fname, int lvl);
580 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
581 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
582 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
583 const char *orig_name);
585 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
587 const struct btf_type *t = btf__type_by_id(d->btf, id);
589 /* __builtin_va_list is a compiler built-in, which causes compilation
590 * errors, when compiling w/ different compiler, then used to compile
591 * original code (e.g., GCC to compile kernel, Clang to use generated
592 * C header from BTF). As it is built-in, it should be already defined
593 * properly internally in compiler.
595 if (t->name_off == 0)
597 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
601 * Emit C-syntax definitions of types from chains of BTF types.
603 * High-level handling of determining necessary forward declarations are handled
604 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
605 * declarations/definitions in C syntax are handled by a combo of
606 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
607 * corresponding btf_dump_emit_*_{def,fwd}() functions.
609 * We also keep track of "containing struct/union type ID" to determine when
610 * we reference it from inside and thus can avoid emitting unnecessary forward
613 * This algorithm is designed in such a way, that even if some error occurs
614 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
615 * that doesn't comply to C rules completely), algorithm will try to proceed
616 * and produce as much meaningful output as possible.
618 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
620 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
621 bool top_level_def = cont_id == 0;
622 const struct btf_type *t;
625 if (tstate->emit_state == EMITTED)
628 t = btf__type_by_id(d->btf, id);
631 if (tstate->emit_state == EMITTING) {
632 if (tstate->fwd_emitted)
636 case BTF_KIND_STRUCT:
639 * if we are referencing a struct/union that we are
640 * part of - then no need for fwd declaration
644 if (t->name_off == 0) {
645 pr_warn("anonymous struct/union loop, id:[%u]\n",
649 btf_dump_emit_struct_fwd(d, id, t);
650 btf_dump_printf(d, ";\n\n");
651 tstate->fwd_emitted = 1;
653 case BTF_KIND_TYPEDEF:
655 * for typedef fwd_emitted means typedef definition
656 * was emitted, but it can be used only for "weak"
657 * references through pointer only, not for embedding
659 if (!btf_dump_is_blacklisted(d, id)) {
660 btf_dump_emit_typedef_def(d, id, t, 0);
661 btf_dump_printf(d, ";\n\n");
663 tstate->fwd_emitted = 1;
674 tstate->emit_state = EMITTED;
678 btf_dump_emit_enum_def(d, id, t, 0);
679 btf_dump_printf(d, ";\n\n");
681 tstate->emit_state = EMITTED;
684 case BTF_KIND_VOLATILE:
686 case BTF_KIND_RESTRICT:
687 btf_dump_emit_type(d, t->type, cont_id);
690 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
693 btf_dump_emit_fwd_def(d, id, t);
694 btf_dump_printf(d, ";\n\n");
695 tstate->emit_state = EMITTED;
697 case BTF_KIND_TYPEDEF:
698 tstate->emit_state = EMITTING;
699 btf_dump_emit_type(d, t->type, id);
701 * typedef can server as both definition and forward
702 * declaration; at this stage someone depends on
703 * typedef as a forward declaration (refers to it
704 * through pointer), so unless we already did it,
705 * emit typedef as a forward declaration
707 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
708 btf_dump_emit_typedef_def(d, id, t, 0);
709 btf_dump_printf(d, ";\n\n");
711 tstate->emit_state = EMITTED;
713 case BTF_KIND_STRUCT:
715 tstate->emit_state = EMITTING;
716 /* if it's a top-level struct/union definition or struct/union
717 * is anonymous, then in C we'll be emitting all fields and
718 * their types (as opposed to just `struct X`), so we need to
719 * make sure that all types, referenced from struct/union
720 * members have necessary forward-declarations, where
723 if (top_level_def || t->name_off == 0) {
724 const struct btf_member *m = btf_members(t);
725 __u16 vlen = btf_vlen(t);
728 new_cont_id = t->name_off == 0 ? cont_id : id;
729 for (i = 0; i < vlen; i++, m++)
730 btf_dump_emit_type(d, m->type, new_cont_id);
731 } else if (!tstate->fwd_emitted && id != cont_id) {
732 btf_dump_emit_struct_fwd(d, id, t);
733 btf_dump_printf(d, ";\n\n");
734 tstate->fwd_emitted = 1;
738 btf_dump_emit_struct_def(d, id, t, 0);
739 btf_dump_printf(d, ";\n\n");
740 tstate->emit_state = EMITTED;
742 tstate->emit_state = NOT_EMITTED;
745 case BTF_KIND_FUNC_PROTO: {
746 const struct btf_param *p = btf_params(t);
747 __u16 vlen = btf_vlen(t);
750 btf_dump_emit_type(d, t->type, cont_id);
751 for (i = 0; i < vlen; i++, p++)
752 btf_dump_emit_type(d, p->type, cont_id);
761 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
762 const struct btf_type *t)
764 const struct btf_member *m;
765 int align, i, bit_sz;
768 align = btf__align_of(btf, id);
769 /* size of a non-packed struct has to be a multiple of its alignment*/
770 if (align && t->size % align)
775 /* all non-bitfield fields have to be naturally aligned */
776 for (i = 0; i < vlen; i++, m++) {
777 align = btf__align_of(btf, m->type);
778 bit_sz = btf_member_bitfield_size(t, i);
779 if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
784 * if original struct was marked as packed, but its layout is
785 * naturally aligned, we'll detect that it's not packed
790 static int chip_away_bits(int total, int at_most)
792 return total % at_most ? : at_most;
795 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
796 int cur_off, int m_off, int m_bit_sz,
799 int off_diff = m_off - cur_off;
800 int ptr_bits = sizeof(void *) * 8;
805 if (m_bit_sz == 0 && off_diff < align * 8)
806 /* natural padding will take care of a gap */
809 while (off_diff > 0) {
810 const char *pad_type;
813 if (ptr_bits > 32 && off_diff > 32) {
815 pad_bits = chip_away_bits(off_diff, ptr_bits);
816 } else if (off_diff > 16) {
818 pad_bits = chip_away_bits(off_diff, 32);
819 } else if (off_diff > 8) {
821 pad_bits = chip_away_bits(off_diff, 16);
824 pad_bits = chip_away_bits(off_diff, 8);
826 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
827 off_diff -= pad_bits;
831 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
832 const struct btf_type *t)
834 btf_dump_printf(d, "%s %s",
835 btf_is_struct(t) ? "struct" : "union",
836 btf_dump_type_name(d, id));
839 static void btf_dump_emit_struct_def(struct btf_dump *d,
841 const struct btf_type *t,
844 const struct btf_member *m = btf_members(t);
845 bool is_struct = btf_is_struct(t);
846 int align, i, packed, off = 0;
847 __u16 vlen = btf_vlen(t);
849 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
851 btf_dump_printf(d, "%s%s%s {",
852 is_struct ? "struct" : "union",
853 t->name_off ? " " : "",
854 btf_dump_type_name(d, id));
856 for (i = 0; i < vlen; i++, m++) {
860 fname = btf_name_of(d, m->name_off);
861 m_sz = btf_member_bitfield_size(t, i);
862 m_off = btf_member_bit_offset(t, i);
863 align = packed ? 1 : btf__align_of(d->btf, m->type);
865 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
866 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
867 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
870 btf_dump_printf(d, ": %d", m_sz);
873 m_sz = max(0, btf__resolve_size(d->btf, m->type));
874 off = m_off + m_sz * 8;
876 btf_dump_printf(d, ";");
879 /* pad at the end, if necessary */
881 align = packed ? 1 : btf__align_of(d->btf, id);
882 btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
887 btf_dump_printf(d, "\n");
888 btf_dump_printf(d, "%s}", pfx(lvl));
890 btf_dump_printf(d, " __attribute__((packed))");
893 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
894 const struct btf_type *t)
896 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
899 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
900 const struct btf_type *t,
903 const struct btf_enum *v = btf_enum(t);
904 __u16 vlen = btf_vlen(t);
909 btf_dump_printf(d, "enum%s%s",
910 t->name_off ? " " : "",
911 btf_dump_type_name(d, id));
914 btf_dump_printf(d, " {");
915 for (i = 0; i < vlen; i++, v++) {
916 name = btf_name_of(d, v->name_off);
917 /* enumerators share namespace with typedef idents */
918 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
920 btf_dump_printf(d, "\n%s%s___%zu = %u,",
921 pfx(lvl + 1), name, dup_cnt,
924 btf_dump_printf(d, "\n%s%s = %u,",
929 btf_dump_printf(d, "\n%s}", pfx(lvl));
933 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
934 const struct btf_type *t)
936 const char *name = btf_dump_type_name(d, id);
939 btf_dump_printf(d, "union %s", name);
941 btf_dump_printf(d, "struct %s", name);
944 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
945 const struct btf_type *t, int lvl)
947 const char *name = btf_dump_ident_name(d, id);
950 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
951 * pointing to VOID. This generates warnings from btf_dump() and
952 * results in uncompilable header file, so we are fixing it up here
953 * with valid typedef into __builtin_va_list.
955 if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
956 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
960 btf_dump_printf(d, "typedef ");
961 btf_dump_emit_type_decl(d, t->type, name, lvl);
964 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
969 if (d->decl_stack_cnt >= d->decl_stack_cap) {
970 new_cap = max(16, d->decl_stack_cap * 3 / 2);
971 new_stack = realloc(d->decl_stack,
972 new_cap * sizeof(new_stack[0]));
975 d->decl_stack = new_stack;
976 d->decl_stack_cap = new_cap;
979 d->decl_stack[d->decl_stack_cnt++] = id;
985 * Emit type declaration (e.g., field type declaration in a struct or argument
986 * declaration in function prototype) in correct C syntax.
988 * For most types it's trivial, but there are few quirky type declaration
989 * cases worth mentioning:
990 * - function prototypes (especially nesting of function prototypes);
992 * - const/volatile/restrict for pointers vs other types.
994 * For a good discussion of *PARSING* C syntax (as a human), see
995 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
996 * Ch.3 "Unscrambling Declarations in C".
998 * It won't help with BTF to C conversion much, though, as it's an opposite
999 * problem. So we came up with this algorithm in reverse to van der Linden's
1000 * parsing algorithm. It goes from structured BTF representation of type
1001 * declaration to a valid compilable C syntax.
1003 * For instance, consider this C typedef:
1004 * typedef const int * const * arr[10] arr_t;
1005 * It will be represented in BTF with this chain of BTF types:
1006 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1008 * Notice how [const] modifier always goes before type it modifies in BTF type
1009 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1010 * the right of pointers, but to the left of other types. There are also other
1011 * quirks, like function pointers, arrays of them, functions returning other
1014 * We handle that by pushing all the types to a stack, until we hit "terminal"
1015 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1016 * top of a stack, modifiers are handled differently. Array/function pointers
1017 * have also wildly different syntax and how nesting of them are done. See
1018 * code for authoritative definition.
1020 * To avoid allocating new stack for each independent chain of BTF types, we
1021 * share one bigger stack, with each chain working only on its own local view
1022 * of a stack frame. Some care is required to "pop" stack frames after
1023 * processing type declaration chain.
1025 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1026 const struct btf_dump_emit_type_decl_opts *opts)
1031 if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1034 fname = OPTS_GET(opts, field_name, "");
1035 lvl = OPTS_GET(opts, indent_level, 0);
1036 d->strip_mods = OPTS_GET(opts, strip_mods, false);
1037 btf_dump_emit_type_decl(d, id, fname, lvl);
1038 d->strip_mods = false;
1042 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1043 const char *fname, int lvl)
1045 struct id_stack decl_stack;
1046 const struct btf_type *t;
1047 int err, stack_start;
1049 stack_start = d->decl_stack_cnt;
1051 t = btf__type_by_id(d->btf, id);
1052 if (d->strip_mods && btf_is_mod(t))
1055 err = btf_dump_push_decl_stack_id(d, id);
1058 * if we don't have enough memory for entire type decl
1059 * chain, restore stack, emit warning, and try to
1060 * proceed nevertheless
1062 pr_warn("not enough memory for decl stack:%d", err);
1063 d->decl_stack_cnt = stack_start;
1071 switch (btf_kind(t)) {
1073 case BTF_KIND_VOLATILE:
1074 case BTF_KIND_CONST:
1075 case BTF_KIND_RESTRICT:
1076 case BTF_KIND_FUNC_PROTO:
1079 case BTF_KIND_ARRAY:
1080 id = btf_array(t)->type;
1085 case BTF_KIND_STRUCT:
1086 case BTF_KIND_UNION:
1087 case BTF_KIND_TYPEDEF:
1090 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1097 * We might be inside a chain of declarations (e.g., array of function
1098 * pointers returning anonymous (so inlined) structs, having another
1099 * array field). Each of those needs its own "stack frame" to handle
1100 * emitting of declarations. Those stack frames are non-overlapping
1101 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1102 * handle this set of nested stacks, we create a view corresponding to
1103 * our own "stack frame" and work with it as an independent stack.
1104 * We'll need to clean up after emit_type_chain() returns, though.
1106 decl_stack.ids = d->decl_stack + stack_start;
1107 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1108 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1110 * emit_type_chain() guarantees that it will pop its entire decl_stack
1111 * frame before returning. But it works with a read-only view into
1112 * decl_stack, so it doesn't actually pop anything from the
1113 * perspective of shared btf_dump->decl_stack, per se. We need to
1114 * reset decl_stack state to how it was before us to avoid it growing
1117 d->decl_stack_cnt = stack_start;
1120 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1122 const struct btf_type *t;
1125 while (decl_stack->cnt) {
1126 id = decl_stack->ids[decl_stack->cnt - 1];
1127 t = btf__type_by_id(d->btf, id);
1129 switch (btf_kind(t)) {
1130 case BTF_KIND_VOLATILE:
1131 btf_dump_printf(d, "volatile ");
1133 case BTF_KIND_CONST:
1134 btf_dump_printf(d, "const ");
1136 case BTF_KIND_RESTRICT:
1137 btf_dump_printf(d, "restrict ");
1146 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1148 const struct btf_type *t;
1151 while (decl_stack->cnt) {
1152 id = decl_stack->ids[decl_stack->cnt - 1];
1153 t = btf__type_by_id(d->btf, id);
1160 static void btf_dump_emit_name(const struct btf_dump *d,
1161 const char *name, bool last_was_ptr)
1163 bool separate = name[0] && !last_was_ptr;
1165 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1168 static void btf_dump_emit_type_chain(struct btf_dump *d,
1169 struct id_stack *decls,
1170 const char *fname, int lvl)
1173 * last_was_ptr is used to determine if we need to separate pointer
1174 * asterisk (*) from previous part of type signature with space, so
1175 * that we get `int ***`, instead of `int * * *`. We default to true
1176 * for cases where we have single pointer in a chain. E.g., in ptr ->
1177 * func_proto case. func_proto will start a new emit_type_chain call
1178 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1179 * don't want to prepend space for that last pointer.
1181 bool last_was_ptr = true;
1182 const struct btf_type *t;
1187 while (decls->cnt) {
1188 id = decls->ids[--decls->cnt];
1190 /* VOID is a special snowflake */
1191 btf_dump_emit_mods(d, decls);
1192 btf_dump_printf(d, "void");
1193 last_was_ptr = false;
1197 t = btf__type_by_id(d->btf, id);
1202 btf_dump_emit_mods(d, decls);
1203 name = btf_name_of(d, t->name_off);
1204 btf_dump_printf(d, "%s", name);
1206 case BTF_KIND_STRUCT:
1207 case BTF_KIND_UNION:
1208 btf_dump_emit_mods(d, decls);
1209 /* inline anonymous struct/union */
1210 if (t->name_off == 0)
1211 btf_dump_emit_struct_def(d, id, t, lvl);
1213 btf_dump_emit_struct_fwd(d, id, t);
1216 btf_dump_emit_mods(d, decls);
1217 /* inline anonymous enum */
1218 if (t->name_off == 0)
1219 btf_dump_emit_enum_def(d, id, t, lvl);
1221 btf_dump_emit_enum_fwd(d, id, t);
1224 btf_dump_emit_mods(d, decls);
1225 btf_dump_emit_fwd_def(d, id, t);
1227 case BTF_KIND_TYPEDEF:
1228 btf_dump_emit_mods(d, decls);
1229 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1232 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1234 case BTF_KIND_VOLATILE:
1235 btf_dump_printf(d, " volatile");
1237 case BTF_KIND_CONST:
1238 btf_dump_printf(d, " const");
1240 case BTF_KIND_RESTRICT:
1241 btf_dump_printf(d, " restrict");
1243 case BTF_KIND_ARRAY: {
1244 const struct btf_array *a = btf_array(t);
1245 const struct btf_type *next_t;
1250 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1251 * which causes it to emit extra const/volatile
1252 * modifiers for an array, if array's element type has
1253 * const/volatile modifiers. Clang doesn't do that.
1254 * In general, it doesn't seem very meaningful to have
1255 * a const/volatile modifier for array, so we are
1256 * going to silently skip them here.
1258 btf_dump_drop_mods(d, decls);
1260 if (decls->cnt == 0) {
1261 btf_dump_emit_name(d, fname, last_was_ptr);
1262 btf_dump_printf(d, "[%u]", a->nelems);
1266 next_id = decls->ids[decls->cnt - 1];
1267 next_t = btf__type_by_id(d->btf, next_id);
1268 multidim = btf_is_array(next_t);
1269 /* we need space if we have named non-pointer */
1270 if (fname[0] && !last_was_ptr)
1271 btf_dump_printf(d, " ");
1272 /* no parentheses for multi-dimensional array */
1274 btf_dump_printf(d, "(");
1275 btf_dump_emit_type_chain(d, decls, fname, lvl);
1277 btf_dump_printf(d, ")");
1278 btf_dump_printf(d, "[%u]", a->nelems);
1281 case BTF_KIND_FUNC_PROTO: {
1282 const struct btf_param *p = btf_params(t);
1283 __u16 vlen = btf_vlen(t);
1287 * GCC emits extra volatile qualifier for
1288 * __attribute__((noreturn)) function pointers. Clang
1289 * doesn't do it. It's a GCC quirk for backwards
1290 * compatibility with code written for GCC <2.5. So,
1291 * similarly to extra qualifiers for array, just drop
1292 * them, instead of handling them.
1294 btf_dump_drop_mods(d, decls);
1296 btf_dump_printf(d, " (");
1297 btf_dump_emit_type_chain(d, decls, fname, lvl);
1298 btf_dump_printf(d, ")");
1300 btf_dump_emit_name(d, fname, last_was_ptr);
1302 btf_dump_printf(d, "(");
1304 * Clang for BPF target generates func_proto with no
1305 * args as a func_proto with a single void arg (e.g.,
1306 * `int (*f)(void)` vs just `int (*f)()`). We are
1307 * going to pretend there are no args for such case.
1309 if (vlen == 1 && p->type == 0) {
1310 btf_dump_printf(d, ")");
1314 for (i = 0; i < vlen; i++, p++) {
1316 btf_dump_printf(d, ", ");
1318 /* last arg of type void is vararg */
1319 if (i == vlen - 1 && p->type == 0) {
1320 btf_dump_printf(d, "...");
1324 name = btf_name_of(d, p->name_off);
1325 btf_dump_emit_type_decl(d, p->type, name, lvl);
1328 btf_dump_printf(d, ")");
1332 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1337 last_was_ptr = kind == BTF_KIND_PTR;
1340 btf_dump_emit_name(d, fname, last_was_ptr);
1343 /* return number of duplicates (occurrences) of a given name */
1344 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1345 const char *orig_name)
1349 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1351 hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1356 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1357 struct hashmap *name_map)
1359 struct btf_dump_type_aux_state *s = &d->type_states[id];
1360 const struct btf_type *t = btf__type_by_id(d->btf, id);
1361 const char *orig_name = btf_name_of(d, t->name_off);
1362 const char **cached_name = &d->cached_names[id];
1365 if (t->name_off == 0)
1368 if (s->name_resolved)
1369 return *cached_name ? *cached_name : orig_name;
1371 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1373 const size_t max_len = 256;
1374 char new_name[max_len];
1376 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1377 *cached_name = strdup(new_name);
1380 s->name_resolved = 1;
1381 return *cached_name ? *cached_name : orig_name;
1384 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1386 return btf_dump_resolve_name(d, id, d->type_names);
1389 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1391 return btf_dump_resolve_name(d, id, d->ident_names);