1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * BTF-to-C type converter.
6 * Copyright (c) 2019 Facebook
16 #include <linux/err.h>
17 #include <linux/btf.h>
18 #include <linux/kernel.h>
22 #include "libbpf_internal.h"
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 */
58 /* indent string length; one indent string is added for each indent level */
59 #define BTF_DATA_INDENT_STR_LEN 32
62 * Common internal data for BTF type data dump operations.
64 struct btf_dump_data {
65 const void *data_end; /* end of valid data to show */
69 __u8 indent_lvl; /* base indent level */
70 char indent_str[BTF_DATA_INDENT_STR_LEN];
71 /* below are used during iteration */
74 bool is_array_terminated;
79 const struct btf *btf;
80 btf_dump_printf_fn_t printf_fn;
87 /* per-type auxiliary state */
88 struct btf_dump_type_aux_state *type_states;
89 size_t type_states_cap;
90 /* per-type optional cached unique name, must be freed, if present */
91 const char **cached_names;
92 size_t cached_names_cap;
94 /* topo-sorted list of dependent type definitions */
100 * stack of type declarations (e.g., chain of modifiers, arrays,
107 /* maps struct/union/enum name to a number of name occurrences */
108 struct hashmap *type_names;
110 * maps typedef identifiers and enum value names to a number of such
113 struct hashmap *ident_names;
115 * data for typed display; allocated if needed.
117 struct btf_dump_data *typed_dump;
120 static size_t str_hash_fn(const void *key, void *ctx)
122 return str_hash(key);
125 static bool str_equal_fn(const void *a, const void *b, void *ctx)
127 return strcmp(a, b) == 0;
130 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
132 return btf__name_by_offset(d->btf, name_off);
135 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
140 d->printf_fn(d->cb_ctx, fmt, args);
144 static int btf_dump_mark_referenced(struct btf_dump *d);
145 static int btf_dump_resize(struct btf_dump *d);
147 struct btf_dump *btf_dump__new(const struct btf *btf,
148 btf_dump_printf_fn_t printf_fn,
150 const struct btf_dump_opts *opts)
155 if (!OPTS_VALID(opts, btf_dump_opts))
156 return libbpf_err_ptr(-EINVAL);
159 return libbpf_err_ptr(-EINVAL);
161 d = calloc(1, sizeof(struct btf_dump));
163 return libbpf_err_ptr(-ENOMEM);
166 d->printf_fn = printf_fn;
168 d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
170 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
171 if (IS_ERR(d->type_names)) {
172 err = PTR_ERR(d->type_names);
173 d->type_names = NULL;
176 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
177 if (IS_ERR(d->ident_names)) {
178 err = PTR_ERR(d->ident_names);
179 d->ident_names = NULL;
183 err = btf_dump_resize(d);
190 return libbpf_err_ptr(err);
193 static int btf_dump_resize(struct btf_dump *d)
195 int err, last_id = btf__type_cnt(d->btf) - 1;
197 if (last_id <= d->last_id)
200 if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
201 sizeof(*d->type_states), last_id + 1))
203 if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
204 sizeof(*d->cached_names), last_id + 1))
207 if (d->last_id == 0) {
208 /* VOID is special */
209 d->type_states[0].order_state = ORDERED;
210 d->type_states[0].emit_state = EMITTED;
213 /* eagerly determine referenced types for anon enums */
214 err = btf_dump_mark_referenced(d);
218 d->last_id = last_id;
222 static void btf_dump_free_names(struct hashmap *map)
225 struct hashmap_entry *cur;
227 hashmap__for_each_entry(map, cur, bkt)
228 free((void *)cur->key);
233 void btf_dump__free(struct btf_dump *d)
237 if (IS_ERR_OR_NULL(d))
240 free(d->type_states);
241 if (d->cached_names) {
242 /* any set cached name is owned by us and should be freed */
243 for (i = 0; i <= d->last_id; i++) {
244 if (d->cached_names[i])
245 free((void *)d->cached_names[i]);
248 free(d->cached_names);
251 btf_dump_free_names(d->type_names);
252 btf_dump_free_names(d->ident_names);
257 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
258 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
261 * Dump BTF type in a compilable C syntax, including all the necessary
262 * dependent types, necessary for compilation. If some of the dependent types
263 * were already emitted as part of previous btf_dump__dump_type() invocation
264 * for another type, they won't be emitted again. This API allows callers to
265 * filter out BTF types according to user-defined criterias and emitted only
266 * minimal subset of types, necessary to compile everything. Full struct/union
267 * definitions will still be emitted, even if the only usage is through
268 * pointer and could be satisfied with just a forward declaration.
270 * Dumping is done in two high-level passes:
271 * 1. Topologically sort type definitions to satisfy C rules of compilation.
272 * 2. Emit type definitions in C syntax.
274 * Returns 0 on success; <0, otherwise.
276 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
280 if (id >= btf__type_cnt(d->btf))
281 return libbpf_err(-EINVAL);
283 err = btf_dump_resize(d);
285 return libbpf_err(err);
287 d->emit_queue_cnt = 0;
288 err = btf_dump_order_type(d, id, false);
290 return libbpf_err(err);
292 for (i = 0; i < d->emit_queue_cnt; i++)
293 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
299 * Mark all types that are referenced from any other type. This is used to
300 * determine top-level anonymous enums that need to be emitted as an
301 * independent type declarations.
302 * Anonymous enums come in two flavors: either embedded in a struct's field
303 * definition, in which case they have to be declared inline as part of field
304 * type declaration; or as a top-level anonymous enum, typically used for
305 * declaring global constants. It's impossible to distinguish between two
306 * without knowning whether given enum type was referenced from other type:
307 * top-level anonymous enum won't be referenced by anything, while embedded
310 static int btf_dump_mark_referenced(struct btf_dump *d)
312 int i, j, n = btf__type_cnt(d->btf);
313 const struct btf_type *t;
316 for (i = d->last_id + 1; i < n; i++) {
317 t = btf__type_by_id(d->btf, i);
320 switch (btf_kind(t)) {
323 case BTF_KIND_ENUM64:
328 case BTF_KIND_VOLATILE:
330 case BTF_KIND_RESTRICT:
332 case BTF_KIND_TYPEDEF:
335 case BTF_KIND_DECL_TAG:
336 case BTF_KIND_TYPE_TAG:
337 d->type_states[t->type].referenced = 1;
340 case BTF_KIND_ARRAY: {
341 const struct btf_array *a = btf_array(t);
343 d->type_states[a->index_type].referenced = 1;
344 d->type_states[a->type].referenced = 1;
347 case BTF_KIND_STRUCT:
348 case BTF_KIND_UNION: {
349 const struct btf_member *m = btf_members(t);
351 for (j = 0; j < vlen; j++, m++)
352 d->type_states[m->type].referenced = 1;
355 case BTF_KIND_FUNC_PROTO: {
356 const struct btf_param *p = btf_params(t);
358 for (j = 0; j < vlen; j++, p++)
359 d->type_states[p->type].referenced = 1;
362 case BTF_KIND_DATASEC: {
363 const struct btf_var_secinfo *v = btf_var_secinfos(t);
365 for (j = 0; j < vlen; j++, v++)
366 d->type_states[v->type].referenced = 1;
376 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
381 if (d->emit_queue_cnt >= d->emit_queue_cap) {
382 new_cap = max(16, d->emit_queue_cap * 3 / 2);
383 new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
386 d->emit_queue = new_queue;
387 d->emit_queue_cap = new_cap;
390 d->emit_queue[d->emit_queue_cnt++] = id;
395 * Determine order of emitting dependent types and specified type to satisfy
396 * C compilation rules. This is done through topological sorting with an
397 * additional complication which comes from C rules. The main idea for C is
398 * that if some type is "embedded" into a struct/union, it's size needs to be
399 * known at the time of definition of containing type. E.g., for:
402 * struct B { struct A x; }
404 * struct A *HAS* to be defined before struct B, because it's "embedded",
405 * i.e., it is part of struct B layout. But in the following case:
408 * struct B { struct A *x; }
411 * it's enough to just have a forward declaration of struct A at the time of
412 * struct B definition, as struct B has a pointer to struct A, so the size of
413 * field x is known without knowing struct A size: it's sizeof(void *).
415 * Unfortunately, there are some trickier cases we need to handle, e.g.:
417 * struct A {}; // if this was forward-declaration: compilation error
419 * struct { // anonymous struct
424 * In this case, struct B's field x is a pointer, so it's size is known
425 * regardless of the size of (anonymous) struct it points to. But because this
426 * struct is anonymous and thus defined inline inside struct B, *and* it
427 * embeds struct A, compiler requires full definition of struct A to be known
428 * before struct B can be defined. This creates a transitive dependency
429 * between struct A and struct B. If struct A was forward-declared before
430 * struct B definition and fully defined after struct B definition, that would
431 * trigger compilation error.
433 * All this means that while we are doing topological sorting on BTF type
434 * graph, we need to determine relationships between different types (graph
436 * - weak link (relationship) between X and Y, if Y *CAN* be
437 * forward-declared at the point of X definition;
438 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
440 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
441 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
442 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
443 * Weak/strong relationship is determined recursively during DFS traversal and
444 * is returned as a result from btf_dump_order_type().
446 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
447 * but it is not guaranteeing that no extraneous forward declarations will be
450 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
451 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
452 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
453 * entire graph path, so depending where from one came to that BTF type, it
454 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
455 * once they are processed, there is no need to do it again, so they are
456 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
457 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
458 * in any case, once those are processed, no need to do it again, as the
459 * result won't change.
462 * - 1, if type is part of strong link (so there is strong topological
463 * ordering requirements);
464 * - 0, if type is part of weak link (so can be satisfied through forward
466 * - <0, on error (e.g., unsatisfiable type loop detected).
468 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
471 * Order state is used to detect strong link cycles, but only for BTF
472 * kinds that are or could be an independent definition (i.e.,
473 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
474 * func_protos, modifiers are just means to get to these definitions.
475 * Int/void don't need definitions, they are assumed to be always
476 * properly defined. We also ignore datasec, var, and funcs for now.
477 * So for all non-defining kinds, we never even set ordering state,
478 * for defining kinds we set ORDERING and subsequently ORDERED if it
479 * forms a strong link.
481 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
482 const struct btf_type *t;
486 /* return true, letting typedefs know that it's ok to be emitted */
487 if (tstate->order_state == ORDERED)
490 t = btf__type_by_id(d->btf, id);
492 if (tstate->order_state == ORDERING) {
493 /* type loop, but resolvable through fwd declaration */
494 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
496 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
500 switch (btf_kind(t)) {
503 tstate->order_state = ORDERED;
507 err = btf_dump_order_type(d, t->type, true);
508 tstate->order_state = ORDERED;
512 return btf_dump_order_type(d, btf_array(t)->type, false);
514 case BTF_KIND_STRUCT:
515 case BTF_KIND_UNION: {
516 const struct btf_member *m = btf_members(t);
518 * struct/union is part of strong link, only if it's embedded
519 * (so no ptr in a path) or it's anonymous (so has to be
520 * defined inline, even if declared through ptr)
522 if (through_ptr && t->name_off != 0)
525 tstate->order_state = ORDERING;
528 for (i = 0; i < vlen; i++, m++) {
529 err = btf_dump_order_type(d, m->type, false);
534 if (t->name_off != 0) {
535 err = btf_dump_add_emit_queue_id(d, id);
540 tstate->order_state = ORDERED;
544 case BTF_KIND_ENUM64:
547 * non-anonymous or non-referenced enums are top-level
548 * declarations and should be emitted. Same logic can be
549 * applied to FWDs, it won't hurt anyways.
551 if (t->name_off != 0 || !tstate->referenced) {
552 err = btf_dump_add_emit_queue_id(d, id);
556 tstate->order_state = ORDERED;
559 case BTF_KIND_TYPEDEF: {
562 is_strong = btf_dump_order_type(d, t->type, through_ptr);
566 /* typedef is similar to struct/union w.r.t. fwd-decls */
567 if (through_ptr && !is_strong)
570 /* typedef is always a named definition */
571 err = btf_dump_add_emit_queue_id(d, id);
575 d->type_states[id].order_state = ORDERED;
578 case BTF_KIND_VOLATILE:
580 case BTF_KIND_RESTRICT:
581 case BTF_KIND_TYPE_TAG:
582 return btf_dump_order_type(d, t->type, through_ptr);
584 case BTF_KIND_FUNC_PROTO: {
585 const struct btf_param *p = btf_params(t);
588 err = btf_dump_order_type(d, t->type, through_ptr);
594 for (i = 0; i < vlen; i++, p++) {
595 err = btf_dump_order_type(d, p->type, through_ptr);
605 case BTF_KIND_DATASEC:
606 case BTF_KIND_DECL_TAG:
607 d->type_states[id].order_state = ORDERED;
615 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
616 const struct btf_type *t);
618 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
619 const struct btf_type *t);
620 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
621 const struct btf_type *t, int lvl);
623 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
624 const struct btf_type *t);
625 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
626 const struct btf_type *t, int lvl);
628 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
629 const struct btf_type *t);
631 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
632 const struct btf_type *t, int lvl);
634 /* a local view into a shared stack */
640 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
641 const char *fname, int lvl);
642 static void btf_dump_emit_type_chain(struct btf_dump *d,
643 struct id_stack *decl_stack,
644 const char *fname, int lvl);
646 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
647 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
648 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
649 const char *orig_name);
651 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
653 const struct btf_type *t = btf__type_by_id(d->btf, id);
655 /* __builtin_va_list is a compiler built-in, which causes compilation
656 * errors, when compiling w/ different compiler, then used to compile
657 * original code (e.g., GCC to compile kernel, Clang to use generated
658 * C header from BTF). As it is built-in, it should be already defined
659 * properly internally in compiler.
661 if (t->name_off == 0)
663 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
667 * Emit C-syntax definitions of types from chains of BTF types.
669 * High-level handling of determining necessary forward declarations are handled
670 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
671 * declarations/definitions in C syntax are handled by a combo of
672 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
673 * corresponding btf_dump_emit_*_{def,fwd}() functions.
675 * We also keep track of "containing struct/union type ID" to determine when
676 * we reference it from inside and thus can avoid emitting unnecessary forward
679 * This algorithm is designed in such a way, that even if some error occurs
680 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
681 * that doesn't comply to C rules completely), algorithm will try to proceed
682 * and produce as much meaningful output as possible.
684 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
686 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
687 bool top_level_def = cont_id == 0;
688 const struct btf_type *t;
691 if (tstate->emit_state == EMITTED)
694 t = btf__type_by_id(d->btf, id);
697 if (tstate->emit_state == EMITTING) {
698 if (tstate->fwd_emitted)
702 case BTF_KIND_STRUCT:
705 * if we are referencing a struct/union that we are
706 * part of - then no need for fwd declaration
710 if (t->name_off == 0) {
711 pr_warn("anonymous struct/union loop, id:[%u]\n",
715 btf_dump_emit_struct_fwd(d, id, t);
716 btf_dump_printf(d, ";\n\n");
717 tstate->fwd_emitted = 1;
719 case BTF_KIND_TYPEDEF:
721 * for typedef fwd_emitted means typedef definition
722 * was emitted, but it can be used only for "weak"
723 * references through pointer only, not for embedding
725 if (!btf_dump_is_blacklisted(d, id)) {
726 btf_dump_emit_typedef_def(d, id, t, 0);
727 btf_dump_printf(d, ";\n\n");
729 tstate->fwd_emitted = 1;
740 /* Emit type alias definitions if necessary */
741 btf_dump_emit_missing_aliases(d, id, t);
743 tstate->emit_state = EMITTED;
746 case BTF_KIND_ENUM64:
748 btf_dump_emit_enum_def(d, id, t, 0);
749 btf_dump_printf(d, ";\n\n");
751 tstate->emit_state = EMITTED;
754 case BTF_KIND_VOLATILE:
756 case BTF_KIND_RESTRICT:
757 case BTF_KIND_TYPE_TAG:
758 btf_dump_emit_type(d, t->type, cont_id);
761 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
764 btf_dump_emit_fwd_def(d, id, t);
765 btf_dump_printf(d, ";\n\n");
766 tstate->emit_state = EMITTED;
768 case BTF_KIND_TYPEDEF:
769 tstate->emit_state = EMITTING;
770 btf_dump_emit_type(d, t->type, id);
772 * typedef can server as both definition and forward
773 * declaration; at this stage someone depends on
774 * typedef as a forward declaration (refers to it
775 * through pointer), so unless we already did it,
776 * emit typedef as a forward declaration
778 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
779 btf_dump_emit_typedef_def(d, id, t, 0);
780 btf_dump_printf(d, ";\n\n");
782 tstate->emit_state = EMITTED;
784 case BTF_KIND_STRUCT:
786 tstate->emit_state = EMITTING;
787 /* if it's a top-level struct/union definition or struct/union
788 * is anonymous, then in C we'll be emitting all fields and
789 * their types (as opposed to just `struct X`), so we need to
790 * make sure that all types, referenced from struct/union
791 * members have necessary forward-declarations, where
794 if (top_level_def || t->name_off == 0) {
795 const struct btf_member *m = btf_members(t);
796 __u16 vlen = btf_vlen(t);
799 new_cont_id = t->name_off == 0 ? cont_id : id;
800 for (i = 0; i < vlen; i++, m++)
801 btf_dump_emit_type(d, m->type, new_cont_id);
802 } else if (!tstate->fwd_emitted && id != cont_id) {
803 btf_dump_emit_struct_fwd(d, id, t);
804 btf_dump_printf(d, ";\n\n");
805 tstate->fwd_emitted = 1;
809 btf_dump_emit_struct_def(d, id, t, 0);
810 btf_dump_printf(d, ";\n\n");
811 tstate->emit_state = EMITTED;
813 tstate->emit_state = NOT_EMITTED;
816 case BTF_KIND_FUNC_PROTO: {
817 const struct btf_param *p = btf_params(t);
818 __u16 n = btf_vlen(t);
821 btf_dump_emit_type(d, t->type, cont_id);
822 for (i = 0; i < n; i++, p++)
823 btf_dump_emit_type(d, p->type, cont_id);
832 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
833 const struct btf_type *t)
835 const struct btf_member *m;
836 int max_align = 1, align, i, bit_sz;
841 /* all non-bitfield fields have to be naturally aligned */
842 for (i = 0; i < vlen; i++, m++) {
843 align = btf__align_of(btf, m->type);
844 bit_sz = btf_member_bitfield_size(t, i);
845 if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
847 max_align = max(align, max_align);
849 /* size of a non-packed struct has to be a multiple of its alignment */
850 if (t->size % max_align != 0)
853 * if original struct was marked as packed, but its layout is
854 * naturally aligned, we'll detect that it's not packed
859 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
860 int cur_off, int next_off, int next_align,
861 bool in_bitfield, int lvl)
867 {"long", d->ptr_sz * 8}, {"int", 32}, {"short", 16}, {"char", 8}
869 int new_off, pad_bits, bits, i;
870 const char *pad_type;
872 if (cur_off >= next_off)
875 /* For filling out padding we want to take advantage of
876 * natural alignment rules to minimize unnecessary explicit
877 * padding. First, we find the largest type (among long, int,
878 * short, or char) that can be used to force naturally aligned
879 * boundary. Once determined, we'll use such type to fill in
880 * the remaining padding gap. In some cases we can rely on
881 * compiler filling some gaps, but sometimes we need to force
882 * alignment to close natural alignment with markers like
883 * `long: 0` (this is always the case for bitfields). Note
884 * that even if struct itself has, let's say 4-byte alignment
885 * (i.e., it only uses up to int-aligned types), using `long:
886 * X;` explicit padding doesn't actually change struct's
887 * overall alignment requirements, but compiler does take into
888 * account that type's (long, in this example) natural
889 * alignment requirements when adding implicit padding. We use
890 * this fact heavily and don't worry about ruining correct
891 * struct alignment requirement.
893 for (i = 0; i < ARRAY_SIZE(pads); i++) {
894 pad_bits = pads[i].bits;
895 pad_type = pads[i].name;
897 new_off = roundup(cur_off, pad_bits);
898 if (new_off <= next_off)
902 if (new_off > cur_off && new_off <= next_off) {
903 /* We need explicit `<type>: 0` aligning mark if next
904 * field is right on alignment offset and its
905 * alignment requirement is less strict than <type>'s
906 * alignment (so compiler won't naturally align to the
907 * offset we expect), or if subsequent `<type>: X`,
908 * will actually completely fit in the remaining hole,
909 * making compiler basically ignore `<type>: X`
913 (new_off == next_off && roundup(cur_off, next_align * 8) != new_off) ||
914 (new_off != next_off && next_off - new_off <= new_off - cur_off))
915 /* but for bitfields we'll emit explicit bit count */
916 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type,
917 in_bitfield ? new_off - cur_off : 0);
921 /* Now we know we start at naturally aligned offset for a chosen
922 * padding type (long, int, short, or char), and so the rest is just
923 * a straightforward filling of remaining padding gap with full
924 * `<type>: sizeof(<type>);` markers, except for the last one, which
925 * might need smaller than sizeof(<type>) padding.
927 while (cur_off != next_off) {
928 bits = min(next_off - cur_off, pad_bits);
929 if (bits == pad_bits) {
930 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
934 /* For the remainder padding that doesn't cover entire
935 * pad_type bit length, we pick the smallest necessary type.
936 * This is pure aesthetics, we could have just used `long`,
937 * but having smallest necessary one communicates better the
938 * scale of the padding gap.
940 for (i = ARRAY_SIZE(pads) - 1; i >= 0; i--) {
941 pad_type = pads[i].name;
942 pad_bits = pads[i].bits;
946 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, bits);
953 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
954 const struct btf_type *t)
956 btf_dump_printf(d, "%s%s%s",
957 btf_is_struct(t) ? "struct" : "union",
958 t->name_off ? " " : "",
959 btf_dump_type_name(d, id));
962 static void btf_dump_emit_struct_def(struct btf_dump *d,
964 const struct btf_type *t,
967 const struct btf_member *m = btf_members(t);
968 bool is_struct = btf_is_struct(t);
969 bool packed, prev_bitfield = false;
970 int align, i, off = 0;
971 __u16 vlen = btf_vlen(t);
973 align = btf__align_of(d->btf, id);
974 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
976 btf_dump_printf(d, "%s%s%s {",
977 is_struct ? "struct" : "union",
978 t->name_off ? " " : "",
979 btf_dump_type_name(d, id));
981 for (i = 0; i < vlen; i++, m++) {
983 int m_off, m_sz, m_align;
986 fname = btf_name_of(d, m->name_off);
987 m_sz = btf_member_bitfield_size(t, i);
988 m_off = btf_member_bit_offset(t, i);
989 m_align = packed ? 1 : btf__align_of(d->btf, m->type);
991 in_bitfield = prev_bitfield && m_sz != 0;
993 btf_dump_emit_bit_padding(d, off, m_off, m_align, in_bitfield, lvl + 1);
994 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
995 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
998 btf_dump_printf(d, ": %d", m_sz);
1000 prev_bitfield = true;
1002 m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
1003 off = m_off + m_sz * 8;
1004 prev_bitfield = false;
1007 btf_dump_printf(d, ";");
1010 /* pad at the end, if necessary */
1012 btf_dump_emit_bit_padding(d, off, t->size * 8, align, false, lvl + 1);
1015 * Keep `struct empty {}` on a single line,
1016 * only print newline when there are regular or padding fields.
1018 if (vlen || t->size)
1019 btf_dump_printf(d, "\n");
1020 btf_dump_printf(d, "%s}", pfx(lvl));
1022 btf_dump_printf(d, " __attribute__((packed))");
1025 static const char *missing_base_types[][2] = {
1027 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
1028 * SIMD intrinsics. Alias them to standard base types.
1030 { "__Poly8_t", "unsigned char" },
1031 { "__Poly16_t", "unsigned short" },
1032 { "__Poly64_t", "unsigned long long" },
1033 { "__Poly128_t", "unsigned __int128" },
1036 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
1037 const struct btf_type *t)
1039 const char *name = btf_dump_type_name(d, id);
1042 for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
1043 if (strcmp(name, missing_base_types[i][0]) == 0) {
1044 btf_dump_printf(d, "typedef %s %s;\n\n",
1045 missing_base_types[i][1], name);
1051 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
1052 const struct btf_type *t)
1054 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
1057 static void btf_dump_emit_enum32_val(struct btf_dump *d,
1058 const struct btf_type *t,
1059 int lvl, __u16 vlen)
1061 const struct btf_enum *v = btf_enum(t);
1062 bool is_signed = btf_kflag(t);
1063 const char *fmt_str;
1068 for (i = 0; i < vlen; i++, v++) {
1069 name = btf_name_of(d, v->name_off);
1070 /* enumerators share namespace with typedef idents */
1071 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1073 fmt_str = is_signed ? "\n%s%s___%zd = %d," : "\n%s%s___%zd = %u,";
1074 btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, dup_cnt, v->val);
1076 fmt_str = is_signed ? "\n%s%s = %d," : "\n%s%s = %u,";
1077 btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, v->val);
1082 static void btf_dump_emit_enum64_val(struct btf_dump *d,
1083 const struct btf_type *t,
1084 int lvl, __u16 vlen)
1086 const struct btf_enum64 *v = btf_enum64(t);
1087 bool is_signed = btf_kflag(t);
1088 const char *fmt_str;
1094 for (i = 0; i < vlen; i++, v++) {
1095 name = btf_name_of(d, v->name_off);
1096 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1097 val = btf_enum64_value(v);
1099 fmt_str = is_signed ? "\n%s%s___%zd = %lldLL,"
1100 : "\n%s%s___%zd = %lluULL,";
1101 btf_dump_printf(d, fmt_str,
1102 pfx(lvl + 1), name, dup_cnt,
1103 (unsigned long long)val);
1105 fmt_str = is_signed ? "\n%s%s = %lldLL,"
1106 : "\n%s%s = %lluULL,";
1107 btf_dump_printf(d, fmt_str,
1109 (unsigned long long)val);
1113 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
1114 const struct btf_type *t,
1117 __u16 vlen = btf_vlen(t);
1119 btf_dump_printf(d, "enum%s%s",
1120 t->name_off ? " " : "",
1121 btf_dump_type_name(d, id));
1126 btf_dump_printf(d, " {");
1128 btf_dump_emit_enum32_val(d, t, lvl, vlen);
1130 btf_dump_emit_enum64_val(d, t, lvl, vlen);
1131 btf_dump_printf(d, "\n%s}", pfx(lvl));
1134 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1135 const struct btf_type *t)
1137 const char *name = btf_dump_type_name(d, id);
1140 btf_dump_printf(d, "union %s", name);
1142 btf_dump_printf(d, "struct %s", name);
1145 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1146 const struct btf_type *t, int lvl)
1148 const char *name = btf_dump_ident_name(d, id);
1151 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
1152 * pointing to VOID. This generates warnings from btf_dump() and
1153 * results in uncompilable header file, so we are fixing it up here
1154 * with valid typedef into __builtin_va_list.
1156 if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1157 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1161 btf_dump_printf(d, "typedef ");
1162 btf_dump_emit_type_decl(d, t->type, name, lvl);
1165 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1170 if (d->decl_stack_cnt >= d->decl_stack_cap) {
1171 new_cap = max(16, d->decl_stack_cap * 3 / 2);
1172 new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
1175 d->decl_stack = new_stack;
1176 d->decl_stack_cap = new_cap;
1179 d->decl_stack[d->decl_stack_cnt++] = id;
1185 * Emit type declaration (e.g., field type declaration in a struct or argument
1186 * declaration in function prototype) in correct C syntax.
1188 * For most types it's trivial, but there are few quirky type declaration
1189 * cases worth mentioning:
1190 * - function prototypes (especially nesting of function prototypes);
1192 * - const/volatile/restrict for pointers vs other types.
1194 * For a good discussion of *PARSING* C syntax (as a human), see
1195 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1196 * Ch.3 "Unscrambling Declarations in C".
1198 * It won't help with BTF to C conversion much, though, as it's an opposite
1199 * problem. So we came up with this algorithm in reverse to van der Linden's
1200 * parsing algorithm. It goes from structured BTF representation of type
1201 * declaration to a valid compilable C syntax.
1203 * For instance, consider this C typedef:
1204 * typedef const int * const * arr[10] arr_t;
1205 * It will be represented in BTF with this chain of BTF types:
1206 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1208 * Notice how [const] modifier always goes before type it modifies in BTF type
1209 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1210 * the right of pointers, but to the left of other types. There are also other
1211 * quirks, like function pointers, arrays of them, functions returning other
1214 * We handle that by pushing all the types to a stack, until we hit "terminal"
1215 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1216 * top of a stack, modifiers are handled differently. Array/function pointers
1217 * have also wildly different syntax and how nesting of them are done. See
1218 * code for authoritative definition.
1220 * To avoid allocating new stack for each independent chain of BTF types, we
1221 * share one bigger stack, with each chain working only on its own local view
1222 * of a stack frame. Some care is required to "pop" stack frames after
1223 * processing type declaration chain.
1225 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1226 const struct btf_dump_emit_type_decl_opts *opts)
1231 if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1232 return libbpf_err(-EINVAL);
1234 err = btf_dump_resize(d);
1236 return libbpf_err(err);
1238 fname = OPTS_GET(opts, field_name, "");
1239 lvl = OPTS_GET(opts, indent_level, 0);
1240 d->strip_mods = OPTS_GET(opts, strip_mods, false);
1241 btf_dump_emit_type_decl(d, id, fname, lvl);
1242 d->strip_mods = false;
1246 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1247 const char *fname, int lvl)
1249 struct id_stack decl_stack;
1250 const struct btf_type *t;
1251 int err, stack_start;
1253 stack_start = d->decl_stack_cnt;
1255 t = btf__type_by_id(d->btf, id);
1256 if (d->strip_mods && btf_is_mod(t))
1259 err = btf_dump_push_decl_stack_id(d, id);
1262 * if we don't have enough memory for entire type decl
1263 * chain, restore stack, emit warning, and try to
1264 * proceed nevertheless
1266 pr_warn("not enough memory for decl stack:%d", err);
1267 d->decl_stack_cnt = stack_start;
1275 switch (btf_kind(t)) {
1277 case BTF_KIND_VOLATILE:
1278 case BTF_KIND_CONST:
1279 case BTF_KIND_RESTRICT:
1280 case BTF_KIND_FUNC_PROTO:
1281 case BTF_KIND_TYPE_TAG:
1284 case BTF_KIND_ARRAY:
1285 id = btf_array(t)->type;
1289 case BTF_KIND_ENUM64:
1291 case BTF_KIND_STRUCT:
1292 case BTF_KIND_UNION:
1293 case BTF_KIND_TYPEDEF:
1294 case BTF_KIND_FLOAT:
1297 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1304 * We might be inside a chain of declarations (e.g., array of function
1305 * pointers returning anonymous (so inlined) structs, having another
1306 * array field). Each of those needs its own "stack frame" to handle
1307 * emitting of declarations. Those stack frames are non-overlapping
1308 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1309 * handle this set of nested stacks, we create a view corresponding to
1310 * our own "stack frame" and work with it as an independent stack.
1311 * We'll need to clean up after emit_type_chain() returns, though.
1313 decl_stack.ids = d->decl_stack + stack_start;
1314 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1315 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1317 * emit_type_chain() guarantees that it will pop its entire decl_stack
1318 * frame before returning. But it works with a read-only view into
1319 * decl_stack, so it doesn't actually pop anything from the
1320 * perspective of shared btf_dump->decl_stack, per se. We need to
1321 * reset decl_stack state to how it was before us to avoid it growing
1324 d->decl_stack_cnt = stack_start;
1327 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1329 const struct btf_type *t;
1332 while (decl_stack->cnt) {
1333 id = decl_stack->ids[decl_stack->cnt - 1];
1334 t = btf__type_by_id(d->btf, id);
1336 switch (btf_kind(t)) {
1337 case BTF_KIND_VOLATILE:
1338 btf_dump_printf(d, "volatile ");
1340 case BTF_KIND_CONST:
1341 btf_dump_printf(d, "const ");
1343 case BTF_KIND_RESTRICT:
1344 btf_dump_printf(d, "restrict ");
1353 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1355 const struct btf_type *t;
1358 while (decl_stack->cnt) {
1359 id = decl_stack->ids[decl_stack->cnt - 1];
1360 t = btf__type_by_id(d->btf, id);
1367 static void btf_dump_emit_name(const struct btf_dump *d,
1368 const char *name, bool last_was_ptr)
1370 bool separate = name[0] && !last_was_ptr;
1372 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1375 static void btf_dump_emit_type_chain(struct btf_dump *d,
1376 struct id_stack *decls,
1377 const char *fname, int lvl)
1380 * last_was_ptr is used to determine if we need to separate pointer
1381 * asterisk (*) from previous part of type signature with space, so
1382 * that we get `int ***`, instead of `int * * *`. We default to true
1383 * for cases where we have single pointer in a chain. E.g., in ptr ->
1384 * func_proto case. func_proto will start a new emit_type_chain call
1385 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1386 * don't want to prepend space for that last pointer.
1388 bool last_was_ptr = true;
1389 const struct btf_type *t;
1394 while (decls->cnt) {
1395 id = decls->ids[--decls->cnt];
1397 /* VOID is a special snowflake */
1398 btf_dump_emit_mods(d, decls);
1399 btf_dump_printf(d, "void");
1400 last_was_ptr = false;
1404 t = btf__type_by_id(d->btf, id);
1409 case BTF_KIND_FLOAT:
1410 btf_dump_emit_mods(d, decls);
1411 name = btf_name_of(d, t->name_off);
1412 btf_dump_printf(d, "%s", name);
1414 case BTF_KIND_STRUCT:
1415 case BTF_KIND_UNION:
1416 btf_dump_emit_mods(d, decls);
1417 /* inline anonymous struct/union */
1418 if (t->name_off == 0 && !d->skip_anon_defs)
1419 btf_dump_emit_struct_def(d, id, t, lvl);
1421 btf_dump_emit_struct_fwd(d, id, t);
1424 case BTF_KIND_ENUM64:
1425 btf_dump_emit_mods(d, decls);
1426 /* inline anonymous enum */
1427 if (t->name_off == 0 && !d->skip_anon_defs)
1428 btf_dump_emit_enum_def(d, id, t, lvl);
1430 btf_dump_emit_enum_fwd(d, id, t);
1433 btf_dump_emit_mods(d, decls);
1434 btf_dump_emit_fwd_def(d, id, t);
1436 case BTF_KIND_TYPEDEF:
1437 btf_dump_emit_mods(d, decls);
1438 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1441 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1443 case BTF_KIND_VOLATILE:
1444 btf_dump_printf(d, " volatile");
1446 case BTF_KIND_CONST:
1447 btf_dump_printf(d, " const");
1449 case BTF_KIND_RESTRICT:
1450 btf_dump_printf(d, " restrict");
1452 case BTF_KIND_TYPE_TAG:
1453 btf_dump_emit_mods(d, decls);
1454 name = btf_name_of(d, t->name_off);
1455 btf_dump_printf(d, " __attribute__((btf_type_tag(\"%s\")))", name);
1457 case BTF_KIND_ARRAY: {
1458 const struct btf_array *a = btf_array(t);
1459 const struct btf_type *next_t;
1464 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1465 * which causes it to emit extra const/volatile
1466 * modifiers for an array, if array's element type has
1467 * const/volatile modifiers. Clang doesn't do that.
1468 * In general, it doesn't seem very meaningful to have
1469 * a const/volatile modifier for array, so we are
1470 * going to silently skip them here.
1472 btf_dump_drop_mods(d, decls);
1474 if (decls->cnt == 0) {
1475 btf_dump_emit_name(d, fname, last_was_ptr);
1476 btf_dump_printf(d, "[%u]", a->nelems);
1480 next_id = decls->ids[decls->cnt - 1];
1481 next_t = btf__type_by_id(d->btf, next_id);
1482 multidim = btf_is_array(next_t);
1483 /* we need space if we have named non-pointer */
1484 if (fname[0] && !last_was_ptr)
1485 btf_dump_printf(d, " ");
1486 /* no parentheses for multi-dimensional array */
1488 btf_dump_printf(d, "(");
1489 btf_dump_emit_type_chain(d, decls, fname, lvl);
1491 btf_dump_printf(d, ")");
1492 btf_dump_printf(d, "[%u]", a->nelems);
1495 case BTF_KIND_FUNC_PROTO: {
1496 const struct btf_param *p = btf_params(t);
1497 __u16 vlen = btf_vlen(t);
1501 * GCC emits extra volatile qualifier for
1502 * __attribute__((noreturn)) function pointers. Clang
1503 * doesn't do it. It's a GCC quirk for backwards
1504 * compatibility with code written for GCC <2.5. So,
1505 * similarly to extra qualifiers for array, just drop
1506 * them, instead of handling them.
1508 btf_dump_drop_mods(d, decls);
1510 btf_dump_printf(d, " (");
1511 btf_dump_emit_type_chain(d, decls, fname, lvl);
1512 btf_dump_printf(d, ")");
1514 btf_dump_emit_name(d, fname, last_was_ptr);
1516 btf_dump_printf(d, "(");
1518 * Clang for BPF target generates func_proto with no
1519 * args as a func_proto with a single void arg (e.g.,
1520 * `int (*f)(void)` vs just `int (*f)()`). We are
1521 * going to pretend there are no args for such case.
1523 if (vlen == 1 && p->type == 0) {
1524 btf_dump_printf(d, ")");
1528 for (i = 0; i < vlen; i++, p++) {
1530 btf_dump_printf(d, ", ");
1532 /* last arg of type void is vararg */
1533 if (i == vlen - 1 && p->type == 0) {
1534 btf_dump_printf(d, "...");
1538 name = btf_name_of(d, p->name_off);
1539 btf_dump_emit_type_decl(d, p->type, name, lvl);
1542 btf_dump_printf(d, ")");
1546 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1551 last_was_ptr = kind == BTF_KIND_PTR;
1554 btf_dump_emit_name(d, fname, last_was_ptr);
1557 /* show type name as (type_name) */
1558 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1561 const struct btf_type *t;
1563 /* for array members, we don't bother emitting type name for each
1564 * member to avoid the redundancy of
1565 * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
1567 if (d->typed_dump->is_array_member)
1570 /* avoid type name specification for variable/section; it will be done
1571 * for the associated variable value(s).
1573 t = btf__type_by_id(d->btf, id);
1574 if (btf_is_var(t) || btf_is_datasec(t))
1578 btf_dump_printf(d, "(");
1580 d->skip_anon_defs = true;
1581 d->strip_mods = true;
1582 btf_dump_emit_type_decl(d, id, "", 0);
1583 d->strip_mods = false;
1584 d->skip_anon_defs = false;
1587 btf_dump_printf(d, ")");
1590 /* return number of duplicates (occurrences) of a given name */
1591 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1592 const char *orig_name)
1594 char *old_name, *new_name;
1598 new_name = strdup(orig_name);
1602 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1605 err = hashmap__set(name_map, new_name, (void *)dup_cnt,
1606 (const void **)&old_name, NULL);
1615 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1616 struct hashmap *name_map)
1618 struct btf_dump_type_aux_state *s = &d->type_states[id];
1619 const struct btf_type *t = btf__type_by_id(d->btf, id);
1620 const char *orig_name = btf_name_of(d, t->name_off);
1621 const char **cached_name = &d->cached_names[id];
1624 if (t->name_off == 0)
1627 if (s->name_resolved)
1628 return *cached_name ? *cached_name : orig_name;
1630 if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1631 s->name_resolved = 1;
1635 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1637 const size_t max_len = 256;
1638 char new_name[max_len];
1640 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1641 *cached_name = strdup(new_name);
1644 s->name_resolved = 1;
1645 return *cached_name ? *cached_name : orig_name;
1648 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1650 return btf_dump_resolve_name(d, id, d->type_names);
1653 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1655 return btf_dump_resolve_name(d, id, d->ident_names);
1658 static int btf_dump_dump_type_data(struct btf_dump *d,
1660 const struct btf_type *t,
1666 static const char *btf_dump_data_newline(struct btf_dump *d)
1668 return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1671 static const char *btf_dump_data_delim(struct btf_dump *d)
1673 return d->typed_dump->depth == 0 ? "" : ",";
1676 static void btf_dump_data_pfx(struct btf_dump *d)
1678 int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1680 if (d->typed_dump->compact)
1683 for (i = 0; i < lvl; i++)
1684 btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1687 /* A macro is used here as btf_type_value[s]() appends format specifiers
1688 * to the format specifier passed in; these do the work of appending
1689 * delimiters etc while the caller simply has to specify the type values
1690 * in the format specifier + value(s).
1692 #define btf_dump_type_values(d, fmt, ...) \
1693 btf_dump_printf(d, fmt "%s%s", \
1695 btf_dump_data_delim(d), \
1696 btf_dump_data_newline(d))
1698 static int btf_dump_unsupported_data(struct btf_dump *d,
1699 const struct btf_type *t,
1702 btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1706 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1707 const struct btf_type *t,
1713 __u16 left_shift_bits, right_shift_bits;
1714 const __u8 *bytes = data;
1719 /* Maximum supported bitfield size is 64 bits */
1721 pr_warn("unexpected bitfield size %d\n", t->size);
1725 /* Bitfield value retrieval is done in two steps; first relevant bytes are
1726 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1728 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1729 for (i = t->size - 1; i >= 0; i--)
1730 num = num * 256 + bytes[i];
1731 nr_copy_bits = bit_sz + bits_offset;
1732 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1733 for (i = 0; i < t->size; i++)
1734 num = num * 256 + bytes[i];
1735 nr_copy_bits = t->size * 8 - bits_offset;
1737 # error "Unrecognized __BYTE_ORDER__"
1739 left_shift_bits = 64 - nr_copy_bits;
1740 right_shift_bits = 64 - bit_sz;
1742 *value = (num << left_shift_bits) >> right_shift_bits;
1747 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1748 const struct btf_type *t,
1756 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1764 static int btf_dump_bitfield_data(struct btf_dump *d,
1765 const struct btf_type *t,
1773 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1777 btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1782 /* ints, floats and ptrs */
1783 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1784 const struct btf_type *t,
1788 static __u8 bytecmp[16] = {};
1791 /* For pointer types, pointer size is not defined on a per-type basis.
1792 * On dump creation however, we store the pointer size.
1794 if (btf_kind(t) == BTF_KIND_PTR)
1795 nr_bytes = d->ptr_sz;
1799 if (nr_bytes < 1 || nr_bytes > 16) {
1800 pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1804 if (memcmp(data, bytecmp, nr_bytes) == 0)
1809 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1812 int alignment = btf__align_of(btf, type_id);
1817 return ((uintptr_t)data) % alignment == 0;
1820 static int btf_dump_int_data(struct btf_dump *d,
1821 const struct btf_type *t,
1826 __u8 encoding = btf_int_encoding(t);
1827 bool sign = encoding & BTF_INT_SIGNED;
1828 char buf[16] __attribute__((aligned(16)));
1831 if (sz == 0 || sz > sizeof(buf)) {
1832 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1836 /* handle packed int data - accesses of integers not aligned on
1837 * int boundaries can cause problems on some platforms.
1839 if (!ptr_is_aligned(d->btf, type_id, data)) {
1840 memcpy(buf, data, sz);
1846 const __u64 *ints = data;
1849 /* avoid use of __int128 as some 32-bit platforms do not
1852 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1855 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1859 # error "Unrecognized __BYTE_ORDER__"
1862 btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1864 btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1865 (unsigned long long)lsi);
1870 btf_dump_type_values(d, "%lld", *(long long *)data);
1872 btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1876 btf_dump_type_values(d, "%d", *(__s32 *)data);
1878 btf_dump_type_values(d, "%u", *(__u32 *)data);
1882 btf_dump_type_values(d, "%d", *(__s16 *)data);
1884 btf_dump_type_values(d, "%u", *(__u16 *)data);
1887 if (d->typed_dump->is_array_char) {
1888 /* check for null terminator */
1889 if (d->typed_dump->is_array_terminated)
1891 if (*(char *)data == '\0') {
1892 d->typed_dump->is_array_terminated = true;
1895 if (isprint(*(char *)data)) {
1896 btf_dump_type_values(d, "'%c'", *(char *)data);
1901 btf_dump_type_values(d, "%d", *(__s8 *)data);
1903 btf_dump_type_values(d, "%u", *(__u8 *)data);
1906 pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1918 static int btf_dump_float_data(struct btf_dump *d,
1919 const struct btf_type *t,
1923 const union float_data *flp = data;
1924 union float_data fl;
1927 /* handle unaligned data; copy to local union */
1928 if (!ptr_is_aligned(d->btf, type_id, data)) {
1929 memcpy(&fl, data, sz);
1935 btf_dump_type_values(d, "%Lf", flp->ld);
1938 btf_dump_type_values(d, "%lf", flp->d);
1941 btf_dump_type_values(d, "%f", flp->f);
1944 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1950 static int btf_dump_var_data(struct btf_dump *d,
1951 const struct btf_type *v,
1955 enum btf_func_linkage linkage = btf_var(v)->linkage;
1956 const struct btf_type *t;
1961 case BTF_FUNC_STATIC:
1964 case BTF_FUNC_EXTERN:
1967 case BTF_FUNC_GLOBAL:
1973 /* format of output here is [linkage] [type] [varname] = (type)value,
1974 * for example "static int cpu_profile_flip = (int)1"
1976 btf_dump_printf(d, "%s", l);
1978 t = btf__type_by_id(d->btf, type_id);
1979 btf_dump_emit_type_cast(d, type_id, false);
1980 btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
1981 return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
1984 static int btf_dump_array_data(struct btf_dump *d,
1985 const struct btf_type *t,
1989 const struct btf_array *array = btf_array(t);
1990 const struct btf_type *elem_type;
1991 __u32 i, elem_type_id;
1993 bool is_array_member;
1995 elem_type_id = array->type;
1996 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
1997 elem_size = btf__resolve_size(d->btf, elem_type_id);
1998 if (elem_size <= 0) {
1999 pr_warn("unexpected elem size %zd for array type [%u]\n",
2000 (ssize_t)elem_size, id);
2004 if (btf_is_int(elem_type)) {
2006 * BTF_INT_CHAR encoding never seems to be set for
2007 * char arrays, so if size is 1 and element is
2008 * printable as a char, we'll do that.
2011 d->typed_dump->is_array_char = true;
2014 /* note that we increment depth before calling btf_dump_print() below;
2015 * this is intentional. btf_dump_data_newline() will not print a
2016 * newline for depth 0 (since this leaves us with trailing newlines
2017 * at the end of typed display), so depth is incremented first.
2018 * For similar reasons, we decrement depth before showing the closing
2021 d->typed_dump->depth++;
2022 btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
2024 /* may be a multidimensional array, so store current "is array member"
2025 * status so we can restore it correctly later.
2027 is_array_member = d->typed_dump->is_array_member;
2028 d->typed_dump->is_array_member = true;
2029 for (i = 0; i < array->nelems; i++, data += elem_size) {
2030 if (d->typed_dump->is_array_terminated)
2032 btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
2034 d->typed_dump->is_array_member = is_array_member;
2035 d->typed_dump->depth--;
2036 btf_dump_data_pfx(d);
2037 btf_dump_type_values(d, "]");
2042 static int btf_dump_struct_data(struct btf_dump *d,
2043 const struct btf_type *t,
2047 const struct btf_member *m = btf_members(t);
2048 __u16 n = btf_vlen(t);
2051 /* note that we increment depth before calling btf_dump_print() below;
2052 * this is intentional. btf_dump_data_newline() will not print a
2053 * newline for depth 0 (since this leaves us with trailing newlines
2054 * at the end of typed display), so depth is incremented first.
2055 * For similar reasons, we decrement depth before showing the closing
2058 d->typed_dump->depth++;
2059 btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
2061 for (i = 0; i < n; i++, m++) {
2062 const struct btf_type *mtype;
2067 mtype = btf__type_by_id(d->btf, m->type);
2068 mname = btf_name_of(d, m->name_off);
2069 moffset = btf_member_bit_offset(t, i);
2071 bit_sz = btf_member_bitfield_size(t, i);
2072 err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
2073 moffset % 8, bit_sz);
2077 d->typed_dump->depth--;
2078 btf_dump_data_pfx(d);
2079 btf_dump_type_values(d, "}");
2085 unsigned long long lp;
2088 static int btf_dump_ptr_data(struct btf_dump *d,
2089 const struct btf_type *t,
2093 if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
2094 btf_dump_type_values(d, "%p", *(void **)data);
2098 memcpy(&pt, data, d->ptr_sz);
2100 btf_dump_type_values(d, "0x%x", pt.p);
2102 btf_dump_type_values(d, "0x%llx", pt.lp);
2107 static int btf_dump_get_enum_value(struct btf_dump *d,
2108 const struct btf_type *t,
2113 bool is_signed = btf_kflag(t);
2115 if (!ptr_is_aligned(d->btf, id, data)) {
2119 err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
2122 *value = (__s64)val;
2128 *value = *(__s64 *)data;
2131 *value = is_signed ? (__s64)*(__s32 *)data : *(__u32 *)data;
2134 *value = is_signed ? *(__s16 *)data : *(__u16 *)data;
2137 *value = is_signed ? *(__s8 *)data : *(__u8 *)data;
2140 pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
2145 static int btf_dump_enum_data(struct btf_dump *d,
2146 const struct btf_type *t,
2154 err = btf_dump_get_enum_value(d, t, data, id, &value);
2158 is_signed = btf_kflag(t);
2159 if (btf_is_enum(t)) {
2160 const struct btf_enum *e;
2162 for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2163 if (value != e->val)
2165 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2169 btf_dump_type_values(d, is_signed ? "%d" : "%u", value);
2171 const struct btf_enum64 *e;
2173 for (i = 0, e = btf_enum64(t); i < btf_vlen(t); i++, e++) {
2174 if (value != btf_enum64_value(e))
2176 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2180 btf_dump_type_values(d, is_signed ? "%lldLL" : "%lluULL",
2181 (unsigned long long)value);
2186 static int btf_dump_datasec_data(struct btf_dump *d,
2187 const struct btf_type *t,
2191 const struct btf_var_secinfo *vsi;
2192 const struct btf_type *var;
2196 btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2198 for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2199 var = btf__type_by_id(d->btf, vsi->type);
2200 err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2203 btf_dump_printf(d, ";");
2208 /* return size of type, or if base type overflows, return -E2BIG. */
2209 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2210 const struct btf_type *t,
2215 __s64 size = btf__resolve_size(d->btf, id);
2217 if (size < 0 || size >= INT_MAX) {
2218 pr_warn("unexpected size [%zu] for id [%u]\n",
2223 /* Only do overflow checking for base types; we do not want to
2224 * avoid showing part of a struct, union or array, even if we
2225 * do not have enough data to show the full object. By
2226 * restricting overflow checking to base types we can ensure
2227 * that partial display succeeds, while avoiding overflowing
2228 * and using bogus data for display.
2230 t = skip_mods_and_typedefs(d->btf, id, NULL);
2232 pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2237 switch (btf_kind(t)) {
2239 case BTF_KIND_FLOAT:
2242 case BTF_KIND_ENUM64:
2243 if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2252 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2253 const struct btf_type *t,
2262 /* toplevel exceptions; we show zero values if
2263 * - we ask for them (emit_zeros)
2264 * - if we are at top-level so we see "struct empty { }"
2265 * - or if we are an array member and the array is non-empty and
2266 * not a char array; we don't want to be in a situation where we
2267 * have an integer array 0, 1, 0, 1 and only show non-zero values.
2268 * If the array contains zeroes only, or is a char array starting
2269 * with a '\0', the array-level check_zero() will prevent showing it;
2270 * we are concerned with determining zero value at the array member
2273 if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2274 (d->typed_dump->is_array_member &&
2275 !d->typed_dump->is_array_char))
2278 t = skip_mods_and_typedefs(d->btf, id, NULL);
2280 switch (btf_kind(t)) {
2283 return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2284 return btf_dump_base_type_check_zero(d, t, id, data);
2285 case BTF_KIND_FLOAT:
2287 return btf_dump_base_type_check_zero(d, t, id, data);
2288 case BTF_KIND_ARRAY: {
2289 const struct btf_array *array = btf_array(t);
2290 const struct btf_type *elem_type;
2291 __u32 elem_type_id, elem_size;
2294 elem_type_id = array->type;
2295 elem_size = btf__resolve_size(d->btf, elem_type_id);
2296 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2298 ischar = btf_is_int(elem_type) && elem_size == 1;
2300 /* check all elements; if _any_ element is nonzero, all
2301 * of array is displayed. We make an exception however
2302 * for char arrays where the first element is 0; these
2303 * are considered zeroed also, even if later elements are
2304 * non-zero because the string is terminated.
2306 for (i = 0; i < array->nelems; i++) {
2307 if (i == 0 && ischar && *(char *)data == 0)
2309 err = btf_dump_type_data_check_zero(d, elem_type,
2314 if (err != -ENODATA)
2319 case BTF_KIND_STRUCT:
2320 case BTF_KIND_UNION: {
2321 const struct btf_member *m = btf_members(t);
2322 __u16 n = btf_vlen(t);
2324 /* if any struct/union member is non-zero, the struct/union
2325 * is considered non-zero and dumped.
2327 for (i = 0; i < n; i++, m++) {
2328 const struct btf_type *mtype;
2331 mtype = btf__type_by_id(d->btf, m->type);
2332 moffset = btf_member_bit_offset(t, i);
2334 /* btf_int_bits() does not store member bitfield size;
2335 * bitfield size needs to be stored here so int display
2336 * of member can retrieve it.
2338 bit_sz = btf_member_bitfield_size(t, i);
2339 err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2340 moffset % 8, bit_sz);
2347 case BTF_KIND_ENUM64:
2348 err = btf_dump_get_enum_value(d, t, data, id, &value);
2359 /* returns size of data dumped, or error. */
2360 static int btf_dump_dump_type_data(struct btf_dump *d,
2362 const struct btf_type *t,
2370 size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2373 err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2375 /* zeroed data is expected and not an error, so simply skip
2376 * dumping such data. Record other errors however.
2378 if (err == -ENODATA)
2382 btf_dump_data_pfx(d);
2384 if (!d->typed_dump->skip_names) {
2385 if (fname && strlen(fname) > 0)
2386 btf_dump_printf(d, ".%s = ", fname);
2387 btf_dump_emit_type_cast(d, id, true);
2390 t = skip_mods_and_typedefs(d->btf, id, NULL);
2392 switch (btf_kind(t)) {
2396 case BTF_KIND_FUNC_PROTO:
2397 case BTF_KIND_DECL_TAG:
2398 err = btf_dump_unsupported_data(d, t, id);
2402 err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2404 err = btf_dump_int_data(d, t, id, data, bits_offset);
2406 case BTF_KIND_FLOAT:
2407 err = btf_dump_float_data(d, t, id, data);
2410 err = btf_dump_ptr_data(d, t, id, data);
2412 case BTF_KIND_ARRAY:
2413 err = btf_dump_array_data(d, t, id, data);
2415 case BTF_KIND_STRUCT:
2416 case BTF_KIND_UNION:
2417 err = btf_dump_struct_data(d, t, id, data);
2420 case BTF_KIND_ENUM64:
2421 /* handle bitfield and int enum values */
2426 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2430 enum_val = (__s64)print_num;
2431 err = btf_dump_enum_data(d, t, id, &enum_val);
2433 err = btf_dump_enum_data(d, t, id, data);
2436 err = btf_dump_var_data(d, t, id, data);
2438 case BTF_KIND_DATASEC:
2439 err = btf_dump_datasec_data(d, t, id, data);
2442 pr_warn("unexpected kind [%u] for id [%u]\n",
2443 BTF_INFO_KIND(t->info), id);
2451 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2452 const void *data, size_t data_sz,
2453 const struct btf_dump_type_data_opts *opts)
2455 struct btf_dump_data typed_dump = {};
2456 const struct btf_type *t;
2459 if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2460 return libbpf_err(-EINVAL);
2462 t = btf__type_by_id(d->btf, id);
2464 return libbpf_err(-ENOENT);
2466 d->typed_dump = &typed_dump;
2467 d->typed_dump->data_end = data + data_sz;
2468 d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2470 /* default indent string is a tab */
2471 if (!OPTS_GET(opts, indent_str, NULL))
2472 d->typed_dump->indent_str[0] = '\t';
2474 libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
2475 sizeof(d->typed_dump->indent_str));
2477 d->typed_dump->compact = OPTS_GET(opts, compact, false);
2478 d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2479 d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2481 ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2483 d->typed_dump = NULL;
2485 return libbpf_err(ret);