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 const struct btf_ext *btf_ext;
81 btf_dump_printf_fn_t printf_fn;
82 struct btf_dump_opts opts;
88 /* per-type auxiliary state */
89 struct btf_dump_type_aux_state *type_states;
90 size_t type_states_cap;
91 /* per-type optional cached unique name, must be freed, if present */
92 const char **cached_names;
93 size_t cached_names_cap;
95 /* topo-sorted list of dependent type definitions */
101 * stack of type declarations (e.g., chain of modifiers, arrays,
108 /* maps struct/union/enum name to a number of name occurrences */
109 struct hashmap *type_names;
111 * maps typedef identifiers and enum value names to a number of such
114 struct hashmap *ident_names;
116 * data for typed display; allocated if needed.
118 struct btf_dump_data *typed_dump;
121 static size_t str_hash_fn(const void *key, void *ctx)
123 return str_hash(key);
126 static bool str_equal_fn(const void *a, const void *b, void *ctx)
128 return strcmp(a, b) == 0;
131 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
133 return btf__name_by_offset(d->btf, name_off);
136 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
141 d->printf_fn(d->opts.ctx, fmt, args);
145 static int btf_dump_mark_referenced(struct btf_dump *d);
146 static int btf_dump_resize(struct btf_dump *d);
148 struct btf_dump *btf_dump__new(const struct btf *btf,
149 const struct btf_ext *btf_ext,
150 const struct btf_dump_opts *opts,
151 btf_dump_printf_fn_t printf_fn)
156 d = calloc(1, sizeof(struct btf_dump));
158 return libbpf_err_ptr(-ENOMEM);
161 d->btf_ext = btf_ext;
162 d->printf_fn = printf_fn;
163 d->opts.ctx = opts ? opts->ctx : NULL;
164 d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
166 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
167 if (IS_ERR(d->type_names)) {
168 err = PTR_ERR(d->type_names);
169 d->type_names = NULL;
172 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
173 if (IS_ERR(d->ident_names)) {
174 err = PTR_ERR(d->ident_names);
175 d->ident_names = NULL;
179 err = btf_dump_resize(d);
186 return libbpf_err_ptr(err);
189 static int btf_dump_resize(struct btf_dump *d)
191 int err, last_id = btf__get_nr_types(d->btf);
193 if (last_id <= d->last_id)
196 if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
197 sizeof(*d->type_states), last_id + 1))
199 if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
200 sizeof(*d->cached_names), last_id + 1))
203 if (d->last_id == 0) {
204 /* VOID is special */
205 d->type_states[0].order_state = ORDERED;
206 d->type_states[0].emit_state = EMITTED;
209 /* eagerly determine referenced types for anon enums */
210 err = btf_dump_mark_referenced(d);
214 d->last_id = last_id;
218 void btf_dump__free(struct btf_dump *d)
222 if (IS_ERR_OR_NULL(d))
225 free(d->type_states);
226 if (d->cached_names) {
227 /* any set cached name is owned by us and should be freed */
228 for (i = 0; i <= d->last_id; i++) {
229 if (d->cached_names[i])
230 free((void *)d->cached_names[i]);
233 free(d->cached_names);
236 hashmap__free(d->type_names);
237 hashmap__free(d->ident_names);
242 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
243 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
246 * Dump BTF type in a compilable C syntax, including all the necessary
247 * dependent types, necessary for compilation. If some of the dependent types
248 * were already emitted as part of previous btf_dump__dump_type() invocation
249 * for another type, they won't be emitted again. This API allows callers to
250 * filter out BTF types according to user-defined criterias and emitted only
251 * minimal subset of types, necessary to compile everything. Full struct/union
252 * definitions will still be emitted, even if the only usage is through
253 * pointer and could be satisfied with just a forward declaration.
255 * Dumping is done in two high-level passes:
256 * 1. Topologically sort type definitions to satisfy C rules of compilation.
257 * 2. Emit type definitions in C syntax.
259 * Returns 0 on success; <0, otherwise.
261 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
265 if (id > btf__get_nr_types(d->btf))
266 return libbpf_err(-EINVAL);
268 err = btf_dump_resize(d);
270 return libbpf_err(err);
272 d->emit_queue_cnt = 0;
273 err = btf_dump_order_type(d, id, false);
275 return libbpf_err(err);
277 for (i = 0; i < d->emit_queue_cnt; i++)
278 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
284 * Mark all types that are referenced from any other type. This is used to
285 * determine top-level anonymous enums that need to be emitted as an
286 * independent type declarations.
287 * Anonymous enums come in two flavors: either embedded in a struct's field
288 * definition, in which case they have to be declared inline as part of field
289 * type declaration; or as a top-level anonymous enum, typically used for
290 * declaring global constants. It's impossible to distinguish between two
291 * without knowning whether given enum type was referenced from other type:
292 * top-level anonymous enum won't be referenced by anything, while embedded
295 static int btf_dump_mark_referenced(struct btf_dump *d)
297 int i, j, n = btf__get_nr_types(d->btf);
298 const struct btf_type *t;
301 for (i = d->last_id + 1; i <= n; i++) {
302 t = btf__type_by_id(d->btf, i);
305 switch (btf_kind(t)) {
312 case BTF_KIND_VOLATILE:
314 case BTF_KIND_RESTRICT:
316 case BTF_KIND_TYPEDEF:
319 d->type_states[t->type].referenced = 1;
322 case BTF_KIND_ARRAY: {
323 const struct btf_array *a = btf_array(t);
325 d->type_states[a->index_type].referenced = 1;
326 d->type_states[a->type].referenced = 1;
329 case BTF_KIND_STRUCT:
330 case BTF_KIND_UNION: {
331 const struct btf_member *m = btf_members(t);
333 for (j = 0; j < vlen; j++, m++)
334 d->type_states[m->type].referenced = 1;
337 case BTF_KIND_FUNC_PROTO: {
338 const struct btf_param *p = btf_params(t);
340 for (j = 0; j < vlen; j++, p++)
341 d->type_states[p->type].referenced = 1;
344 case BTF_KIND_DATASEC: {
345 const struct btf_var_secinfo *v = btf_var_secinfos(t);
347 for (j = 0; j < vlen; j++, v++)
348 d->type_states[v->type].referenced = 1;
358 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
363 if (d->emit_queue_cnt >= d->emit_queue_cap) {
364 new_cap = max(16, d->emit_queue_cap * 3 / 2);
365 new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
368 d->emit_queue = new_queue;
369 d->emit_queue_cap = new_cap;
372 d->emit_queue[d->emit_queue_cnt++] = id;
377 * Determine order of emitting dependent types and specified type to satisfy
378 * C compilation rules. This is done through topological sorting with an
379 * additional complication which comes from C rules. The main idea for C is
380 * that if some type is "embedded" into a struct/union, it's size needs to be
381 * known at the time of definition of containing type. E.g., for:
384 * struct B { struct A x; }
386 * struct A *HAS* to be defined before struct B, because it's "embedded",
387 * i.e., it is part of struct B layout. But in the following case:
390 * struct B { struct A *x; }
393 * it's enough to just have a forward declaration of struct A at the time of
394 * struct B definition, as struct B has a pointer to struct A, so the size of
395 * field x is known without knowing struct A size: it's sizeof(void *).
397 * Unfortunately, there are some trickier cases we need to handle, e.g.:
399 * struct A {}; // if this was forward-declaration: compilation error
401 * struct { // anonymous struct
406 * In this case, struct B's field x is a pointer, so it's size is known
407 * regardless of the size of (anonymous) struct it points to. But because this
408 * struct is anonymous and thus defined inline inside struct B, *and* it
409 * embeds struct A, compiler requires full definition of struct A to be known
410 * before struct B can be defined. This creates a transitive dependency
411 * between struct A and struct B. If struct A was forward-declared before
412 * struct B definition and fully defined after struct B definition, that would
413 * trigger compilation error.
415 * All this means that while we are doing topological sorting on BTF type
416 * graph, we need to determine relationships between different types (graph
418 * - weak link (relationship) between X and Y, if Y *CAN* be
419 * forward-declared at the point of X definition;
420 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
422 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
423 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
424 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
425 * Weak/strong relationship is determined recursively during DFS traversal and
426 * is returned as a result from btf_dump_order_type().
428 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
429 * but it is not guaranteeing that no extraneous forward declarations will be
432 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
433 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
434 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
435 * entire graph path, so depending where from one came to that BTF type, it
436 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
437 * once they are processed, there is no need to do it again, so they are
438 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
439 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
440 * in any case, once those are processed, no need to do it again, as the
441 * result won't change.
444 * - 1, if type is part of strong link (so there is strong topological
445 * ordering requirements);
446 * - 0, if type is part of weak link (so can be satisfied through forward
448 * - <0, on error (e.g., unsatisfiable type loop detected).
450 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
453 * Order state is used to detect strong link cycles, but only for BTF
454 * kinds that are or could be an independent definition (i.e.,
455 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
456 * func_protos, modifiers are just means to get to these definitions.
457 * Int/void don't need definitions, they are assumed to be always
458 * properly defined. We also ignore datasec, var, and funcs for now.
459 * So for all non-defining kinds, we never even set ordering state,
460 * for defining kinds we set ORDERING and subsequently ORDERED if it
461 * forms a strong link.
463 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
464 const struct btf_type *t;
468 /* return true, letting typedefs know that it's ok to be emitted */
469 if (tstate->order_state == ORDERED)
472 t = btf__type_by_id(d->btf, id);
474 if (tstate->order_state == ORDERING) {
475 /* type loop, but resolvable through fwd declaration */
476 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
478 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
482 switch (btf_kind(t)) {
485 tstate->order_state = ORDERED;
489 err = btf_dump_order_type(d, t->type, true);
490 tstate->order_state = ORDERED;
494 return btf_dump_order_type(d, btf_array(t)->type, false);
496 case BTF_KIND_STRUCT:
497 case BTF_KIND_UNION: {
498 const struct btf_member *m = btf_members(t);
500 * struct/union is part of strong link, only if it's embedded
501 * (so no ptr in a path) or it's anonymous (so has to be
502 * defined inline, even if declared through ptr)
504 if (through_ptr && t->name_off != 0)
507 tstate->order_state = ORDERING;
510 for (i = 0; i < vlen; i++, m++) {
511 err = btf_dump_order_type(d, m->type, false);
516 if (t->name_off != 0) {
517 err = btf_dump_add_emit_queue_id(d, id);
522 tstate->order_state = ORDERED;
528 * non-anonymous or non-referenced enums are top-level
529 * declarations and should be emitted. Same logic can be
530 * applied to FWDs, it won't hurt anyways.
532 if (t->name_off != 0 || !tstate->referenced) {
533 err = btf_dump_add_emit_queue_id(d, id);
537 tstate->order_state = ORDERED;
540 case BTF_KIND_TYPEDEF: {
543 is_strong = btf_dump_order_type(d, t->type, through_ptr);
547 /* typedef is similar to struct/union w.r.t. fwd-decls */
548 if (through_ptr && !is_strong)
551 /* typedef is always a named definition */
552 err = btf_dump_add_emit_queue_id(d, id);
556 d->type_states[id].order_state = ORDERED;
559 case BTF_KIND_VOLATILE:
561 case BTF_KIND_RESTRICT:
562 return btf_dump_order_type(d, t->type, through_ptr);
564 case BTF_KIND_FUNC_PROTO: {
565 const struct btf_param *p = btf_params(t);
568 err = btf_dump_order_type(d, t->type, through_ptr);
574 for (i = 0; i < vlen; i++, p++) {
575 err = btf_dump_order_type(d, p->type, through_ptr);
585 case BTF_KIND_DATASEC:
586 d->type_states[id].order_state = ORDERED;
594 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
595 const struct btf_type *t);
597 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
598 const struct btf_type *t);
599 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
600 const struct btf_type *t, int lvl);
602 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
603 const struct btf_type *t);
604 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
605 const struct btf_type *t, int lvl);
607 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
608 const struct btf_type *t);
610 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
611 const struct btf_type *t, int lvl);
613 /* a local view into a shared stack */
619 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
620 const char *fname, int lvl);
621 static void btf_dump_emit_type_chain(struct btf_dump *d,
622 struct id_stack *decl_stack,
623 const char *fname, int lvl);
625 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
626 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
627 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
628 const char *orig_name);
630 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
632 const struct btf_type *t = btf__type_by_id(d->btf, id);
634 /* __builtin_va_list is a compiler built-in, which causes compilation
635 * errors, when compiling w/ different compiler, then used to compile
636 * original code (e.g., GCC to compile kernel, Clang to use generated
637 * C header from BTF). As it is built-in, it should be already defined
638 * properly internally in compiler.
640 if (t->name_off == 0)
642 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
646 * Emit C-syntax definitions of types from chains of BTF types.
648 * High-level handling of determining necessary forward declarations are handled
649 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
650 * declarations/definitions in C syntax are handled by a combo of
651 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
652 * corresponding btf_dump_emit_*_{def,fwd}() functions.
654 * We also keep track of "containing struct/union type ID" to determine when
655 * we reference it from inside and thus can avoid emitting unnecessary forward
658 * This algorithm is designed in such a way, that even if some error occurs
659 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
660 * that doesn't comply to C rules completely), algorithm will try to proceed
661 * and produce as much meaningful output as possible.
663 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
665 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
666 bool top_level_def = cont_id == 0;
667 const struct btf_type *t;
670 if (tstate->emit_state == EMITTED)
673 t = btf__type_by_id(d->btf, id);
676 if (tstate->emit_state == EMITTING) {
677 if (tstate->fwd_emitted)
681 case BTF_KIND_STRUCT:
684 * if we are referencing a struct/union that we are
685 * part of - then no need for fwd declaration
689 if (t->name_off == 0) {
690 pr_warn("anonymous struct/union loop, id:[%u]\n",
694 btf_dump_emit_struct_fwd(d, id, t);
695 btf_dump_printf(d, ";\n\n");
696 tstate->fwd_emitted = 1;
698 case BTF_KIND_TYPEDEF:
700 * for typedef fwd_emitted means typedef definition
701 * was emitted, but it can be used only for "weak"
702 * references through pointer only, not for embedding
704 if (!btf_dump_is_blacklisted(d, id)) {
705 btf_dump_emit_typedef_def(d, id, t, 0);
706 btf_dump_printf(d, ";\n\n");
708 tstate->fwd_emitted = 1;
719 /* Emit type alias definitions if necessary */
720 btf_dump_emit_missing_aliases(d, id, t);
722 tstate->emit_state = EMITTED;
726 btf_dump_emit_enum_def(d, id, t, 0);
727 btf_dump_printf(d, ";\n\n");
729 tstate->emit_state = EMITTED;
732 case BTF_KIND_VOLATILE:
734 case BTF_KIND_RESTRICT:
735 btf_dump_emit_type(d, t->type, cont_id);
738 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
741 btf_dump_emit_fwd_def(d, id, t);
742 btf_dump_printf(d, ";\n\n");
743 tstate->emit_state = EMITTED;
745 case BTF_KIND_TYPEDEF:
746 tstate->emit_state = EMITTING;
747 btf_dump_emit_type(d, t->type, id);
749 * typedef can server as both definition and forward
750 * declaration; at this stage someone depends on
751 * typedef as a forward declaration (refers to it
752 * through pointer), so unless we already did it,
753 * emit typedef as a forward declaration
755 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
756 btf_dump_emit_typedef_def(d, id, t, 0);
757 btf_dump_printf(d, ";\n\n");
759 tstate->emit_state = EMITTED;
761 case BTF_KIND_STRUCT:
763 tstate->emit_state = EMITTING;
764 /* if it's a top-level struct/union definition or struct/union
765 * is anonymous, then in C we'll be emitting all fields and
766 * their types (as opposed to just `struct X`), so we need to
767 * make sure that all types, referenced from struct/union
768 * members have necessary forward-declarations, where
771 if (top_level_def || t->name_off == 0) {
772 const struct btf_member *m = btf_members(t);
773 __u16 vlen = btf_vlen(t);
776 new_cont_id = t->name_off == 0 ? cont_id : id;
777 for (i = 0; i < vlen; i++, m++)
778 btf_dump_emit_type(d, m->type, new_cont_id);
779 } else if (!tstate->fwd_emitted && id != cont_id) {
780 btf_dump_emit_struct_fwd(d, id, t);
781 btf_dump_printf(d, ";\n\n");
782 tstate->fwd_emitted = 1;
786 btf_dump_emit_struct_def(d, id, t, 0);
787 btf_dump_printf(d, ";\n\n");
788 tstate->emit_state = EMITTED;
790 tstate->emit_state = NOT_EMITTED;
793 case BTF_KIND_FUNC_PROTO: {
794 const struct btf_param *p = btf_params(t);
795 __u16 n = btf_vlen(t);
798 btf_dump_emit_type(d, t->type, cont_id);
799 for (i = 0; i < n; i++, p++)
800 btf_dump_emit_type(d, p->type, cont_id);
809 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
810 const struct btf_type *t)
812 const struct btf_member *m;
813 int align, i, bit_sz;
816 align = btf__align_of(btf, id);
817 /* size of a non-packed struct has to be a multiple of its alignment*/
818 if (align && t->size % align)
823 /* all non-bitfield fields have to be naturally aligned */
824 for (i = 0; i < vlen; i++, m++) {
825 align = btf__align_of(btf, m->type);
826 bit_sz = btf_member_bitfield_size(t, i);
827 if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
832 * if original struct was marked as packed, but its layout is
833 * naturally aligned, we'll detect that it's not packed
838 static int chip_away_bits(int total, int at_most)
840 return total % at_most ? : at_most;
843 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
844 int cur_off, int m_off, int m_bit_sz,
847 int off_diff = m_off - cur_off;
848 int ptr_bits = d->ptr_sz * 8;
853 if (m_bit_sz == 0 && off_diff < align * 8)
854 /* natural padding will take care of a gap */
857 while (off_diff > 0) {
858 const char *pad_type;
861 if (ptr_bits > 32 && off_diff > 32) {
863 pad_bits = chip_away_bits(off_diff, ptr_bits);
864 } else if (off_diff > 16) {
866 pad_bits = chip_away_bits(off_diff, 32);
867 } else if (off_diff > 8) {
869 pad_bits = chip_away_bits(off_diff, 16);
872 pad_bits = chip_away_bits(off_diff, 8);
874 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
875 off_diff -= pad_bits;
879 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
880 const struct btf_type *t)
882 btf_dump_printf(d, "%s%s%s",
883 btf_is_struct(t) ? "struct" : "union",
884 t->name_off ? " " : "",
885 btf_dump_type_name(d, id));
888 static void btf_dump_emit_struct_def(struct btf_dump *d,
890 const struct btf_type *t,
893 const struct btf_member *m = btf_members(t);
894 bool is_struct = btf_is_struct(t);
895 int align, i, packed, off = 0;
896 __u16 vlen = btf_vlen(t);
898 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
900 btf_dump_printf(d, "%s%s%s {",
901 is_struct ? "struct" : "union",
902 t->name_off ? " " : "",
903 btf_dump_type_name(d, id));
905 for (i = 0; i < vlen; i++, m++) {
909 fname = btf_name_of(d, m->name_off);
910 m_sz = btf_member_bitfield_size(t, i);
911 m_off = btf_member_bit_offset(t, i);
912 align = packed ? 1 : btf__align_of(d->btf, m->type);
914 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
915 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
916 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
919 btf_dump_printf(d, ": %d", m_sz);
922 m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
923 off = m_off + m_sz * 8;
925 btf_dump_printf(d, ";");
928 /* pad at the end, if necessary */
930 align = packed ? 1 : btf__align_of(d->btf, id);
931 btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
936 btf_dump_printf(d, "\n");
937 btf_dump_printf(d, "%s}", pfx(lvl));
939 btf_dump_printf(d, " __attribute__((packed))");
942 static const char *missing_base_types[][2] = {
944 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
945 * SIMD intrinsics. Alias them to standard base types.
947 { "__Poly8_t", "unsigned char" },
948 { "__Poly16_t", "unsigned short" },
949 { "__Poly64_t", "unsigned long long" },
950 { "__Poly128_t", "unsigned __int128" },
953 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
954 const struct btf_type *t)
956 const char *name = btf_dump_type_name(d, id);
959 for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
960 if (strcmp(name, missing_base_types[i][0]) == 0) {
961 btf_dump_printf(d, "typedef %s %s;\n\n",
962 missing_base_types[i][1], name);
968 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
969 const struct btf_type *t)
971 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
974 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
975 const struct btf_type *t,
978 const struct btf_enum *v = btf_enum(t);
979 __u16 vlen = btf_vlen(t);
984 btf_dump_printf(d, "enum%s%s",
985 t->name_off ? " " : "",
986 btf_dump_type_name(d, id));
989 btf_dump_printf(d, " {");
990 for (i = 0; i < vlen; i++, v++) {
991 name = btf_name_of(d, v->name_off);
992 /* enumerators share namespace with typedef idents */
993 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
995 btf_dump_printf(d, "\n%s%s___%zu = %u,",
996 pfx(lvl + 1), name, dup_cnt,
999 btf_dump_printf(d, "\n%s%s = %u,",
1004 btf_dump_printf(d, "\n%s}", pfx(lvl));
1008 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1009 const struct btf_type *t)
1011 const char *name = btf_dump_type_name(d, id);
1014 btf_dump_printf(d, "union %s", name);
1016 btf_dump_printf(d, "struct %s", name);
1019 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1020 const struct btf_type *t, int lvl)
1022 const char *name = btf_dump_ident_name(d, id);
1025 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
1026 * pointing to VOID. This generates warnings from btf_dump() and
1027 * results in uncompilable header file, so we are fixing it up here
1028 * with valid typedef into __builtin_va_list.
1030 if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1031 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1035 btf_dump_printf(d, "typedef ");
1036 btf_dump_emit_type_decl(d, t->type, name, lvl);
1039 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1044 if (d->decl_stack_cnt >= d->decl_stack_cap) {
1045 new_cap = max(16, d->decl_stack_cap * 3 / 2);
1046 new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
1049 d->decl_stack = new_stack;
1050 d->decl_stack_cap = new_cap;
1053 d->decl_stack[d->decl_stack_cnt++] = id;
1059 * Emit type declaration (e.g., field type declaration in a struct or argument
1060 * declaration in function prototype) in correct C syntax.
1062 * For most types it's trivial, but there are few quirky type declaration
1063 * cases worth mentioning:
1064 * - function prototypes (especially nesting of function prototypes);
1066 * - const/volatile/restrict for pointers vs other types.
1068 * For a good discussion of *PARSING* C syntax (as a human), see
1069 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1070 * Ch.3 "Unscrambling Declarations in C".
1072 * It won't help with BTF to C conversion much, though, as it's an opposite
1073 * problem. So we came up with this algorithm in reverse to van der Linden's
1074 * parsing algorithm. It goes from structured BTF representation of type
1075 * declaration to a valid compilable C syntax.
1077 * For instance, consider this C typedef:
1078 * typedef const int * const * arr[10] arr_t;
1079 * It will be represented in BTF with this chain of BTF types:
1080 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1082 * Notice how [const] modifier always goes before type it modifies in BTF type
1083 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1084 * the right of pointers, but to the left of other types. There are also other
1085 * quirks, like function pointers, arrays of them, functions returning other
1088 * We handle that by pushing all the types to a stack, until we hit "terminal"
1089 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1090 * top of a stack, modifiers are handled differently. Array/function pointers
1091 * have also wildly different syntax and how nesting of them are done. See
1092 * code for authoritative definition.
1094 * To avoid allocating new stack for each independent chain of BTF types, we
1095 * share one bigger stack, with each chain working only on its own local view
1096 * of a stack frame. Some care is required to "pop" stack frames after
1097 * processing type declaration chain.
1099 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1100 const struct btf_dump_emit_type_decl_opts *opts)
1105 if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1106 return libbpf_err(-EINVAL);
1108 err = btf_dump_resize(d);
1110 return libbpf_err(err);
1112 fname = OPTS_GET(opts, field_name, "");
1113 lvl = OPTS_GET(opts, indent_level, 0);
1114 d->strip_mods = OPTS_GET(opts, strip_mods, false);
1115 btf_dump_emit_type_decl(d, id, fname, lvl);
1116 d->strip_mods = false;
1120 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1121 const char *fname, int lvl)
1123 struct id_stack decl_stack;
1124 const struct btf_type *t;
1125 int err, stack_start;
1127 stack_start = d->decl_stack_cnt;
1129 t = btf__type_by_id(d->btf, id);
1130 if (d->strip_mods && btf_is_mod(t))
1133 err = btf_dump_push_decl_stack_id(d, id);
1136 * if we don't have enough memory for entire type decl
1137 * chain, restore stack, emit warning, and try to
1138 * proceed nevertheless
1140 pr_warn("not enough memory for decl stack:%d", err);
1141 d->decl_stack_cnt = stack_start;
1149 switch (btf_kind(t)) {
1151 case BTF_KIND_VOLATILE:
1152 case BTF_KIND_CONST:
1153 case BTF_KIND_RESTRICT:
1154 case BTF_KIND_FUNC_PROTO:
1157 case BTF_KIND_ARRAY:
1158 id = btf_array(t)->type;
1163 case BTF_KIND_STRUCT:
1164 case BTF_KIND_UNION:
1165 case BTF_KIND_TYPEDEF:
1166 case BTF_KIND_FLOAT:
1169 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1176 * We might be inside a chain of declarations (e.g., array of function
1177 * pointers returning anonymous (so inlined) structs, having another
1178 * array field). Each of those needs its own "stack frame" to handle
1179 * emitting of declarations. Those stack frames are non-overlapping
1180 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1181 * handle this set of nested stacks, we create a view corresponding to
1182 * our own "stack frame" and work with it as an independent stack.
1183 * We'll need to clean up after emit_type_chain() returns, though.
1185 decl_stack.ids = d->decl_stack + stack_start;
1186 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1187 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1189 * emit_type_chain() guarantees that it will pop its entire decl_stack
1190 * frame before returning. But it works with a read-only view into
1191 * decl_stack, so it doesn't actually pop anything from the
1192 * perspective of shared btf_dump->decl_stack, per se. We need to
1193 * reset decl_stack state to how it was before us to avoid it growing
1196 d->decl_stack_cnt = stack_start;
1199 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1201 const struct btf_type *t;
1204 while (decl_stack->cnt) {
1205 id = decl_stack->ids[decl_stack->cnt - 1];
1206 t = btf__type_by_id(d->btf, id);
1208 switch (btf_kind(t)) {
1209 case BTF_KIND_VOLATILE:
1210 btf_dump_printf(d, "volatile ");
1212 case BTF_KIND_CONST:
1213 btf_dump_printf(d, "const ");
1215 case BTF_KIND_RESTRICT:
1216 btf_dump_printf(d, "restrict ");
1225 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1227 const struct btf_type *t;
1230 while (decl_stack->cnt) {
1231 id = decl_stack->ids[decl_stack->cnt - 1];
1232 t = btf__type_by_id(d->btf, id);
1239 static void btf_dump_emit_name(const struct btf_dump *d,
1240 const char *name, bool last_was_ptr)
1242 bool separate = name[0] && !last_was_ptr;
1244 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1247 static void btf_dump_emit_type_chain(struct btf_dump *d,
1248 struct id_stack *decls,
1249 const char *fname, int lvl)
1252 * last_was_ptr is used to determine if we need to separate pointer
1253 * asterisk (*) from previous part of type signature with space, so
1254 * that we get `int ***`, instead of `int * * *`. We default to true
1255 * for cases where we have single pointer in a chain. E.g., in ptr ->
1256 * func_proto case. func_proto will start a new emit_type_chain call
1257 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1258 * don't want to prepend space for that last pointer.
1260 bool last_was_ptr = true;
1261 const struct btf_type *t;
1266 while (decls->cnt) {
1267 id = decls->ids[--decls->cnt];
1269 /* VOID is a special snowflake */
1270 btf_dump_emit_mods(d, decls);
1271 btf_dump_printf(d, "void");
1272 last_was_ptr = false;
1276 t = btf__type_by_id(d->btf, id);
1281 case BTF_KIND_FLOAT:
1282 btf_dump_emit_mods(d, decls);
1283 name = btf_name_of(d, t->name_off);
1284 btf_dump_printf(d, "%s", name);
1286 case BTF_KIND_STRUCT:
1287 case BTF_KIND_UNION:
1288 btf_dump_emit_mods(d, decls);
1289 /* inline anonymous struct/union */
1290 if (t->name_off == 0 && !d->skip_anon_defs)
1291 btf_dump_emit_struct_def(d, id, t, lvl);
1293 btf_dump_emit_struct_fwd(d, id, t);
1296 btf_dump_emit_mods(d, decls);
1297 /* inline anonymous enum */
1298 if (t->name_off == 0 && !d->skip_anon_defs)
1299 btf_dump_emit_enum_def(d, id, t, lvl);
1301 btf_dump_emit_enum_fwd(d, id, t);
1304 btf_dump_emit_mods(d, decls);
1305 btf_dump_emit_fwd_def(d, id, t);
1307 case BTF_KIND_TYPEDEF:
1308 btf_dump_emit_mods(d, decls);
1309 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1312 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1314 case BTF_KIND_VOLATILE:
1315 btf_dump_printf(d, " volatile");
1317 case BTF_KIND_CONST:
1318 btf_dump_printf(d, " const");
1320 case BTF_KIND_RESTRICT:
1321 btf_dump_printf(d, " restrict");
1323 case BTF_KIND_ARRAY: {
1324 const struct btf_array *a = btf_array(t);
1325 const struct btf_type *next_t;
1330 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1331 * which causes it to emit extra const/volatile
1332 * modifiers for an array, if array's element type has
1333 * const/volatile modifiers. Clang doesn't do that.
1334 * In general, it doesn't seem very meaningful to have
1335 * a const/volatile modifier for array, so we are
1336 * going to silently skip them here.
1338 btf_dump_drop_mods(d, decls);
1340 if (decls->cnt == 0) {
1341 btf_dump_emit_name(d, fname, last_was_ptr);
1342 btf_dump_printf(d, "[%u]", a->nelems);
1346 next_id = decls->ids[decls->cnt - 1];
1347 next_t = btf__type_by_id(d->btf, next_id);
1348 multidim = btf_is_array(next_t);
1349 /* we need space if we have named non-pointer */
1350 if (fname[0] && !last_was_ptr)
1351 btf_dump_printf(d, " ");
1352 /* no parentheses for multi-dimensional array */
1354 btf_dump_printf(d, "(");
1355 btf_dump_emit_type_chain(d, decls, fname, lvl);
1357 btf_dump_printf(d, ")");
1358 btf_dump_printf(d, "[%u]", a->nelems);
1361 case BTF_KIND_FUNC_PROTO: {
1362 const struct btf_param *p = btf_params(t);
1363 __u16 vlen = btf_vlen(t);
1367 * GCC emits extra volatile qualifier for
1368 * __attribute__((noreturn)) function pointers. Clang
1369 * doesn't do it. It's a GCC quirk for backwards
1370 * compatibility with code written for GCC <2.5. So,
1371 * similarly to extra qualifiers for array, just drop
1372 * them, instead of handling them.
1374 btf_dump_drop_mods(d, decls);
1376 btf_dump_printf(d, " (");
1377 btf_dump_emit_type_chain(d, decls, fname, lvl);
1378 btf_dump_printf(d, ")");
1380 btf_dump_emit_name(d, fname, last_was_ptr);
1382 btf_dump_printf(d, "(");
1384 * Clang for BPF target generates func_proto with no
1385 * args as a func_proto with a single void arg (e.g.,
1386 * `int (*f)(void)` vs just `int (*f)()`). We are
1387 * going to pretend there are no args for such case.
1389 if (vlen == 1 && p->type == 0) {
1390 btf_dump_printf(d, ")");
1394 for (i = 0; i < vlen; i++, p++) {
1396 btf_dump_printf(d, ", ");
1398 /* last arg of type void is vararg */
1399 if (i == vlen - 1 && p->type == 0) {
1400 btf_dump_printf(d, "...");
1404 name = btf_name_of(d, p->name_off);
1405 btf_dump_emit_type_decl(d, p->type, name, lvl);
1408 btf_dump_printf(d, ")");
1412 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1417 last_was_ptr = kind == BTF_KIND_PTR;
1420 btf_dump_emit_name(d, fname, last_was_ptr);
1423 /* show type name as (type_name) */
1424 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1427 const struct btf_type *t;
1429 /* for array members, we don't bother emitting type name for each
1430 * member to avoid the redundancy of
1431 * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
1433 if (d->typed_dump->is_array_member)
1436 /* avoid type name specification for variable/section; it will be done
1437 * for the associated variable value(s).
1439 t = btf__type_by_id(d->btf, id);
1440 if (btf_is_var(t) || btf_is_datasec(t))
1444 btf_dump_printf(d, "(");
1446 d->skip_anon_defs = true;
1447 d->strip_mods = true;
1448 btf_dump_emit_type_decl(d, id, "", 0);
1449 d->strip_mods = false;
1450 d->skip_anon_defs = false;
1453 btf_dump_printf(d, ")");
1456 /* return number of duplicates (occurrences) of a given name */
1457 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1458 const char *orig_name)
1462 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1464 hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1469 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1470 struct hashmap *name_map)
1472 struct btf_dump_type_aux_state *s = &d->type_states[id];
1473 const struct btf_type *t = btf__type_by_id(d->btf, id);
1474 const char *orig_name = btf_name_of(d, t->name_off);
1475 const char **cached_name = &d->cached_names[id];
1478 if (t->name_off == 0)
1481 if (s->name_resolved)
1482 return *cached_name ? *cached_name : orig_name;
1484 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1486 const size_t max_len = 256;
1487 char new_name[max_len];
1489 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1490 *cached_name = strdup(new_name);
1493 s->name_resolved = 1;
1494 return *cached_name ? *cached_name : orig_name;
1497 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1499 return btf_dump_resolve_name(d, id, d->type_names);
1502 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1504 return btf_dump_resolve_name(d, id, d->ident_names);
1507 static int btf_dump_dump_type_data(struct btf_dump *d,
1509 const struct btf_type *t,
1515 static const char *btf_dump_data_newline(struct btf_dump *d)
1517 return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1520 static const char *btf_dump_data_delim(struct btf_dump *d)
1522 return d->typed_dump->depth == 0 ? "" : ",";
1525 static void btf_dump_data_pfx(struct btf_dump *d)
1527 int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1529 if (d->typed_dump->compact)
1532 for (i = 0; i < lvl; i++)
1533 btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1536 /* A macro is used here as btf_type_value[s]() appends format specifiers
1537 * to the format specifier passed in; these do the work of appending
1538 * delimiters etc while the caller simply has to specify the type values
1539 * in the format specifier + value(s).
1541 #define btf_dump_type_values(d, fmt, ...) \
1542 btf_dump_printf(d, fmt "%s%s", \
1544 btf_dump_data_delim(d), \
1545 btf_dump_data_newline(d))
1547 static int btf_dump_unsupported_data(struct btf_dump *d,
1548 const struct btf_type *t,
1551 btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1555 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1556 const struct btf_type *t,
1562 __u16 left_shift_bits, right_shift_bits;
1563 __u8 nr_copy_bits, nr_copy_bytes;
1564 const __u8 *bytes = data;
1569 /* Maximum supported bitfield size is 64 bits */
1571 pr_warn("unexpected bitfield size %d\n", sz);
1575 /* Bitfield value retrieval is done in two steps; first relevant bytes are
1576 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1578 nr_copy_bits = bit_sz + bits_offset;
1579 nr_copy_bytes = t->size;
1580 #if __BYTE_ORDER == __LITTLE_ENDIAN
1581 for (i = nr_copy_bytes - 1; i >= 0; i--)
1582 num = num * 256 + bytes[i];
1583 #elif __BYTE_ORDER == __BIG_ENDIAN
1584 for (i = 0; i < nr_copy_bytes; i++)
1585 num = num * 256 + bytes[i];
1587 # error "Unrecognized __BYTE_ORDER__"
1589 left_shift_bits = 64 - nr_copy_bits;
1590 right_shift_bits = 64 - bit_sz;
1592 *value = (num << left_shift_bits) >> right_shift_bits;
1597 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1598 const struct btf_type *t,
1606 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1614 static int btf_dump_bitfield_data(struct btf_dump *d,
1615 const struct btf_type *t,
1623 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1627 btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1632 /* ints, floats and ptrs */
1633 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1634 const struct btf_type *t,
1638 static __u8 bytecmp[16] = {};
1641 /* For pointer types, pointer size is not defined on a per-type basis.
1642 * On dump creation however, we store the pointer size.
1644 if (btf_kind(t) == BTF_KIND_PTR)
1645 nr_bytes = d->ptr_sz;
1649 if (nr_bytes < 1 || nr_bytes > 16) {
1650 pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1654 if (memcmp(data, bytecmp, nr_bytes) == 0)
1659 static bool ptr_is_aligned(const void *data, int data_sz)
1661 return ((uintptr_t)data) % data_sz == 0;
1664 static int btf_dump_int_data(struct btf_dump *d,
1665 const struct btf_type *t,
1670 __u8 encoding = btf_int_encoding(t);
1671 bool sign = encoding & BTF_INT_SIGNED;
1675 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1679 /* handle packed int data - accesses of integers not aligned on
1680 * int boundaries can cause problems on some platforms.
1682 if (!ptr_is_aligned(data, sz))
1683 return btf_dump_bitfield_data(d, t, data, 0, 0);
1687 const __u64 *ints = data;
1690 /* avoid use of __int128 as some 32-bit platforms do not
1693 #if __BYTE_ORDER == __LITTLE_ENDIAN
1696 #elif __BYTE_ORDER == __BIG_ENDIAN
1700 # error "Unrecognized __BYTE_ORDER__"
1703 btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1705 btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1706 (unsigned long long)lsi);
1711 btf_dump_type_values(d, "%lld", *(long long *)data);
1713 btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1717 btf_dump_type_values(d, "%d", *(__s32 *)data);
1719 btf_dump_type_values(d, "%u", *(__u32 *)data);
1723 btf_dump_type_values(d, "%d", *(__s16 *)data);
1725 btf_dump_type_values(d, "%u", *(__u16 *)data);
1728 if (d->typed_dump->is_array_char) {
1729 /* check for null terminator */
1730 if (d->typed_dump->is_array_terminated)
1732 if (*(char *)data == '\0') {
1733 d->typed_dump->is_array_terminated = true;
1736 if (isprint(*(char *)data)) {
1737 btf_dump_type_values(d, "'%c'", *(char *)data);
1742 btf_dump_type_values(d, "%d", *(__s8 *)data);
1744 btf_dump_type_values(d, "%u", *(__u8 *)data);
1747 pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1759 static int btf_dump_float_data(struct btf_dump *d,
1760 const struct btf_type *t,
1764 const union float_data *flp = data;
1765 union float_data fl;
1768 /* handle unaligned data; copy to local union */
1769 if (!ptr_is_aligned(data, sz)) {
1770 memcpy(&fl, data, sz);
1776 btf_dump_type_values(d, "%Lf", flp->ld);
1779 btf_dump_type_values(d, "%lf", flp->d);
1782 btf_dump_type_values(d, "%f", flp->f);
1785 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1791 static int btf_dump_var_data(struct btf_dump *d,
1792 const struct btf_type *v,
1796 enum btf_func_linkage linkage = btf_var(v)->linkage;
1797 const struct btf_type *t;
1802 case BTF_FUNC_STATIC:
1805 case BTF_FUNC_EXTERN:
1808 case BTF_FUNC_GLOBAL:
1814 /* format of output here is [linkage] [type] [varname] = (type)value,
1815 * for example "static int cpu_profile_flip = (int)1"
1817 btf_dump_printf(d, "%s", l);
1819 t = btf__type_by_id(d->btf, type_id);
1820 btf_dump_emit_type_cast(d, type_id, false);
1821 btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
1822 return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
1825 static int btf_dump_array_data(struct btf_dump *d,
1826 const struct btf_type *t,
1830 const struct btf_array *array = btf_array(t);
1831 const struct btf_type *elem_type;
1832 __u32 i, elem_size = 0, elem_type_id;
1833 bool is_array_member;
1835 elem_type_id = array->type;
1836 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
1837 elem_size = btf__resolve_size(d->btf, elem_type_id);
1838 if (elem_size <= 0) {
1839 pr_warn("unexpected elem size %d for array type [%u]\n", elem_size, id);
1843 if (btf_is_int(elem_type)) {
1845 * BTF_INT_CHAR encoding never seems to be set for
1846 * char arrays, so if size is 1 and element is
1847 * printable as a char, we'll do that.
1850 d->typed_dump->is_array_char = true;
1853 /* note that we increment depth before calling btf_dump_print() below;
1854 * this is intentional. btf_dump_data_newline() will not print a
1855 * newline for depth 0 (since this leaves us with trailing newlines
1856 * at the end of typed display), so depth is incremented first.
1857 * For similar reasons, we decrement depth before showing the closing
1860 d->typed_dump->depth++;
1861 btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
1863 /* may be a multidimensional array, so store current "is array member"
1864 * status so we can restore it correctly later.
1866 is_array_member = d->typed_dump->is_array_member;
1867 d->typed_dump->is_array_member = true;
1868 for (i = 0; i < array->nelems; i++, data += elem_size) {
1869 if (d->typed_dump->is_array_terminated)
1871 btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
1873 d->typed_dump->is_array_member = is_array_member;
1874 d->typed_dump->depth--;
1875 btf_dump_data_pfx(d);
1876 btf_dump_type_values(d, "]");
1881 static int btf_dump_struct_data(struct btf_dump *d,
1882 const struct btf_type *t,
1886 const struct btf_member *m = btf_members(t);
1887 __u16 n = btf_vlen(t);
1890 /* note that we increment depth before calling btf_dump_print() below;
1891 * this is intentional. btf_dump_data_newline() will not print a
1892 * newline for depth 0 (since this leaves us with trailing newlines
1893 * at the end of typed display), so depth is incremented first.
1894 * For similar reasons, we decrement depth before showing the closing
1897 d->typed_dump->depth++;
1898 btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
1900 for (i = 0; i < n; i++, m++) {
1901 const struct btf_type *mtype;
1906 mtype = btf__type_by_id(d->btf, m->type);
1907 mname = btf_name_of(d, m->name_off);
1908 moffset = btf_member_bit_offset(t, i);
1910 bit_sz = btf_member_bitfield_size(t, i);
1911 err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
1912 moffset % 8, bit_sz);
1916 d->typed_dump->depth--;
1917 btf_dump_data_pfx(d);
1918 btf_dump_type_values(d, "}");
1924 unsigned long long lp;
1927 static int btf_dump_ptr_data(struct btf_dump *d,
1928 const struct btf_type *t,
1932 if (ptr_is_aligned(data, d->ptr_sz) && d->ptr_sz == sizeof(void *)) {
1933 btf_dump_type_values(d, "%p", *(void **)data);
1937 memcpy(&pt, data, d->ptr_sz);
1939 btf_dump_type_values(d, "0x%x", pt.p);
1941 btf_dump_type_values(d, "0x%llx", pt.lp);
1946 static int btf_dump_get_enum_value(struct btf_dump *d,
1947 const struct btf_type *t,
1954 /* handle unaligned enum value */
1955 if (!ptr_is_aligned(data, sz)) {
1959 err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
1962 *value = (__s64)val;
1968 *value = *(__s64 *)data;
1971 *value = *(__s32 *)data;
1974 *value = *(__s16 *)data;
1977 *value = *(__s8 *)data;
1980 pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
1985 static int btf_dump_enum_data(struct btf_dump *d,
1986 const struct btf_type *t,
1990 const struct btf_enum *e;
1994 err = btf_dump_get_enum_value(d, t, data, id, &value);
1998 for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
1999 if (value != e->val)
2001 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2005 btf_dump_type_values(d, "%d", value);
2009 static int btf_dump_datasec_data(struct btf_dump *d,
2010 const struct btf_type *t,
2014 const struct btf_var_secinfo *vsi;
2015 const struct btf_type *var;
2019 btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2021 for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2022 var = btf__type_by_id(d->btf, vsi->type);
2023 err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2026 btf_dump_printf(d, ";");
2031 /* return size of type, or if base type overflows, return -E2BIG. */
2032 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2033 const struct btf_type *t,
2038 __s64 size = btf__resolve_size(d->btf, id);
2040 if (size < 0 || size >= INT_MAX) {
2041 pr_warn("unexpected size [%zu] for id [%u]\n",
2046 /* Only do overflow checking for base types; we do not want to
2047 * avoid showing part of a struct, union or array, even if we
2048 * do not have enough data to show the full object. By
2049 * restricting overflow checking to base types we can ensure
2050 * that partial display succeeds, while avoiding overflowing
2051 * and using bogus data for display.
2053 t = skip_mods_and_typedefs(d->btf, id, NULL);
2055 pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2060 switch (btf_kind(t)) {
2062 case BTF_KIND_FLOAT:
2065 if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2074 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2075 const struct btf_type *t,
2084 /* toplevel exceptions; we show zero values if
2085 * - we ask for them (emit_zeros)
2086 * - if we are at top-level so we see "struct empty { }"
2087 * - or if we are an array member and the array is non-empty and
2088 * not a char array; we don't want to be in a situation where we
2089 * have an integer array 0, 1, 0, 1 and only show non-zero values.
2090 * If the array contains zeroes only, or is a char array starting
2091 * with a '\0', the array-level check_zero() will prevent showing it;
2092 * we are concerned with determining zero value at the array member
2095 if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2096 (d->typed_dump->is_array_member &&
2097 !d->typed_dump->is_array_char))
2100 t = skip_mods_and_typedefs(d->btf, id, NULL);
2102 switch (btf_kind(t)) {
2105 return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2106 return btf_dump_base_type_check_zero(d, t, id, data);
2107 case BTF_KIND_FLOAT:
2109 return btf_dump_base_type_check_zero(d, t, id, data);
2110 case BTF_KIND_ARRAY: {
2111 const struct btf_array *array = btf_array(t);
2112 const struct btf_type *elem_type;
2113 __u32 elem_type_id, elem_size;
2116 elem_type_id = array->type;
2117 elem_size = btf__resolve_size(d->btf, elem_type_id);
2118 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2120 ischar = btf_is_int(elem_type) && elem_size == 1;
2122 /* check all elements; if _any_ element is nonzero, all
2123 * of array is displayed. We make an exception however
2124 * for char arrays where the first element is 0; these
2125 * are considered zeroed also, even if later elements are
2126 * non-zero because the string is terminated.
2128 for (i = 0; i < array->nelems; i++) {
2129 if (i == 0 && ischar && *(char *)data == 0)
2131 err = btf_dump_type_data_check_zero(d, elem_type,
2136 if (err != -ENODATA)
2141 case BTF_KIND_STRUCT:
2142 case BTF_KIND_UNION: {
2143 const struct btf_member *m = btf_members(t);
2144 __u16 n = btf_vlen(t);
2146 /* if any struct/union member is non-zero, the struct/union
2147 * is considered non-zero and dumped.
2149 for (i = 0; i < n; i++, m++) {
2150 const struct btf_type *mtype;
2153 mtype = btf__type_by_id(d->btf, m->type);
2154 moffset = btf_member_bit_offset(t, i);
2156 /* btf_int_bits() does not store member bitfield size;
2157 * bitfield size needs to be stored here so int display
2158 * of member can retrieve it.
2160 bit_sz = btf_member_bitfield_size(t, i);
2161 err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2162 moffset % 8, bit_sz);
2169 err = btf_dump_get_enum_value(d, t, data, id, &value);
2180 /* returns size of data dumped, or error. */
2181 static int btf_dump_dump_type_data(struct btf_dump *d,
2183 const struct btf_type *t,
2191 size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2194 err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2196 /* zeroed data is expected and not an error, so simply skip
2197 * dumping such data. Record other errors however.
2199 if (err == -ENODATA)
2203 btf_dump_data_pfx(d);
2205 if (!d->typed_dump->skip_names) {
2206 if (fname && strlen(fname) > 0)
2207 btf_dump_printf(d, ".%s = ", fname);
2208 btf_dump_emit_type_cast(d, id, true);
2211 t = skip_mods_and_typedefs(d->btf, id, NULL);
2213 switch (btf_kind(t)) {
2217 case BTF_KIND_FUNC_PROTO:
2218 err = btf_dump_unsupported_data(d, t, id);
2222 err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2224 err = btf_dump_int_data(d, t, id, data, bits_offset);
2226 case BTF_KIND_FLOAT:
2227 err = btf_dump_float_data(d, t, id, data);
2230 err = btf_dump_ptr_data(d, t, id, data);
2232 case BTF_KIND_ARRAY:
2233 err = btf_dump_array_data(d, t, id, data);
2235 case BTF_KIND_STRUCT:
2236 case BTF_KIND_UNION:
2237 err = btf_dump_struct_data(d, t, id, data);
2240 /* handle bitfield and int enum values */
2245 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2249 enum_val = (__s64)print_num;
2250 err = btf_dump_enum_data(d, t, id, &enum_val);
2252 err = btf_dump_enum_data(d, t, id, data);
2255 err = btf_dump_var_data(d, t, id, data);
2257 case BTF_KIND_DATASEC:
2258 err = btf_dump_datasec_data(d, t, id, data);
2261 pr_warn("unexpected kind [%u] for id [%u]\n",
2262 BTF_INFO_KIND(t->info), id);
2270 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2271 const void *data, size_t data_sz,
2272 const struct btf_dump_type_data_opts *opts)
2274 struct btf_dump_data typed_dump = {};
2275 const struct btf_type *t;
2278 if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2279 return libbpf_err(-EINVAL);
2281 t = btf__type_by_id(d->btf, id);
2283 return libbpf_err(-ENOENT);
2285 d->typed_dump = &typed_dump;
2286 d->typed_dump->data_end = data + data_sz;
2287 d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2289 /* default indent string is a tab */
2290 if (!opts->indent_str)
2291 d->typed_dump->indent_str[0] = '\t';
2293 strncat(d->typed_dump->indent_str, opts->indent_str,
2294 sizeof(d->typed_dump->indent_str) - 1);
2296 d->typed_dump->compact = OPTS_GET(opts, compact, false);
2297 d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2298 d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2300 ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2302 d->typed_dump = NULL;
2304 return libbpf_err(ret);