Merge branch 'io_uring-zerocopy-send' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-2.6-microblaze.git] / tools / lib / bpf / btf_dump.c
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3 /*
4  * BTF-to-C type converter.
5  *
6  * Copyright (c) 2019 Facebook
7  */
8
9 #include <stdbool.h>
10 #include <stddef.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ctype.h>
14 #include <endian.h>
15 #include <errno.h>
16 #include <linux/err.h>
17 #include <linux/btf.h>
18 #include <linux/kernel.h>
19 #include "btf.h"
20 #include "hashmap.h"
21 #include "libbpf.h"
22 #include "libbpf_internal.h"
23
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;
26
27 static const char *pfx(int lvl)
28 {
29         return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
30 }
31
32 enum btf_dump_type_order_state {
33         NOT_ORDERED,
34         ORDERING,
35         ORDERED,
36 };
37
38 enum btf_dump_type_emit_state {
39         NOT_EMITTED,
40         EMITTING,
41         EMITTED,
42 };
43
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 */
51         __u8 fwd_emitted: 1;
52         /* whether unique non-duplicate name was already assigned */
53         __u8 name_resolved: 1;
54         /* whether type is referenced from any other type */
55         __u8 referenced: 1;
56 };
57
58 /* indent string length; one indent string is added for each indent level */
59 #define BTF_DATA_INDENT_STR_LEN                 32
60
61 /*
62  * Common internal data for BTF type data dump operations.
63  */
64 struct btf_dump_data {
65         const void *data_end;           /* end of valid data to show */
66         bool compact;
67         bool skip_names;
68         bool emit_zeroes;
69         __u8 indent_lvl;        /* base indent level */
70         char indent_str[BTF_DATA_INDENT_STR_LEN];
71         /* below are used during iteration */
72         int depth;
73         bool is_array_member;
74         bool is_array_terminated;
75         bool is_array_char;
76 };
77
78 struct btf_dump {
79         const struct btf *btf;
80         btf_dump_printf_fn_t printf_fn;
81         void *cb_ctx;
82         int ptr_sz;
83         bool strip_mods;
84         bool skip_anon_defs;
85         int last_id;
86
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;
93
94         /* topo-sorted list of dependent type definitions */
95         __u32 *emit_queue;
96         int emit_queue_cap;
97         int emit_queue_cnt;
98
99         /*
100          * stack of type declarations (e.g., chain of modifiers, arrays,
101          * funcs, etc)
102          */
103         __u32 *decl_stack;
104         int decl_stack_cap;
105         int decl_stack_cnt;
106
107         /* maps struct/union/enum name to a number of name occurrences */
108         struct hashmap *type_names;
109         /*
110          * maps typedef identifiers and enum value names to a number of such
111          * name occurrences
112          */
113         struct hashmap *ident_names;
114         /*
115          * data for typed display; allocated if needed.
116          */
117         struct btf_dump_data *typed_dump;
118 };
119
120 static size_t str_hash_fn(const void *key, void *ctx)
121 {
122         return str_hash(key);
123 }
124
125 static bool str_equal_fn(const void *a, const void *b, void *ctx)
126 {
127         return strcmp(a, b) == 0;
128 }
129
130 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
131 {
132         return btf__name_by_offset(d->btf, name_off);
133 }
134
135 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
136 {
137         va_list args;
138
139         va_start(args, fmt);
140         d->printf_fn(d->cb_ctx, fmt, args);
141         va_end(args);
142 }
143
144 static int btf_dump_mark_referenced(struct btf_dump *d);
145 static int btf_dump_resize(struct btf_dump *d);
146
147 struct btf_dump *btf_dump__new(const struct btf *btf,
148                                btf_dump_printf_fn_t printf_fn,
149                                void *ctx,
150                                const struct btf_dump_opts *opts)
151 {
152         struct btf_dump *d;
153         int err;
154
155         if (!OPTS_VALID(opts, btf_dump_opts))
156                 return libbpf_err_ptr(-EINVAL);
157
158         if (!printf_fn)
159                 return libbpf_err_ptr(-EINVAL);
160
161         d = calloc(1, sizeof(struct btf_dump));
162         if (!d)
163                 return libbpf_err_ptr(-ENOMEM);
164
165         d->btf = btf;
166         d->printf_fn = printf_fn;
167         d->cb_ctx = ctx;
168         d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
169
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;
174                 goto err;
175         }
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;
180                 goto err;
181         }
182
183         err = btf_dump_resize(d);
184         if (err)
185                 goto err;
186
187         return d;
188 err:
189         btf_dump__free(d);
190         return libbpf_err_ptr(err);
191 }
192
193 static int btf_dump_resize(struct btf_dump *d)
194 {
195         int err, last_id = btf__type_cnt(d->btf) - 1;
196
197         if (last_id <= d->last_id)
198                 return 0;
199
200         if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
201                               sizeof(*d->type_states), last_id + 1))
202                 return -ENOMEM;
203         if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
204                               sizeof(*d->cached_names), last_id + 1))
205                 return -ENOMEM;
206
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;
211         }
212
213         /* eagerly determine referenced types for anon enums */
214         err = btf_dump_mark_referenced(d);
215         if (err)
216                 return err;
217
218         d->last_id = last_id;
219         return 0;
220 }
221
222 void btf_dump__free(struct btf_dump *d)
223 {
224         int i;
225
226         if (IS_ERR_OR_NULL(d))
227                 return;
228
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]);
235                 }
236         }
237         free(d->cached_names);
238         free(d->emit_queue);
239         free(d->decl_stack);
240         hashmap__free(d->type_names);
241         hashmap__free(d->ident_names);
242
243         free(d);
244 }
245
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);
248
249 /*
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.
258  *
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.
262  *
263  * Returns 0 on success; <0, otherwise.
264  */
265 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
266 {
267         int err, i;
268
269         if (id >= btf__type_cnt(d->btf))
270                 return libbpf_err(-EINVAL);
271
272         err = btf_dump_resize(d);
273         if (err)
274                 return libbpf_err(err);
275
276         d->emit_queue_cnt = 0;
277         err = btf_dump_order_type(d, id, false);
278         if (err < 0)
279                 return libbpf_err(err);
280
281         for (i = 0; i < d->emit_queue_cnt; i++)
282                 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
283
284         return 0;
285 }
286
287 /*
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
297  * one will.
298  */
299 static int btf_dump_mark_referenced(struct btf_dump *d)
300 {
301         int i, j, n = btf__type_cnt(d->btf);
302         const struct btf_type *t;
303         __u16 vlen;
304
305         for (i = d->last_id + 1; i < n; i++) {
306                 t = btf__type_by_id(d->btf, i);
307                 vlen = btf_vlen(t);
308
309                 switch (btf_kind(t)) {
310                 case BTF_KIND_INT:
311                 case BTF_KIND_ENUM:
312                 case BTF_KIND_ENUM64:
313                 case BTF_KIND_FWD:
314                 case BTF_KIND_FLOAT:
315                         break;
316
317                 case BTF_KIND_VOLATILE:
318                 case BTF_KIND_CONST:
319                 case BTF_KIND_RESTRICT:
320                 case BTF_KIND_PTR:
321                 case BTF_KIND_TYPEDEF:
322                 case BTF_KIND_FUNC:
323                 case BTF_KIND_VAR:
324                 case BTF_KIND_DECL_TAG:
325                 case BTF_KIND_TYPE_TAG:
326                         d->type_states[t->type].referenced = 1;
327                         break;
328
329                 case BTF_KIND_ARRAY: {
330                         const struct btf_array *a = btf_array(t);
331
332                         d->type_states[a->index_type].referenced = 1;
333                         d->type_states[a->type].referenced = 1;
334                         break;
335                 }
336                 case BTF_KIND_STRUCT:
337                 case BTF_KIND_UNION: {
338                         const struct btf_member *m = btf_members(t);
339
340                         for (j = 0; j < vlen; j++, m++)
341                                 d->type_states[m->type].referenced = 1;
342                         break;
343                 }
344                 case BTF_KIND_FUNC_PROTO: {
345                         const struct btf_param *p = btf_params(t);
346
347                         for (j = 0; j < vlen; j++, p++)
348                                 d->type_states[p->type].referenced = 1;
349                         break;
350                 }
351                 case BTF_KIND_DATASEC: {
352                         const struct btf_var_secinfo *v = btf_var_secinfos(t);
353
354                         for (j = 0; j < vlen; j++, v++)
355                                 d->type_states[v->type].referenced = 1;
356                         break;
357                 }
358                 default:
359                         return -EINVAL;
360                 }
361         }
362         return 0;
363 }
364
365 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
366 {
367         __u32 *new_queue;
368         size_t new_cap;
369
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]));
373                 if (!new_queue)
374                         return -ENOMEM;
375                 d->emit_queue = new_queue;
376                 d->emit_queue_cap = new_cap;
377         }
378
379         d->emit_queue[d->emit_queue_cnt++] = id;
380         return 0;
381 }
382
383 /*
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:
389  *
390  *      struct A {};
391  *      struct B { struct A x; }
392  *
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:
395  *
396  *      struct A;
397  *      struct B { struct A *x; }
398  *      struct A {};
399  *
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 *).
403  *
404  * Unfortunately, there are some trickier cases we need to handle, e.g.:
405  *
406  *      struct A {}; // if this was forward-declaration: compilation error
407  *      struct B {
408  *              struct { // anonymous struct
409  *                      struct A y;
410  *              } *x;
411  *      };
412  *
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.
421  *
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
424  * nodes):
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.
428  *
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().
434  *
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
437  * emitted.
438  *
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.
449  *
450  * Returns:
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
454  *   declaration);
455  *   - <0, on error (e.g., unsatisfiable type loop detected).
456  */
457 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
458 {
459         /*
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.
469          */
470         struct btf_dump_type_aux_state *tstate = &d->type_states[id];
471         const struct btf_type *t;
472         __u16 vlen;
473         int err, i;
474
475         /* return true, letting typedefs know that it's ok to be emitted */
476         if (tstate->order_state == ORDERED)
477                 return 1;
478
479         t = btf__type_by_id(d->btf, id);
480
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)
484                         return 0;
485                 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
486                 return -ELOOP;
487         }
488
489         switch (btf_kind(t)) {
490         case BTF_KIND_INT:
491         case BTF_KIND_FLOAT:
492                 tstate->order_state = ORDERED;
493                 return 0;
494
495         case BTF_KIND_PTR:
496                 err = btf_dump_order_type(d, t->type, true);
497                 tstate->order_state = ORDERED;
498                 return err;
499
500         case BTF_KIND_ARRAY:
501                 return btf_dump_order_type(d, btf_array(t)->type, false);
502
503         case BTF_KIND_STRUCT:
504         case BTF_KIND_UNION: {
505                 const struct btf_member *m = btf_members(t);
506                 /*
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)
510                  */
511                 if (through_ptr && t->name_off != 0)
512                         return 0;
513
514                 tstate->order_state = ORDERING;
515
516                 vlen = btf_vlen(t);
517                 for (i = 0; i < vlen; i++, m++) {
518                         err = btf_dump_order_type(d, m->type, false);
519                         if (err < 0)
520                                 return err;
521                 }
522
523                 if (t->name_off != 0) {
524                         err = btf_dump_add_emit_queue_id(d, id);
525                         if (err < 0)
526                                 return err;
527                 }
528
529                 tstate->order_state = ORDERED;
530                 return 1;
531         }
532         case BTF_KIND_ENUM:
533         case BTF_KIND_ENUM64:
534         case BTF_KIND_FWD:
535                 /*
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.
539                  */
540                 if (t->name_off != 0 || !tstate->referenced) {
541                         err = btf_dump_add_emit_queue_id(d, id);
542                         if (err)
543                                 return err;
544                 }
545                 tstate->order_state = ORDERED;
546                 return 1;
547
548         case BTF_KIND_TYPEDEF: {
549                 int is_strong;
550
551                 is_strong = btf_dump_order_type(d, t->type, through_ptr);
552                 if (is_strong < 0)
553                         return is_strong;
554
555                 /* typedef is similar to struct/union w.r.t. fwd-decls */
556                 if (through_ptr && !is_strong)
557                         return 0;
558
559                 /* typedef is always a named definition */
560                 err = btf_dump_add_emit_queue_id(d, id);
561                 if (err)
562                         return err;
563
564                 d->type_states[id].order_state = ORDERED;
565                 return 1;
566         }
567         case BTF_KIND_VOLATILE:
568         case BTF_KIND_CONST:
569         case BTF_KIND_RESTRICT:
570         case BTF_KIND_TYPE_TAG:
571                 return btf_dump_order_type(d, t->type, through_ptr);
572
573         case BTF_KIND_FUNC_PROTO: {
574                 const struct btf_param *p = btf_params(t);
575                 bool is_strong;
576
577                 err = btf_dump_order_type(d, t->type, through_ptr);
578                 if (err < 0)
579                         return err;
580                 is_strong = err > 0;
581
582                 vlen = btf_vlen(t);
583                 for (i = 0; i < vlen; i++, p++) {
584                         err = btf_dump_order_type(d, p->type, through_ptr);
585                         if (err < 0)
586                                 return err;
587                         if (err > 0)
588                                 is_strong = true;
589                 }
590                 return is_strong;
591         }
592         case BTF_KIND_FUNC:
593         case BTF_KIND_VAR:
594         case BTF_KIND_DATASEC:
595         case BTF_KIND_DECL_TAG:
596                 d->type_states[id].order_state = ORDERED;
597                 return 0;
598
599         default:
600                 return -EINVAL;
601         }
602 }
603
604 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
605                                           const struct btf_type *t);
606
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);
611
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);
616
617 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
618                                   const struct btf_type *t);
619
620 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
621                                       const struct btf_type *t, int lvl);
622
623 /* a local view into a shared stack */
624 struct id_stack {
625         const __u32 *ids;
626         int cnt;
627 };
628
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);
634
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);
639
640 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
641 {
642         const struct btf_type *t = btf__type_by_id(d->btf, id);
643
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.
649          */
650         if (t->name_off == 0)
651                 return false;
652         return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
653 }
654
655 /*
656  * Emit C-syntax definitions of types from chains of BTF types.
657  *
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.
663  *
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
666  * declaration.
667  *
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.
672  */
673 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
674 {
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;
678         __u16 kind;
679
680         if (tstate->emit_state == EMITTED)
681                 return;
682
683         t = btf__type_by_id(d->btf, id);
684         kind = btf_kind(t);
685
686         if (tstate->emit_state == EMITTING) {
687                 if (tstate->fwd_emitted)
688                         return;
689
690                 switch (kind) {
691                 case BTF_KIND_STRUCT:
692                 case BTF_KIND_UNION:
693                         /*
694                          * if we are referencing a struct/union that we are
695                          * part of - then no need for fwd declaration
696                          */
697                         if (id == cont_id)
698                                 return;
699                         if (t->name_off == 0) {
700                                 pr_warn("anonymous struct/union loop, id:[%u]\n",
701                                         id);
702                                 return;
703                         }
704                         btf_dump_emit_struct_fwd(d, id, t);
705                         btf_dump_printf(d, ";\n\n");
706                         tstate->fwd_emitted = 1;
707                         break;
708                 case BTF_KIND_TYPEDEF:
709                         /*
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
713                          */
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");
717                         }
718                         tstate->fwd_emitted = 1;
719                         break;
720                 default:
721                         break;
722                 }
723
724                 return;
725         }
726
727         switch (kind) {
728         case BTF_KIND_INT:
729                 /* Emit type alias definitions if necessary */
730                 btf_dump_emit_missing_aliases(d, id, t);
731
732                 tstate->emit_state = EMITTED;
733                 break;
734         case BTF_KIND_ENUM:
735         case BTF_KIND_ENUM64:
736                 if (top_level_def) {
737                         btf_dump_emit_enum_def(d, id, t, 0);
738                         btf_dump_printf(d, ";\n\n");
739                 }
740                 tstate->emit_state = EMITTED;
741                 break;
742         case BTF_KIND_PTR:
743         case BTF_KIND_VOLATILE:
744         case BTF_KIND_CONST:
745         case BTF_KIND_RESTRICT:
746         case BTF_KIND_TYPE_TAG:
747                 btf_dump_emit_type(d, t->type, cont_id);
748                 break;
749         case BTF_KIND_ARRAY:
750                 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
751                 break;
752         case BTF_KIND_FWD:
753                 btf_dump_emit_fwd_def(d, id, t);
754                 btf_dump_printf(d, ";\n\n");
755                 tstate->emit_state = EMITTED;
756                 break;
757         case BTF_KIND_TYPEDEF:
758                 tstate->emit_state = EMITTING;
759                 btf_dump_emit_type(d, t->type, id);
760                 /*
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
766                  */
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");
770                 }
771                 tstate->emit_state = EMITTED;
772                 break;
773         case BTF_KIND_STRUCT:
774         case BTF_KIND_UNION:
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
781                  * applicable
782                  */
783                 if (top_level_def || t->name_off == 0) {
784                         const struct btf_member *m = btf_members(t);
785                         __u16 vlen = btf_vlen(t);
786                         int i, new_cont_id;
787
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;
795                 }
796
797                 if (top_level_def) {
798                         btf_dump_emit_struct_def(d, id, t, 0);
799                         btf_dump_printf(d, ";\n\n");
800                         tstate->emit_state = EMITTED;
801                 } else {
802                         tstate->emit_state = NOT_EMITTED;
803                 }
804                 break;
805         case BTF_KIND_FUNC_PROTO: {
806                 const struct btf_param *p = btf_params(t);
807                 __u16 n = btf_vlen(t);
808                 int i;
809
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);
813
814                 break;
815         }
816         default:
817                 break;
818         }
819 }
820
821 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
822                                  const struct btf_type *t)
823 {
824         const struct btf_member *m;
825         int align, i, bit_sz;
826         __u16 vlen;
827
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)
831                 return true;
832
833         m = btf_members(t);
834         vlen = btf_vlen(t);
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)
840                         return true;
841         }
842
843         /*
844          * if original struct was marked as packed, but its layout is
845          * naturally aligned, we'll detect that it's not packed
846          */
847         return false;
848 }
849
850 static int chip_away_bits(int total, int at_most)
851 {
852         return total % at_most ? : at_most;
853 }
854
855 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
856                                       int cur_off, int m_off, int m_bit_sz,
857                                       int align, int lvl)
858 {
859         int off_diff = m_off - cur_off;
860         int ptr_bits = d->ptr_sz * 8;
861
862         if (off_diff <= 0)
863                 /* no gap */
864                 return;
865         if (m_bit_sz == 0 && off_diff < align * 8)
866                 /* natural padding will take care of a gap */
867                 return;
868
869         while (off_diff > 0) {
870                 const char *pad_type;
871                 int pad_bits;
872
873                 if (ptr_bits > 32 && off_diff > 32) {
874                         pad_type = "long";
875                         pad_bits = chip_away_bits(off_diff, ptr_bits);
876                 } else if (off_diff > 16) {
877                         pad_type = "int";
878                         pad_bits = chip_away_bits(off_diff, 32);
879                 } else if (off_diff > 8) {
880                         pad_type = "short";
881                         pad_bits = chip_away_bits(off_diff, 16);
882                 } else {
883                         pad_type = "char";
884                         pad_bits = chip_away_bits(off_diff, 8);
885                 }
886                 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
887                 off_diff -= pad_bits;
888         }
889 }
890
891 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
892                                      const struct btf_type *t)
893 {
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));
898 }
899
900 static void btf_dump_emit_struct_def(struct btf_dump *d,
901                                      __u32 id,
902                                      const struct btf_type *t,
903                                      int lvl)
904 {
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);
909
910         packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
911
912         btf_dump_printf(d, "%s%s%s {",
913                         is_struct ? "struct" : "union",
914                         t->name_off ? " " : "",
915                         btf_dump_type_name(d, id));
916
917         for (i = 0; i < vlen; i++, m++) {
918                 const char *fname;
919                 int m_off, m_sz;
920
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);
925
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);
929
930                 if (m_sz) {
931                         btf_dump_printf(d, ": %d", m_sz);
932                         off = m_off + m_sz;
933                 } else {
934                         m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
935                         off = m_off + m_sz * 8;
936                 }
937                 btf_dump_printf(d, ";");
938         }
939
940         /* pad at the end, if necessary */
941         if (is_struct) {
942                 align = packed ? 1 : btf__align_of(d->btf, id);
943                 btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
944                                           lvl + 1);
945         }
946
947         if (vlen)
948                 btf_dump_printf(d, "\n");
949         btf_dump_printf(d, "%s}", pfx(lvl));
950         if (packed)
951                 btf_dump_printf(d, " __attribute__((packed))");
952 }
953
954 static const char *missing_base_types[][2] = {
955         /*
956          * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
957          * SIMD intrinsics. Alias them to standard base types.
958          */
959         { "__Poly8_t",          "unsigned char" },
960         { "__Poly16_t",         "unsigned short" },
961         { "__Poly64_t",         "unsigned long long" },
962         { "__Poly128_t",        "unsigned __int128" },
963 };
964
965 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
966                                           const struct btf_type *t)
967 {
968         const char *name = btf_dump_type_name(d, id);
969         int i;
970
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);
975                         break;
976                 }
977         }
978 }
979
980 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
981                                    const struct btf_type *t)
982 {
983         btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
984 }
985
986 static void btf_dump_emit_enum32_val(struct btf_dump *d,
987                                      const struct btf_type *t,
988                                      int lvl, __u16 vlen)
989 {
990         const struct btf_enum *v = btf_enum(t);
991         bool is_signed = btf_kflag(t);
992         const char *fmt_str;
993         const char *name;
994         size_t dup_cnt;
995         int i;
996
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);
1001                 if (dup_cnt > 1) {
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);
1004                 } else {
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);
1007                 }
1008         }
1009 }
1010
1011 static void btf_dump_emit_enum64_val(struct btf_dump *d,
1012                                      const struct btf_type *t,
1013                                      int lvl, __u16 vlen)
1014 {
1015         const struct btf_enum64 *v = btf_enum64(t);
1016         bool is_signed = btf_kflag(t);
1017         const char *fmt_str;
1018         const char *name;
1019         size_t dup_cnt;
1020         __u64 val;
1021         int i;
1022
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);
1027                 if (dup_cnt > 1) {
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);
1033                 } else {
1034                         fmt_str = is_signed ? "\n%s%s = %lldLL,"
1035                                             : "\n%s%s = %lluULL,";
1036                         btf_dump_printf(d, fmt_str,
1037                                         pfx(lvl + 1), name,
1038                                         (unsigned long long)val);
1039                 }
1040         }
1041 }
1042 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
1043                                    const struct btf_type *t,
1044                                    int lvl)
1045 {
1046         __u16 vlen = btf_vlen(t);
1047
1048         btf_dump_printf(d, "enum%s%s",
1049                         t->name_off ? " " : "",
1050                         btf_dump_type_name(d, id));
1051
1052         if (!vlen)
1053                 return;
1054
1055         btf_dump_printf(d, " {");
1056         if (btf_is_enum(t))
1057                 btf_dump_emit_enum32_val(d, t, lvl, vlen);
1058         else
1059                 btf_dump_emit_enum64_val(d, t, lvl, vlen);
1060         btf_dump_printf(d, "\n%s}", pfx(lvl));
1061 }
1062
1063 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1064                                   const struct btf_type *t)
1065 {
1066         const char *name = btf_dump_type_name(d, id);
1067
1068         if (btf_kflag(t))
1069                 btf_dump_printf(d, "union %s", name);
1070         else
1071                 btf_dump_printf(d, "struct %s", name);
1072 }
1073
1074 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1075                                      const struct btf_type *t, int lvl)
1076 {
1077         const char *name = btf_dump_ident_name(d, id);
1078
1079         /*
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.
1084          */
1085         if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1086                 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1087                 return;
1088         }
1089
1090         btf_dump_printf(d, "typedef ");
1091         btf_dump_emit_type_decl(d, t->type, name, lvl);
1092 }
1093
1094 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1095 {
1096         __u32 *new_stack;
1097         size_t new_cap;
1098
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]));
1102                 if (!new_stack)
1103                         return -ENOMEM;
1104                 d->decl_stack = new_stack;
1105                 d->decl_stack_cap = new_cap;
1106         }
1107
1108         d->decl_stack[d->decl_stack_cnt++] = id;
1109
1110         return 0;
1111 }
1112
1113 /*
1114  * Emit type declaration (e.g., field type declaration in a struct or argument
1115  * declaration in function prototype) in correct C syntax.
1116  *
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);
1120  *   - arrays;
1121  *   - const/volatile/restrict for pointers vs other types.
1122  *
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".
1126  *
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.
1131  *
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]
1136  *
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
1141  * functions, etc.
1142  *
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.
1148  *
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.
1153  */
1154 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1155                              const struct btf_dump_emit_type_decl_opts *opts)
1156 {
1157         const char *fname;
1158         int lvl, err;
1159
1160         if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1161                 return libbpf_err(-EINVAL);
1162
1163         err = btf_dump_resize(d);
1164         if (err)
1165                 return libbpf_err(err);
1166
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;
1172         return 0;
1173 }
1174
1175 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1176                                     const char *fname, int lvl)
1177 {
1178         struct id_stack decl_stack;
1179         const struct btf_type *t;
1180         int err, stack_start;
1181
1182         stack_start = d->decl_stack_cnt;
1183         for (;;) {
1184                 t = btf__type_by_id(d->btf, id);
1185                 if (d->strip_mods && btf_is_mod(t))
1186                         goto skip_mod;
1187
1188                 err = btf_dump_push_decl_stack_id(d, id);
1189                 if (err < 0) {
1190                         /*
1191                          * if we don't have enough memory for entire type decl
1192                          * chain, restore stack, emit warning, and try to
1193                          * proceed nevertheless
1194                          */
1195                         pr_warn("not enough memory for decl stack:%d", err);
1196                         d->decl_stack_cnt = stack_start;
1197                         return;
1198                 }
1199 skip_mod:
1200                 /* VOID */
1201                 if (id == 0)
1202                         break;
1203
1204                 switch (btf_kind(t)) {
1205                 case BTF_KIND_PTR:
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:
1211                         id = t->type;
1212                         break;
1213                 case BTF_KIND_ARRAY:
1214                         id = btf_array(t)->type;
1215                         break;
1216                 case BTF_KIND_INT:
1217                 case BTF_KIND_ENUM:
1218                 case BTF_KIND_ENUM64:
1219                 case BTF_KIND_FWD:
1220                 case BTF_KIND_STRUCT:
1221                 case BTF_KIND_UNION:
1222                 case BTF_KIND_TYPEDEF:
1223                 case BTF_KIND_FLOAT:
1224                         goto done;
1225                 default:
1226                         pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1227                                 btf_kind(t), id);
1228                         goto done;
1229                 }
1230         }
1231 done:
1232         /*
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.
1241          */
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);
1245         /*
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
1251          * all the time.
1252          */
1253         d->decl_stack_cnt = stack_start;
1254 }
1255
1256 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1257 {
1258         const struct btf_type *t;
1259         __u32 id;
1260
1261         while (decl_stack->cnt) {
1262                 id = decl_stack->ids[decl_stack->cnt - 1];
1263                 t = btf__type_by_id(d->btf, id);
1264
1265                 switch (btf_kind(t)) {
1266                 case BTF_KIND_VOLATILE:
1267                         btf_dump_printf(d, "volatile ");
1268                         break;
1269                 case BTF_KIND_CONST:
1270                         btf_dump_printf(d, "const ");
1271                         break;
1272                 case BTF_KIND_RESTRICT:
1273                         btf_dump_printf(d, "restrict ");
1274                         break;
1275                 default:
1276                         return;
1277                 }
1278                 decl_stack->cnt--;
1279         }
1280 }
1281
1282 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1283 {
1284         const struct btf_type *t;
1285         __u32 id;
1286
1287         while (decl_stack->cnt) {
1288                 id = decl_stack->ids[decl_stack->cnt - 1];
1289                 t = btf__type_by_id(d->btf, id);
1290                 if (!btf_is_mod(t))
1291                         return;
1292                 decl_stack->cnt--;
1293         }
1294 }
1295
1296 static void btf_dump_emit_name(const struct btf_dump *d,
1297                                const char *name, bool last_was_ptr)
1298 {
1299         bool separate = name[0] && !last_was_ptr;
1300
1301         btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1302 }
1303
1304 static void btf_dump_emit_type_chain(struct btf_dump *d,
1305                                      struct id_stack *decls,
1306                                      const char *fname, int lvl)
1307 {
1308         /*
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.
1316          */
1317         bool last_was_ptr = true;
1318         const struct btf_type *t;
1319         const char *name;
1320         __u16 kind;
1321         __u32 id;
1322
1323         while (decls->cnt) {
1324                 id = decls->ids[--decls->cnt];
1325                 if (id == 0) {
1326                         /* VOID is a special snowflake */
1327                         btf_dump_emit_mods(d, decls);
1328                         btf_dump_printf(d, "void");
1329                         last_was_ptr = false;
1330                         continue;
1331                 }
1332
1333                 t = btf__type_by_id(d->btf, id);
1334                 kind = btf_kind(t);
1335
1336                 switch (kind) {
1337                 case BTF_KIND_INT:
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);
1342                         break;
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);
1349                         else
1350                                 btf_dump_emit_struct_fwd(d, id, t);
1351                         break;
1352                 case BTF_KIND_ENUM:
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);
1358                         else
1359                                 btf_dump_emit_enum_fwd(d, id, t);
1360                         break;
1361                 case BTF_KIND_FWD:
1362                         btf_dump_emit_mods(d, decls);
1363                         btf_dump_emit_fwd_def(d, id, t);
1364                         break;
1365                 case BTF_KIND_TYPEDEF:
1366                         btf_dump_emit_mods(d, decls);
1367                         btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1368                         break;
1369                 case BTF_KIND_PTR:
1370                         btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1371                         break;
1372                 case BTF_KIND_VOLATILE:
1373                         btf_dump_printf(d, " volatile");
1374                         break;
1375                 case BTF_KIND_CONST:
1376                         btf_dump_printf(d, " const");
1377                         break;
1378                 case BTF_KIND_RESTRICT:
1379                         btf_dump_printf(d, " restrict");
1380                         break;
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);
1385                         break;
1386                 case BTF_KIND_ARRAY: {
1387                         const struct btf_array *a = btf_array(t);
1388                         const struct btf_type *next_t;
1389                         __u32 next_id;
1390                         bool multidim;
1391                         /*
1392                          * GCC has a bug
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.
1400                          */
1401                         btf_dump_drop_mods(d, decls);
1402
1403                         if (decls->cnt == 0) {
1404                                 btf_dump_emit_name(d, fname, last_was_ptr);
1405                                 btf_dump_printf(d, "[%u]", a->nelems);
1406                                 return;
1407                         }
1408
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 */
1416                         if (!multidim)
1417                                 btf_dump_printf(d, "(");
1418                         btf_dump_emit_type_chain(d, decls, fname, lvl);
1419                         if (!multidim)
1420                                 btf_dump_printf(d, ")");
1421                         btf_dump_printf(d, "[%u]", a->nelems);
1422                         return;
1423                 }
1424                 case BTF_KIND_FUNC_PROTO: {
1425                         const struct btf_param *p = btf_params(t);
1426                         __u16 vlen = btf_vlen(t);
1427                         int i;
1428
1429                         /*
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.
1436                          */
1437                         btf_dump_drop_mods(d, decls);
1438                         if (decls->cnt) {
1439                                 btf_dump_printf(d, " (");
1440                                 btf_dump_emit_type_chain(d, decls, fname, lvl);
1441                                 btf_dump_printf(d, ")");
1442                         } else {
1443                                 btf_dump_emit_name(d, fname, last_was_ptr);
1444                         }
1445                         btf_dump_printf(d, "(");
1446                         /*
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.
1451                          */
1452                         if (vlen == 1 && p->type == 0) {
1453                                 btf_dump_printf(d, ")");
1454                                 return;
1455                         }
1456
1457                         for (i = 0; i < vlen; i++, p++) {
1458                                 if (i > 0)
1459                                         btf_dump_printf(d, ", ");
1460
1461                                 /* last arg of type void is vararg */
1462                                 if (i == vlen - 1 && p->type == 0) {
1463                                         btf_dump_printf(d, "...");
1464                                         break;
1465                                 }
1466
1467                                 name = btf_name_of(d, p->name_off);
1468                                 btf_dump_emit_type_decl(d, p->type, name, lvl);
1469                         }
1470
1471                         btf_dump_printf(d, ")");
1472                         return;
1473                 }
1474                 default:
1475                         pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1476                                 kind, id);
1477                         return;
1478                 }
1479
1480                 last_was_ptr = kind == BTF_KIND_PTR;
1481         }
1482
1483         btf_dump_emit_name(d, fname, last_was_ptr);
1484 }
1485
1486 /* show type name as (type_name) */
1487 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1488                                     bool top_level)
1489 {
1490         const struct btf_type *t;
1491
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',]
1495          */
1496         if (d->typed_dump->is_array_member)
1497                 return;
1498
1499         /* avoid type name specification for variable/section; it will be done
1500          * for the associated variable value(s).
1501          */
1502         t = btf__type_by_id(d->btf, id);
1503         if (btf_is_var(t) || btf_is_datasec(t))
1504                 return;
1505
1506         if (top_level)
1507                 btf_dump_printf(d, "(");
1508
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;
1514
1515         if (top_level)
1516                 btf_dump_printf(d, ")");
1517 }
1518
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)
1522 {
1523         size_t dup_cnt = 0;
1524
1525         hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1526         dup_cnt++;
1527         hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1528
1529         return dup_cnt;
1530 }
1531
1532 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1533                                          struct hashmap *name_map)
1534 {
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];
1539         size_t dup_cnt;
1540
1541         if (t->name_off == 0)
1542                 return "";
1543
1544         if (s->name_resolved)
1545                 return *cached_name ? *cached_name : orig_name;
1546
1547         if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1548                 s->name_resolved = 1;
1549                 return orig_name;
1550         }
1551
1552         dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1553         if (dup_cnt > 1) {
1554                 const size_t max_len = 256;
1555                 char new_name[max_len];
1556
1557                 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1558                 *cached_name = strdup(new_name);
1559         }
1560
1561         s->name_resolved = 1;
1562         return *cached_name ? *cached_name : orig_name;
1563 }
1564
1565 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1566 {
1567         return btf_dump_resolve_name(d, id, d->type_names);
1568 }
1569
1570 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1571 {
1572         return btf_dump_resolve_name(d, id, d->ident_names);
1573 }
1574
1575 static int btf_dump_dump_type_data(struct btf_dump *d,
1576                                    const char *fname,
1577                                    const struct btf_type *t,
1578                                    __u32 id,
1579                                    const void *data,
1580                                    __u8 bits_offset,
1581                                    __u8 bit_sz);
1582
1583 static const char *btf_dump_data_newline(struct btf_dump *d)
1584 {
1585         return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1586 }
1587
1588 static const char *btf_dump_data_delim(struct btf_dump *d)
1589 {
1590         return d->typed_dump->depth == 0 ? "" : ",";
1591 }
1592
1593 static void btf_dump_data_pfx(struct btf_dump *d)
1594 {
1595         int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1596
1597         if (d->typed_dump->compact)
1598                 return;
1599
1600         for (i = 0; i < lvl; i++)
1601                 btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1602 }
1603
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).
1608  */
1609 #define btf_dump_type_values(d, fmt, ...)                               \
1610         btf_dump_printf(d, fmt "%s%s",                                  \
1611                         ##__VA_ARGS__,                                  \
1612                         btf_dump_data_delim(d),                         \
1613                         btf_dump_data_newline(d))
1614
1615 static int btf_dump_unsupported_data(struct btf_dump *d,
1616                                      const struct btf_type *t,
1617                                      __u32 id)
1618 {
1619         btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1620         return -ENOTSUP;
1621 }
1622
1623 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1624                                        const struct btf_type *t,
1625                                        const void *data,
1626                                        __u8 bits_offset,
1627                                        __u8 bit_sz,
1628                                        __u64 *value)
1629 {
1630         __u16 left_shift_bits, right_shift_bits;
1631         const __u8 *bytes = data;
1632         __u8 nr_copy_bits;
1633         __u64 num = 0;
1634         int i;
1635
1636         /* Maximum supported bitfield size is 64 bits */
1637         if (t->size > 8) {
1638                 pr_warn("unexpected bitfield size %d\n", t->size);
1639                 return -EINVAL;
1640         }
1641
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.
1644          */
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;
1653 #else
1654 # error "Unrecognized __BYTE_ORDER__"
1655 #endif
1656         left_shift_bits = 64 - nr_copy_bits;
1657         right_shift_bits = 64 - bit_sz;
1658
1659         *value = (num << left_shift_bits) >> right_shift_bits;
1660
1661         return 0;
1662 }
1663
1664 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1665                                         const struct btf_type *t,
1666                                         const void *data,
1667                                         __u8 bits_offset,
1668                                         __u8 bit_sz)
1669 {
1670         __u64 check_num;
1671         int err;
1672
1673         err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1674         if (err)
1675                 return err;
1676         if (check_num == 0)
1677                 return -ENODATA;
1678         return 0;
1679 }
1680
1681 static int btf_dump_bitfield_data(struct btf_dump *d,
1682                                   const struct btf_type *t,
1683                                   const void *data,
1684                                   __u8 bits_offset,
1685                                   __u8 bit_sz)
1686 {
1687         __u64 print_num;
1688         int err;
1689
1690         err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1691         if (err)
1692                 return err;
1693
1694         btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1695
1696         return 0;
1697 }
1698
1699 /* ints, floats and ptrs */
1700 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1701                                          const struct btf_type *t,
1702                                          __u32 id,
1703                                          const void *data)
1704 {
1705         static __u8 bytecmp[16] = {};
1706         int nr_bytes;
1707
1708         /* For pointer types, pointer size is not defined on a per-type basis.
1709          * On dump creation however, we store the pointer size.
1710          */
1711         if (btf_kind(t) == BTF_KIND_PTR)
1712                 nr_bytes = d->ptr_sz;
1713         else
1714                 nr_bytes = t->size;
1715
1716         if (nr_bytes < 1 || nr_bytes > 16) {
1717                 pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1718                 return -EINVAL;
1719         }
1720
1721         if (memcmp(data, bytecmp, nr_bytes) == 0)
1722                 return -ENODATA;
1723         return 0;
1724 }
1725
1726 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1727                            const void *data)
1728 {
1729         int alignment = btf__align_of(btf, type_id);
1730
1731         if (alignment == 0)
1732                 return false;
1733
1734         return ((uintptr_t)data) % alignment == 0;
1735 }
1736
1737 static int btf_dump_int_data(struct btf_dump *d,
1738                              const struct btf_type *t,
1739                              __u32 type_id,
1740                              const void *data,
1741                              __u8 bits_offset)
1742 {
1743         __u8 encoding = btf_int_encoding(t);
1744         bool sign = encoding & BTF_INT_SIGNED;
1745         char buf[16] __attribute__((aligned(16)));
1746         int sz = t->size;
1747
1748         if (sz == 0 || sz > sizeof(buf)) {
1749                 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1750                 return -EINVAL;
1751         }
1752
1753         /* handle packed int data - accesses of integers not aligned on
1754          * int boundaries can cause problems on some platforms.
1755          */
1756         if (!ptr_is_aligned(d->btf, type_id, data)) {
1757                 memcpy(buf, data, sz);
1758                 data = buf;
1759         }
1760
1761         switch (sz) {
1762         case 16: {
1763                 const __u64 *ints = data;
1764                 __u64 lsi, msi;
1765
1766                 /* avoid use of __int128 as some 32-bit platforms do not
1767                  * support it.
1768                  */
1769 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1770                 lsi = ints[0];
1771                 msi = ints[1];
1772 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1773                 lsi = ints[1];
1774                 msi = ints[0];
1775 #else
1776 # error "Unrecognized __BYTE_ORDER__"
1777 #endif
1778                 if (msi == 0)
1779                         btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1780                 else
1781                         btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1782                                              (unsigned long long)lsi);
1783                 break;
1784         }
1785         case 8:
1786                 if (sign)
1787                         btf_dump_type_values(d, "%lld", *(long long *)data);
1788                 else
1789                         btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1790                 break;
1791         case 4:
1792                 if (sign)
1793                         btf_dump_type_values(d, "%d", *(__s32 *)data);
1794                 else
1795                         btf_dump_type_values(d, "%u", *(__u32 *)data);
1796                 break;
1797         case 2:
1798                 if (sign)
1799                         btf_dump_type_values(d, "%d", *(__s16 *)data);
1800                 else
1801                         btf_dump_type_values(d, "%u", *(__u16 *)data);
1802                 break;
1803         case 1:
1804                 if (d->typed_dump->is_array_char) {
1805                         /* check for null terminator */
1806                         if (d->typed_dump->is_array_terminated)
1807                                 break;
1808                         if (*(char *)data == '\0') {
1809                                 d->typed_dump->is_array_terminated = true;
1810                                 break;
1811                         }
1812                         if (isprint(*(char *)data)) {
1813                                 btf_dump_type_values(d, "'%c'", *(char *)data);
1814                                 break;
1815                         }
1816                 }
1817                 if (sign)
1818                         btf_dump_type_values(d, "%d", *(__s8 *)data);
1819                 else
1820                         btf_dump_type_values(d, "%u", *(__u8 *)data);
1821                 break;
1822         default:
1823                 pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1824                 return -EINVAL;
1825         }
1826         return 0;
1827 }
1828
1829 union float_data {
1830         long double ld;
1831         double d;
1832         float f;
1833 };
1834
1835 static int btf_dump_float_data(struct btf_dump *d,
1836                                const struct btf_type *t,
1837                                __u32 type_id,
1838                                const void *data)
1839 {
1840         const union float_data *flp = data;
1841         union float_data fl;
1842         int sz = t->size;
1843
1844         /* handle unaligned data; copy to local union */
1845         if (!ptr_is_aligned(d->btf, type_id, data)) {
1846                 memcpy(&fl, data, sz);
1847                 flp = &fl;
1848         }
1849
1850         switch (sz) {
1851         case 16:
1852                 btf_dump_type_values(d, "%Lf", flp->ld);
1853                 break;
1854         case 8:
1855                 btf_dump_type_values(d, "%lf", flp->d);
1856                 break;
1857         case 4:
1858                 btf_dump_type_values(d, "%f", flp->f);
1859                 break;
1860         default:
1861                 pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1862                 return -EINVAL;
1863         }
1864         return 0;
1865 }
1866
1867 static int btf_dump_var_data(struct btf_dump *d,
1868                              const struct btf_type *v,
1869                              __u32 id,
1870                              const void *data)
1871 {
1872         enum btf_func_linkage linkage = btf_var(v)->linkage;
1873         const struct btf_type *t;
1874         const char *l;
1875         __u32 type_id;
1876
1877         switch (linkage) {
1878         case BTF_FUNC_STATIC:
1879                 l = "static ";
1880                 break;
1881         case BTF_FUNC_EXTERN:
1882                 l = "extern ";
1883                 break;
1884         case BTF_FUNC_GLOBAL:
1885         default:
1886                 l = "";
1887                 break;
1888         }
1889
1890         /* format of output here is [linkage] [type] [varname] = (type)value,
1891          * for example "static int cpu_profile_flip = (int)1"
1892          */
1893         btf_dump_printf(d, "%s", l);
1894         type_id = v->type;
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);
1899 }
1900
1901 static int btf_dump_array_data(struct btf_dump *d,
1902                                const struct btf_type *t,
1903                                __u32 id,
1904                                const void *data)
1905 {
1906         const struct btf_array *array = btf_array(t);
1907         const struct btf_type *elem_type;
1908         __u32 i, elem_type_id;
1909         __s64 elem_size;
1910         bool is_array_member;
1911
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);
1918                 return -EINVAL;
1919         }
1920
1921         if (btf_is_int(elem_type)) {
1922                 /*
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.
1926                  */
1927                 if (elem_size == 1)
1928                         d->typed_dump->is_array_char = true;
1929         }
1930
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
1936          * parenthesis.
1937          */
1938         d->typed_dump->depth++;
1939         btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
1940
1941         /* may be a multidimensional array, so store current "is array member"
1942          * status so we can restore it correctly later.
1943          */
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)
1948                         break;
1949                 btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
1950         }
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, "]");
1955
1956         return 0;
1957 }
1958
1959 static int btf_dump_struct_data(struct btf_dump *d,
1960                                 const struct btf_type *t,
1961                                 __u32 id,
1962                                 const void *data)
1963 {
1964         const struct btf_member *m = btf_members(t);
1965         __u16 n = btf_vlen(t);
1966         int i, err;
1967
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
1973          * parenthesis.
1974          */
1975         d->typed_dump->depth++;
1976         btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
1977
1978         for (i = 0; i < n; i++, m++) {
1979                 const struct btf_type *mtype;
1980                 const char *mname;
1981                 __u32 moffset;
1982                 __u8 bit_sz;
1983
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);
1987
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);
1991                 if (err < 0)
1992                         return err;
1993         }
1994         d->typed_dump->depth--;
1995         btf_dump_data_pfx(d);
1996         btf_dump_type_values(d, "}");
1997         return err;
1998 }
1999
2000 union ptr_data {
2001         unsigned int p;
2002         unsigned long long lp;
2003 };
2004
2005 static int btf_dump_ptr_data(struct btf_dump *d,
2006                               const struct btf_type *t,
2007                               __u32 id,
2008                               const void *data)
2009 {
2010         if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
2011                 btf_dump_type_values(d, "%p", *(void **)data);
2012         } else {
2013                 union ptr_data pt;
2014
2015                 memcpy(&pt, data, d->ptr_sz);
2016                 if (d->ptr_sz == 4)
2017                         btf_dump_type_values(d, "0x%x", pt.p);
2018                 else
2019                         btf_dump_type_values(d, "0x%llx", pt.lp);
2020         }
2021         return 0;
2022 }
2023
2024 static int btf_dump_get_enum_value(struct btf_dump *d,
2025                                    const struct btf_type *t,
2026                                    const void *data,
2027                                    __u32 id,
2028                                    __s64 *value)
2029 {
2030         bool is_signed = btf_kflag(t);
2031
2032         if (!ptr_is_aligned(d->btf, id, data)) {
2033                 __u64 val;
2034                 int err;
2035
2036                 err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
2037                 if (err)
2038                         return err;
2039                 *value = (__s64)val;
2040                 return 0;
2041         }
2042
2043         switch (t->size) {
2044         case 8:
2045                 *value = *(__s64 *)data;
2046                 return 0;
2047         case 4:
2048                 *value = is_signed ? *(__s32 *)data : *(__u32 *)data;
2049                 return 0;
2050         case 2:
2051                 *value = is_signed ? *(__s16 *)data : *(__u16 *)data;
2052                 return 0;
2053         case 1:
2054                 *value = is_signed ? *(__s8 *)data : *(__u8 *)data;
2055                 return 0;
2056         default:
2057                 pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
2058                 return -EINVAL;
2059         }
2060 }
2061
2062 static int btf_dump_enum_data(struct btf_dump *d,
2063                               const struct btf_type *t,
2064                               __u32 id,
2065                               const void *data)
2066 {
2067         bool is_signed;
2068         __s64 value;
2069         int i, err;
2070
2071         err = btf_dump_get_enum_value(d, t, data, id, &value);
2072         if (err)
2073                 return err;
2074
2075         is_signed = btf_kflag(t);
2076         if (btf_is_enum(t)) {
2077                 const struct btf_enum *e;
2078
2079                 for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2080                         if (value != e->val)
2081                                 continue;
2082                         btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2083                         return 0;
2084                 }
2085
2086                 btf_dump_type_values(d, is_signed ? "%d" : "%u", value);
2087         } else {
2088                 const struct btf_enum64 *e;
2089
2090                 for (i = 0, e = btf_enum64(t); i < btf_vlen(t); i++, e++) {
2091                         if (value != btf_enum64_value(e))
2092                                 continue;
2093                         btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2094                         return 0;
2095                 }
2096
2097                 btf_dump_type_values(d, is_signed ? "%lldLL" : "%lluULL",
2098                                      (unsigned long long)value);
2099         }
2100         return 0;
2101 }
2102
2103 static int btf_dump_datasec_data(struct btf_dump *d,
2104                                  const struct btf_type *t,
2105                                  __u32 id,
2106                                  const void *data)
2107 {
2108         const struct btf_var_secinfo *vsi;
2109         const struct btf_type *var;
2110         __u32 i;
2111         int err;
2112
2113         btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2114
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);
2118                 if (err < 0)
2119                         return err;
2120                 btf_dump_printf(d, ";");
2121         }
2122         return 0;
2123 }
2124
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,
2128                                              __u32 id,
2129                                              const void *data,
2130                                              __u8 bits_offset)
2131 {
2132         __s64 size = btf__resolve_size(d->btf, id);
2133
2134         if (size < 0 || size >= INT_MAX) {
2135                 pr_warn("unexpected size [%zu] for id [%u]\n",
2136                         (size_t)size, id);
2137                 return -EINVAL;
2138         }
2139
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.
2146          */
2147         t = skip_mods_and_typedefs(d->btf, id, NULL);
2148         if (!t) {
2149                 pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2150                         id);
2151                 return -EINVAL;
2152         }
2153
2154         switch (btf_kind(t)) {
2155         case BTF_KIND_INT:
2156         case BTF_KIND_FLOAT:
2157         case BTF_KIND_PTR:
2158         case BTF_KIND_ENUM:
2159         case BTF_KIND_ENUM64:
2160                 if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2161                         return -E2BIG;
2162                 break;
2163         default:
2164                 break;
2165         }
2166         return (int)size;
2167 }
2168
2169 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2170                                          const struct btf_type *t,
2171                                          __u32 id,
2172                                          const void *data,
2173                                          __u8 bits_offset,
2174                                          __u8 bit_sz)
2175 {
2176         __s64 value;
2177         int i, err;
2178
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
2188          *   level here.
2189          */
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))
2193                 return 0;
2194
2195         t = skip_mods_and_typedefs(d->btf, id, NULL);
2196
2197         switch (btf_kind(t)) {
2198         case BTF_KIND_INT:
2199                 if (bit_sz)
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:
2203         case BTF_KIND_PTR:
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;
2209                 bool ischar;
2210
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);
2214
2215                 ischar = btf_is_int(elem_type) && elem_size == 1;
2216
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.
2222                  */
2223                 for (i = 0; i < array->nelems; i++) {
2224                         if (i == 0 && ischar && *(char *)data == 0)
2225                                 return -ENODATA;
2226                         err = btf_dump_type_data_check_zero(d, elem_type,
2227                                                             elem_type_id,
2228                                                             data +
2229                                                             (i * elem_size),
2230                                                             bits_offset, 0);
2231                         if (err != -ENODATA)
2232                                 return err;
2233                 }
2234                 return -ENODATA;
2235         }
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);
2240
2241                 /* if any struct/union member is non-zero, the struct/union
2242                  * is considered non-zero and dumped.
2243                  */
2244                 for (i = 0; i < n; i++, m++) {
2245                         const struct btf_type *mtype;
2246                         __u32 moffset;
2247
2248                         mtype = btf__type_by_id(d->btf, m->type);
2249                         moffset = btf_member_bit_offset(t, i);
2250
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.
2254                          */
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);
2258                         if (err != ENODATA)
2259                                 return err;
2260                 }
2261                 return -ENODATA;
2262         }
2263         case BTF_KIND_ENUM:
2264         case BTF_KIND_ENUM64:
2265                 err = btf_dump_get_enum_value(d, t, data, id, &value);
2266                 if (err)
2267                         return err;
2268                 if (value == 0)
2269                         return -ENODATA;
2270                 return 0;
2271         default:
2272                 return 0;
2273         }
2274 }
2275
2276 /* returns size of data dumped, or error. */
2277 static int btf_dump_dump_type_data(struct btf_dump *d,
2278                                    const char *fname,
2279                                    const struct btf_type *t,
2280                                    __u32 id,
2281                                    const void *data,
2282                                    __u8 bits_offset,
2283                                    __u8 bit_sz)
2284 {
2285         int size, err = 0;
2286
2287         size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2288         if (size < 0)
2289                 return size;
2290         err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2291         if (err) {
2292                 /* zeroed data is expected and not an error, so simply skip
2293                  * dumping such data.  Record other errors however.
2294                  */
2295                 if (err == -ENODATA)
2296                         return size;
2297                 return err;
2298         }
2299         btf_dump_data_pfx(d);
2300
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);
2305         }
2306
2307         t = skip_mods_and_typedefs(d->btf, id, NULL);
2308
2309         switch (btf_kind(t)) {
2310         case BTF_KIND_UNKN:
2311         case BTF_KIND_FWD:
2312         case BTF_KIND_FUNC:
2313         case BTF_KIND_FUNC_PROTO:
2314         case BTF_KIND_DECL_TAG:
2315                 err = btf_dump_unsupported_data(d, t, id);
2316                 break;
2317         case BTF_KIND_INT:
2318                 if (bit_sz)
2319                         err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2320                 else
2321                         err = btf_dump_int_data(d, t, id, data, bits_offset);
2322                 break;
2323         case BTF_KIND_FLOAT:
2324                 err = btf_dump_float_data(d, t, id, data);
2325                 break;
2326         case BTF_KIND_PTR:
2327                 err = btf_dump_ptr_data(d, t, id, data);
2328                 break;
2329         case BTF_KIND_ARRAY:
2330                 err = btf_dump_array_data(d, t, id, data);
2331                 break;
2332         case BTF_KIND_STRUCT:
2333         case BTF_KIND_UNION:
2334                 err = btf_dump_struct_data(d, t, id, data);
2335                 break;
2336         case BTF_KIND_ENUM:
2337         case BTF_KIND_ENUM64:
2338                 /* handle bitfield and int enum values */
2339                 if (bit_sz) {
2340                         __u64 print_num;
2341                         __s64 enum_val;
2342
2343                         err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2344                                                           &print_num);
2345                         if (err)
2346                                 break;
2347                         enum_val = (__s64)print_num;
2348                         err = btf_dump_enum_data(d, t, id, &enum_val);
2349                 } else
2350                         err = btf_dump_enum_data(d, t, id, data);
2351                 break;
2352         case BTF_KIND_VAR:
2353                 err = btf_dump_var_data(d, t, id, data);
2354                 break;
2355         case BTF_KIND_DATASEC:
2356                 err = btf_dump_datasec_data(d, t, id, data);
2357                 break;
2358         default:
2359                 pr_warn("unexpected kind [%u] for id [%u]\n",
2360                         BTF_INFO_KIND(t->info), id);
2361                 return -EINVAL;
2362         }
2363         if (err < 0)
2364                 return err;
2365         return size;
2366 }
2367
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)
2371 {
2372         struct btf_dump_data typed_dump = {};
2373         const struct btf_type *t;
2374         int ret;
2375
2376         if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2377                 return libbpf_err(-EINVAL);
2378
2379         t = btf__type_by_id(d->btf, id);
2380         if (!t)
2381                 return libbpf_err(-ENOENT);
2382
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);
2386
2387         /* default indent string is a tab */
2388         if (!opts->indent_str)
2389                 d->typed_dump->indent_str[0] = '\t';
2390         else
2391                 libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
2392                                sizeof(d->typed_dump->indent_str));
2393
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);
2397
2398         ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2399
2400         d->typed_dump = NULL;
2401
2402         return libbpf_err(ret);
2403 }