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 DEFAULT_VERSION(btf_dump__new_v0_6_0, btf_dump__new, LIBBPF_0.6.0)
148 struct btf_dump *btf_dump__new_v0_6_0(const struct btf *btf,
149 btf_dump_printf_fn_t printf_fn,
151 const struct btf_dump_opts *opts)
157 return libbpf_err_ptr(-EINVAL);
159 d = calloc(1, sizeof(struct btf_dump));
161 return libbpf_err_ptr(-ENOMEM);
164 d->printf_fn = printf_fn;
166 d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
168 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
169 if (IS_ERR(d->type_names)) {
170 err = PTR_ERR(d->type_names);
171 d->type_names = NULL;
174 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
175 if (IS_ERR(d->ident_names)) {
176 err = PTR_ERR(d->ident_names);
177 d->ident_names = NULL;
181 err = btf_dump_resize(d);
188 return libbpf_err_ptr(err);
191 COMPAT_VERSION(btf_dump__new_deprecated, btf_dump__new, LIBBPF_0.0.4)
192 struct btf_dump *btf_dump__new_deprecated(const struct btf *btf,
193 const struct btf_ext *btf_ext,
194 const struct btf_dump_opts *opts,
195 btf_dump_printf_fn_t printf_fn)
198 return libbpf_err_ptr(-EINVAL);
199 return btf_dump__new_v0_6_0(btf, printf_fn, opts ? opts->ctx : NULL, opts);
202 static int btf_dump_resize(struct btf_dump *d)
204 int err, last_id = btf__type_cnt(d->btf) - 1;
206 if (last_id <= d->last_id)
209 if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
210 sizeof(*d->type_states), last_id + 1))
212 if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
213 sizeof(*d->cached_names), last_id + 1))
216 if (d->last_id == 0) {
217 /* VOID is special */
218 d->type_states[0].order_state = ORDERED;
219 d->type_states[0].emit_state = EMITTED;
222 /* eagerly determine referenced types for anon enums */
223 err = btf_dump_mark_referenced(d);
227 d->last_id = last_id;
231 void btf_dump__free(struct btf_dump *d)
235 if (IS_ERR_OR_NULL(d))
238 free(d->type_states);
239 if (d->cached_names) {
240 /* any set cached name is owned by us and should be freed */
241 for (i = 0; i <= d->last_id; i++) {
242 if (d->cached_names[i])
243 free((void *)d->cached_names[i]);
246 free(d->cached_names);
249 hashmap__free(d->type_names);
250 hashmap__free(d->ident_names);
255 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
256 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
259 * Dump BTF type in a compilable C syntax, including all the necessary
260 * dependent types, necessary for compilation. If some of the dependent types
261 * were already emitted as part of previous btf_dump__dump_type() invocation
262 * for another type, they won't be emitted again. This API allows callers to
263 * filter out BTF types according to user-defined criterias and emitted only
264 * minimal subset of types, necessary to compile everything. Full struct/union
265 * definitions will still be emitted, even if the only usage is through
266 * pointer and could be satisfied with just a forward declaration.
268 * Dumping is done in two high-level passes:
269 * 1. Topologically sort type definitions to satisfy C rules of compilation.
270 * 2. Emit type definitions in C syntax.
272 * Returns 0 on success; <0, otherwise.
274 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
278 if (id >= btf__type_cnt(d->btf))
279 return libbpf_err(-EINVAL);
281 err = btf_dump_resize(d);
283 return libbpf_err(err);
285 d->emit_queue_cnt = 0;
286 err = btf_dump_order_type(d, id, false);
288 return libbpf_err(err);
290 for (i = 0; i < d->emit_queue_cnt; i++)
291 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
297 * Mark all types that are referenced from any other type. This is used to
298 * determine top-level anonymous enums that need to be emitted as an
299 * independent type declarations.
300 * Anonymous enums come in two flavors: either embedded in a struct's field
301 * definition, in which case they have to be declared inline as part of field
302 * type declaration; or as a top-level anonymous enum, typically used for
303 * declaring global constants. It's impossible to distinguish between two
304 * without knowning whether given enum type was referenced from other type:
305 * top-level anonymous enum won't be referenced by anything, while embedded
308 static int btf_dump_mark_referenced(struct btf_dump *d)
310 int i, j, n = btf__type_cnt(d->btf);
311 const struct btf_type *t;
314 for (i = d->last_id + 1; i < n; i++) {
315 t = btf__type_by_id(d->btf, i);
318 switch (btf_kind(t)) {
321 case BTF_KIND_ENUM64:
326 case BTF_KIND_VOLATILE:
328 case BTF_KIND_RESTRICT:
330 case BTF_KIND_TYPEDEF:
333 case BTF_KIND_DECL_TAG:
334 case BTF_KIND_TYPE_TAG:
335 d->type_states[t->type].referenced = 1;
338 case BTF_KIND_ARRAY: {
339 const struct btf_array *a = btf_array(t);
341 d->type_states[a->index_type].referenced = 1;
342 d->type_states[a->type].referenced = 1;
345 case BTF_KIND_STRUCT:
346 case BTF_KIND_UNION: {
347 const struct btf_member *m = btf_members(t);
349 for (j = 0; j < vlen; j++, m++)
350 d->type_states[m->type].referenced = 1;
353 case BTF_KIND_FUNC_PROTO: {
354 const struct btf_param *p = btf_params(t);
356 for (j = 0; j < vlen; j++, p++)
357 d->type_states[p->type].referenced = 1;
360 case BTF_KIND_DATASEC: {
361 const struct btf_var_secinfo *v = btf_var_secinfos(t);
363 for (j = 0; j < vlen; j++, v++)
364 d->type_states[v->type].referenced = 1;
374 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
379 if (d->emit_queue_cnt >= d->emit_queue_cap) {
380 new_cap = max(16, d->emit_queue_cap * 3 / 2);
381 new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
384 d->emit_queue = new_queue;
385 d->emit_queue_cap = new_cap;
388 d->emit_queue[d->emit_queue_cnt++] = id;
393 * Determine order of emitting dependent types and specified type to satisfy
394 * C compilation rules. This is done through topological sorting with an
395 * additional complication which comes from C rules. The main idea for C is
396 * that if some type is "embedded" into a struct/union, it's size needs to be
397 * known at the time of definition of containing type. E.g., for:
400 * struct B { struct A x; }
402 * struct A *HAS* to be defined before struct B, because it's "embedded",
403 * i.e., it is part of struct B layout. But in the following case:
406 * struct B { struct A *x; }
409 * it's enough to just have a forward declaration of struct A at the time of
410 * struct B definition, as struct B has a pointer to struct A, so the size of
411 * field x is known without knowing struct A size: it's sizeof(void *).
413 * Unfortunately, there are some trickier cases we need to handle, e.g.:
415 * struct A {}; // if this was forward-declaration: compilation error
417 * struct { // anonymous struct
422 * In this case, struct B's field x is a pointer, so it's size is known
423 * regardless of the size of (anonymous) struct it points to. But because this
424 * struct is anonymous and thus defined inline inside struct B, *and* it
425 * embeds struct A, compiler requires full definition of struct A to be known
426 * before struct B can be defined. This creates a transitive dependency
427 * between struct A and struct B. If struct A was forward-declared before
428 * struct B definition and fully defined after struct B definition, that would
429 * trigger compilation error.
431 * All this means that while we are doing topological sorting on BTF type
432 * graph, we need to determine relationships between different types (graph
434 * - weak link (relationship) between X and Y, if Y *CAN* be
435 * forward-declared at the point of X definition;
436 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
438 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
439 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
440 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
441 * Weak/strong relationship is determined recursively during DFS traversal and
442 * is returned as a result from btf_dump_order_type().
444 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
445 * but it is not guaranteeing that no extraneous forward declarations will be
448 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
449 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
450 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
451 * entire graph path, so depending where from one came to that BTF type, it
452 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
453 * once they are processed, there is no need to do it again, so they are
454 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
455 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
456 * in any case, once those are processed, no need to do it again, as the
457 * result won't change.
460 * - 1, if type is part of strong link (so there is strong topological
461 * ordering requirements);
462 * - 0, if type is part of weak link (so can be satisfied through forward
464 * - <0, on error (e.g., unsatisfiable type loop detected).
466 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
469 * Order state is used to detect strong link cycles, but only for BTF
470 * kinds that are or could be an independent definition (i.e.,
471 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
472 * func_protos, modifiers are just means to get to these definitions.
473 * Int/void don't need definitions, they are assumed to be always
474 * properly defined. We also ignore datasec, var, and funcs for now.
475 * So for all non-defining kinds, we never even set ordering state,
476 * for defining kinds we set ORDERING and subsequently ORDERED if it
477 * forms a strong link.
479 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
480 const struct btf_type *t;
484 /* return true, letting typedefs know that it's ok to be emitted */
485 if (tstate->order_state == ORDERED)
488 t = btf__type_by_id(d->btf, id);
490 if (tstate->order_state == ORDERING) {
491 /* type loop, but resolvable through fwd declaration */
492 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
494 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
498 switch (btf_kind(t)) {
501 tstate->order_state = ORDERED;
505 err = btf_dump_order_type(d, t->type, true);
506 tstate->order_state = ORDERED;
510 return btf_dump_order_type(d, btf_array(t)->type, false);
512 case BTF_KIND_STRUCT:
513 case BTF_KIND_UNION: {
514 const struct btf_member *m = btf_members(t);
516 * struct/union is part of strong link, only if it's embedded
517 * (so no ptr in a path) or it's anonymous (so has to be
518 * defined inline, even if declared through ptr)
520 if (through_ptr && t->name_off != 0)
523 tstate->order_state = ORDERING;
526 for (i = 0; i < vlen; i++, m++) {
527 err = btf_dump_order_type(d, m->type, false);
532 if (t->name_off != 0) {
533 err = btf_dump_add_emit_queue_id(d, id);
538 tstate->order_state = ORDERED;
542 case BTF_KIND_ENUM64:
545 * non-anonymous or non-referenced enums are top-level
546 * declarations and should be emitted. Same logic can be
547 * applied to FWDs, it won't hurt anyways.
549 if (t->name_off != 0 || !tstate->referenced) {
550 err = btf_dump_add_emit_queue_id(d, id);
554 tstate->order_state = ORDERED;
557 case BTF_KIND_TYPEDEF: {
560 is_strong = btf_dump_order_type(d, t->type, through_ptr);
564 /* typedef is similar to struct/union w.r.t. fwd-decls */
565 if (through_ptr && !is_strong)
568 /* typedef is always a named definition */
569 err = btf_dump_add_emit_queue_id(d, id);
573 d->type_states[id].order_state = ORDERED;
576 case BTF_KIND_VOLATILE:
578 case BTF_KIND_RESTRICT:
579 case BTF_KIND_TYPE_TAG:
580 return btf_dump_order_type(d, t->type, through_ptr);
582 case BTF_KIND_FUNC_PROTO: {
583 const struct btf_param *p = btf_params(t);
586 err = btf_dump_order_type(d, t->type, through_ptr);
592 for (i = 0; i < vlen; i++, p++) {
593 err = btf_dump_order_type(d, p->type, through_ptr);
603 case BTF_KIND_DATASEC:
604 case BTF_KIND_DECL_TAG:
605 d->type_states[id].order_state = ORDERED;
613 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
614 const struct btf_type *t);
616 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
617 const struct btf_type *t);
618 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
619 const struct btf_type *t, int lvl);
621 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
622 const struct btf_type *t);
623 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
624 const struct btf_type *t, int lvl);
626 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
627 const struct btf_type *t);
629 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
630 const struct btf_type *t, int lvl);
632 /* a local view into a shared stack */
638 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
639 const char *fname, int lvl);
640 static void btf_dump_emit_type_chain(struct btf_dump *d,
641 struct id_stack *decl_stack,
642 const char *fname, int lvl);
644 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
645 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
646 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
647 const char *orig_name);
649 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
651 const struct btf_type *t = btf__type_by_id(d->btf, id);
653 /* __builtin_va_list is a compiler built-in, which causes compilation
654 * errors, when compiling w/ different compiler, then used to compile
655 * original code (e.g., GCC to compile kernel, Clang to use generated
656 * C header from BTF). As it is built-in, it should be already defined
657 * properly internally in compiler.
659 if (t->name_off == 0)
661 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
665 * Emit C-syntax definitions of types from chains of BTF types.
667 * High-level handling of determining necessary forward declarations are handled
668 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
669 * declarations/definitions in C syntax are handled by a combo of
670 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
671 * corresponding btf_dump_emit_*_{def,fwd}() functions.
673 * We also keep track of "containing struct/union type ID" to determine when
674 * we reference it from inside and thus can avoid emitting unnecessary forward
677 * This algorithm is designed in such a way, that even if some error occurs
678 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
679 * that doesn't comply to C rules completely), algorithm will try to proceed
680 * and produce as much meaningful output as possible.
682 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
684 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
685 bool top_level_def = cont_id == 0;
686 const struct btf_type *t;
689 if (tstate->emit_state == EMITTED)
692 t = btf__type_by_id(d->btf, id);
695 if (tstate->emit_state == EMITTING) {
696 if (tstate->fwd_emitted)
700 case BTF_KIND_STRUCT:
703 * if we are referencing a struct/union that we are
704 * part of - then no need for fwd declaration
708 if (t->name_off == 0) {
709 pr_warn("anonymous struct/union loop, id:[%u]\n",
713 btf_dump_emit_struct_fwd(d, id, t);
714 btf_dump_printf(d, ";\n\n");
715 tstate->fwd_emitted = 1;
717 case BTF_KIND_TYPEDEF:
719 * for typedef fwd_emitted means typedef definition
720 * was emitted, but it can be used only for "weak"
721 * references through pointer only, not for embedding
723 if (!btf_dump_is_blacklisted(d, id)) {
724 btf_dump_emit_typedef_def(d, id, t, 0);
725 btf_dump_printf(d, ";\n\n");
727 tstate->fwd_emitted = 1;
738 /* Emit type alias definitions if necessary */
739 btf_dump_emit_missing_aliases(d, id, t);
741 tstate->emit_state = EMITTED;
744 case BTF_KIND_ENUM64:
746 btf_dump_emit_enum_def(d, id, t, 0);
747 btf_dump_printf(d, ";\n\n");
749 tstate->emit_state = EMITTED;
752 case BTF_KIND_VOLATILE:
754 case BTF_KIND_RESTRICT:
755 case BTF_KIND_TYPE_TAG:
756 btf_dump_emit_type(d, t->type, cont_id);
759 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
762 btf_dump_emit_fwd_def(d, id, t);
763 btf_dump_printf(d, ";\n\n");
764 tstate->emit_state = EMITTED;
766 case BTF_KIND_TYPEDEF:
767 tstate->emit_state = EMITTING;
768 btf_dump_emit_type(d, t->type, id);
770 * typedef can server as both definition and forward
771 * declaration; at this stage someone depends on
772 * typedef as a forward declaration (refers to it
773 * through pointer), so unless we already did it,
774 * emit typedef as a forward declaration
776 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
777 btf_dump_emit_typedef_def(d, id, t, 0);
778 btf_dump_printf(d, ";\n\n");
780 tstate->emit_state = EMITTED;
782 case BTF_KIND_STRUCT:
784 tstate->emit_state = EMITTING;
785 /* if it's a top-level struct/union definition or struct/union
786 * is anonymous, then in C we'll be emitting all fields and
787 * their types (as opposed to just `struct X`), so we need to
788 * make sure that all types, referenced from struct/union
789 * members have necessary forward-declarations, where
792 if (top_level_def || t->name_off == 0) {
793 const struct btf_member *m = btf_members(t);
794 __u16 vlen = btf_vlen(t);
797 new_cont_id = t->name_off == 0 ? cont_id : id;
798 for (i = 0; i < vlen; i++, m++)
799 btf_dump_emit_type(d, m->type, new_cont_id);
800 } else if (!tstate->fwd_emitted && id != cont_id) {
801 btf_dump_emit_struct_fwd(d, id, t);
802 btf_dump_printf(d, ";\n\n");
803 tstate->fwd_emitted = 1;
807 btf_dump_emit_struct_def(d, id, t, 0);
808 btf_dump_printf(d, ";\n\n");
809 tstate->emit_state = EMITTED;
811 tstate->emit_state = NOT_EMITTED;
814 case BTF_KIND_FUNC_PROTO: {
815 const struct btf_param *p = btf_params(t);
816 __u16 n = btf_vlen(t);
819 btf_dump_emit_type(d, t->type, cont_id);
820 for (i = 0; i < n; i++, p++)
821 btf_dump_emit_type(d, p->type, cont_id);
830 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
831 const struct btf_type *t)
833 const struct btf_member *m;
834 int align, i, bit_sz;
837 align = btf__align_of(btf, id);
838 /* size of a non-packed struct has to be a multiple of its alignment*/
839 if (align && t->size % align)
844 /* all non-bitfield fields have to be naturally aligned */
845 for (i = 0; i < vlen; i++, m++) {
846 align = btf__align_of(btf, m->type);
847 bit_sz = btf_member_bitfield_size(t, i);
848 if (align && bit_sz == 0 && m->offset % (8 * 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 int chip_away_bits(int total, int at_most)
861 return total % at_most ? : at_most;
864 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
865 int cur_off, int m_off, int m_bit_sz,
868 int off_diff = m_off - cur_off;
869 int ptr_bits = d->ptr_sz * 8;
874 if (m_bit_sz == 0 && off_diff < align * 8)
875 /* natural padding will take care of a gap */
878 while (off_diff > 0) {
879 const char *pad_type;
882 if (ptr_bits > 32 && off_diff > 32) {
884 pad_bits = chip_away_bits(off_diff, ptr_bits);
885 } else if (off_diff > 16) {
887 pad_bits = chip_away_bits(off_diff, 32);
888 } else if (off_diff > 8) {
890 pad_bits = chip_away_bits(off_diff, 16);
893 pad_bits = chip_away_bits(off_diff, 8);
895 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
896 off_diff -= pad_bits;
900 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
901 const struct btf_type *t)
903 btf_dump_printf(d, "%s%s%s",
904 btf_is_struct(t) ? "struct" : "union",
905 t->name_off ? " " : "",
906 btf_dump_type_name(d, id));
909 static void btf_dump_emit_struct_def(struct btf_dump *d,
911 const struct btf_type *t,
914 const struct btf_member *m = btf_members(t);
915 bool is_struct = btf_is_struct(t);
916 int align, i, packed, off = 0;
917 __u16 vlen = btf_vlen(t);
919 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
921 btf_dump_printf(d, "%s%s%s {",
922 is_struct ? "struct" : "union",
923 t->name_off ? " " : "",
924 btf_dump_type_name(d, id));
926 for (i = 0; i < vlen; i++, m++) {
930 fname = btf_name_of(d, m->name_off);
931 m_sz = btf_member_bitfield_size(t, i);
932 m_off = btf_member_bit_offset(t, i);
933 align = packed ? 1 : btf__align_of(d->btf, m->type);
935 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
936 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
937 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
940 btf_dump_printf(d, ": %d", m_sz);
943 m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
944 off = m_off + m_sz * 8;
946 btf_dump_printf(d, ";");
949 /* pad at the end, if necessary */
951 align = packed ? 1 : btf__align_of(d->btf, id);
952 btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
957 btf_dump_printf(d, "\n");
958 btf_dump_printf(d, "%s}", pfx(lvl));
960 btf_dump_printf(d, " __attribute__((packed))");
963 static const char *missing_base_types[][2] = {
965 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
966 * SIMD intrinsics. Alias them to standard base types.
968 { "__Poly8_t", "unsigned char" },
969 { "__Poly16_t", "unsigned short" },
970 { "__Poly64_t", "unsigned long long" },
971 { "__Poly128_t", "unsigned __int128" },
974 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
975 const struct btf_type *t)
977 const char *name = btf_dump_type_name(d, id);
980 for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
981 if (strcmp(name, missing_base_types[i][0]) == 0) {
982 btf_dump_printf(d, "typedef %s %s;\n\n",
983 missing_base_types[i][1], name);
989 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
990 const struct btf_type *t)
992 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
995 static void btf_dump_emit_enum32_val(struct btf_dump *d,
996 const struct btf_type *t,
999 const struct btf_enum *v = btf_enum(t);
1000 bool is_signed = btf_kflag(t);
1001 const char *fmt_str;
1006 for (i = 0; i < vlen; i++, v++) {
1007 name = btf_name_of(d, v->name_off);
1008 /* enumerators share namespace with typedef idents */
1009 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1011 fmt_str = is_signed ? "\n%s%s___%zd = %d," : "\n%s%s___%zd = %u,";
1012 btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, dup_cnt, v->val);
1014 fmt_str = is_signed ? "\n%s%s = %d," : "\n%s%s = %u,";
1015 btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, v->val);
1020 static void btf_dump_emit_enum64_val(struct btf_dump *d,
1021 const struct btf_type *t,
1022 int lvl, __u16 vlen)
1024 const struct btf_enum64 *v = btf_enum64(t);
1025 bool is_signed = btf_kflag(t);
1026 const char *fmt_str;
1032 for (i = 0; i < vlen; i++, v++) {
1033 name = btf_name_of(d, v->name_off);
1034 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1035 val = btf_enum64_value(v);
1037 fmt_str = is_signed ? "\n%s%s___%zd = %lldLL,"
1038 : "\n%s%s___%zd = %lluULL,";
1039 btf_dump_printf(d, fmt_str,
1040 pfx(lvl + 1), name, dup_cnt,
1041 (unsigned long long)val);
1043 fmt_str = is_signed ? "\n%s%s = %lldLL,"
1044 : "\n%s%s = %lluULL,";
1045 btf_dump_printf(d, fmt_str,
1047 (unsigned long long)val);
1051 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
1052 const struct btf_type *t,
1055 __u16 vlen = btf_vlen(t);
1057 btf_dump_printf(d, "enum%s%s",
1058 t->name_off ? " " : "",
1059 btf_dump_type_name(d, id));
1064 btf_dump_printf(d, " {");
1066 btf_dump_emit_enum32_val(d, t, lvl, vlen);
1068 btf_dump_emit_enum64_val(d, t, lvl, vlen);
1069 btf_dump_printf(d, "\n%s}", pfx(lvl));
1072 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1073 const struct btf_type *t)
1075 const char *name = btf_dump_type_name(d, id);
1078 btf_dump_printf(d, "union %s", name);
1080 btf_dump_printf(d, "struct %s", name);
1083 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1084 const struct btf_type *t, int lvl)
1086 const char *name = btf_dump_ident_name(d, id);
1089 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
1090 * pointing to VOID. This generates warnings from btf_dump() and
1091 * results in uncompilable header file, so we are fixing it up here
1092 * with valid typedef into __builtin_va_list.
1094 if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1095 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1099 btf_dump_printf(d, "typedef ");
1100 btf_dump_emit_type_decl(d, t->type, name, lvl);
1103 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1108 if (d->decl_stack_cnt >= d->decl_stack_cap) {
1109 new_cap = max(16, d->decl_stack_cap * 3 / 2);
1110 new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
1113 d->decl_stack = new_stack;
1114 d->decl_stack_cap = new_cap;
1117 d->decl_stack[d->decl_stack_cnt++] = id;
1123 * Emit type declaration (e.g., field type declaration in a struct or argument
1124 * declaration in function prototype) in correct C syntax.
1126 * For most types it's trivial, but there are few quirky type declaration
1127 * cases worth mentioning:
1128 * - function prototypes (especially nesting of function prototypes);
1130 * - const/volatile/restrict for pointers vs other types.
1132 * For a good discussion of *PARSING* C syntax (as a human), see
1133 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1134 * Ch.3 "Unscrambling Declarations in C".
1136 * It won't help with BTF to C conversion much, though, as it's an opposite
1137 * problem. So we came up with this algorithm in reverse to van der Linden's
1138 * parsing algorithm. It goes from structured BTF representation of type
1139 * declaration to a valid compilable C syntax.
1141 * For instance, consider this C typedef:
1142 * typedef const int * const * arr[10] arr_t;
1143 * It will be represented in BTF with this chain of BTF types:
1144 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1146 * Notice how [const] modifier always goes before type it modifies in BTF type
1147 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1148 * the right of pointers, but to the left of other types. There are also other
1149 * quirks, like function pointers, arrays of them, functions returning other
1152 * We handle that by pushing all the types to a stack, until we hit "terminal"
1153 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1154 * top of a stack, modifiers are handled differently. Array/function pointers
1155 * have also wildly different syntax and how nesting of them are done. See
1156 * code for authoritative definition.
1158 * To avoid allocating new stack for each independent chain of BTF types, we
1159 * share one bigger stack, with each chain working only on its own local view
1160 * of a stack frame. Some care is required to "pop" stack frames after
1161 * processing type declaration chain.
1163 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1164 const struct btf_dump_emit_type_decl_opts *opts)
1169 if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1170 return libbpf_err(-EINVAL);
1172 err = btf_dump_resize(d);
1174 return libbpf_err(err);
1176 fname = OPTS_GET(opts, field_name, "");
1177 lvl = OPTS_GET(opts, indent_level, 0);
1178 d->strip_mods = OPTS_GET(opts, strip_mods, false);
1179 btf_dump_emit_type_decl(d, id, fname, lvl);
1180 d->strip_mods = false;
1184 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1185 const char *fname, int lvl)
1187 struct id_stack decl_stack;
1188 const struct btf_type *t;
1189 int err, stack_start;
1191 stack_start = d->decl_stack_cnt;
1193 t = btf__type_by_id(d->btf, id);
1194 if (d->strip_mods && btf_is_mod(t))
1197 err = btf_dump_push_decl_stack_id(d, id);
1200 * if we don't have enough memory for entire type decl
1201 * chain, restore stack, emit warning, and try to
1202 * proceed nevertheless
1204 pr_warn("not enough memory for decl stack:%d", err);
1205 d->decl_stack_cnt = stack_start;
1213 switch (btf_kind(t)) {
1215 case BTF_KIND_VOLATILE:
1216 case BTF_KIND_CONST:
1217 case BTF_KIND_RESTRICT:
1218 case BTF_KIND_FUNC_PROTO:
1219 case BTF_KIND_TYPE_TAG:
1222 case BTF_KIND_ARRAY:
1223 id = btf_array(t)->type;
1227 case BTF_KIND_ENUM64:
1229 case BTF_KIND_STRUCT:
1230 case BTF_KIND_UNION:
1231 case BTF_KIND_TYPEDEF:
1232 case BTF_KIND_FLOAT:
1235 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1242 * We might be inside a chain of declarations (e.g., array of function
1243 * pointers returning anonymous (so inlined) structs, having another
1244 * array field). Each of those needs its own "stack frame" to handle
1245 * emitting of declarations. Those stack frames are non-overlapping
1246 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1247 * handle this set of nested stacks, we create a view corresponding to
1248 * our own "stack frame" and work with it as an independent stack.
1249 * We'll need to clean up after emit_type_chain() returns, though.
1251 decl_stack.ids = d->decl_stack + stack_start;
1252 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1253 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1255 * emit_type_chain() guarantees that it will pop its entire decl_stack
1256 * frame before returning. But it works with a read-only view into
1257 * decl_stack, so it doesn't actually pop anything from the
1258 * perspective of shared btf_dump->decl_stack, per se. We need to
1259 * reset decl_stack state to how it was before us to avoid it growing
1262 d->decl_stack_cnt = stack_start;
1265 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1267 const struct btf_type *t;
1270 while (decl_stack->cnt) {
1271 id = decl_stack->ids[decl_stack->cnt - 1];
1272 t = btf__type_by_id(d->btf, id);
1274 switch (btf_kind(t)) {
1275 case BTF_KIND_VOLATILE:
1276 btf_dump_printf(d, "volatile ");
1278 case BTF_KIND_CONST:
1279 btf_dump_printf(d, "const ");
1281 case BTF_KIND_RESTRICT:
1282 btf_dump_printf(d, "restrict ");
1291 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1293 const struct btf_type *t;
1296 while (decl_stack->cnt) {
1297 id = decl_stack->ids[decl_stack->cnt - 1];
1298 t = btf__type_by_id(d->btf, id);
1305 static void btf_dump_emit_name(const struct btf_dump *d,
1306 const char *name, bool last_was_ptr)
1308 bool separate = name[0] && !last_was_ptr;
1310 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1313 static void btf_dump_emit_type_chain(struct btf_dump *d,
1314 struct id_stack *decls,
1315 const char *fname, int lvl)
1318 * last_was_ptr is used to determine if we need to separate pointer
1319 * asterisk (*) from previous part of type signature with space, so
1320 * that we get `int ***`, instead of `int * * *`. We default to true
1321 * for cases where we have single pointer in a chain. E.g., in ptr ->
1322 * func_proto case. func_proto will start a new emit_type_chain call
1323 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1324 * don't want to prepend space for that last pointer.
1326 bool last_was_ptr = true;
1327 const struct btf_type *t;
1332 while (decls->cnt) {
1333 id = decls->ids[--decls->cnt];
1335 /* VOID is a special snowflake */
1336 btf_dump_emit_mods(d, decls);
1337 btf_dump_printf(d, "void");
1338 last_was_ptr = false;
1342 t = btf__type_by_id(d->btf, id);
1347 case BTF_KIND_FLOAT:
1348 btf_dump_emit_mods(d, decls);
1349 name = btf_name_of(d, t->name_off);
1350 btf_dump_printf(d, "%s", name);
1352 case BTF_KIND_STRUCT:
1353 case BTF_KIND_UNION:
1354 btf_dump_emit_mods(d, decls);
1355 /* inline anonymous struct/union */
1356 if (t->name_off == 0 && !d->skip_anon_defs)
1357 btf_dump_emit_struct_def(d, id, t, lvl);
1359 btf_dump_emit_struct_fwd(d, id, t);
1362 case BTF_KIND_ENUM64:
1363 btf_dump_emit_mods(d, decls);
1364 /* inline anonymous enum */
1365 if (t->name_off == 0 && !d->skip_anon_defs)
1366 btf_dump_emit_enum_def(d, id, t, lvl);
1368 btf_dump_emit_enum_fwd(d, id, t);
1371 btf_dump_emit_mods(d, decls);
1372 btf_dump_emit_fwd_def(d, id, t);
1374 case BTF_KIND_TYPEDEF:
1375 btf_dump_emit_mods(d, decls);
1376 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1379 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1381 case BTF_KIND_VOLATILE:
1382 btf_dump_printf(d, " volatile");
1384 case BTF_KIND_CONST:
1385 btf_dump_printf(d, " const");
1387 case BTF_KIND_RESTRICT:
1388 btf_dump_printf(d, " restrict");
1390 case BTF_KIND_TYPE_TAG:
1391 btf_dump_emit_mods(d, decls);
1392 name = btf_name_of(d, t->name_off);
1393 btf_dump_printf(d, " __attribute__((btf_type_tag(\"%s\")))", name);
1395 case BTF_KIND_ARRAY: {
1396 const struct btf_array *a = btf_array(t);
1397 const struct btf_type *next_t;
1402 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1403 * which causes it to emit extra const/volatile
1404 * modifiers for an array, if array's element type has
1405 * const/volatile modifiers. Clang doesn't do that.
1406 * In general, it doesn't seem very meaningful to have
1407 * a const/volatile modifier for array, so we are
1408 * going to silently skip them here.
1410 btf_dump_drop_mods(d, decls);
1412 if (decls->cnt == 0) {
1413 btf_dump_emit_name(d, fname, last_was_ptr);
1414 btf_dump_printf(d, "[%u]", a->nelems);
1418 next_id = decls->ids[decls->cnt - 1];
1419 next_t = btf__type_by_id(d->btf, next_id);
1420 multidim = btf_is_array(next_t);
1421 /* we need space if we have named non-pointer */
1422 if (fname[0] && !last_was_ptr)
1423 btf_dump_printf(d, " ");
1424 /* no parentheses for multi-dimensional array */
1426 btf_dump_printf(d, "(");
1427 btf_dump_emit_type_chain(d, decls, fname, lvl);
1429 btf_dump_printf(d, ")");
1430 btf_dump_printf(d, "[%u]", a->nelems);
1433 case BTF_KIND_FUNC_PROTO: {
1434 const struct btf_param *p = btf_params(t);
1435 __u16 vlen = btf_vlen(t);
1439 * GCC emits extra volatile qualifier for
1440 * __attribute__((noreturn)) function pointers. Clang
1441 * doesn't do it. It's a GCC quirk for backwards
1442 * compatibility with code written for GCC <2.5. So,
1443 * similarly to extra qualifiers for array, just drop
1444 * them, instead of handling them.
1446 btf_dump_drop_mods(d, decls);
1448 btf_dump_printf(d, " (");
1449 btf_dump_emit_type_chain(d, decls, fname, lvl);
1450 btf_dump_printf(d, ")");
1452 btf_dump_emit_name(d, fname, last_was_ptr);
1454 btf_dump_printf(d, "(");
1456 * Clang for BPF target generates func_proto with no
1457 * args as a func_proto with a single void arg (e.g.,
1458 * `int (*f)(void)` vs just `int (*f)()`). We are
1459 * going to pretend there are no args for such case.
1461 if (vlen == 1 && p->type == 0) {
1462 btf_dump_printf(d, ")");
1466 for (i = 0; i < vlen; i++, p++) {
1468 btf_dump_printf(d, ", ");
1470 /* last arg of type void is vararg */
1471 if (i == vlen - 1 && p->type == 0) {
1472 btf_dump_printf(d, "...");
1476 name = btf_name_of(d, p->name_off);
1477 btf_dump_emit_type_decl(d, p->type, name, lvl);
1480 btf_dump_printf(d, ")");
1484 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1489 last_was_ptr = kind == BTF_KIND_PTR;
1492 btf_dump_emit_name(d, fname, last_was_ptr);
1495 /* show type name as (type_name) */
1496 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1499 const struct btf_type *t;
1501 /* for array members, we don't bother emitting type name for each
1502 * member to avoid the redundancy of
1503 * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
1505 if (d->typed_dump->is_array_member)
1508 /* avoid type name specification for variable/section; it will be done
1509 * for the associated variable value(s).
1511 t = btf__type_by_id(d->btf, id);
1512 if (btf_is_var(t) || btf_is_datasec(t))
1516 btf_dump_printf(d, "(");
1518 d->skip_anon_defs = true;
1519 d->strip_mods = true;
1520 btf_dump_emit_type_decl(d, id, "", 0);
1521 d->strip_mods = false;
1522 d->skip_anon_defs = false;
1525 btf_dump_printf(d, ")");
1528 /* return number of duplicates (occurrences) of a given name */
1529 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1530 const char *orig_name)
1534 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1536 hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1541 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1542 struct hashmap *name_map)
1544 struct btf_dump_type_aux_state *s = &d->type_states[id];
1545 const struct btf_type *t = btf__type_by_id(d->btf, id);
1546 const char *orig_name = btf_name_of(d, t->name_off);
1547 const char **cached_name = &d->cached_names[id];
1550 if (t->name_off == 0)
1553 if (s->name_resolved)
1554 return *cached_name ? *cached_name : orig_name;
1556 if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1557 s->name_resolved = 1;
1561 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1563 const size_t max_len = 256;
1564 char new_name[max_len];
1566 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1567 *cached_name = strdup(new_name);
1570 s->name_resolved = 1;
1571 return *cached_name ? *cached_name : orig_name;
1574 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1576 return btf_dump_resolve_name(d, id, d->type_names);
1579 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1581 return btf_dump_resolve_name(d, id, d->ident_names);
1584 static int btf_dump_dump_type_data(struct btf_dump *d,
1586 const struct btf_type *t,
1592 static const char *btf_dump_data_newline(struct btf_dump *d)
1594 return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1597 static const char *btf_dump_data_delim(struct btf_dump *d)
1599 return d->typed_dump->depth == 0 ? "" : ",";
1602 static void btf_dump_data_pfx(struct btf_dump *d)
1604 int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1606 if (d->typed_dump->compact)
1609 for (i = 0; i < lvl; i++)
1610 btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1613 /* A macro is used here as btf_type_value[s]() appends format specifiers
1614 * to the format specifier passed in; these do the work of appending
1615 * delimiters etc while the caller simply has to specify the type values
1616 * in the format specifier + value(s).
1618 #define btf_dump_type_values(d, fmt, ...) \
1619 btf_dump_printf(d, fmt "%s%s", \
1621 btf_dump_data_delim(d), \
1622 btf_dump_data_newline(d))
1624 static int btf_dump_unsupported_data(struct btf_dump *d,
1625 const struct btf_type *t,
1628 btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1632 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1633 const struct btf_type *t,
1639 __u16 left_shift_bits, right_shift_bits;
1640 const __u8 *bytes = data;
1645 /* Maximum supported bitfield size is 64 bits */
1647 pr_warn("unexpected bitfield size %d\n", t->size);
1651 /* Bitfield value retrieval is done in two steps; first relevant bytes are
1652 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1654 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1655 for (i = t->size - 1; i >= 0; i--)
1656 num = num * 256 + bytes[i];
1657 nr_copy_bits = bit_sz + bits_offset;
1658 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1659 for (i = 0; i < t->size; i++)
1660 num = num * 256 + bytes[i];
1661 nr_copy_bits = t->size * 8 - bits_offset;
1663 # error "Unrecognized __BYTE_ORDER__"
1665 left_shift_bits = 64 - nr_copy_bits;
1666 right_shift_bits = 64 - bit_sz;
1668 *value = (num << left_shift_bits) >> right_shift_bits;
1673 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1674 const struct btf_type *t,
1682 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1690 static int btf_dump_bitfield_data(struct btf_dump *d,
1691 const struct btf_type *t,
1699 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1703 btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1708 /* ints, floats and ptrs */
1709 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1710 const struct btf_type *t,
1714 static __u8 bytecmp[16] = {};
1717 /* For pointer types, pointer size is not defined on a per-type basis.
1718 * On dump creation however, we store the pointer size.
1720 if (btf_kind(t) == BTF_KIND_PTR)
1721 nr_bytes = d->ptr_sz;
1725 if (nr_bytes < 1 || nr_bytes > 16) {
1726 pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1730 if (memcmp(data, bytecmp, nr_bytes) == 0)
1735 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1738 int alignment = btf__align_of(btf, type_id);
1743 return ((uintptr_t)data) % alignment == 0;
1746 static int btf_dump_int_data(struct btf_dump *d,
1747 const struct btf_type *t,
1752 __u8 encoding = btf_int_encoding(t);
1753 bool sign = encoding & BTF_INT_SIGNED;
1754 char buf[16] __attribute__((aligned(16)));
1757 if (sz == 0 || sz > sizeof(buf)) {
1758 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1762 /* handle packed int data - accesses of integers not aligned on
1763 * int boundaries can cause problems on some platforms.
1765 if (!ptr_is_aligned(d->btf, type_id, data)) {
1766 memcpy(buf, data, sz);
1772 const __u64 *ints = data;
1775 /* avoid use of __int128 as some 32-bit platforms do not
1778 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1781 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1785 # error "Unrecognized __BYTE_ORDER__"
1788 btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1790 btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1791 (unsigned long long)lsi);
1796 btf_dump_type_values(d, "%lld", *(long long *)data);
1798 btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1802 btf_dump_type_values(d, "%d", *(__s32 *)data);
1804 btf_dump_type_values(d, "%u", *(__u32 *)data);
1808 btf_dump_type_values(d, "%d", *(__s16 *)data);
1810 btf_dump_type_values(d, "%u", *(__u16 *)data);
1813 if (d->typed_dump->is_array_char) {
1814 /* check for null terminator */
1815 if (d->typed_dump->is_array_terminated)
1817 if (*(char *)data == '\0') {
1818 d->typed_dump->is_array_terminated = true;
1821 if (isprint(*(char *)data)) {
1822 btf_dump_type_values(d, "'%c'", *(char *)data);
1827 btf_dump_type_values(d, "%d", *(__s8 *)data);
1829 btf_dump_type_values(d, "%u", *(__u8 *)data);
1832 pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1844 static int btf_dump_float_data(struct btf_dump *d,
1845 const struct btf_type *t,
1849 const union float_data *flp = data;
1850 union float_data fl;
1853 /* handle unaligned data; copy to local union */
1854 if (!ptr_is_aligned(d->btf, type_id, data)) {
1855 memcpy(&fl, data, sz);
1861 btf_dump_type_values(d, "%Lf", flp->ld);
1864 btf_dump_type_values(d, "%lf", flp->d);
1867 btf_dump_type_values(d, "%f", flp->f);
1870 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1876 static int btf_dump_var_data(struct btf_dump *d,
1877 const struct btf_type *v,
1881 enum btf_func_linkage linkage = btf_var(v)->linkage;
1882 const struct btf_type *t;
1887 case BTF_FUNC_STATIC:
1890 case BTF_FUNC_EXTERN:
1893 case BTF_FUNC_GLOBAL:
1899 /* format of output here is [linkage] [type] [varname] = (type)value,
1900 * for example "static int cpu_profile_flip = (int)1"
1902 btf_dump_printf(d, "%s", l);
1904 t = btf__type_by_id(d->btf, type_id);
1905 btf_dump_emit_type_cast(d, type_id, false);
1906 btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
1907 return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
1910 static int btf_dump_array_data(struct btf_dump *d,
1911 const struct btf_type *t,
1915 const struct btf_array *array = btf_array(t);
1916 const struct btf_type *elem_type;
1917 __u32 i, elem_type_id;
1919 bool is_array_member;
1921 elem_type_id = array->type;
1922 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
1923 elem_size = btf__resolve_size(d->btf, elem_type_id);
1924 if (elem_size <= 0) {
1925 pr_warn("unexpected elem size %zd for array type [%u]\n",
1926 (ssize_t)elem_size, id);
1930 if (btf_is_int(elem_type)) {
1932 * BTF_INT_CHAR encoding never seems to be set for
1933 * char arrays, so if size is 1 and element is
1934 * printable as a char, we'll do that.
1937 d->typed_dump->is_array_char = true;
1940 /* note that we increment depth before calling btf_dump_print() below;
1941 * this is intentional. btf_dump_data_newline() will not print a
1942 * newline for depth 0 (since this leaves us with trailing newlines
1943 * at the end of typed display), so depth is incremented first.
1944 * For similar reasons, we decrement depth before showing the closing
1947 d->typed_dump->depth++;
1948 btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
1950 /* may be a multidimensional array, so store current "is array member"
1951 * status so we can restore it correctly later.
1953 is_array_member = d->typed_dump->is_array_member;
1954 d->typed_dump->is_array_member = true;
1955 for (i = 0; i < array->nelems; i++, data += elem_size) {
1956 if (d->typed_dump->is_array_terminated)
1958 btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
1960 d->typed_dump->is_array_member = is_array_member;
1961 d->typed_dump->depth--;
1962 btf_dump_data_pfx(d);
1963 btf_dump_type_values(d, "]");
1968 static int btf_dump_struct_data(struct btf_dump *d,
1969 const struct btf_type *t,
1973 const struct btf_member *m = btf_members(t);
1974 __u16 n = btf_vlen(t);
1977 /* note that we increment depth before calling btf_dump_print() below;
1978 * this is intentional. btf_dump_data_newline() will not print a
1979 * newline for depth 0 (since this leaves us with trailing newlines
1980 * at the end of typed display), so depth is incremented first.
1981 * For similar reasons, we decrement depth before showing the closing
1984 d->typed_dump->depth++;
1985 btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
1987 for (i = 0; i < n; i++, m++) {
1988 const struct btf_type *mtype;
1993 mtype = btf__type_by_id(d->btf, m->type);
1994 mname = btf_name_of(d, m->name_off);
1995 moffset = btf_member_bit_offset(t, i);
1997 bit_sz = btf_member_bitfield_size(t, i);
1998 err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
1999 moffset % 8, bit_sz);
2003 d->typed_dump->depth--;
2004 btf_dump_data_pfx(d);
2005 btf_dump_type_values(d, "}");
2011 unsigned long long lp;
2014 static int btf_dump_ptr_data(struct btf_dump *d,
2015 const struct btf_type *t,
2019 if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
2020 btf_dump_type_values(d, "%p", *(void **)data);
2024 memcpy(&pt, data, d->ptr_sz);
2026 btf_dump_type_values(d, "0x%x", pt.p);
2028 btf_dump_type_values(d, "0x%llx", pt.lp);
2033 static int btf_dump_get_enum_value(struct btf_dump *d,
2034 const struct btf_type *t,
2039 bool is_signed = btf_kflag(t);
2041 if (!ptr_is_aligned(d->btf, id, data)) {
2045 err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
2048 *value = (__s64)val;
2054 *value = *(__s64 *)data;
2057 *value = is_signed ? *(__s32 *)data : *(__u32 *)data;
2060 *value = is_signed ? *(__s16 *)data : *(__u16 *)data;
2063 *value = is_signed ? *(__s8 *)data : *(__u8 *)data;
2066 pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
2071 static int btf_dump_enum_data(struct btf_dump *d,
2072 const struct btf_type *t,
2080 err = btf_dump_get_enum_value(d, t, data, id, &value);
2084 is_signed = btf_kflag(t);
2085 if (btf_is_enum(t)) {
2086 const struct btf_enum *e;
2088 for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2089 if (value != e->val)
2091 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2095 btf_dump_type_values(d, is_signed ? "%d" : "%u", value);
2097 const struct btf_enum64 *e;
2099 for (i = 0, e = btf_enum64(t); i < btf_vlen(t); i++, e++) {
2100 if (value != btf_enum64_value(e))
2102 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2106 btf_dump_type_values(d, is_signed ? "%lldLL" : "%lluULL",
2107 (unsigned long long)value);
2112 static int btf_dump_datasec_data(struct btf_dump *d,
2113 const struct btf_type *t,
2117 const struct btf_var_secinfo *vsi;
2118 const struct btf_type *var;
2122 btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2124 for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2125 var = btf__type_by_id(d->btf, vsi->type);
2126 err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2129 btf_dump_printf(d, ";");
2134 /* return size of type, or if base type overflows, return -E2BIG. */
2135 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2136 const struct btf_type *t,
2141 __s64 size = btf__resolve_size(d->btf, id);
2143 if (size < 0 || size >= INT_MAX) {
2144 pr_warn("unexpected size [%zu] for id [%u]\n",
2149 /* Only do overflow checking for base types; we do not want to
2150 * avoid showing part of a struct, union or array, even if we
2151 * do not have enough data to show the full object. By
2152 * restricting overflow checking to base types we can ensure
2153 * that partial display succeeds, while avoiding overflowing
2154 * and using bogus data for display.
2156 t = skip_mods_and_typedefs(d->btf, id, NULL);
2158 pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2163 switch (btf_kind(t)) {
2165 case BTF_KIND_FLOAT:
2168 case BTF_KIND_ENUM64:
2169 if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2178 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2179 const struct btf_type *t,
2188 /* toplevel exceptions; we show zero values if
2189 * - we ask for them (emit_zeros)
2190 * - if we are at top-level so we see "struct empty { }"
2191 * - or if we are an array member and the array is non-empty and
2192 * not a char array; we don't want to be in a situation where we
2193 * have an integer array 0, 1, 0, 1 and only show non-zero values.
2194 * If the array contains zeroes only, or is a char array starting
2195 * with a '\0', the array-level check_zero() will prevent showing it;
2196 * we are concerned with determining zero value at the array member
2199 if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2200 (d->typed_dump->is_array_member &&
2201 !d->typed_dump->is_array_char))
2204 t = skip_mods_and_typedefs(d->btf, id, NULL);
2206 switch (btf_kind(t)) {
2209 return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2210 return btf_dump_base_type_check_zero(d, t, id, data);
2211 case BTF_KIND_FLOAT:
2213 return btf_dump_base_type_check_zero(d, t, id, data);
2214 case BTF_KIND_ARRAY: {
2215 const struct btf_array *array = btf_array(t);
2216 const struct btf_type *elem_type;
2217 __u32 elem_type_id, elem_size;
2220 elem_type_id = array->type;
2221 elem_size = btf__resolve_size(d->btf, elem_type_id);
2222 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2224 ischar = btf_is_int(elem_type) && elem_size == 1;
2226 /* check all elements; if _any_ element is nonzero, all
2227 * of array is displayed. We make an exception however
2228 * for char arrays where the first element is 0; these
2229 * are considered zeroed also, even if later elements are
2230 * non-zero because the string is terminated.
2232 for (i = 0; i < array->nelems; i++) {
2233 if (i == 0 && ischar && *(char *)data == 0)
2235 err = btf_dump_type_data_check_zero(d, elem_type,
2240 if (err != -ENODATA)
2245 case BTF_KIND_STRUCT:
2246 case BTF_KIND_UNION: {
2247 const struct btf_member *m = btf_members(t);
2248 __u16 n = btf_vlen(t);
2250 /* if any struct/union member is non-zero, the struct/union
2251 * is considered non-zero and dumped.
2253 for (i = 0; i < n; i++, m++) {
2254 const struct btf_type *mtype;
2257 mtype = btf__type_by_id(d->btf, m->type);
2258 moffset = btf_member_bit_offset(t, i);
2260 /* btf_int_bits() does not store member bitfield size;
2261 * bitfield size needs to be stored here so int display
2262 * of member can retrieve it.
2264 bit_sz = btf_member_bitfield_size(t, i);
2265 err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2266 moffset % 8, bit_sz);
2273 case BTF_KIND_ENUM64:
2274 err = btf_dump_get_enum_value(d, t, data, id, &value);
2285 /* returns size of data dumped, or error. */
2286 static int btf_dump_dump_type_data(struct btf_dump *d,
2288 const struct btf_type *t,
2296 size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2299 err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2301 /* zeroed data is expected and not an error, so simply skip
2302 * dumping such data. Record other errors however.
2304 if (err == -ENODATA)
2308 btf_dump_data_pfx(d);
2310 if (!d->typed_dump->skip_names) {
2311 if (fname && strlen(fname) > 0)
2312 btf_dump_printf(d, ".%s = ", fname);
2313 btf_dump_emit_type_cast(d, id, true);
2316 t = skip_mods_and_typedefs(d->btf, id, NULL);
2318 switch (btf_kind(t)) {
2322 case BTF_KIND_FUNC_PROTO:
2323 case BTF_KIND_DECL_TAG:
2324 err = btf_dump_unsupported_data(d, t, id);
2328 err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2330 err = btf_dump_int_data(d, t, id, data, bits_offset);
2332 case BTF_KIND_FLOAT:
2333 err = btf_dump_float_data(d, t, id, data);
2336 err = btf_dump_ptr_data(d, t, id, data);
2338 case BTF_KIND_ARRAY:
2339 err = btf_dump_array_data(d, t, id, data);
2341 case BTF_KIND_STRUCT:
2342 case BTF_KIND_UNION:
2343 err = btf_dump_struct_data(d, t, id, data);
2346 case BTF_KIND_ENUM64:
2347 /* handle bitfield and int enum values */
2352 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2356 enum_val = (__s64)print_num;
2357 err = btf_dump_enum_data(d, t, id, &enum_val);
2359 err = btf_dump_enum_data(d, t, id, data);
2362 err = btf_dump_var_data(d, t, id, data);
2364 case BTF_KIND_DATASEC:
2365 err = btf_dump_datasec_data(d, t, id, data);
2368 pr_warn("unexpected kind [%u] for id [%u]\n",
2369 BTF_INFO_KIND(t->info), id);
2377 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2378 const void *data, size_t data_sz,
2379 const struct btf_dump_type_data_opts *opts)
2381 struct btf_dump_data typed_dump = {};
2382 const struct btf_type *t;
2385 if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2386 return libbpf_err(-EINVAL);
2388 t = btf__type_by_id(d->btf, id);
2390 return libbpf_err(-ENOENT);
2392 d->typed_dump = &typed_dump;
2393 d->typed_dump->data_end = data + data_sz;
2394 d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2396 /* default indent string is a tab */
2397 if (!opts->indent_str)
2398 d->typed_dump->indent_str[0] = '\t';
2400 libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
2401 sizeof(d->typed_dump->indent_str));
2403 d->typed_dump->compact = OPTS_GET(opts, compact, false);
2404 d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2405 d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2407 ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2409 d->typed_dump = NULL;
2411 return libbpf_err(ret);