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)) {
325 case BTF_KIND_VOLATILE:
327 case BTF_KIND_RESTRICT:
329 case BTF_KIND_TYPEDEF:
332 case BTF_KIND_DECL_TAG:
333 case BTF_KIND_TYPE_TAG:
334 d->type_states[t->type].referenced = 1;
337 case BTF_KIND_ARRAY: {
338 const struct btf_array *a = btf_array(t);
340 d->type_states[a->index_type].referenced = 1;
341 d->type_states[a->type].referenced = 1;
344 case BTF_KIND_STRUCT:
345 case BTF_KIND_UNION: {
346 const struct btf_member *m = btf_members(t);
348 for (j = 0; j < vlen; j++, m++)
349 d->type_states[m->type].referenced = 1;
352 case BTF_KIND_FUNC_PROTO: {
353 const struct btf_param *p = btf_params(t);
355 for (j = 0; j < vlen; j++, p++)
356 d->type_states[p->type].referenced = 1;
359 case BTF_KIND_DATASEC: {
360 const struct btf_var_secinfo *v = btf_var_secinfos(t);
362 for (j = 0; j < vlen; j++, v++)
363 d->type_states[v->type].referenced = 1;
373 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
378 if (d->emit_queue_cnt >= d->emit_queue_cap) {
379 new_cap = max(16, d->emit_queue_cap * 3 / 2);
380 new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
383 d->emit_queue = new_queue;
384 d->emit_queue_cap = new_cap;
387 d->emit_queue[d->emit_queue_cnt++] = id;
392 * Determine order of emitting dependent types and specified type to satisfy
393 * C compilation rules. This is done through topological sorting with an
394 * additional complication which comes from C rules. The main idea for C is
395 * that if some type is "embedded" into a struct/union, it's size needs to be
396 * known at the time of definition of containing type. E.g., for:
399 * struct B { struct A x; }
401 * struct A *HAS* to be defined before struct B, because it's "embedded",
402 * i.e., it is part of struct B layout. But in the following case:
405 * struct B { struct A *x; }
408 * it's enough to just have a forward declaration of struct A at the time of
409 * struct B definition, as struct B has a pointer to struct A, so the size of
410 * field x is known without knowing struct A size: it's sizeof(void *).
412 * Unfortunately, there are some trickier cases we need to handle, e.g.:
414 * struct A {}; // if this was forward-declaration: compilation error
416 * struct { // anonymous struct
421 * In this case, struct B's field x is a pointer, so it's size is known
422 * regardless of the size of (anonymous) struct it points to. But because this
423 * struct is anonymous and thus defined inline inside struct B, *and* it
424 * embeds struct A, compiler requires full definition of struct A to be known
425 * before struct B can be defined. This creates a transitive dependency
426 * between struct A and struct B. If struct A was forward-declared before
427 * struct B definition and fully defined after struct B definition, that would
428 * trigger compilation error.
430 * All this means that while we are doing topological sorting on BTF type
431 * graph, we need to determine relationships between different types (graph
433 * - weak link (relationship) between X and Y, if Y *CAN* be
434 * forward-declared at the point of X definition;
435 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
437 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
438 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
439 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
440 * Weak/strong relationship is determined recursively during DFS traversal and
441 * is returned as a result from btf_dump_order_type().
443 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
444 * but it is not guaranteeing that no extraneous forward declarations will be
447 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
448 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
449 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
450 * entire graph path, so depending where from one came to that BTF type, it
451 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
452 * once they are processed, there is no need to do it again, so they are
453 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
454 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
455 * in any case, once those are processed, no need to do it again, as the
456 * result won't change.
459 * - 1, if type is part of strong link (so there is strong topological
460 * ordering requirements);
461 * - 0, if type is part of weak link (so can be satisfied through forward
463 * - <0, on error (e.g., unsatisfiable type loop detected).
465 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
468 * Order state is used to detect strong link cycles, but only for BTF
469 * kinds that are or could be an independent definition (i.e.,
470 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
471 * func_protos, modifiers are just means to get to these definitions.
472 * Int/void don't need definitions, they are assumed to be always
473 * properly defined. We also ignore datasec, var, and funcs for now.
474 * So for all non-defining kinds, we never even set ordering state,
475 * for defining kinds we set ORDERING and subsequently ORDERED if it
476 * forms a strong link.
478 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
479 const struct btf_type *t;
483 /* return true, letting typedefs know that it's ok to be emitted */
484 if (tstate->order_state == ORDERED)
487 t = btf__type_by_id(d->btf, id);
489 if (tstate->order_state == ORDERING) {
490 /* type loop, but resolvable through fwd declaration */
491 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
493 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
497 switch (btf_kind(t)) {
500 tstate->order_state = ORDERED;
504 err = btf_dump_order_type(d, t->type, true);
505 tstate->order_state = ORDERED;
509 return btf_dump_order_type(d, btf_array(t)->type, false);
511 case BTF_KIND_STRUCT:
512 case BTF_KIND_UNION: {
513 const struct btf_member *m = btf_members(t);
515 * struct/union is part of strong link, only if it's embedded
516 * (so no ptr in a path) or it's anonymous (so has to be
517 * defined inline, even if declared through ptr)
519 if (through_ptr && t->name_off != 0)
522 tstate->order_state = ORDERING;
525 for (i = 0; i < vlen; i++, m++) {
526 err = btf_dump_order_type(d, m->type, false);
531 if (t->name_off != 0) {
532 err = btf_dump_add_emit_queue_id(d, id);
537 tstate->order_state = ORDERED;
543 * non-anonymous or non-referenced enums are top-level
544 * declarations and should be emitted. Same logic can be
545 * applied to FWDs, it won't hurt anyways.
547 if (t->name_off != 0 || !tstate->referenced) {
548 err = btf_dump_add_emit_queue_id(d, id);
552 tstate->order_state = ORDERED;
555 case BTF_KIND_TYPEDEF: {
558 is_strong = btf_dump_order_type(d, t->type, through_ptr);
562 /* typedef is similar to struct/union w.r.t. fwd-decls */
563 if (through_ptr && !is_strong)
566 /* typedef is always a named definition */
567 err = btf_dump_add_emit_queue_id(d, id);
571 d->type_states[id].order_state = ORDERED;
574 case BTF_KIND_VOLATILE:
576 case BTF_KIND_RESTRICT:
577 case BTF_KIND_TYPE_TAG:
578 return btf_dump_order_type(d, t->type, through_ptr);
580 case BTF_KIND_FUNC_PROTO: {
581 const struct btf_param *p = btf_params(t);
584 err = btf_dump_order_type(d, t->type, through_ptr);
590 for (i = 0; i < vlen; i++, p++) {
591 err = btf_dump_order_type(d, p->type, through_ptr);
601 case BTF_KIND_DATASEC:
602 case BTF_KIND_DECL_TAG:
603 d->type_states[id].order_state = ORDERED;
611 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
612 const struct btf_type *t);
614 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
615 const struct btf_type *t);
616 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
617 const struct btf_type *t, int lvl);
619 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
620 const struct btf_type *t);
621 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
622 const struct btf_type *t, int lvl);
624 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
625 const struct btf_type *t);
627 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
628 const struct btf_type *t, int lvl);
630 /* a local view into a shared stack */
636 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
637 const char *fname, int lvl);
638 static void btf_dump_emit_type_chain(struct btf_dump *d,
639 struct id_stack *decl_stack,
640 const char *fname, int lvl);
642 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
643 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
644 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
645 const char *orig_name);
647 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
649 const struct btf_type *t = btf__type_by_id(d->btf, id);
651 /* __builtin_va_list is a compiler built-in, which causes compilation
652 * errors, when compiling w/ different compiler, then used to compile
653 * original code (e.g., GCC to compile kernel, Clang to use generated
654 * C header from BTF). As it is built-in, it should be already defined
655 * properly internally in compiler.
657 if (t->name_off == 0)
659 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
663 * Emit C-syntax definitions of types from chains of BTF types.
665 * High-level handling of determining necessary forward declarations are handled
666 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
667 * declarations/definitions in C syntax are handled by a combo of
668 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
669 * corresponding btf_dump_emit_*_{def,fwd}() functions.
671 * We also keep track of "containing struct/union type ID" to determine when
672 * we reference it from inside and thus can avoid emitting unnecessary forward
675 * This algorithm is designed in such a way, that even if some error occurs
676 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
677 * that doesn't comply to C rules completely), algorithm will try to proceed
678 * and produce as much meaningful output as possible.
680 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
682 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
683 bool top_level_def = cont_id == 0;
684 const struct btf_type *t;
687 if (tstate->emit_state == EMITTED)
690 t = btf__type_by_id(d->btf, id);
693 if (tstate->emit_state == EMITTING) {
694 if (tstate->fwd_emitted)
698 case BTF_KIND_STRUCT:
701 * if we are referencing a struct/union that we are
702 * part of - then no need for fwd declaration
706 if (t->name_off == 0) {
707 pr_warn("anonymous struct/union loop, id:[%u]\n",
711 btf_dump_emit_struct_fwd(d, id, t);
712 btf_dump_printf(d, ";\n\n");
713 tstate->fwd_emitted = 1;
715 case BTF_KIND_TYPEDEF:
717 * for typedef fwd_emitted means typedef definition
718 * was emitted, but it can be used only for "weak"
719 * references through pointer only, not for embedding
721 if (!btf_dump_is_blacklisted(d, id)) {
722 btf_dump_emit_typedef_def(d, id, t, 0);
723 btf_dump_printf(d, ";\n\n");
725 tstate->fwd_emitted = 1;
736 /* Emit type alias definitions if necessary */
737 btf_dump_emit_missing_aliases(d, id, t);
739 tstate->emit_state = EMITTED;
743 btf_dump_emit_enum_def(d, id, t, 0);
744 btf_dump_printf(d, ";\n\n");
746 tstate->emit_state = EMITTED;
749 case BTF_KIND_VOLATILE:
751 case BTF_KIND_RESTRICT:
752 case BTF_KIND_TYPE_TAG:
753 btf_dump_emit_type(d, t->type, cont_id);
756 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
759 btf_dump_emit_fwd_def(d, id, t);
760 btf_dump_printf(d, ";\n\n");
761 tstate->emit_state = EMITTED;
763 case BTF_KIND_TYPEDEF:
764 tstate->emit_state = EMITTING;
765 btf_dump_emit_type(d, t->type, id);
767 * typedef can server as both definition and forward
768 * declaration; at this stage someone depends on
769 * typedef as a forward declaration (refers to it
770 * through pointer), so unless we already did it,
771 * emit typedef as a forward declaration
773 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
774 btf_dump_emit_typedef_def(d, id, t, 0);
775 btf_dump_printf(d, ";\n\n");
777 tstate->emit_state = EMITTED;
779 case BTF_KIND_STRUCT:
781 tstate->emit_state = EMITTING;
782 /* if it's a top-level struct/union definition or struct/union
783 * is anonymous, then in C we'll be emitting all fields and
784 * their types (as opposed to just `struct X`), so we need to
785 * make sure that all types, referenced from struct/union
786 * members have necessary forward-declarations, where
789 if (top_level_def || t->name_off == 0) {
790 const struct btf_member *m = btf_members(t);
791 __u16 vlen = btf_vlen(t);
794 new_cont_id = t->name_off == 0 ? cont_id : id;
795 for (i = 0; i < vlen; i++, m++)
796 btf_dump_emit_type(d, m->type, new_cont_id);
797 } else if (!tstate->fwd_emitted && id != cont_id) {
798 btf_dump_emit_struct_fwd(d, id, t);
799 btf_dump_printf(d, ";\n\n");
800 tstate->fwd_emitted = 1;
804 btf_dump_emit_struct_def(d, id, t, 0);
805 btf_dump_printf(d, ";\n\n");
806 tstate->emit_state = EMITTED;
808 tstate->emit_state = NOT_EMITTED;
811 case BTF_KIND_FUNC_PROTO: {
812 const struct btf_param *p = btf_params(t);
813 __u16 n = btf_vlen(t);
816 btf_dump_emit_type(d, t->type, cont_id);
817 for (i = 0; i < n; i++, p++)
818 btf_dump_emit_type(d, p->type, cont_id);
827 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
828 const struct btf_type *t)
830 const struct btf_member *m;
831 int align, i, bit_sz;
834 align = btf__align_of(btf, id);
835 /* size of a non-packed struct has to be a multiple of its alignment*/
836 if (align && t->size % align)
841 /* all non-bitfield fields have to be naturally aligned */
842 for (i = 0; i < vlen; i++, m++) {
843 align = btf__align_of(btf, m->type);
844 bit_sz = btf_member_bitfield_size(t, i);
845 if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
850 * if original struct was marked as packed, but its layout is
851 * naturally aligned, we'll detect that it's not packed
856 static int chip_away_bits(int total, int at_most)
858 return total % at_most ? : at_most;
861 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
862 int cur_off, int m_off, int m_bit_sz,
865 int off_diff = m_off - cur_off;
866 int ptr_bits = d->ptr_sz * 8;
871 if (m_bit_sz == 0 && off_diff < align * 8)
872 /* natural padding will take care of a gap */
875 while (off_diff > 0) {
876 const char *pad_type;
879 if (ptr_bits > 32 && off_diff > 32) {
881 pad_bits = chip_away_bits(off_diff, ptr_bits);
882 } else if (off_diff > 16) {
884 pad_bits = chip_away_bits(off_diff, 32);
885 } else if (off_diff > 8) {
887 pad_bits = chip_away_bits(off_diff, 16);
890 pad_bits = chip_away_bits(off_diff, 8);
892 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
893 off_diff -= pad_bits;
897 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
898 const struct btf_type *t)
900 btf_dump_printf(d, "%s%s%s",
901 btf_is_struct(t) ? "struct" : "union",
902 t->name_off ? " " : "",
903 btf_dump_type_name(d, id));
906 static void btf_dump_emit_struct_def(struct btf_dump *d,
908 const struct btf_type *t,
911 const struct btf_member *m = btf_members(t);
912 bool is_struct = btf_is_struct(t);
913 int align, i, packed, off = 0;
914 __u16 vlen = btf_vlen(t);
916 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
918 btf_dump_printf(d, "%s%s%s {",
919 is_struct ? "struct" : "union",
920 t->name_off ? " " : "",
921 btf_dump_type_name(d, id));
923 for (i = 0; i < vlen; i++, m++) {
927 fname = btf_name_of(d, m->name_off);
928 m_sz = btf_member_bitfield_size(t, i);
929 m_off = btf_member_bit_offset(t, i);
930 align = packed ? 1 : btf__align_of(d->btf, m->type);
932 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
933 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
934 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
937 btf_dump_printf(d, ": %d", m_sz);
940 m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
941 off = m_off + m_sz * 8;
943 btf_dump_printf(d, ";");
946 /* pad at the end, if necessary */
948 align = packed ? 1 : btf__align_of(d->btf, id);
949 btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
954 btf_dump_printf(d, "\n");
955 btf_dump_printf(d, "%s}", pfx(lvl));
957 btf_dump_printf(d, " __attribute__((packed))");
960 static const char *missing_base_types[][2] = {
962 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
963 * SIMD intrinsics. Alias them to standard base types.
965 { "__Poly8_t", "unsigned char" },
966 { "__Poly16_t", "unsigned short" },
967 { "__Poly64_t", "unsigned long long" },
968 { "__Poly128_t", "unsigned __int128" },
971 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
972 const struct btf_type *t)
974 const char *name = btf_dump_type_name(d, id);
977 for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
978 if (strcmp(name, missing_base_types[i][0]) == 0) {
979 btf_dump_printf(d, "typedef %s %s;\n\n",
980 missing_base_types[i][1], name);
986 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
987 const struct btf_type *t)
989 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
992 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
993 const struct btf_type *t,
996 const struct btf_enum *v = btf_enum(t);
997 __u16 vlen = btf_vlen(t);
1002 btf_dump_printf(d, "enum%s%s",
1003 t->name_off ? " " : "",
1004 btf_dump_type_name(d, id));
1007 btf_dump_printf(d, " {");
1008 for (i = 0; i < vlen; i++, v++) {
1009 name = btf_name_of(d, v->name_off);
1010 /* enumerators share namespace with typedef idents */
1011 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1013 btf_dump_printf(d, "\n%s%s___%zu = %u,",
1014 pfx(lvl + 1), name, dup_cnt,
1017 btf_dump_printf(d, "\n%s%s = %u,",
1022 btf_dump_printf(d, "\n%s}", pfx(lvl));
1026 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1027 const struct btf_type *t)
1029 const char *name = btf_dump_type_name(d, id);
1032 btf_dump_printf(d, "union %s", name);
1034 btf_dump_printf(d, "struct %s", name);
1037 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1038 const struct btf_type *t, int lvl)
1040 const char *name = btf_dump_ident_name(d, id);
1043 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
1044 * pointing to VOID. This generates warnings from btf_dump() and
1045 * results in uncompilable header file, so we are fixing it up here
1046 * with valid typedef into __builtin_va_list.
1048 if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1049 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1053 btf_dump_printf(d, "typedef ");
1054 btf_dump_emit_type_decl(d, t->type, name, lvl);
1057 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1062 if (d->decl_stack_cnt >= d->decl_stack_cap) {
1063 new_cap = max(16, d->decl_stack_cap * 3 / 2);
1064 new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
1067 d->decl_stack = new_stack;
1068 d->decl_stack_cap = new_cap;
1071 d->decl_stack[d->decl_stack_cnt++] = id;
1077 * Emit type declaration (e.g., field type declaration in a struct or argument
1078 * declaration in function prototype) in correct C syntax.
1080 * For most types it's trivial, but there are few quirky type declaration
1081 * cases worth mentioning:
1082 * - function prototypes (especially nesting of function prototypes);
1084 * - const/volatile/restrict for pointers vs other types.
1086 * For a good discussion of *PARSING* C syntax (as a human), see
1087 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1088 * Ch.3 "Unscrambling Declarations in C".
1090 * It won't help with BTF to C conversion much, though, as it's an opposite
1091 * problem. So we came up with this algorithm in reverse to van der Linden's
1092 * parsing algorithm. It goes from structured BTF representation of type
1093 * declaration to a valid compilable C syntax.
1095 * For instance, consider this C typedef:
1096 * typedef const int * const * arr[10] arr_t;
1097 * It will be represented in BTF with this chain of BTF types:
1098 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1100 * Notice how [const] modifier always goes before type it modifies in BTF type
1101 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1102 * the right of pointers, but to the left of other types. There are also other
1103 * quirks, like function pointers, arrays of them, functions returning other
1106 * We handle that by pushing all the types to a stack, until we hit "terminal"
1107 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1108 * top of a stack, modifiers are handled differently. Array/function pointers
1109 * have also wildly different syntax and how nesting of them are done. See
1110 * code for authoritative definition.
1112 * To avoid allocating new stack for each independent chain of BTF types, we
1113 * share one bigger stack, with each chain working only on its own local view
1114 * of a stack frame. Some care is required to "pop" stack frames after
1115 * processing type declaration chain.
1117 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1118 const struct btf_dump_emit_type_decl_opts *opts)
1123 if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1124 return libbpf_err(-EINVAL);
1126 err = btf_dump_resize(d);
1128 return libbpf_err(err);
1130 fname = OPTS_GET(opts, field_name, "");
1131 lvl = OPTS_GET(opts, indent_level, 0);
1132 d->strip_mods = OPTS_GET(opts, strip_mods, false);
1133 btf_dump_emit_type_decl(d, id, fname, lvl);
1134 d->strip_mods = false;
1138 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1139 const char *fname, int lvl)
1141 struct id_stack decl_stack;
1142 const struct btf_type *t;
1143 int err, stack_start;
1145 stack_start = d->decl_stack_cnt;
1147 t = btf__type_by_id(d->btf, id);
1148 if (d->strip_mods && btf_is_mod(t))
1151 err = btf_dump_push_decl_stack_id(d, id);
1154 * if we don't have enough memory for entire type decl
1155 * chain, restore stack, emit warning, and try to
1156 * proceed nevertheless
1158 pr_warn("not enough memory for decl stack:%d", err);
1159 d->decl_stack_cnt = stack_start;
1167 switch (btf_kind(t)) {
1169 case BTF_KIND_VOLATILE:
1170 case BTF_KIND_CONST:
1171 case BTF_KIND_RESTRICT:
1172 case BTF_KIND_FUNC_PROTO:
1173 case BTF_KIND_TYPE_TAG:
1176 case BTF_KIND_ARRAY:
1177 id = btf_array(t)->type;
1182 case BTF_KIND_STRUCT:
1183 case BTF_KIND_UNION:
1184 case BTF_KIND_TYPEDEF:
1185 case BTF_KIND_FLOAT:
1188 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1195 * We might be inside a chain of declarations (e.g., array of function
1196 * pointers returning anonymous (so inlined) structs, having another
1197 * array field). Each of those needs its own "stack frame" to handle
1198 * emitting of declarations. Those stack frames are non-overlapping
1199 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1200 * handle this set of nested stacks, we create a view corresponding to
1201 * our own "stack frame" and work with it as an independent stack.
1202 * We'll need to clean up after emit_type_chain() returns, though.
1204 decl_stack.ids = d->decl_stack + stack_start;
1205 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1206 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1208 * emit_type_chain() guarantees that it will pop its entire decl_stack
1209 * frame before returning. But it works with a read-only view into
1210 * decl_stack, so it doesn't actually pop anything from the
1211 * perspective of shared btf_dump->decl_stack, per se. We need to
1212 * reset decl_stack state to how it was before us to avoid it growing
1215 d->decl_stack_cnt = stack_start;
1218 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1220 const struct btf_type *t;
1223 while (decl_stack->cnt) {
1224 id = decl_stack->ids[decl_stack->cnt - 1];
1225 t = btf__type_by_id(d->btf, id);
1227 switch (btf_kind(t)) {
1228 case BTF_KIND_VOLATILE:
1229 btf_dump_printf(d, "volatile ");
1231 case BTF_KIND_CONST:
1232 btf_dump_printf(d, "const ");
1234 case BTF_KIND_RESTRICT:
1235 btf_dump_printf(d, "restrict ");
1244 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1246 const struct btf_type *t;
1249 while (decl_stack->cnt) {
1250 id = decl_stack->ids[decl_stack->cnt - 1];
1251 t = btf__type_by_id(d->btf, id);
1258 static void btf_dump_emit_name(const struct btf_dump *d,
1259 const char *name, bool last_was_ptr)
1261 bool separate = name[0] && !last_was_ptr;
1263 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1266 static void btf_dump_emit_type_chain(struct btf_dump *d,
1267 struct id_stack *decls,
1268 const char *fname, int lvl)
1271 * last_was_ptr is used to determine if we need to separate pointer
1272 * asterisk (*) from previous part of type signature with space, so
1273 * that we get `int ***`, instead of `int * * *`. We default to true
1274 * for cases where we have single pointer in a chain. E.g., in ptr ->
1275 * func_proto case. func_proto will start a new emit_type_chain call
1276 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1277 * don't want to prepend space for that last pointer.
1279 bool last_was_ptr = true;
1280 const struct btf_type *t;
1285 while (decls->cnt) {
1286 id = decls->ids[--decls->cnt];
1288 /* VOID is a special snowflake */
1289 btf_dump_emit_mods(d, decls);
1290 btf_dump_printf(d, "void");
1291 last_was_ptr = false;
1295 t = btf__type_by_id(d->btf, id);
1300 case BTF_KIND_FLOAT:
1301 btf_dump_emit_mods(d, decls);
1302 name = btf_name_of(d, t->name_off);
1303 btf_dump_printf(d, "%s", name);
1305 case BTF_KIND_STRUCT:
1306 case BTF_KIND_UNION:
1307 btf_dump_emit_mods(d, decls);
1308 /* inline anonymous struct/union */
1309 if (t->name_off == 0 && !d->skip_anon_defs)
1310 btf_dump_emit_struct_def(d, id, t, lvl);
1312 btf_dump_emit_struct_fwd(d, id, t);
1315 btf_dump_emit_mods(d, decls);
1316 /* inline anonymous enum */
1317 if (t->name_off == 0 && !d->skip_anon_defs)
1318 btf_dump_emit_enum_def(d, id, t, lvl);
1320 btf_dump_emit_enum_fwd(d, id, t);
1323 btf_dump_emit_mods(d, decls);
1324 btf_dump_emit_fwd_def(d, id, t);
1326 case BTF_KIND_TYPEDEF:
1327 btf_dump_emit_mods(d, decls);
1328 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1331 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1333 case BTF_KIND_VOLATILE:
1334 btf_dump_printf(d, " volatile");
1336 case BTF_KIND_CONST:
1337 btf_dump_printf(d, " const");
1339 case BTF_KIND_RESTRICT:
1340 btf_dump_printf(d, " restrict");
1342 case BTF_KIND_TYPE_TAG:
1343 btf_dump_emit_mods(d, decls);
1344 name = btf_name_of(d, t->name_off);
1345 btf_dump_printf(d, " __attribute__((btf_type_tag(\"%s\")))", name);
1347 case BTF_KIND_ARRAY: {
1348 const struct btf_array *a = btf_array(t);
1349 const struct btf_type *next_t;
1354 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1355 * which causes it to emit extra const/volatile
1356 * modifiers for an array, if array's element type has
1357 * const/volatile modifiers. Clang doesn't do that.
1358 * In general, it doesn't seem very meaningful to have
1359 * a const/volatile modifier for array, so we are
1360 * going to silently skip them here.
1362 btf_dump_drop_mods(d, decls);
1364 if (decls->cnt == 0) {
1365 btf_dump_emit_name(d, fname, last_was_ptr);
1366 btf_dump_printf(d, "[%u]", a->nelems);
1370 next_id = decls->ids[decls->cnt - 1];
1371 next_t = btf__type_by_id(d->btf, next_id);
1372 multidim = btf_is_array(next_t);
1373 /* we need space if we have named non-pointer */
1374 if (fname[0] && !last_was_ptr)
1375 btf_dump_printf(d, " ");
1376 /* no parentheses for multi-dimensional array */
1378 btf_dump_printf(d, "(");
1379 btf_dump_emit_type_chain(d, decls, fname, lvl);
1381 btf_dump_printf(d, ")");
1382 btf_dump_printf(d, "[%u]", a->nelems);
1385 case BTF_KIND_FUNC_PROTO: {
1386 const struct btf_param *p = btf_params(t);
1387 __u16 vlen = btf_vlen(t);
1391 * GCC emits extra volatile qualifier for
1392 * __attribute__((noreturn)) function pointers. Clang
1393 * doesn't do it. It's a GCC quirk for backwards
1394 * compatibility with code written for GCC <2.5. So,
1395 * similarly to extra qualifiers for array, just drop
1396 * them, instead of handling them.
1398 btf_dump_drop_mods(d, decls);
1400 btf_dump_printf(d, " (");
1401 btf_dump_emit_type_chain(d, decls, fname, lvl);
1402 btf_dump_printf(d, ")");
1404 btf_dump_emit_name(d, fname, last_was_ptr);
1406 btf_dump_printf(d, "(");
1408 * Clang for BPF target generates func_proto with no
1409 * args as a func_proto with a single void arg (e.g.,
1410 * `int (*f)(void)` vs just `int (*f)()`). We are
1411 * going to pretend there are no args for such case.
1413 if (vlen == 1 && p->type == 0) {
1414 btf_dump_printf(d, ")");
1418 for (i = 0; i < vlen; i++, p++) {
1420 btf_dump_printf(d, ", ");
1422 /* last arg of type void is vararg */
1423 if (i == vlen - 1 && p->type == 0) {
1424 btf_dump_printf(d, "...");
1428 name = btf_name_of(d, p->name_off);
1429 btf_dump_emit_type_decl(d, p->type, name, lvl);
1432 btf_dump_printf(d, ")");
1436 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1441 last_was_ptr = kind == BTF_KIND_PTR;
1444 btf_dump_emit_name(d, fname, last_was_ptr);
1447 /* show type name as (type_name) */
1448 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1451 const struct btf_type *t;
1453 /* for array members, we don't bother emitting type name for each
1454 * member to avoid the redundancy of
1455 * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
1457 if (d->typed_dump->is_array_member)
1460 /* avoid type name specification for variable/section; it will be done
1461 * for the associated variable value(s).
1463 t = btf__type_by_id(d->btf, id);
1464 if (btf_is_var(t) || btf_is_datasec(t))
1468 btf_dump_printf(d, "(");
1470 d->skip_anon_defs = true;
1471 d->strip_mods = true;
1472 btf_dump_emit_type_decl(d, id, "", 0);
1473 d->strip_mods = false;
1474 d->skip_anon_defs = false;
1477 btf_dump_printf(d, ")");
1480 /* return number of duplicates (occurrences) of a given name */
1481 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1482 const char *orig_name)
1486 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1488 hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1493 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1494 struct hashmap *name_map)
1496 struct btf_dump_type_aux_state *s = &d->type_states[id];
1497 const struct btf_type *t = btf__type_by_id(d->btf, id);
1498 const char *orig_name = btf_name_of(d, t->name_off);
1499 const char **cached_name = &d->cached_names[id];
1502 if (t->name_off == 0)
1505 if (s->name_resolved)
1506 return *cached_name ? *cached_name : orig_name;
1508 if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1509 s->name_resolved = 1;
1513 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1515 const size_t max_len = 256;
1516 char new_name[max_len];
1518 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1519 *cached_name = strdup(new_name);
1522 s->name_resolved = 1;
1523 return *cached_name ? *cached_name : orig_name;
1526 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1528 return btf_dump_resolve_name(d, id, d->type_names);
1531 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1533 return btf_dump_resolve_name(d, id, d->ident_names);
1536 static int btf_dump_dump_type_data(struct btf_dump *d,
1538 const struct btf_type *t,
1544 static const char *btf_dump_data_newline(struct btf_dump *d)
1546 return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1549 static const char *btf_dump_data_delim(struct btf_dump *d)
1551 return d->typed_dump->depth == 0 ? "" : ",";
1554 static void btf_dump_data_pfx(struct btf_dump *d)
1556 int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1558 if (d->typed_dump->compact)
1561 for (i = 0; i < lvl; i++)
1562 btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1565 /* A macro is used here as btf_type_value[s]() appends format specifiers
1566 * to the format specifier passed in; these do the work of appending
1567 * delimiters etc while the caller simply has to specify the type values
1568 * in the format specifier + value(s).
1570 #define btf_dump_type_values(d, fmt, ...) \
1571 btf_dump_printf(d, fmt "%s%s", \
1573 btf_dump_data_delim(d), \
1574 btf_dump_data_newline(d))
1576 static int btf_dump_unsupported_data(struct btf_dump *d,
1577 const struct btf_type *t,
1580 btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1584 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1585 const struct btf_type *t,
1591 __u16 left_shift_bits, right_shift_bits;
1592 const __u8 *bytes = data;
1597 /* Maximum supported bitfield size is 64 bits */
1599 pr_warn("unexpected bitfield size %d\n", t->size);
1603 /* Bitfield value retrieval is done in two steps; first relevant bytes are
1604 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1606 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1607 for (i = t->size - 1; i >= 0; i--)
1608 num = num * 256 + bytes[i];
1609 nr_copy_bits = bit_sz + bits_offset;
1610 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1611 for (i = 0; i < t->size; i++)
1612 num = num * 256 + bytes[i];
1613 nr_copy_bits = t->size * 8 - bits_offset;
1615 # error "Unrecognized __BYTE_ORDER__"
1617 left_shift_bits = 64 - nr_copy_bits;
1618 right_shift_bits = 64 - bit_sz;
1620 *value = (num << left_shift_bits) >> right_shift_bits;
1625 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1626 const struct btf_type *t,
1634 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1642 static int btf_dump_bitfield_data(struct btf_dump *d,
1643 const struct btf_type *t,
1651 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1655 btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1660 /* ints, floats and ptrs */
1661 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1662 const struct btf_type *t,
1666 static __u8 bytecmp[16] = {};
1669 /* For pointer types, pointer size is not defined on a per-type basis.
1670 * On dump creation however, we store the pointer size.
1672 if (btf_kind(t) == BTF_KIND_PTR)
1673 nr_bytes = d->ptr_sz;
1677 if (nr_bytes < 1 || nr_bytes > 16) {
1678 pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1682 if (memcmp(data, bytecmp, nr_bytes) == 0)
1687 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1690 int alignment = btf__align_of(btf, type_id);
1695 return ((uintptr_t)data) % alignment == 0;
1698 static int btf_dump_int_data(struct btf_dump *d,
1699 const struct btf_type *t,
1704 __u8 encoding = btf_int_encoding(t);
1705 bool sign = encoding & BTF_INT_SIGNED;
1706 char buf[16] __attribute__((aligned(16)));
1709 if (sz == 0 || sz > sizeof(buf)) {
1710 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1714 /* handle packed int data - accesses of integers not aligned on
1715 * int boundaries can cause problems on some platforms.
1717 if (!ptr_is_aligned(d->btf, type_id, data)) {
1718 memcpy(buf, data, sz);
1724 const __u64 *ints = data;
1727 /* avoid use of __int128 as some 32-bit platforms do not
1730 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1733 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1737 # error "Unrecognized __BYTE_ORDER__"
1740 btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1742 btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1743 (unsigned long long)lsi);
1748 btf_dump_type_values(d, "%lld", *(long long *)data);
1750 btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1754 btf_dump_type_values(d, "%d", *(__s32 *)data);
1756 btf_dump_type_values(d, "%u", *(__u32 *)data);
1760 btf_dump_type_values(d, "%d", *(__s16 *)data);
1762 btf_dump_type_values(d, "%u", *(__u16 *)data);
1765 if (d->typed_dump->is_array_char) {
1766 /* check for null terminator */
1767 if (d->typed_dump->is_array_terminated)
1769 if (*(char *)data == '\0') {
1770 d->typed_dump->is_array_terminated = true;
1773 if (isprint(*(char *)data)) {
1774 btf_dump_type_values(d, "'%c'", *(char *)data);
1779 btf_dump_type_values(d, "%d", *(__s8 *)data);
1781 btf_dump_type_values(d, "%u", *(__u8 *)data);
1784 pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1796 static int btf_dump_float_data(struct btf_dump *d,
1797 const struct btf_type *t,
1801 const union float_data *flp = data;
1802 union float_data fl;
1805 /* handle unaligned data; copy to local union */
1806 if (!ptr_is_aligned(d->btf, type_id, data)) {
1807 memcpy(&fl, data, sz);
1813 btf_dump_type_values(d, "%Lf", flp->ld);
1816 btf_dump_type_values(d, "%lf", flp->d);
1819 btf_dump_type_values(d, "%f", flp->f);
1822 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1828 static int btf_dump_var_data(struct btf_dump *d,
1829 const struct btf_type *v,
1833 enum btf_func_linkage linkage = btf_var(v)->linkage;
1834 const struct btf_type *t;
1839 case BTF_FUNC_STATIC:
1842 case BTF_FUNC_EXTERN:
1845 case BTF_FUNC_GLOBAL:
1851 /* format of output here is [linkage] [type] [varname] = (type)value,
1852 * for example "static int cpu_profile_flip = (int)1"
1854 btf_dump_printf(d, "%s", l);
1856 t = btf__type_by_id(d->btf, type_id);
1857 btf_dump_emit_type_cast(d, type_id, false);
1858 btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
1859 return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
1862 static int btf_dump_array_data(struct btf_dump *d,
1863 const struct btf_type *t,
1867 const struct btf_array *array = btf_array(t);
1868 const struct btf_type *elem_type;
1869 __u32 i, elem_type_id;
1871 bool is_array_member;
1873 elem_type_id = array->type;
1874 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
1875 elem_size = btf__resolve_size(d->btf, elem_type_id);
1876 if (elem_size <= 0) {
1877 pr_warn("unexpected elem size %zd for array type [%u]\n",
1878 (ssize_t)elem_size, id);
1882 if (btf_is_int(elem_type)) {
1884 * BTF_INT_CHAR encoding never seems to be set for
1885 * char arrays, so if size is 1 and element is
1886 * printable as a char, we'll do that.
1889 d->typed_dump->is_array_char = true;
1892 /* note that we increment depth before calling btf_dump_print() below;
1893 * this is intentional. btf_dump_data_newline() will not print a
1894 * newline for depth 0 (since this leaves us with trailing newlines
1895 * at the end of typed display), so depth is incremented first.
1896 * For similar reasons, we decrement depth before showing the closing
1899 d->typed_dump->depth++;
1900 btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
1902 /* may be a multidimensional array, so store current "is array member"
1903 * status so we can restore it correctly later.
1905 is_array_member = d->typed_dump->is_array_member;
1906 d->typed_dump->is_array_member = true;
1907 for (i = 0; i < array->nelems; i++, data += elem_size) {
1908 if (d->typed_dump->is_array_terminated)
1910 btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
1912 d->typed_dump->is_array_member = is_array_member;
1913 d->typed_dump->depth--;
1914 btf_dump_data_pfx(d);
1915 btf_dump_type_values(d, "]");
1920 static int btf_dump_struct_data(struct btf_dump *d,
1921 const struct btf_type *t,
1925 const struct btf_member *m = btf_members(t);
1926 __u16 n = btf_vlen(t);
1929 /* note that we increment depth before calling btf_dump_print() below;
1930 * this is intentional. btf_dump_data_newline() will not print a
1931 * newline for depth 0 (since this leaves us with trailing newlines
1932 * at the end of typed display), so depth is incremented first.
1933 * For similar reasons, we decrement depth before showing the closing
1936 d->typed_dump->depth++;
1937 btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
1939 for (i = 0; i < n; i++, m++) {
1940 const struct btf_type *mtype;
1945 mtype = btf__type_by_id(d->btf, m->type);
1946 mname = btf_name_of(d, m->name_off);
1947 moffset = btf_member_bit_offset(t, i);
1949 bit_sz = btf_member_bitfield_size(t, i);
1950 err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
1951 moffset % 8, bit_sz);
1955 d->typed_dump->depth--;
1956 btf_dump_data_pfx(d);
1957 btf_dump_type_values(d, "}");
1963 unsigned long long lp;
1966 static int btf_dump_ptr_data(struct btf_dump *d,
1967 const struct btf_type *t,
1971 if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
1972 btf_dump_type_values(d, "%p", *(void **)data);
1976 memcpy(&pt, data, d->ptr_sz);
1978 btf_dump_type_values(d, "0x%x", pt.p);
1980 btf_dump_type_values(d, "0x%llx", pt.lp);
1985 static int btf_dump_get_enum_value(struct btf_dump *d,
1986 const struct btf_type *t,
1991 /* handle unaligned enum value */
1992 if (!ptr_is_aligned(d->btf, id, data)) {
1996 err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
1999 *value = (__s64)val;
2005 *value = *(__s64 *)data;
2008 *value = *(__s32 *)data;
2011 *value = *(__s16 *)data;
2014 *value = *(__s8 *)data;
2017 pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
2022 static int btf_dump_enum_data(struct btf_dump *d,
2023 const struct btf_type *t,
2027 const struct btf_enum *e;
2031 err = btf_dump_get_enum_value(d, t, data, id, &value);
2035 for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2036 if (value != e->val)
2038 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2042 btf_dump_type_values(d, "%d", value);
2046 static int btf_dump_datasec_data(struct btf_dump *d,
2047 const struct btf_type *t,
2051 const struct btf_var_secinfo *vsi;
2052 const struct btf_type *var;
2056 btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2058 for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2059 var = btf__type_by_id(d->btf, vsi->type);
2060 err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2063 btf_dump_printf(d, ";");
2068 /* return size of type, or if base type overflows, return -E2BIG. */
2069 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2070 const struct btf_type *t,
2075 __s64 size = btf__resolve_size(d->btf, id);
2077 if (size < 0 || size >= INT_MAX) {
2078 pr_warn("unexpected size [%zu] for id [%u]\n",
2083 /* Only do overflow checking for base types; we do not want to
2084 * avoid showing part of a struct, union or array, even if we
2085 * do not have enough data to show the full object. By
2086 * restricting overflow checking to base types we can ensure
2087 * that partial display succeeds, while avoiding overflowing
2088 * and using bogus data for display.
2090 t = skip_mods_and_typedefs(d->btf, id, NULL);
2092 pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2097 switch (btf_kind(t)) {
2099 case BTF_KIND_FLOAT:
2102 if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2111 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2112 const struct btf_type *t,
2121 /* toplevel exceptions; we show zero values if
2122 * - we ask for them (emit_zeros)
2123 * - if we are at top-level so we see "struct empty { }"
2124 * - or if we are an array member and the array is non-empty and
2125 * not a char array; we don't want to be in a situation where we
2126 * have an integer array 0, 1, 0, 1 and only show non-zero values.
2127 * If the array contains zeroes only, or is a char array starting
2128 * with a '\0', the array-level check_zero() will prevent showing it;
2129 * we are concerned with determining zero value at the array member
2132 if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2133 (d->typed_dump->is_array_member &&
2134 !d->typed_dump->is_array_char))
2137 t = skip_mods_and_typedefs(d->btf, id, NULL);
2139 switch (btf_kind(t)) {
2142 return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2143 return btf_dump_base_type_check_zero(d, t, id, data);
2144 case BTF_KIND_FLOAT:
2146 return btf_dump_base_type_check_zero(d, t, id, data);
2147 case BTF_KIND_ARRAY: {
2148 const struct btf_array *array = btf_array(t);
2149 const struct btf_type *elem_type;
2150 __u32 elem_type_id, elem_size;
2153 elem_type_id = array->type;
2154 elem_size = btf__resolve_size(d->btf, elem_type_id);
2155 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2157 ischar = btf_is_int(elem_type) && elem_size == 1;
2159 /* check all elements; if _any_ element is nonzero, all
2160 * of array is displayed. We make an exception however
2161 * for char arrays where the first element is 0; these
2162 * are considered zeroed also, even if later elements are
2163 * non-zero because the string is terminated.
2165 for (i = 0; i < array->nelems; i++) {
2166 if (i == 0 && ischar && *(char *)data == 0)
2168 err = btf_dump_type_data_check_zero(d, elem_type,
2173 if (err != -ENODATA)
2178 case BTF_KIND_STRUCT:
2179 case BTF_KIND_UNION: {
2180 const struct btf_member *m = btf_members(t);
2181 __u16 n = btf_vlen(t);
2183 /* if any struct/union member is non-zero, the struct/union
2184 * is considered non-zero and dumped.
2186 for (i = 0; i < n; i++, m++) {
2187 const struct btf_type *mtype;
2190 mtype = btf__type_by_id(d->btf, m->type);
2191 moffset = btf_member_bit_offset(t, i);
2193 /* btf_int_bits() does not store member bitfield size;
2194 * bitfield size needs to be stored here so int display
2195 * of member can retrieve it.
2197 bit_sz = btf_member_bitfield_size(t, i);
2198 err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2199 moffset % 8, bit_sz);
2206 err = btf_dump_get_enum_value(d, t, data, id, &value);
2217 /* returns size of data dumped, or error. */
2218 static int btf_dump_dump_type_data(struct btf_dump *d,
2220 const struct btf_type *t,
2228 size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2231 err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2233 /* zeroed data is expected and not an error, so simply skip
2234 * dumping such data. Record other errors however.
2236 if (err == -ENODATA)
2240 btf_dump_data_pfx(d);
2242 if (!d->typed_dump->skip_names) {
2243 if (fname && strlen(fname) > 0)
2244 btf_dump_printf(d, ".%s = ", fname);
2245 btf_dump_emit_type_cast(d, id, true);
2248 t = skip_mods_and_typedefs(d->btf, id, NULL);
2250 switch (btf_kind(t)) {
2254 case BTF_KIND_FUNC_PROTO:
2255 case BTF_KIND_DECL_TAG:
2256 err = btf_dump_unsupported_data(d, t, id);
2260 err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2262 err = btf_dump_int_data(d, t, id, data, bits_offset);
2264 case BTF_KIND_FLOAT:
2265 err = btf_dump_float_data(d, t, id, data);
2268 err = btf_dump_ptr_data(d, t, id, data);
2270 case BTF_KIND_ARRAY:
2271 err = btf_dump_array_data(d, t, id, data);
2273 case BTF_KIND_STRUCT:
2274 case BTF_KIND_UNION:
2275 err = btf_dump_struct_data(d, t, id, data);
2278 /* handle bitfield and int enum values */
2283 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2287 enum_val = (__s64)print_num;
2288 err = btf_dump_enum_data(d, t, id, &enum_val);
2290 err = btf_dump_enum_data(d, t, id, data);
2293 err = btf_dump_var_data(d, t, id, data);
2295 case BTF_KIND_DATASEC:
2296 err = btf_dump_datasec_data(d, t, id, data);
2299 pr_warn("unexpected kind [%u] for id [%u]\n",
2300 BTF_INFO_KIND(t->info), id);
2308 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2309 const void *data, size_t data_sz,
2310 const struct btf_dump_type_data_opts *opts)
2312 struct btf_dump_data typed_dump = {};
2313 const struct btf_type *t;
2316 if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2317 return libbpf_err(-EINVAL);
2319 t = btf__type_by_id(d->btf, id);
2321 return libbpf_err(-ENOENT);
2323 d->typed_dump = &typed_dump;
2324 d->typed_dump->data_end = data + data_sz;
2325 d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2327 /* default indent string is a tab */
2328 if (!opts->indent_str)
2329 d->typed_dump->indent_str[0] = '\t';
2331 libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
2332 sizeof(d->typed_dump->indent_str));
2334 d->typed_dump->compact = OPTS_GET(opts, compact, false);
2335 d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2336 d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2338 ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2340 d->typed_dump = NULL;
2342 return libbpf_err(ret);