1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
4 * BTF-to-C type converter.
6 * Copyright (c) 2019 Facebook
16 #include <linux/err.h>
17 #include <linux/btf.h>
18 #include <linux/kernel.h>
22 #include "libbpf_internal.h"
24 static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
25 static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
27 static const char *pfx(int lvl)
29 return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
32 enum btf_dump_type_order_state {
38 enum btf_dump_type_emit_state {
44 /* per-type auxiliary state */
45 struct btf_dump_type_aux_state {
46 /* topological sorting state */
47 enum btf_dump_type_order_state order_state: 2;
48 /* emitting state used to determine the need for forward declaration */
49 enum btf_dump_type_emit_state emit_state: 2;
50 /* whether forward declaration was already emitted */
52 /* whether unique non-duplicate name was already assigned */
53 __u8 name_resolved: 1;
54 /* whether type is referenced from any other type */
58 /* indent string length; one indent string is added for each indent level */
59 #define BTF_DATA_INDENT_STR_LEN 32
62 * Common internal data for BTF type data dump operations.
64 struct btf_dump_data {
65 const void *data_end; /* end of valid data to show */
69 __u8 indent_lvl; /* base indent level */
70 char indent_str[BTF_DATA_INDENT_STR_LEN];
71 /* below are used during iteration */
74 bool is_array_terminated;
79 const struct btf *btf;
80 btf_dump_printf_fn_t printf_fn;
87 /* per-type auxiliary state */
88 struct btf_dump_type_aux_state *type_states;
89 size_t type_states_cap;
90 /* per-type optional cached unique name, must be freed, if present */
91 const char **cached_names;
92 size_t cached_names_cap;
94 /* topo-sorted list of dependent type definitions */
100 * stack of type declarations (e.g., chain of modifiers, arrays,
107 /* maps struct/union/enum name to a number of name occurrences */
108 struct hashmap *type_names;
110 * maps typedef identifiers and enum value names to a number of such
113 struct hashmap *ident_names;
115 * data for typed display; allocated if needed.
117 struct btf_dump_data *typed_dump;
120 static size_t str_hash_fn(const void *key, void *ctx)
122 return str_hash(key);
125 static bool str_equal_fn(const void *a, const void *b, void *ctx)
127 return strcmp(a, b) == 0;
130 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
132 return btf__name_by_offset(d->btf, name_off);
135 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
140 d->printf_fn(d->cb_ctx, fmt, args);
144 static int btf_dump_mark_referenced(struct btf_dump *d);
145 static int btf_dump_resize(struct btf_dump *d);
147 struct btf_dump *btf_dump__new(const struct btf *btf,
148 btf_dump_printf_fn_t printf_fn,
150 const struct btf_dump_opts *opts)
155 if (!OPTS_VALID(opts, btf_dump_opts))
156 return libbpf_err_ptr(-EINVAL);
159 return libbpf_err_ptr(-EINVAL);
161 d = calloc(1, sizeof(struct btf_dump));
163 return libbpf_err_ptr(-ENOMEM);
166 d->printf_fn = printf_fn;
168 d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
170 d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
171 if (IS_ERR(d->type_names)) {
172 err = PTR_ERR(d->type_names);
173 d->type_names = NULL;
176 d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
177 if (IS_ERR(d->ident_names)) {
178 err = PTR_ERR(d->ident_names);
179 d->ident_names = NULL;
183 err = btf_dump_resize(d);
190 return libbpf_err_ptr(err);
193 static int btf_dump_resize(struct btf_dump *d)
195 int err, last_id = btf__type_cnt(d->btf) - 1;
197 if (last_id <= d->last_id)
200 if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
201 sizeof(*d->type_states), last_id + 1))
203 if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
204 sizeof(*d->cached_names), last_id + 1))
207 if (d->last_id == 0) {
208 /* VOID is special */
209 d->type_states[0].order_state = ORDERED;
210 d->type_states[0].emit_state = EMITTED;
213 /* eagerly determine referenced types for anon enums */
214 err = btf_dump_mark_referenced(d);
218 d->last_id = last_id;
222 void btf_dump__free(struct btf_dump *d)
226 if (IS_ERR_OR_NULL(d))
229 free(d->type_states);
230 if (d->cached_names) {
231 /* any set cached name is owned by us and should be freed */
232 for (i = 0; i <= d->last_id; i++) {
233 if (d->cached_names[i])
234 free((void *)d->cached_names[i]);
237 free(d->cached_names);
240 hashmap__free(d->type_names);
241 hashmap__free(d->ident_names);
246 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
247 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
250 * Dump BTF type in a compilable C syntax, including all the necessary
251 * dependent types, necessary for compilation. If some of the dependent types
252 * were already emitted as part of previous btf_dump__dump_type() invocation
253 * for another type, they won't be emitted again. This API allows callers to
254 * filter out BTF types according to user-defined criterias and emitted only
255 * minimal subset of types, necessary to compile everything. Full struct/union
256 * definitions will still be emitted, even if the only usage is through
257 * pointer and could be satisfied with just a forward declaration.
259 * Dumping is done in two high-level passes:
260 * 1. Topologically sort type definitions to satisfy C rules of compilation.
261 * 2. Emit type definitions in C syntax.
263 * Returns 0 on success; <0, otherwise.
265 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
269 if (id >= btf__type_cnt(d->btf))
270 return libbpf_err(-EINVAL);
272 err = btf_dump_resize(d);
274 return libbpf_err(err);
276 d->emit_queue_cnt = 0;
277 err = btf_dump_order_type(d, id, false);
279 return libbpf_err(err);
281 for (i = 0; i < d->emit_queue_cnt; i++)
282 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
288 * Mark all types that are referenced from any other type. This is used to
289 * determine top-level anonymous enums that need to be emitted as an
290 * independent type declarations.
291 * Anonymous enums come in two flavors: either embedded in a struct's field
292 * definition, in which case they have to be declared inline as part of field
293 * type declaration; or as a top-level anonymous enum, typically used for
294 * declaring global constants. It's impossible to distinguish between two
295 * without knowning whether given enum type was referenced from other type:
296 * top-level anonymous enum won't be referenced by anything, while embedded
299 static int btf_dump_mark_referenced(struct btf_dump *d)
301 int i, j, n = btf__type_cnt(d->btf);
302 const struct btf_type *t;
305 for (i = d->last_id + 1; i < n; i++) {
306 t = btf__type_by_id(d->btf, i);
309 switch (btf_kind(t)) {
312 case BTF_KIND_ENUM64:
317 case BTF_KIND_VOLATILE:
319 case BTF_KIND_RESTRICT:
321 case BTF_KIND_TYPEDEF:
324 case BTF_KIND_DECL_TAG:
325 case BTF_KIND_TYPE_TAG:
326 d->type_states[t->type].referenced = 1;
329 case BTF_KIND_ARRAY: {
330 const struct btf_array *a = btf_array(t);
332 d->type_states[a->index_type].referenced = 1;
333 d->type_states[a->type].referenced = 1;
336 case BTF_KIND_STRUCT:
337 case BTF_KIND_UNION: {
338 const struct btf_member *m = btf_members(t);
340 for (j = 0; j < vlen; j++, m++)
341 d->type_states[m->type].referenced = 1;
344 case BTF_KIND_FUNC_PROTO: {
345 const struct btf_param *p = btf_params(t);
347 for (j = 0; j < vlen; j++, p++)
348 d->type_states[p->type].referenced = 1;
351 case BTF_KIND_DATASEC: {
352 const struct btf_var_secinfo *v = btf_var_secinfos(t);
354 for (j = 0; j < vlen; j++, v++)
355 d->type_states[v->type].referenced = 1;
365 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
370 if (d->emit_queue_cnt >= d->emit_queue_cap) {
371 new_cap = max(16, d->emit_queue_cap * 3 / 2);
372 new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
375 d->emit_queue = new_queue;
376 d->emit_queue_cap = new_cap;
379 d->emit_queue[d->emit_queue_cnt++] = id;
384 * Determine order of emitting dependent types and specified type to satisfy
385 * C compilation rules. This is done through topological sorting with an
386 * additional complication which comes from C rules. The main idea for C is
387 * that if some type is "embedded" into a struct/union, it's size needs to be
388 * known at the time of definition of containing type. E.g., for:
391 * struct B { struct A x; }
393 * struct A *HAS* to be defined before struct B, because it's "embedded",
394 * i.e., it is part of struct B layout. But in the following case:
397 * struct B { struct A *x; }
400 * it's enough to just have a forward declaration of struct A at the time of
401 * struct B definition, as struct B has a pointer to struct A, so the size of
402 * field x is known without knowing struct A size: it's sizeof(void *).
404 * Unfortunately, there are some trickier cases we need to handle, e.g.:
406 * struct A {}; // if this was forward-declaration: compilation error
408 * struct { // anonymous struct
413 * In this case, struct B's field x is a pointer, so it's size is known
414 * regardless of the size of (anonymous) struct it points to. But because this
415 * struct is anonymous and thus defined inline inside struct B, *and* it
416 * embeds struct A, compiler requires full definition of struct A to be known
417 * before struct B can be defined. This creates a transitive dependency
418 * between struct A and struct B. If struct A was forward-declared before
419 * struct B definition and fully defined after struct B definition, that would
420 * trigger compilation error.
422 * All this means that while we are doing topological sorting on BTF type
423 * graph, we need to determine relationships between different types (graph
425 * - weak link (relationship) between X and Y, if Y *CAN* be
426 * forward-declared at the point of X definition;
427 * - strong link, if Y *HAS* to be fully-defined before X can be defined.
429 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
430 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
431 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
432 * Weak/strong relationship is determined recursively during DFS traversal and
433 * is returned as a result from btf_dump_order_type().
435 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
436 * but it is not guaranteeing that no extraneous forward declarations will be
439 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
440 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
441 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
442 * entire graph path, so depending where from one came to that BTF type, it
443 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
444 * once they are processed, there is no need to do it again, so they are
445 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
446 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
447 * in any case, once those are processed, no need to do it again, as the
448 * result won't change.
451 * - 1, if type is part of strong link (so there is strong topological
452 * ordering requirements);
453 * - 0, if type is part of weak link (so can be satisfied through forward
455 * - <0, on error (e.g., unsatisfiable type loop detected).
457 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
460 * Order state is used to detect strong link cycles, but only for BTF
461 * kinds that are or could be an independent definition (i.e.,
462 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
463 * func_protos, modifiers are just means to get to these definitions.
464 * Int/void don't need definitions, they are assumed to be always
465 * properly defined. We also ignore datasec, var, and funcs for now.
466 * So for all non-defining kinds, we never even set ordering state,
467 * for defining kinds we set ORDERING and subsequently ORDERED if it
468 * forms a strong link.
470 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
471 const struct btf_type *t;
475 /* return true, letting typedefs know that it's ok to be emitted */
476 if (tstate->order_state == ORDERED)
479 t = btf__type_by_id(d->btf, id);
481 if (tstate->order_state == ORDERING) {
482 /* type loop, but resolvable through fwd declaration */
483 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
485 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
489 switch (btf_kind(t)) {
492 tstate->order_state = ORDERED;
496 err = btf_dump_order_type(d, t->type, true);
497 tstate->order_state = ORDERED;
501 return btf_dump_order_type(d, btf_array(t)->type, false);
503 case BTF_KIND_STRUCT:
504 case BTF_KIND_UNION: {
505 const struct btf_member *m = btf_members(t);
507 * struct/union is part of strong link, only if it's embedded
508 * (so no ptr in a path) or it's anonymous (so has to be
509 * defined inline, even if declared through ptr)
511 if (through_ptr && t->name_off != 0)
514 tstate->order_state = ORDERING;
517 for (i = 0; i < vlen; i++, m++) {
518 err = btf_dump_order_type(d, m->type, false);
523 if (t->name_off != 0) {
524 err = btf_dump_add_emit_queue_id(d, id);
529 tstate->order_state = ORDERED;
533 case BTF_KIND_ENUM64:
536 * non-anonymous or non-referenced enums are top-level
537 * declarations and should be emitted. Same logic can be
538 * applied to FWDs, it won't hurt anyways.
540 if (t->name_off != 0 || !tstate->referenced) {
541 err = btf_dump_add_emit_queue_id(d, id);
545 tstate->order_state = ORDERED;
548 case BTF_KIND_TYPEDEF: {
551 is_strong = btf_dump_order_type(d, t->type, through_ptr);
555 /* typedef is similar to struct/union w.r.t. fwd-decls */
556 if (through_ptr && !is_strong)
559 /* typedef is always a named definition */
560 err = btf_dump_add_emit_queue_id(d, id);
564 d->type_states[id].order_state = ORDERED;
567 case BTF_KIND_VOLATILE:
569 case BTF_KIND_RESTRICT:
570 case BTF_KIND_TYPE_TAG:
571 return btf_dump_order_type(d, t->type, through_ptr);
573 case BTF_KIND_FUNC_PROTO: {
574 const struct btf_param *p = btf_params(t);
577 err = btf_dump_order_type(d, t->type, through_ptr);
583 for (i = 0; i < vlen; i++, p++) {
584 err = btf_dump_order_type(d, p->type, through_ptr);
594 case BTF_KIND_DATASEC:
595 case BTF_KIND_DECL_TAG:
596 d->type_states[id].order_state = ORDERED;
604 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
605 const struct btf_type *t);
607 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
608 const struct btf_type *t);
609 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
610 const struct btf_type *t, int lvl);
612 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
613 const struct btf_type *t);
614 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
615 const struct btf_type *t, int lvl);
617 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
618 const struct btf_type *t);
620 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
621 const struct btf_type *t, int lvl);
623 /* a local view into a shared stack */
629 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
630 const char *fname, int lvl);
631 static void btf_dump_emit_type_chain(struct btf_dump *d,
632 struct id_stack *decl_stack,
633 const char *fname, int lvl);
635 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
636 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
637 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
638 const char *orig_name);
640 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
642 const struct btf_type *t = btf__type_by_id(d->btf, id);
644 /* __builtin_va_list is a compiler built-in, which causes compilation
645 * errors, when compiling w/ different compiler, then used to compile
646 * original code (e.g., GCC to compile kernel, Clang to use generated
647 * C header from BTF). As it is built-in, it should be already defined
648 * properly internally in compiler.
650 if (t->name_off == 0)
652 return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
656 * Emit C-syntax definitions of types from chains of BTF types.
658 * High-level handling of determining necessary forward declarations are handled
659 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
660 * declarations/definitions in C syntax are handled by a combo of
661 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
662 * corresponding btf_dump_emit_*_{def,fwd}() functions.
664 * We also keep track of "containing struct/union type ID" to determine when
665 * we reference it from inside and thus can avoid emitting unnecessary forward
668 * This algorithm is designed in such a way, that even if some error occurs
669 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
670 * that doesn't comply to C rules completely), algorithm will try to proceed
671 * and produce as much meaningful output as possible.
673 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
675 struct btf_dump_type_aux_state *tstate = &d->type_states[id];
676 bool top_level_def = cont_id == 0;
677 const struct btf_type *t;
680 if (tstate->emit_state == EMITTED)
683 t = btf__type_by_id(d->btf, id);
686 if (tstate->emit_state == EMITTING) {
687 if (tstate->fwd_emitted)
691 case BTF_KIND_STRUCT:
694 * if we are referencing a struct/union that we are
695 * part of - then no need for fwd declaration
699 if (t->name_off == 0) {
700 pr_warn("anonymous struct/union loop, id:[%u]\n",
704 btf_dump_emit_struct_fwd(d, id, t);
705 btf_dump_printf(d, ";\n\n");
706 tstate->fwd_emitted = 1;
708 case BTF_KIND_TYPEDEF:
710 * for typedef fwd_emitted means typedef definition
711 * was emitted, but it can be used only for "weak"
712 * references through pointer only, not for embedding
714 if (!btf_dump_is_blacklisted(d, id)) {
715 btf_dump_emit_typedef_def(d, id, t, 0);
716 btf_dump_printf(d, ";\n\n");
718 tstate->fwd_emitted = 1;
729 /* Emit type alias definitions if necessary */
730 btf_dump_emit_missing_aliases(d, id, t);
732 tstate->emit_state = EMITTED;
735 case BTF_KIND_ENUM64:
737 btf_dump_emit_enum_def(d, id, t, 0);
738 btf_dump_printf(d, ";\n\n");
740 tstate->emit_state = EMITTED;
743 case BTF_KIND_VOLATILE:
745 case BTF_KIND_RESTRICT:
746 case BTF_KIND_TYPE_TAG:
747 btf_dump_emit_type(d, t->type, cont_id);
750 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
753 btf_dump_emit_fwd_def(d, id, t);
754 btf_dump_printf(d, ";\n\n");
755 tstate->emit_state = EMITTED;
757 case BTF_KIND_TYPEDEF:
758 tstate->emit_state = EMITTING;
759 btf_dump_emit_type(d, t->type, id);
761 * typedef can server as both definition and forward
762 * declaration; at this stage someone depends on
763 * typedef as a forward declaration (refers to it
764 * through pointer), so unless we already did it,
765 * emit typedef as a forward declaration
767 if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
768 btf_dump_emit_typedef_def(d, id, t, 0);
769 btf_dump_printf(d, ";\n\n");
771 tstate->emit_state = EMITTED;
773 case BTF_KIND_STRUCT:
775 tstate->emit_state = EMITTING;
776 /* if it's a top-level struct/union definition or struct/union
777 * is anonymous, then in C we'll be emitting all fields and
778 * their types (as opposed to just `struct X`), so we need to
779 * make sure that all types, referenced from struct/union
780 * members have necessary forward-declarations, where
783 if (top_level_def || t->name_off == 0) {
784 const struct btf_member *m = btf_members(t);
785 __u16 vlen = btf_vlen(t);
788 new_cont_id = t->name_off == 0 ? cont_id : id;
789 for (i = 0; i < vlen; i++, m++)
790 btf_dump_emit_type(d, m->type, new_cont_id);
791 } else if (!tstate->fwd_emitted && id != cont_id) {
792 btf_dump_emit_struct_fwd(d, id, t);
793 btf_dump_printf(d, ";\n\n");
794 tstate->fwd_emitted = 1;
798 btf_dump_emit_struct_def(d, id, t, 0);
799 btf_dump_printf(d, ";\n\n");
800 tstate->emit_state = EMITTED;
802 tstate->emit_state = NOT_EMITTED;
805 case BTF_KIND_FUNC_PROTO: {
806 const struct btf_param *p = btf_params(t);
807 __u16 n = btf_vlen(t);
810 btf_dump_emit_type(d, t->type, cont_id);
811 for (i = 0; i < n; i++, p++)
812 btf_dump_emit_type(d, p->type, cont_id);
821 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
822 const struct btf_type *t)
824 const struct btf_member *m;
825 int align, i, bit_sz;
828 align = btf__align_of(btf, id);
829 /* size of a non-packed struct has to be a multiple of its alignment*/
830 if (align && t->size % align)
835 /* all non-bitfield fields have to be naturally aligned */
836 for (i = 0; i < vlen; i++, m++) {
837 align = btf__align_of(btf, m->type);
838 bit_sz = btf_member_bitfield_size(t, i);
839 if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
844 * if original struct was marked as packed, but its layout is
845 * naturally aligned, we'll detect that it's not packed
850 static int chip_away_bits(int total, int at_most)
852 return total % at_most ? : at_most;
855 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
856 int cur_off, int m_off, int m_bit_sz,
859 int off_diff = m_off - cur_off;
860 int ptr_bits = d->ptr_sz * 8;
865 if (m_bit_sz == 0 && off_diff < align * 8)
866 /* natural padding will take care of a gap */
869 while (off_diff > 0) {
870 const char *pad_type;
873 if (ptr_bits > 32 && off_diff > 32) {
875 pad_bits = chip_away_bits(off_diff, ptr_bits);
876 } else if (off_diff > 16) {
878 pad_bits = chip_away_bits(off_diff, 32);
879 } else if (off_diff > 8) {
881 pad_bits = chip_away_bits(off_diff, 16);
884 pad_bits = chip_away_bits(off_diff, 8);
886 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
887 off_diff -= pad_bits;
891 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
892 const struct btf_type *t)
894 btf_dump_printf(d, "%s%s%s",
895 btf_is_struct(t) ? "struct" : "union",
896 t->name_off ? " " : "",
897 btf_dump_type_name(d, id));
900 static void btf_dump_emit_struct_def(struct btf_dump *d,
902 const struct btf_type *t,
905 const struct btf_member *m = btf_members(t);
906 bool is_struct = btf_is_struct(t);
907 int align, i, packed, off = 0;
908 __u16 vlen = btf_vlen(t);
910 packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
912 btf_dump_printf(d, "%s%s%s {",
913 is_struct ? "struct" : "union",
914 t->name_off ? " " : "",
915 btf_dump_type_name(d, id));
917 for (i = 0; i < vlen; i++, m++) {
921 fname = btf_name_of(d, m->name_off);
922 m_sz = btf_member_bitfield_size(t, i);
923 m_off = btf_member_bit_offset(t, i);
924 align = packed ? 1 : btf__align_of(d->btf, m->type);
926 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
927 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
928 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
931 btf_dump_printf(d, ": %d", m_sz);
934 m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
935 off = m_off + m_sz * 8;
937 btf_dump_printf(d, ";");
940 /* pad at the end, if necessary */
942 align = packed ? 1 : btf__align_of(d->btf, id);
943 btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
948 btf_dump_printf(d, "\n");
949 btf_dump_printf(d, "%s}", pfx(lvl));
951 btf_dump_printf(d, " __attribute__((packed))");
954 static const char *missing_base_types[][2] = {
956 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
957 * SIMD intrinsics. Alias them to standard base types.
959 { "__Poly8_t", "unsigned char" },
960 { "__Poly16_t", "unsigned short" },
961 { "__Poly64_t", "unsigned long long" },
962 { "__Poly128_t", "unsigned __int128" },
965 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
966 const struct btf_type *t)
968 const char *name = btf_dump_type_name(d, id);
971 for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
972 if (strcmp(name, missing_base_types[i][0]) == 0) {
973 btf_dump_printf(d, "typedef %s %s;\n\n",
974 missing_base_types[i][1], name);
980 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
981 const struct btf_type *t)
983 btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
986 static void btf_dump_emit_enum32_val(struct btf_dump *d,
987 const struct btf_type *t,
990 const struct btf_enum *v = btf_enum(t);
991 bool is_signed = btf_kflag(t);
997 for (i = 0; i < vlen; i++, v++) {
998 name = btf_name_of(d, v->name_off);
999 /* enumerators share namespace with typedef idents */
1000 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1002 fmt_str = is_signed ? "\n%s%s___%zd = %d," : "\n%s%s___%zd = %u,";
1003 btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, dup_cnt, v->val);
1005 fmt_str = is_signed ? "\n%s%s = %d," : "\n%s%s = %u,";
1006 btf_dump_printf(d, fmt_str, pfx(lvl + 1), name, v->val);
1011 static void btf_dump_emit_enum64_val(struct btf_dump *d,
1012 const struct btf_type *t,
1013 int lvl, __u16 vlen)
1015 const struct btf_enum64 *v = btf_enum64(t);
1016 bool is_signed = btf_kflag(t);
1017 const char *fmt_str;
1023 for (i = 0; i < vlen; i++, v++) {
1024 name = btf_name_of(d, v->name_off);
1025 dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
1026 val = btf_enum64_value(v);
1028 fmt_str = is_signed ? "\n%s%s___%zd = %lldLL,"
1029 : "\n%s%s___%zd = %lluULL,";
1030 btf_dump_printf(d, fmt_str,
1031 pfx(lvl + 1), name, dup_cnt,
1032 (unsigned long long)val);
1034 fmt_str = is_signed ? "\n%s%s = %lldLL,"
1035 : "\n%s%s = %lluULL,";
1036 btf_dump_printf(d, fmt_str,
1038 (unsigned long long)val);
1042 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
1043 const struct btf_type *t,
1046 __u16 vlen = btf_vlen(t);
1048 btf_dump_printf(d, "enum%s%s",
1049 t->name_off ? " " : "",
1050 btf_dump_type_name(d, id));
1055 btf_dump_printf(d, " {");
1057 btf_dump_emit_enum32_val(d, t, lvl, vlen);
1059 btf_dump_emit_enum64_val(d, t, lvl, vlen);
1060 btf_dump_printf(d, "\n%s}", pfx(lvl));
1063 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1064 const struct btf_type *t)
1066 const char *name = btf_dump_type_name(d, id);
1069 btf_dump_printf(d, "union %s", name);
1071 btf_dump_printf(d, "struct %s", name);
1074 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1075 const struct btf_type *t, int lvl)
1077 const char *name = btf_dump_ident_name(d, id);
1080 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
1081 * pointing to VOID. This generates warnings from btf_dump() and
1082 * results in uncompilable header file, so we are fixing it up here
1083 * with valid typedef into __builtin_va_list.
1085 if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1086 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1090 btf_dump_printf(d, "typedef ");
1091 btf_dump_emit_type_decl(d, t->type, name, lvl);
1094 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1099 if (d->decl_stack_cnt >= d->decl_stack_cap) {
1100 new_cap = max(16, d->decl_stack_cap * 3 / 2);
1101 new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
1104 d->decl_stack = new_stack;
1105 d->decl_stack_cap = new_cap;
1108 d->decl_stack[d->decl_stack_cnt++] = id;
1114 * Emit type declaration (e.g., field type declaration in a struct or argument
1115 * declaration in function prototype) in correct C syntax.
1117 * For most types it's trivial, but there are few quirky type declaration
1118 * cases worth mentioning:
1119 * - function prototypes (especially nesting of function prototypes);
1121 * - const/volatile/restrict for pointers vs other types.
1123 * For a good discussion of *PARSING* C syntax (as a human), see
1124 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1125 * Ch.3 "Unscrambling Declarations in C".
1127 * It won't help with BTF to C conversion much, though, as it's an opposite
1128 * problem. So we came up with this algorithm in reverse to van der Linden's
1129 * parsing algorithm. It goes from structured BTF representation of type
1130 * declaration to a valid compilable C syntax.
1132 * For instance, consider this C typedef:
1133 * typedef const int * const * arr[10] arr_t;
1134 * It will be represented in BTF with this chain of BTF types:
1135 * [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1137 * Notice how [const] modifier always goes before type it modifies in BTF type
1138 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1139 * the right of pointers, but to the left of other types. There are also other
1140 * quirks, like function pointers, arrays of them, functions returning other
1143 * We handle that by pushing all the types to a stack, until we hit "terminal"
1144 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1145 * top of a stack, modifiers are handled differently. Array/function pointers
1146 * have also wildly different syntax and how nesting of them are done. See
1147 * code for authoritative definition.
1149 * To avoid allocating new stack for each independent chain of BTF types, we
1150 * share one bigger stack, with each chain working only on its own local view
1151 * of a stack frame. Some care is required to "pop" stack frames after
1152 * processing type declaration chain.
1154 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1155 const struct btf_dump_emit_type_decl_opts *opts)
1160 if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1161 return libbpf_err(-EINVAL);
1163 err = btf_dump_resize(d);
1165 return libbpf_err(err);
1167 fname = OPTS_GET(opts, field_name, "");
1168 lvl = OPTS_GET(opts, indent_level, 0);
1169 d->strip_mods = OPTS_GET(opts, strip_mods, false);
1170 btf_dump_emit_type_decl(d, id, fname, lvl);
1171 d->strip_mods = false;
1175 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1176 const char *fname, int lvl)
1178 struct id_stack decl_stack;
1179 const struct btf_type *t;
1180 int err, stack_start;
1182 stack_start = d->decl_stack_cnt;
1184 t = btf__type_by_id(d->btf, id);
1185 if (d->strip_mods && btf_is_mod(t))
1188 err = btf_dump_push_decl_stack_id(d, id);
1191 * if we don't have enough memory for entire type decl
1192 * chain, restore stack, emit warning, and try to
1193 * proceed nevertheless
1195 pr_warn("not enough memory for decl stack:%d", err);
1196 d->decl_stack_cnt = stack_start;
1204 switch (btf_kind(t)) {
1206 case BTF_KIND_VOLATILE:
1207 case BTF_KIND_CONST:
1208 case BTF_KIND_RESTRICT:
1209 case BTF_KIND_FUNC_PROTO:
1210 case BTF_KIND_TYPE_TAG:
1213 case BTF_KIND_ARRAY:
1214 id = btf_array(t)->type;
1218 case BTF_KIND_ENUM64:
1220 case BTF_KIND_STRUCT:
1221 case BTF_KIND_UNION:
1222 case BTF_KIND_TYPEDEF:
1223 case BTF_KIND_FLOAT:
1226 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1233 * We might be inside a chain of declarations (e.g., array of function
1234 * pointers returning anonymous (so inlined) structs, having another
1235 * array field). Each of those needs its own "stack frame" to handle
1236 * emitting of declarations. Those stack frames are non-overlapping
1237 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1238 * handle this set of nested stacks, we create a view corresponding to
1239 * our own "stack frame" and work with it as an independent stack.
1240 * We'll need to clean up after emit_type_chain() returns, though.
1242 decl_stack.ids = d->decl_stack + stack_start;
1243 decl_stack.cnt = d->decl_stack_cnt - stack_start;
1244 btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1246 * emit_type_chain() guarantees that it will pop its entire decl_stack
1247 * frame before returning. But it works with a read-only view into
1248 * decl_stack, so it doesn't actually pop anything from the
1249 * perspective of shared btf_dump->decl_stack, per se. We need to
1250 * reset decl_stack state to how it was before us to avoid it growing
1253 d->decl_stack_cnt = stack_start;
1256 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1258 const struct btf_type *t;
1261 while (decl_stack->cnt) {
1262 id = decl_stack->ids[decl_stack->cnt - 1];
1263 t = btf__type_by_id(d->btf, id);
1265 switch (btf_kind(t)) {
1266 case BTF_KIND_VOLATILE:
1267 btf_dump_printf(d, "volatile ");
1269 case BTF_KIND_CONST:
1270 btf_dump_printf(d, "const ");
1272 case BTF_KIND_RESTRICT:
1273 btf_dump_printf(d, "restrict ");
1282 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1284 const struct btf_type *t;
1287 while (decl_stack->cnt) {
1288 id = decl_stack->ids[decl_stack->cnt - 1];
1289 t = btf__type_by_id(d->btf, id);
1296 static void btf_dump_emit_name(const struct btf_dump *d,
1297 const char *name, bool last_was_ptr)
1299 bool separate = name[0] && !last_was_ptr;
1301 btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1304 static void btf_dump_emit_type_chain(struct btf_dump *d,
1305 struct id_stack *decls,
1306 const char *fname, int lvl)
1309 * last_was_ptr is used to determine if we need to separate pointer
1310 * asterisk (*) from previous part of type signature with space, so
1311 * that we get `int ***`, instead of `int * * *`. We default to true
1312 * for cases where we have single pointer in a chain. E.g., in ptr ->
1313 * func_proto case. func_proto will start a new emit_type_chain call
1314 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1315 * don't want to prepend space for that last pointer.
1317 bool last_was_ptr = true;
1318 const struct btf_type *t;
1323 while (decls->cnt) {
1324 id = decls->ids[--decls->cnt];
1326 /* VOID is a special snowflake */
1327 btf_dump_emit_mods(d, decls);
1328 btf_dump_printf(d, "void");
1329 last_was_ptr = false;
1333 t = btf__type_by_id(d->btf, id);
1338 case BTF_KIND_FLOAT:
1339 btf_dump_emit_mods(d, decls);
1340 name = btf_name_of(d, t->name_off);
1341 btf_dump_printf(d, "%s", name);
1343 case BTF_KIND_STRUCT:
1344 case BTF_KIND_UNION:
1345 btf_dump_emit_mods(d, decls);
1346 /* inline anonymous struct/union */
1347 if (t->name_off == 0 && !d->skip_anon_defs)
1348 btf_dump_emit_struct_def(d, id, t, lvl);
1350 btf_dump_emit_struct_fwd(d, id, t);
1353 case BTF_KIND_ENUM64:
1354 btf_dump_emit_mods(d, decls);
1355 /* inline anonymous enum */
1356 if (t->name_off == 0 && !d->skip_anon_defs)
1357 btf_dump_emit_enum_def(d, id, t, lvl);
1359 btf_dump_emit_enum_fwd(d, id, t);
1362 btf_dump_emit_mods(d, decls);
1363 btf_dump_emit_fwd_def(d, id, t);
1365 case BTF_KIND_TYPEDEF:
1366 btf_dump_emit_mods(d, decls);
1367 btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1370 btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1372 case BTF_KIND_VOLATILE:
1373 btf_dump_printf(d, " volatile");
1375 case BTF_KIND_CONST:
1376 btf_dump_printf(d, " const");
1378 case BTF_KIND_RESTRICT:
1379 btf_dump_printf(d, " restrict");
1381 case BTF_KIND_TYPE_TAG:
1382 btf_dump_emit_mods(d, decls);
1383 name = btf_name_of(d, t->name_off);
1384 btf_dump_printf(d, " __attribute__((btf_type_tag(\"%s\")))", name);
1386 case BTF_KIND_ARRAY: {
1387 const struct btf_array *a = btf_array(t);
1388 const struct btf_type *next_t;
1393 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1394 * which causes it to emit extra const/volatile
1395 * modifiers for an array, if array's element type has
1396 * const/volatile modifiers. Clang doesn't do that.
1397 * In general, it doesn't seem very meaningful to have
1398 * a const/volatile modifier for array, so we are
1399 * going to silently skip them here.
1401 btf_dump_drop_mods(d, decls);
1403 if (decls->cnt == 0) {
1404 btf_dump_emit_name(d, fname, last_was_ptr);
1405 btf_dump_printf(d, "[%u]", a->nelems);
1409 next_id = decls->ids[decls->cnt - 1];
1410 next_t = btf__type_by_id(d->btf, next_id);
1411 multidim = btf_is_array(next_t);
1412 /* we need space if we have named non-pointer */
1413 if (fname[0] && !last_was_ptr)
1414 btf_dump_printf(d, " ");
1415 /* no parentheses for multi-dimensional array */
1417 btf_dump_printf(d, "(");
1418 btf_dump_emit_type_chain(d, decls, fname, lvl);
1420 btf_dump_printf(d, ")");
1421 btf_dump_printf(d, "[%u]", a->nelems);
1424 case BTF_KIND_FUNC_PROTO: {
1425 const struct btf_param *p = btf_params(t);
1426 __u16 vlen = btf_vlen(t);
1430 * GCC emits extra volatile qualifier for
1431 * __attribute__((noreturn)) function pointers. Clang
1432 * doesn't do it. It's a GCC quirk for backwards
1433 * compatibility with code written for GCC <2.5. So,
1434 * similarly to extra qualifiers for array, just drop
1435 * them, instead of handling them.
1437 btf_dump_drop_mods(d, decls);
1439 btf_dump_printf(d, " (");
1440 btf_dump_emit_type_chain(d, decls, fname, lvl);
1441 btf_dump_printf(d, ")");
1443 btf_dump_emit_name(d, fname, last_was_ptr);
1445 btf_dump_printf(d, "(");
1447 * Clang for BPF target generates func_proto with no
1448 * args as a func_proto with a single void arg (e.g.,
1449 * `int (*f)(void)` vs just `int (*f)()`). We are
1450 * going to pretend there are no args for such case.
1452 if (vlen == 1 && p->type == 0) {
1453 btf_dump_printf(d, ")");
1457 for (i = 0; i < vlen; i++, p++) {
1459 btf_dump_printf(d, ", ");
1461 /* last arg of type void is vararg */
1462 if (i == vlen - 1 && p->type == 0) {
1463 btf_dump_printf(d, "...");
1467 name = btf_name_of(d, p->name_off);
1468 btf_dump_emit_type_decl(d, p->type, name, lvl);
1471 btf_dump_printf(d, ")");
1475 pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1480 last_was_ptr = kind == BTF_KIND_PTR;
1483 btf_dump_emit_name(d, fname, last_was_ptr);
1486 /* show type name as (type_name) */
1487 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1490 const struct btf_type *t;
1492 /* for array members, we don't bother emitting type name for each
1493 * member to avoid the redundancy of
1494 * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
1496 if (d->typed_dump->is_array_member)
1499 /* avoid type name specification for variable/section; it will be done
1500 * for the associated variable value(s).
1502 t = btf__type_by_id(d->btf, id);
1503 if (btf_is_var(t) || btf_is_datasec(t))
1507 btf_dump_printf(d, "(");
1509 d->skip_anon_defs = true;
1510 d->strip_mods = true;
1511 btf_dump_emit_type_decl(d, id, "", 0);
1512 d->strip_mods = false;
1513 d->skip_anon_defs = false;
1516 btf_dump_printf(d, ")");
1519 /* return number of duplicates (occurrences) of a given name */
1520 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1521 const char *orig_name)
1525 hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1527 hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1532 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1533 struct hashmap *name_map)
1535 struct btf_dump_type_aux_state *s = &d->type_states[id];
1536 const struct btf_type *t = btf__type_by_id(d->btf, id);
1537 const char *orig_name = btf_name_of(d, t->name_off);
1538 const char **cached_name = &d->cached_names[id];
1541 if (t->name_off == 0)
1544 if (s->name_resolved)
1545 return *cached_name ? *cached_name : orig_name;
1547 if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1548 s->name_resolved = 1;
1552 dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1554 const size_t max_len = 256;
1555 char new_name[max_len];
1557 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1558 *cached_name = strdup(new_name);
1561 s->name_resolved = 1;
1562 return *cached_name ? *cached_name : orig_name;
1565 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1567 return btf_dump_resolve_name(d, id, d->type_names);
1570 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1572 return btf_dump_resolve_name(d, id, d->ident_names);
1575 static int btf_dump_dump_type_data(struct btf_dump *d,
1577 const struct btf_type *t,
1583 static const char *btf_dump_data_newline(struct btf_dump *d)
1585 return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1588 static const char *btf_dump_data_delim(struct btf_dump *d)
1590 return d->typed_dump->depth == 0 ? "" : ",";
1593 static void btf_dump_data_pfx(struct btf_dump *d)
1595 int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1597 if (d->typed_dump->compact)
1600 for (i = 0; i < lvl; i++)
1601 btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1604 /* A macro is used here as btf_type_value[s]() appends format specifiers
1605 * to the format specifier passed in; these do the work of appending
1606 * delimiters etc while the caller simply has to specify the type values
1607 * in the format specifier + value(s).
1609 #define btf_dump_type_values(d, fmt, ...) \
1610 btf_dump_printf(d, fmt "%s%s", \
1612 btf_dump_data_delim(d), \
1613 btf_dump_data_newline(d))
1615 static int btf_dump_unsupported_data(struct btf_dump *d,
1616 const struct btf_type *t,
1619 btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1623 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1624 const struct btf_type *t,
1630 __u16 left_shift_bits, right_shift_bits;
1631 const __u8 *bytes = data;
1636 /* Maximum supported bitfield size is 64 bits */
1638 pr_warn("unexpected bitfield size %d\n", t->size);
1642 /* Bitfield value retrieval is done in two steps; first relevant bytes are
1643 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1645 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1646 for (i = t->size - 1; i >= 0; i--)
1647 num = num * 256 + bytes[i];
1648 nr_copy_bits = bit_sz + bits_offset;
1649 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1650 for (i = 0; i < t->size; i++)
1651 num = num * 256 + bytes[i];
1652 nr_copy_bits = t->size * 8 - bits_offset;
1654 # error "Unrecognized __BYTE_ORDER__"
1656 left_shift_bits = 64 - nr_copy_bits;
1657 right_shift_bits = 64 - bit_sz;
1659 *value = (num << left_shift_bits) >> right_shift_bits;
1664 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1665 const struct btf_type *t,
1673 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1681 static int btf_dump_bitfield_data(struct btf_dump *d,
1682 const struct btf_type *t,
1690 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1694 btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1699 /* ints, floats and ptrs */
1700 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1701 const struct btf_type *t,
1705 static __u8 bytecmp[16] = {};
1708 /* For pointer types, pointer size is not defined on a per-type basis.
1709 * On dump creation however, we store the pointer size.
1711 if (btf_kind(t) == BTF_KIND_PTR)
1712 nr_bytes = d->ptr_sz;
1716 if (nr_bytes < 1 || nr_bytes > 16) {
1717 pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1721 if (memcmp(data, bytecmp, nr_bytes) == 0)
1726 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1729 int alignment = btf__align_of(btf, type_id);
1734 return ((uintptr_t)data) % alignment == 0;
1737 static int btf_dump_int_data(struct btf_dump *d,
1738 const struct btf_type *t,
1743 __u8 encoding = btf_int_encoding(t);
1744 bool sign = encoding & BTF_INT_SIGNED;
1745 char buf[16] __attribute__((aligned(16)));
1748 if (sz == 0 || sz > sizeof(buf)) {
1749 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1753 /* handle packed int data - accesses of integers not aligned on
1754 * int boundaries can cause problems on some platforms.
1756 if (!ptr_is_aligned(d->btf, type_id, data)) {
1757 memcpy(buf, data, sz);
1763 const __u64 *ints = data;
1766 /* avoid use of __int128 as some 32-bit platforms do not
1769 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1772 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1776 # error "Unrecognized __BYTE_ORDER__"
1779 btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1781 btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1782 (unsigned long long)lsi);
1787 btf_dump_type_values(d, "%lld", *(long long *)data);
1789 btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1793 btf_dump_type_values(d, "%d", *(__s32 *)data);
1795 btf_dump_type_values(d, "%u", *(__u32 *)data);
1799 btf_dump_type_values(d, "%d", *(__s16 *)data);
1801 btf_dump_type_values(d, "%u", *(__u16 *)data);
1804 if (d->typed_dump->is_array_char) {
1805 /* check for null terminator */
1806 if (d->typed_dump->is_array_terminated)
1808 if (*(char *)data == '\0') {
1809 d->typed_dump->is_array_terminated = true;
1812 if (isprint(*(char *)data)) {
1813 btf_dump_type_values(d, "'%c'", *(char *)data);
1818 btf_dump_type_values(d, "%d", *(__s8 *)data);
1820 btf_dump_type_values(d, "%u", *(__u8 *)data);
1823 pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1835 static int btf_dump_float_data(struct btf_dump *d,
1836 const struct btf_type *t,
1840 const union float_data *flp = data;
1841 union float_data fl;
1844 /* handle unaligned data; copy to local union */
1845 if (!ptr_is_aligned(d->btf, type_id, data)) {
1846 memcpy(&fl, data, sz);
1852 btf_dump_type_values(d, "%Lf", flp->ld);
1855 btf_dump_type_values(d, "%lf", flp->d);
1858 btf_dump_type_values(d, "%f", flp->f);
1861 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1867 static int btf_dump_var_data(struct btf_dump *d,
1868 const struct btf_type *v,
1872 enum btf_func_linkage linkage = btf_var(v)->linkage;
1873 const struct btf_type *t;
1878 case BTF_FUNC_STATIC:
1881 case BTF_FUNC_EXTERN:
1884 case BTF_FUNC_GLOBAL:
1890 /* format of output here is [linkage] [type] [varname] = (type)value,
1891 * for example "static int cpu_profile_flip = (int)1"
1893 btf_dump_printf(d, "%s", l);
1895 t = btf__type_by_id(d->btf, type_id);
1896 btf_dump_emit_type_cast(d, type_id, false);
1897 btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
1898 return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
1901 static int btf_dump_array_data(struct btf_dump *d,
1902 const struct btf_type *t,
1906 const struct btf_array *array = btf_array(t);
1907 const struct btf_type *elem_type;
1908 __u32 i, elem_type_id;
1910 bool is_array_member;
1912 elem_type_id = array->type;
1913 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
1914 elem_size = btf__resolve_size(d->btf, elem_type_id);
1915 if (elem_size <= 0) {
1916 pr_warn("unexpected elem size %zd for array type [%u]\n",
1917 (ssize_t)elem_size, id);
1921 if (btf_is_int(elem_type)) {
1923 * BTF_INT_CHAR encoding never seems to be set for
1924 * char arrays, so if size is 1 and element is
1925 * printable as a char, we'll do that.
1928 d->typed_dump->is_array_char = true;
1931 /* note that we increment depth before calling btf_dump_print() below;
1932 * this is intentional. btf_dump_data_newline() will not print a
1933 * newline for depth 0 (since this leaves us with trailing newlines
1934 * at the end of typed display), so depth is incremented first.
1935 * For similar reasons, we decrement depth before showing the closing
1938 d->typed_dump->depth++;
1939 btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
1941 /* may be a multidimensional array, so store current "is array member"
1942 * status so we can restore it correctly later.
1944 is_array_member = d->typed_dump->is_array_member;
1945 d->typed_dump->is_array_member = true;
1946 for (i = 0; i < array->nelems; i++, data += elem_size) {
1947 if (d->typed_dump->is_array_terminated)
1949 btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
1951 d->typed_dump->is_array_member = is_array_member;
1952 d->typed_dump->depth--;
1953 btf_dump_data_pfx(d);
1954 btf_dump_type_values(d, "]");
1959 static int btf_dump_struct_data(struct btf_dump *d,
1960 const struct btf_type *t,
1964 const struct btf_member *m = btf_members(t);
1965 __u16 n = btf_vlen(t);
1968 /* note that we increment depth before calling btf_dump_print() below;
1969 * this is intentional. btf_dump_data_newline() will not print a
1970 * newline for depth 0 (since this leaves us with trailing newlines
1971 * at the end of typed display), so depth is incremented first.
1972 * For similar reasons, we decrement depth before showing the closing
1975 d->typed_dump->depth++;
1976 btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
1978 for (i = 0; i < n; i++, m++) {
1979 const struct btf_type *mtype;
1984 mtype = btf__type_by_id(d->btf, m->type);
1985 mname = btf_name_of(d, m->name_off);
1986 moffset = btf_member_bit_offset(t, i);
1988 bit_sz = btf_member_bitfield_size(t, i);
1989 err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
1990 moffset % 8, bit_sz);
1994 d->typed_dump->depth--;
1995 btf_dump_data_pfx(d);
1996 btf_dump_type_values(d, "}");
2002 unsigned long long lp;
2005 static int btf_dump_ptr_data(struct btf_dump *d,
2006 const struct btf_type *t,
2010 if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
2011 btf_dump_type_values(d, "%p", *(void **)data);
2015 memcpy(&pt, data, d->ptr_sz);
2017 btf_dump_type_values(d, "0x%x", pt.p);
2019 btf_dump_type_values(d, "0x%llx", pt.lp);
2024 static int btf_dump_get_enum_value(struct btf_dump *d,
2025 const struct btf_type *t,
2030 bool is_signed = btf_kflag(t);
2032 if (!ptr_is_aligned(d->btf, id, data)) {
2036 err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
2039 *value = (__s64)val;
2045 *value = *(__s64 *)data;
2048 *value = is_signed ? *(__s32 *)data : *(__u32 *)data;
2051 *value = is_signed ? *(__s16 *)data : *(__u16 *)data;
2054 *value = is_signed ? *(__s8 *)data : *(__u8 *)data;
2057 pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
2062 static int btf_dump_enum_data(struct btf_dump *d,
2063 const struct btf_type *t,
2071 err = btf_dump_get_enum_value(d, t, data, id, &value);
2075 is_signed = btf_kflag(t);
2076 if (btf_is_enum(t)) {
2077 const struct btf_enum *e;
2079 for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2080 if (value != e->val)
2082 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2086 btf_dump_type_values(d, is_signed ? "%d" : "%u", value);
2088 const struct btf_enum64 *e;
2090 for (i = 0, e = btf_enum64(t); i < btf_vlen(t); i++, e++) {
2091 if (value != btf_enum64_value(e))
2093 btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2097 btf_dump_type_values(d, is_signed ? "%lldLL" : "%lluULL",
2098 (unsigned long long)value);
2103 static int btf_dump_datasec_data(struct btf_dump *d,
2104 const struct btf_type *t,
2108 const struct btf_var_secinfo *vsi;
2109 const struct btf_type *var;
2113 btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2115 for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2116 var = btf__type_by_id(d->btf, vsi->type);
2117 err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2120 btf_dump_printf(d, ";");
2125 /* return size of type, or if base type overflows, return -E2BIG. */
2126 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2127 const struct btf_type *t,
2132 __s64 size = btf__resolve_size(d->btf, id);
2134 if (size < 0 || size >= INT_MAX) {
2135 pr_warn("unexpected size [%zu] for id [%u]\n",
2140 /* Only do overflow checking for base types; we do not want to
2141 * avoid showing part of a struct, union or array, even if we
2142 * do not have enough data to show the full object. By
2143 * restricting overflow checking to base types we can ensure
2144 * that partial display succeeds, while avoiding overflowing
2145 * and using bogus data for display.
2147 t = skip_mods_and_typedefs(d->btf, id, NULL);
2149 pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2154 switch (btf_kind(t)) {
2156 case BTF_KIND_FLOAT:
2159 case BTF_KIND_ENUM64:
2160 if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2169 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2170 const struct btf_type *t,
2179 /* toplevel exceptions; we show zero values if
2180 * - we ask for them (emit_zeros)
2181 * - if we are at top-level so we see "struct empty { }"
2182 * - or if we are an array member and the array is non-empty and
2183 * not a char array; we don't want to be in a situation where we
2184 * have an integer array 0, 1, 0, 1 and only show non-zero values.
2185 * If the array contains zeroes only, or is a char array starting
2186 * with a '\0', the array-level check_zero() will prevent showing it;
2187 * we are concerned with determining zero value at the array member
2190 if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2191 (d->typed_dump->is_array_member &&
2192 !d->typed_dump->is_array_char))
2195 t = skip_mods_and_typedefs(d->btf, id, NULL);
2197 switch (btf_kind(t)) {
2200 return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2201 return btf_dump_base_type_check_zero(d, t, id, data);
2202 case BTF_KIND_FLOAT:
2204 return btf_dump_base_type_check_zero(d, t, id, data);
2205 case BTF_KIND_ARRAY: {
2206 const struct btf_array *array = btf_array(t);
2207 const struct btf_type *elem_type;
2208 __u32 elem_type_id, elem_size;
2211 elem_type_id = array->type;
2212 elem_size = btf__resolve_size(d->btf, elem_type_id);
2213 elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2215 ischar = btf_is_int(elem_type) && elem_size == 1;
2217 /* check all elements; if _any_ element is nonzero, all
2218 * of array is displayed. We make an exception however
2219 * for char arrays where the first element is 0; these
2220 * are considered zeroed also, even if later elements are
2221 * non-zero because the string is terminated.
2223 for (i = 0; i < array->nelems; i++) {
2224 if (i == 0 && ischar && *(char *)data == 0)
2226 err = btf_dump_type_data_check_zero(d, elem_type,
2231 if (err != -ENODATA)
2236 case BTF_KIND_STRUCT:
2237 case BTF_KIND_UNION: {
2238 const struct btf_member *m = btf_members(t);
2239 __u16 n = btf_vlen(t);
2241 /* if any struct/union member is non-zero, the struct/union
2242 * is considered non-zero and dumped.
2244 for (i = 0; i < n; i++, m++) {
2245 const struct btf_type *mtype;
2248 mtype = btf__type_by_id(d->btf, m->type);
2249 moffset = btf_member_bit_offset(t, i);
2251 /* btf_int_bits() does not store member bitfield size;
2252 * bitfield size needs to be stored here so int display
2253 * of member can retrieve it.
2255 bit_sz = btf_member_bitfield_size(t, i);
2256 err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2257 moffset % 8, bit_sz);
2264 case BTF_KIND_ENUM64:
2265 err = btf_dump_get_enum_value(d, t, data, id, &value);
2276 /* returns size of data dumped, or error. */
2277 static int btf_dump_dump_type_data(struct btf_dump *d,
2279 const struct btf_type *t,
2287 size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2290 err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2292 /* zeroed data is expected and not an error, so simply skip
2293 * dumping such data. Record other errors however.
2295 if (err == -ENODATA)
2299 btf_dump_data_pfx(d);
2301 if (!d->typed_dump->skip_names) {
2302 if (fname && strlen(fname) > 0)
2303 btf_dump_printf(d, ".%s = ", fname);
2304 btf_dump_emit_type_cast(d, id, true);
2307 t = skip_mods_and_typedefs(d->btf, id, NULL);
2309 switch (btf_kind(t)) {
2313 case BTF_KIND_FUNC_PROTO:
2314 case BTF_KIND_DECL_TAG:
2315 err = btf_dump_unsupported_data(d, t, id);
2319 err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2321 err = btf_dump_int_data(d, t, id, data, bits_offset);
2323 case BTF_KIND_FLOAT:
2324 err = btf_dump_float_data(d, t, id, data);
2327 err = btf_dump_ptr_data(d, t, id, data);
2329 case BTF_KIND_ARRAY:
2330 err = btf_dump_array_data(d, t, id, data);
2332 case BTF_KIND_STRUCT:
2333 case BTF_KIND_UNION:
2334 err = btf_dump_struct_data(d, t, id, data);
2337 case BTF_KIND_ENUM64:
2338 /* handle bitfield and int enum values */
2343 err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2347 enum_val = (__s64)print_num;
2348 err = btf_dump_enum_data(d, t, id, &enum_val);
2350 err = btf_dump_enum_data(d, t, id, data);
2353 err = btf_dump_var_data(d, t, id, data);
2355 case BTF_KIND_DATASEC:
2356 err = btf_dump_datasec_data(d, t, id, data);
2359 pr_warn("unexpected kind [%u] for id [%u]\n",
2360 BTF_INFO_KIND(t->info), id);
2368 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2369 const void *data, size_t data_sz,
2370 const struct btf_dump_type_data_opts *opts)
2372 struct btf_dump_data typed_dump = {};
2373 const struct btf_type *t;
2376 if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2377 return libbpf_err(-EINVAL);
2379 t = btf__type_by_id(d->btf, id);
2381 return libbpf_err(-ENOENT);
2383 d->typed_dump = &typed_dump;
2384 d->typed_dump->data_end = data + data_sz;
2385 d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2387 /* default indent string is a tab */
2388 if (!opts->indent_str)
2389 d->typed_dump->indent_str[0] = '\t';
2391 libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
2392 sizeof(d->typed_dump->indent_str));
2394 d->typed_dump->compact = OPTS_GET(opts, compact, false);
2395 d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2396 d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2398 ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2400 d->typed_dump = NULL;
2402 return libbpf_err(ret);