libbpf: Handle GCC built-in types for Arm NEON
[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 <errno.h>
14 #include <linux/err.h>
15 #include <linux/btf.h>
16 #include <linux/kernel.h>
17 #include "btf.h"
18 #include "hashmap.h"
19 #include "libbpf.h"
20 #include "libbpf_internal.h"
21
22 /* make sure libbpf doesn't use kernel-only integer typedefs */
23 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
24
25 static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
26 static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
27
28 static const char *pfx(int lvl)
29 {
30         return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
31 }
32
33 enum btf_dump_type_order_state {
34         NOT_ORDERED,
35         ORDERING,
36         ORDERED,
37 };
38
39 enum btf_dump_type_emit_state {
40         NOT_EMITTED,
41         EMITTING,
42         EMITTED,
43 };
44
45 /* per-type auxiliary state */
46 struct btf_dump_type_aux_state {
47         /* topological sorting state */
48         enum btf_dump_type_order_state order_state: 2;
49         /* emitting state used to determine the need for forward declaration */
50         enum btf_dump_type_emit_state emit_state: 2;
51         /* whether forward declaration was already emitted */
52         __u8 fwd_emitted: 1;
53         /* whether unique non-duplicate name was already assigned */
54         __u8 name_resolved: 1;
55         /* whether type is referenced from any other type */
56         __u8 referenced: 1;
57 };
58
59 struct btf_dump {
60         const struct btf *btf;
61         const struct btf_ext *btf_ext;
62         btf_dump_printf_fn_t printf_fn;
63         struct btf_dump_opts opts;
64         bool strip_mods;
65
66         /* per-type auxiliary state */
67         struct btf_dump_type_aux_state *type_states;
68         /* per-type optional cached unique name, must be freed, if present */
69         const char **cached_names;
70
71         /* topo-sorted list of dependent type definitions */
72         __u32 *emit_queue;
73         int emit_queue_cap;
74         int emit_queue_cnt;
75
76         /*
77          * stack of type declarations (e.g., chain of modifiers, arrays,
78          * funcs, etc)
79          */
80         __u32 *decl_stack;
81         int decl_stack_cap;
82         int decl_stack_cnt;
83
84         /* maps struct/union/enum name to a number of name occurrences */
85         struct hashmap *type_names;
86         /*
87          * maps typedef identifiers and enum value names to a number of such
88          * name occurrences
89          */
90         struct hashmap *ident_names;
91 };
92
93 static size_t str_hash_fn(const void *key, void *ctx)
94 {
95         const char *s = key;
96         size_t h = 0;
97
98         while (*s) {
99                 h = h * 31 + *s;
100                 s++;
101         }
102         return h;
103 }
104
105 static bool str_equal_fn(const void *a, const void *b, void *ctx)
106 {
107         return strcmp(a, b) == 0;
108 }
109
110 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
111 {
112         return btf__name_by_offset(d->btf, name_off);
113 }
114
115 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
116 {
117         va_list args;
118
119         va_start(args, fmt);
120         d->printf_fn(d->opts.ctx, fmt, args);
121         va_end(args);
122 }
123
124 static int btf_dump_mark_referenced(struct btf_dump *d);
125
126 struct btf_dump *btf_dump__new(const struct btf *btf,
127                                const struct btf_ext *btf_ext,
128                                const struct btf_dump_opts *opts,
129                                btf_dump_printf_fn_t printf_fn)
130 {
131         struct btf_dump *d;
132         int err;
133
134         d = calloc(1, sizeof(struct btf_dump));
135         if (!d)
136                 return ERR_PTR(-ENOMEM);
137
138         d->btf = btf;
139         d->btf_ext = btf_ext;
140         d->printf_fn = printf_fn;
141         d->opts.ctx = opts ? opts->ctx : NULL;
142
143         d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
144         if (IS_ERR(d->type_names)) {
145                 err = PTR_ERR(d->type_names);
146                 d->type_names = NULL;
147                 goto err;
148         }
149         d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
150         if (IS_ERR(d->ident_names)) {
151                 err = PTR_ERR(d->ident_names);
152                 d->ident_names = NULL;
153                 goto err;
154         }
155         d->type_states = calloc(1 + btf__get_nr_types(d->btf),
156                                 sizeof(d->type_states[0]));
157         if (!d->type_states) {
158                 err = -ENOMEM;
159                 goto err;
160         }
161         d->cached_names = calloc(1 + btf__get_nr_types(d->btf),
162                                  sizeof(d->cached_names[0]));
163         if (!d->cached_names) {
164                 err = -ENOMEM;
165                 goto err;
166         }
167
168         /* VOID is special */
169         d->type_states[0].order_state = ORDERED;
170         d->type_states[0].emit_state = EMITTED;
171
172         /* eagerly determine referenced types for anon enums */
173         err = btf_dump_mark_referenced(d);
174         if (err)
175                 goto err;
176
177         return d;
178 err:
179         btf_dump__free(d);
180         return ERR_PTR(err);
181 }
182
183 void btf_dump__free(struct btf_dump *d)
184 {
185         int i, cnt;
186
187         if (IS_ERR_OR_NULL(d))
188                 return;
189
190         free(d->type_states);
191         if (d->cached_names) {
192                 /* any set cached name is owned by us and should be freed */
193                 for (i = 0, cnt = btf__get_nr_types(d->btf); i <= cnt; i++) {
194                         if (d->cached_names[i])
195                                 free((void *)d->cached_names[i]);
196                 }
197         }
198         free(d->cached_names);
199         free(d->emit_queue);
200         free(d->decl_stack);
201         hashmap__free(d->type_names);
202         hashmap__free(d->ident_names);
203
204         free(d);
205 }
206
207 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
208 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
209
210 /*
211  * Dump BTF type in a compilable C syntax, including all the necessary
212  * dependent types, necessary for compilation. If some of the dependent types
213  * were already emitted as part of previous btf_dump__dump_type() invocation
214  * for another type, they won't be emitted again. This API allows callers to
215  * filter out BTF types according to user-defined criterias and emitted only
216  * minimal subset of types, necessary to compile everything. Full struct/union
217  * definitions will still be emitted, even if the only usage is through
218  * pointer and could be satisfied with just a forward declaration.
219  *
220  * Dumping is done in two high-level passes:
221  *   1. Topologically sort type definitions to satisfy C rules of compilation.
222  *   2. Emit type definitions in C syntax.
223  *
224  * Returns 0 on success; <0, otherwise.
225  */
226 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
227 {
228         int err, i;
229
230         if (id > btf__get_nr_types(d->btf))
231                 return -EINVAL;
232
233         d->emit_queue_cnt = 0;
234         err = btf_dump_order_type(d, id, false);
235         if (err < 0)
236                 return err;
237
238         for (i = 0; i < d->emit_queue_cnt; i++)
239                 btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
240
241         return 0;
242 }
243
244 /*
245  * Mark all types that are referenced from any other type. This is used to
246  * determine top-level anonymous enums that need to be emitted as an
247  * independent type declarations.
248  * Anonymous enums come in two flavors: either embedded in a struct's field
249  * definition, in which case they have to be declared inline as part of field
250  * type declaration; or as a top-level anonymous enum, typically used for
251  * declaring global constants. It's impossible to distinguish between two
252  * without knowning whether given enum type was referenced from other type:
253  * top-level anonymous enum won't be referenced by anything, while embedded
254  * one will.
255  */
256 static int btf_dump_mark_referenced(struct btf_dump *d)
257 {
258         int i, j, n = btf__get_nr_types(d->btf);
259         const struct btf_type *t;
260         __u16 vlen;
261
262         for (i = 1; i <= n; i++) {
263                 t = btf__type_by_id(d->btf, i);
264                 vlen = btf_vlen(t);
265
266                 switch (btf_kind(t)) {
267                 case BTF_KIND_INT:
268                 case BTF_KIND_ENUM:
269                 case BTF_KIND_FWD:
270                         break;
271
272                 case BTF_KIND_VOLATILE:
273                 case BTF_KIND_CONST:
274                 case BTF_KIND_RESTRICT:
275                 case BTF_KIND_PTR:
276                 case BTF_KIND_TYPEDEF:
277                 case BTF_KIND_FUNC:
278                 case BTF_KIND_VAR:
279                         d->type_states[t->type].referenced = 1;
280                         break;
281
282                 case BTF_KIND_ARRAY: {
283                         const struct btf_array *a = btf_array(t);
284
285                         d->type_states[a->index_type].referenced = 1;
286                         d->type_states[a->type].referenced = 1;
287                         break;
288                 }
289                 case BTF_KIND_STRUCT:
290                 case BTF_KIND_UNION: {
291                         const struct btf_member *m = btf_members(t);
292
293                         for (j = 0; j < vlen; j++, m++)
294                                 d->type_states[m->type].referenced = 1;
295                         break;
296                 }
297                 case BTF_KIND_FUNC_PROTO: {
298                         const struct btf_param *p = btf_params(t);
299
300                         for (j = 0; j < vlen; j++, p++)
301                                 d->type_states[p->type].referenced = 1;
302                         break;
303                 }
304                 case BTF_KIND_DATASEC: {
305                         const struct btf_var_secinfo *v = btf_var_secinfos(t);
306
307                         for (j = 0; j < vlen; j++, v++)
308                                 d->type_states[v->type].referenced = 1;
309                         break;
310                 }
311                 default:
312                         return -EINVAL;
313                 }
314         }
315         return 0;
316 }
317 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
318 {
319         __u32 *new_queue;
320         size_t new_cap;
321
322         if (d->emit_queue_cnt >= d->emit_queue_cap) {
323                 new_cap = max(16, d->emit_queue_cap * 3 / 2);
324                 new_queue = realloc(d->emit_queue,
325                                     new_cap * sizeof(new_queue[0]));
326                 if (!new_queue)
327                         return -ENOMEM;
328                 d->emit_queue = new_queue;
329                 d->emit_queue_cap = new_cap;
330         }
331
332         d->emit_queue[d->emit_queue_cnt++] = id;
333         return 0;
334 }
335
336 /*
337  * Determine order of emitting dependent types and specified type to satisfy
338  * C compilation rules.  This is done through topological sorting with an
339  * additional complication which comes from C rules. The main idea for C is
340  * that if some type is "embedded" into a struct/union, it's size needs to be
341  * known at the time of definition of containing type. E.g., for:
342  *
343  *      struct A {};
344  *      struct B { struct A x; }
345  *
346  * struct A *HAS* to be defined before struct B, because it's "embedded",
347  * i.e., it is part of struct B layout. But in the following case:
348  *
349  *      struct A;
350  *      struct B { struct A *x; }
351  *      struct A {};
352  *
353  * it's enough to just have a forward declaration of struct A at the time of
354  * struct B definition, as struct B has a pointer to struct A, so the size of
355  * field x is known without knowing struct A size: it's sizeof(void *).
356  *
357  * Unfortunately, there are some trickier cases we need to handle, e.g.:
358  *
359  *      struct A {}; // if this was forward-declaration: compilation error
360  *      struct B {
361  *              struct { // anonymous struct
362  *                      struct A y;
363  *              } *x;
364  *      };
365  *
366  * In this case, struct B's field x is a pointer, so it's size is known
367  * regardless of the size of (anonymous) struct it points to. But because this
368  * struct is anonymous and thus defined inline inside struct B, *and* it
369  * embeds struct A, compiler requires full definition of struct A to be known
370  * before struct B can be defined. This creates a transitive dependency
371  * between struct A and struct B. If struct A was forward-declared before
372  * struct B definition and fully defined after struct B definition, that would
373  * trigger compilation error.
374  *
375  * All this means that while we are doing topological sorting on BTF type
376  * graph, we need to determine relationships between different types (graph
377  * nodes):
378  *   - weak link (relationship) between X and Y, if Y *CAN* be
379  *   forward-declared at the point of X definition;
380  *   - strong link, if Y *HAS* to be fully-defined before X can be defined.
381  *
382  * The rule is as follows. Given a chain of BTF types from X to Y, if there is
383  * BTF_KIND_PTR type in the chain and at least one non-anonymous type
384  * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
385  * Weak/strong relationship is determined recursively during DFS traversal and
386  * is returned as a result from btf_dump_order_type().
387  *
388  * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
389  * but it is not guaranteeing that no extraneous forward declarations will be
390  * emitted.
391  *
392  * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
393  * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
394  * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
395  * entire graph path, so depending where from one came to that BTF type, it
396  * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
397  * once they are processed, there is no need to do it again, so they are
398  * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
399  * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
400  * in any case, once those are processed, no need to do it again, as the
401  * result won't change.
402  *
403  * Returns:
404  *   - 1, if type is part of strong link (so there is strong topological
405  *   ordering requirements);
406  *   - 0, if type is part of weak link (so can be satisfied through forward
407  *   declaration);
408  *   - <0, on error (e.g., unsatisfiable type loop detected).
409  */
410 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
411 {
412         /*
413          * Order state is used to detect strong link cycles, but only for BTF
414          * kinds that are or could be an independent definition (i.e.,
415          * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
416          * func_protos, modifiers are just means to get to these definitions.
417          * Int/void don't need definitions, they are assumed to be always
418          * properly defined.  We also ignore datasec, var, and funcs for now.
419          * So for all non-defining kinds, we never even set ordering state,
420          * for defining kinds we set ORDERING and subsequently ORDERED if it
421          * forms a strong link.
422          */
423         struct btf_dump_type_aux_state *tstate = &d->type_states[id];
424         const struct btf_type *t;
425         __u16 vlen;
426         int err, i;
427
428         /* return true, letting typedefs know that it's ok to be emitted */
429         if (tstate->order_state == ORDERED)
430                 return 1;
431
432         t = btf__type_by_id(d->btf, id);
433
434         if (tstate->order_state == ORDERING) {
435                 /* type loop, but resolvable through fwd declaration */
436                 if (btf_is_composite(t) && through_ptr && t->name_off != 0)
437                         return 0;
438                 pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
439                 return -ELOOP;
440         }
441
442         switch (btf_kind(t)) {
443         case BTF_KIND_INT:
444                 tstate->order_state = ORDERED;
445                 return 0;
446
447         case BTF_KIND_PTR:
448                 err = btf_dump_order_type(d, t->type, true);
449                 tstate->order_state = ORDERED;
450                 return err;
451
452         case BTF_KIND_ARRAY:
453                 return btf_dump_order_type(d, btf_array(t)->type, through_ptr);
454
455         case BTF_KIND_STRUCT:
456         case BTF_KIND_UNION: {
457                 const struct btf_member *m = btf_members(t);
458                 /*
459                  * struct/union is part of strong link, only if it's embedded
460                  * (so no ptr in a path) or it's anonymous (so has to be
461                  * defined inline, even if declared through ptr)
462                  */
463                 if (through_ptr && t->name_off != 0)
464                         return 0;
465
466                 tstate->order_state = ORDERING;
467
468                 vlen = btf_vlen(t);
469                 for (i = 0; i < vlen; i++, m++) {
470                         err = btf_dump_order_type(d, m->type, false);
471                         if (err < 0)
472                                 return err;
473                 }
474
475                 if (t->name_off != 0) {
476                         err = btf_dump_add_emit_queue_id(d, id);
477                         if (err < 0)
478                                 return err;
479                 }
480
481                 tstate->order_state = ORDERED;
482                 return 1;
483         }
484         case BTF_KIND_ENUM:
485         case BTF_KIND_FWD:
486                 /*
487                  * non-anonymous or non-referenced enums are top-level
488                  * declarations and should be emitted. Same logic can be
489                  * applied to FWDs, it won't hurt anyways.
490                  */
491                 if (t->name_off != 0 || !tstate->referenced) {
492                         err = btf_dump_add_emit_queue_id(d, id);
493                         if (err)
494                                 return err;
495                 }
496                 tstate->order_state = ORDERED;
497                 return 1;
498
499         case BTF_KIND_TYPEDEF: {
500                 int is_strong;
501
502                 is_strong = btf_dump_order_type(d, t->type, through_ptr);
503                 if (is_strong < 0)
504                         return is_strong;
505
506                 /* typedef is similar to struct/union w.r.t. fwd-decls */
507                 if (through_ptr && !is_strong)
508                         return 0;
509
510                 /* typedef is always a named definition */
511                 err = btf_dump_add_emit_queue_id(d, id);
512                 if (err)
513                         return err;
514
515                 d->type_states[id].order_state = ORDERED;
516                 return 1;
517         }
518         case BTF_KIND_VOLATILE:
519         case BTF_KIND_CONST:
520         case BTF_KIND_RESTRICT:
521                 return btf_dump_order_type(d, t->type, through_ptr);
522
523         case BTF_KIND_FUNC_PROTO: {
524                 const struct btf_param *p = btf_params(t);
525                 bool is_strong;
526
527                 err = btf_dump_order_type(d, t->type, through_ptr);
528                 if (err < 0)
529                         return err;
530                 is_strong = err > 0;
531
532                 vlen = btf_vlen(t);
533                 for (i = 0; i < vlen; i++, p++) {
534                         err = btf_dump_order_type(d, p->type, through_ptr);
535                         if (err < 0)
536                                 return err;
537                         if (err > 0)
538                                 is_strong = true;
539                 }
540                 return is_strong;
541         }
542         case BTF_KIND_FUNC:
543         case BTF_KIND_VAR:
544         case BTF_KIND_DATASEC:
545                 d->type_states[id].order_state = ORDERED;
546                 return 0;
547
548         default:
549                 return -EINVAL;
550         }
551 }
552
553 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
554                                           const struct btf_type *t);
555
556 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
557                                      const struct btf_type *t);
558 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
559                                      const struct btf_type *t, int lvl);
560
561 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
562                                    const struct btf_type *t);
563 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
564                                    const struct btf_type *t, int lvl);
565
566 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
567                                   const struct btf_type *t);
568
569 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
570                                       const struct btf_type *t, int lvl);
571
572 /* a local view into a shared stack */
573 struct id_stack {
574         const __u32 *ids;
575         int cnt;
576 };
577
578 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
579                                     const char *fname, int lvl);
580 static void btf_dump_emit_type_chain(struct btf_dump *d,
581                                      struct id_stack *decl_stack,
582                                      const char *fname, int lvl);
583
584 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
585 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
586 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
587                                  const char *orig_name);
588
589 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
590 {
591         const struct btf_type *t = btf__type_by_id(d->btf, id);
592
593         /* __builtin_va_list is a compiler built-in, which causes compilation
594          * errors, when compiling w/ different compiler, then used to compile
595          * original code (e.g., GCC to compile kernel, Clang to use generated
596          * C header from BTF). As it is built-in, it should be already defined
597          * properly internally in compiler.
598          */
599         if (t->name_off == 0)
600                 return false;
601         return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
602 }
603
604 /*
605  * Emit C-syntax definitions of types from chains of BTF types.
606  *
607  * High-level handling of determining necessary forward declarations are handled
608  * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
609  * declarations/definitions in C syntax  are handled by a combo of
610  * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
611  * corresponding btf_dump_emit_*_{def,fwd}() functions.
612  *
613  * We also keep track of "containing struct/union type ID" to determine when
614  * we reference it from inside and thus can avoid emitting unnecessary forward
615  * declaration.
616  *
617  * This algorithm is designed in such a way, that even if some error occurs
618  * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
619  * that doesn't comply to C rules completely), algorithm will try to proceed
620  * and produce as much meaningful output as possible.
621  */
622 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
623 {
624         struct btf_dump_type_aux_state *tstate = &d->type_states[id];
625         bool top_level_def = cont_id == 0;
626         const struct btf_type *t;
627         __u16 kind;
628
629         if (tstate->emit_state == EMITTED)
630                 return;
631
632         t = btf__type_by_id(d->btf, id);
633         kind = btf_kind(t);
634
635         if (tstate->emit_state == EMITTING) {
636                 if (tstate->fwd_emitted)
637                         return;
638
639                 switch (kind) {
640                 case BTF_KIND_STRUCT:
641                 case BTF_KIND_UNION:
642                         /*
643                          * if we are referencing a struct/union that we are
644                          * part of - then no need for fwd declaration
645                          */
646                         if (id == cont_id)
647                                 return;
648                         if (t->name_off == 0) {
649                                 pr_warn("anonymous struct/union loop, id:[%u]\n",
650                                         id);
651                                 return;
652                         }
653                         btf_dump_emit_struct_fwd(d, id, t);
654                         btf_dump_printf(d, ";\n\n");
655                         tstate->fwd_emitted = 1;
656                         break;
657                 case BTF_KIND_TYPEDEF:
658                         /*
659                          * for typedef fwd_emitted means typedef definition
660                          * was emitted, but it can be used only for "weak"
661                          * references through pointer only, not for embedding
662                          */
663                         if (!btf_dump_is_blacklisted(d, id)) {
664                                 btf_dump_emit_typedef_def(d, id, t, 0);
665                                 btf_dump_printf(d, ";\n\n");
666                         }
667                         tstate->fwd_emitted = 1;
668                         break;
669                 default:
670                         break;
671                 }
672
673                 return;
674         }
675
676         switch (kind) {
677         case BTF_KIND_INT:
678                 /* Emit type alias definitions if necessary */
679                 btf_dump_emit_missing_aliases(d, id, t);
680
681                 tstate->emit_state = EMITTED;
682                 break;
683         case BTF_KIND_ENUM:
684                 if (top_level_def) {
685                         btf_dump_emit_enum_def(d, id, t, 0);
686                         btf_dump_printf(d, ";\n\n");
687                 }
688                 tstate->emit_state = EMITTED;
689                 break;
690         case BTF_KIND_PTR:
691         case BTF_KIND_VOLATILE:
692         case BTF_KIND_CONST:
693         case BTF_KIND_RESTRICT:
694                 btf_dump_emit_type(d, t->type, cont_id);
695                 break;
696         case BTF_KIND_ARRAY:
697                 btf_dump_emit_type(d, btf_array(t)->type, cont_id);
698                 break;
699         case BTF_KIND_FWD:
700                 btf_dump_emit_fwd_def(d, id, t);
701                 btf_dump_printf(d, ";\n\n");
702                 tstate->emit_state = EMITTED;
703                 break;
704         case BTF_KIND_TYPEDEF:
705                 tstate->emit_state = EMITTING;
706                 btf_dump_emit_type(d, t->type, id);
707                 /*
708                  * typedef can server as both definition and forward
709                  * declaration; at this stage someone depends on
710                  * typedef as a forward declaration (refers to it
711                  * through pointer), so unless we already did it,
712                  * emit typedef as a forward declaration
713                  */
714                 if (!tstate->fwd_emitted && !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->emit_state = EMITTED;
719                 break;
720         case BTF_KIND_STRUCT:
721         case BTF_KIND_UNION:
722                 tstate->emit_state = EMITTING;
723                 /* if it's a top-level struct/union definition or struct/union
724                  * is anonymous, then in C we'll be emitting all fields and
725                  * their types (as opposed to just `struct X`), so we need to
726                  * make sure that all types, referenced from struct/union
727                  * members have necessary forward-declarations, where
728                  * applicable
729                  */
730                 if (top_level_def || t->name_off == 0) {
731                         const struct btf_member *m = btf_members(t);
732                         __u16 vlen = btf_vlen(t);
733                         int i, new_cont_id;
734
735                         new_cont_id = t->name_off == 0 ? cont_id : id;
736                         for (i = 0; i < vlen; i++, m++)
737                                 btf_dump_emit_type(d, m->type, new_cont_id);
738                 } else if (!tstate->fwd_emitted && id != cont_id) {
739                         btf_dump_emit_struct_fwd(d, id, t);
740                         btf_dump_printf(d, ";\n\n");
741                         tstate->fwd_emitted = 1;
742                 }
743
744                 if (top_level_def) {
745                         btf_dump_emit_struct_def(d, id, t, 0);
746                         btf_dump_printf(d, ";\n\n");
747                         tstate->emit_state = EMITTED;
748                 } else {
749                         tstate->emit_state = NOT_EMITTED;
750                 }
751                 break;
752         case BTF_KIND_FUNC_PROTO: {
753                 const struct btf_param *p = btf_params(t);
754                 __u16 vlen = btf_vlen(t);
755                 int i;
756
757                 btf_dump_emit_type(d, t->type, cont_id);
758                 for (i = 0; i < vlen; i++, p++)
759                         btf_dump_emit_type(d, p->type, cont_id);
760
761                 break;
762         }
763         default:
764                 break;
765         }
766 }
767
768 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
769                                  const struct btf_type *t)
770 {
771         const struct btf_member *m;
772         int align, i, bit_sz;
773         __u16 vlen;
774
775         align = btf__align_of(btf, id);
776         /* size of a non-packed struct has to be a multiple of its alignment*/
777         if (align && t->size % align)
778                 return true;
779
780         m = btf_members(t);
781         vlen = btf_vlen(t);
782         /* all non-bitfield fields have to be naturally aligned */
783         for (i = 0; i < vlen; i++, m++) {
784                 align = btf__align_of(btf, m->type);
785                 bit_sz = btf_member_bitfield_size(t, i);
786                 if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
787                         return true;
788         }
789
790         /*
791          * if original struct was marked as packed, but its layout is
792          * naturally aligned, we'll detect that it's not packed
793          */
794         return false;
795 }
796
797 static int chip_away_bits(int total, int at_most)
798 {
799         return total % at_most ? : at_most;
800 }
801
802 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
803                                       int cur_off, int m_off, int m_bit_sz,
804                                       int align, int lvl)
805 {
806         int off_diff = m_off - cur_off;
807         int ptr_bits = sizeof(void *) * 8;
808
809         if (off_diff <= 0)
810                 /* no gap */
811                 return;
812         if (m_bit_sz == 0 && off_diff < align * 8)
813                 /* natural padding will take care of a gap */
814                 return;
815
816         while (off_diff > 0) {
817                 const char *pad_type;
818                 int pad_bits;
819
820                 if (ptr_bits > 32 && off_diff > 32) {
821                         pad_type = "long";
822                         pad_bits = chip_away_bits(off_diff, ptr_bits);
823                 } else if (off_diff > 16) {
824                         pad_type = "int";
825                         pad_bits = chip_away_bits(off_diff, 32);
826                 } else if (off_diff > 8) {
827                         pad_type = "short";
828                         pad_bits = chip_away_bits(off_diff, 16);
829                 } else {
830                         pad_type = "char";
831                         pad_bits = chip_away_bits(off_diff, 8);
832                 }
833                 btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
834                 off_diff -= pad_bits;
835         }
836 }
837
838 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
839                                      const struct btf_type *t)
840 {
841         btf_dump_printf(d, "%s %s",
842                         btf_is_struct(t) ? "struct" : "union",
843                         btf_dump_type_name(d, id));
844 }
845
846 static void btf_dump_emit_struct_def(struct btf_dump *d,
847                                      __u32 id,
848                                      const struct btf_type *t,
849                                      int lvl)
850 {
851         const struct btf_member *m = btf_members(t);
852         bool is_struct = btf_is_struct(t);
853         int align, i, packed, off = 0;
854         __u16 vlen = btf_vlen(t);
855
856         packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
857
858         btf_dump_printf(d, "%s%s%s {",
859                         is_struct ? "struct" : "union",
860                         t->name_off ? " " : "",
861                         btf_dump_type_name(d, id));
862
863         for (i = 0; i < vlen; i++, m++) {
864                 const char *fname;
865                 int m_off, m_sz;
866
867                 fname = btf_name_of(d, m->name_off);
868                 m_sz = btf_member_bitfield_size(t, i);
869                 m_off = btf_member_bit_offset(t, i);
870                 align = packed ? 1 : btf__align_of(d->btf, m->type);
871
872                 btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
873                 btf_dump_printf(d, "\n%s", pfx(lvl + 1));
874                 btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
875
876                 if (m_sz) {
877                         btf_dump_printf(d, ": %d", m_sz);
878                         off = m_off + m_sz;
879                 } else {
880                         m_sz = max(0LL, btf__resolve_size(d->btf, m->type));
881                         off = m_off + m_sz * 8;
882                 }
883                 btf_dump_printf(d, ";");
884         }
885
886         /* pad at the end, if necessary */
887         if (is_struct) {
888                 align = packed ? 1 : btf__align_of(d->btf, id);
889                 btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
890                                           lvl + 1);
891         }
892
893         if (vlen)
894                 btf_dump_printf(d, "\n");
895         btf_dump_printf(d, "%s}", pfx(lvl));
896         if (packed)
897                 btf_dump_printf(d, " __attribute__((packed))");
898 }
899
900 static const char *missing_base_types[][2] = {
901         /*
902          * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
903          * SIMD intrinsics. Alias them to standard base types.
904          */
905         { "__Poly8_t",          "unsigned char" },
906         { "__Poly16_t",         "unsigned short" },
907         { "__Poly64_t",         "unsigned long long" },
908         { "__Poly128_t",        "unsigned __int128" },
909 };
910
911 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
912                                           const struct btf_type *t)
913 {
914         const char *name = btf_dump_type_name(d, id);
915         int i;
916
917         for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
918                 if (strcmp(name, missing_base_types[i][0]) == 0) {
919                         btf_dump_printf(d, "typedef %s %s;\n\n",
920                                         missing_base_types[i][1], name);
921                         break;
922                 }
923         }
924 }
925
926 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
927                                    const struct btf_type *t)
928 {
929         btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
930 }
931
932 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
933                                    const struct btf_type *t,
934                                    int lvl)
935 {
936         const struct btf_enum *v = btf_enum(t);
937         __u16 vlen = btf_vlen(t);
938         const char *name;
939         size_t dup_cnt;
940         int i;
941
942         btf_dump_printf(d, "enum%s%s",
943                         t->name_off ? " " : "",
944                         btf_dump_type_name(d, id));
945
946         if (vlen) {
947                 btf_dump_printf(d, " {");
948                 for (i = 0; i < vlen; i++, v++) {
949                         name = btf_name_of(d, v->name_off);
950                         /* enumerators share namespace with typedef idents */
951                         dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
952                         if (dup_cnt > 1) {
953                                 btf_dump_printf(d, "\n%s%s___%zu = %u,",
954                                                 pfx(lvl + 1), name, dup_cnt,
955                                                 (__u32)v->val);
956                         } else {
957                                 btf_dump_printf(d, "\n%s%s = %u,",
958                                                 pfx(lvl + 1), name,
959                                                 (__u32)v->val);
960                         }
961                 }
962                 btf_dump_printf(d, "\n%s}", pfx(lvl));
963         }
964 }
965
966 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
967                                   const struct btf_type *t)
968 {
969         const char *name = btf_dump_type_name(d, id);
970
971         if (btf_kflag(t))
972                 btf_dump_printf(d, "union %s", name);
973         else
974                 btf_dump_printf(d, "struct %s", name);
975 }
976
977 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
978                                      const struct btf_type *t, int lvl)
979 {
980         const char *name = btf_dump_ident_name(d, id);
981
982         /*
983          * Old GCC versions are emitting invalid typedef for __gnuc_va_list
984          * pointing to VOID. This generates warnings from btf_dump() and
985          * results in uncompilable header file, so we are fixing it up here
986          * with valid typedef into __builtin_va_list.
987          */
988         if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
989                 btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
990                 return;
991         }
992
993         btf_dump_printf(d, "typedef ");
994         btf_dump_emit_type_decl(d, t->type, name, lvl);
995 }
996
997 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
998 {
999         __u32 *new_stack;
1000         size_t new_cap;
1001
1002         if (d->decl_stack_cnt >= d->decl_stack_cap) {
1003                 new_cap = max(16, d->decl_stack_cap * 3 / 2);
1004                 new_stack = realloc(d->decl_stack,
1005                                     new_cap * sizeof(new_stack[0]));
1006                 if (!new_stack)
1007                         return -ENOMEM;
1008                 d->decl_stack = new_stack;
1009                 d->decl_stack_cap = new_cap;
1010         }
1011
1012         d->decl_stack[d->decl_stack_cnt++] = id;
1013
1014         return 0;
1015 }
1016
1017 /*
1018  * Emit type declaration (e.g., field type declaration in a struct or argument
1019  * declaration in function prototype) in correct C syntax.
1020  *
1021  * For most types it's trivial, but there are few quirky type declaration
1022  * cases worth mentioning:
1023  *   - function prototypes (especially nesting of function prototypes);
1024  *   - arrays;
1025  *   - const/volatile/restrict for pointers vs other types.
1026  *
1027  * For a good discussion of *PARSING* C syntax (as a human), see
1028  * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1029  * Ch.3 "Unscrambling Declarations in C".
1030  *
1031  * It won't help with BTF to C conversion much, though, as it's an opposite
1032  * problem. So we came up with this algorithm in reverse to van der Linden's
1033  * parsing algorithm. It goes from structured BTF representation of type
1034  * declaration to a valid compilable C syntax.
1035  *
1036  * For instance, consider this C typedef:
1037  *      typedef const int * const * arr[10] arr_t;
1038  * It will be represented in BTF with this chain of BTF types:
1039  *      [typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1040  *
1041  * Notice how [const] modifier always goes before type it modifies in BTF type
1042  * graph, but in C syntax, const/volatile/restrict modifiers are written to
1043  * the right of pointers, but to the left of other types. There are also other
1044  * quirks, like function pointers, arrays of them, functions returning other
1045  * functions, etc.
1046  *
1047  * We handle that by pushing all the types to a stack, until we hit "terminal"
1048  * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1049  * top of a stack, modifiers are handled differently. Array/function pointers
1050  * have also wildly different syntax and how nesting of them are done. See
1051  * code for authoritative definition.
1052  *
1053  * To avoid allocating new stack for each independent chain of BTF types, we
1054  * share one bigger stack, with each chain working only on its own local view
1055  * of a stack frame. Some care is required to "pop" stack frames after
1056  * processing type declaration chain.
1057  */
1058 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1059                              const struct btf_dump_emit_type_decl_opts *opts)
1060 {
1061         const char *fname;
1062         int lvl;
1063
1064         if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1065                 return -EINVAL;
1066
1067         fname = OPTS_GET(opts, field_name, "");
1068         lvl = OPTS_GET(opts, indent_level, 0);
1069         d->strip_mods = OPTS_GET(opts, strip_mods, false);
1070         btf_dump_emit_type_decl(d, id, fname, lvl);
1071         d->strip_mods = false;
1072         return 0;
1073 }
1074
1075 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1076                                     const char *fname, int lvl)
1077 {
1078         struct id_stack decl_stack;
1079         const struct btf_type *t;
1080         int err, stack_start;
1081
1082         stack_start = d->decl_stack_cnt;
1083         for (;;) {
1084                 t = btf__type_by_id(d->btf, id);
1085                 if (d->strip_mods && btf_is_mod(t))
1086                         goto skip_mod;
1087
1088                 err = btf_dump_push_decl_stack_id(d, id);
1089                 if (err < 0) {
1090                         /*
1091                          * if we don't have enough memory for entire type decl
1092                          * chain, restore stack, emit warning, and try to
1093                          * proceed nevertheless
1094                          */
1095                         pr_warn("not enough memory for decl stack:%d", err);
1096                         d->decl_stack_cnt = stack_start;
1097                         return;
1098                 }
1099 skip_mod:
1100                 /* VOID */
1101                 if (id == 0)
1102                         break;
1103
1104                 switch (btf_kind(t)) {
1105                 case BTF_KIND_PTR:
1106                 case BTF_KIND_VOLATILE:
1107                 case BTF_KIND_CONST:
1108                 case BTF_KIND_RESTRICT:
1109                 case BTF_KIND_FUNC_PROTO:
1110                         id = t->type;
1111                         break;
1112                 case BTF_KIND_ARRAY:
1113                         id = btf_array(t)->type;
1114                         break;
1115                 case BTF_KIND_INT:
1116                 case BTF_KIND_ENUM:
1117                 case BTF_KIND_FWD:
1118                 case BTF_KIND_STRUCT:
1119                 case BTF_KIND_UNION:
1120                 case BTF_KIND_TYPEDEF:
1121                         goto done;
1122                 default:
1123                         pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1124                                 btf_kind(t), id);
1125                         goto done;
1126                 }
1127         }
1128 done:
1129         /*
1130          * We might be inside a chain of declarations (e.g., array of function
1131          * pointers returning anonymous (so inlined) structs, having another
1132          * array field). Each of those needs its own "stack frame" to handle
1133          * emitting of declarations. Those stack frames are non-overlapping
1134          * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1135          * handle this set of nested stacks, we create a view corresponding to
1136          * our own "stack frame" and work with it as an independent stack.
1137          * We'll need to clean up after emit_type_chain() returns, though.
1138          */
1139         decl_stack.ids = d->decl_stack + stack_start;
1140         decl_stack.cnt = d->decl_stack_cnt - stack_start;
1141         btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1142         /*
1143          * emit_type_chain() guarantees that it will pop its entire decl_stack
1144          * frame before returning. But it works with a read-only view into
1145          * decl_stack, so it doesn't actually pop anything from the
1146          * perspective of shared btf_dump->decl_stack, per se. We need to
1147          * reset decl_stack state to how it was before us to avoid it growing
1148          * all the time.
1149          */
1150         d->decl_stack_cnt = stack_start;
1151 }
1152
1153 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1154 {
1155         const struct btf_type *t;
1156         __u32 id;
1157
1158         while (decl_stack->cnt) {
1159                 id = decl_stack->ids[decl_stack->cnt - 1];
1160                 t = btf__type_by_id(d->btf, id);
1161
1162                 switch (btf_kind(t)) {
1163                 case BTF_KIND_VOLATILE:
1164                         btf_dump_printf(d, "volatile ");
1165                         break;
1166                 case BTF_KIND_CONST:
1167                         btf_dump_printf(d, "const ");
1168                         break;
1169                 case BTF_KIND_RESTRICT:
1170                         btf_dump_printf(d, "restrict ");
1171                         break;
1172                 default:
1173                         return;
1174                 }
1175                 decl_stack->cnt--;
1176         }
1177 }
1178
1179 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1180 {
1181         const struct btf_type *t;
1182         __u32 id;
1183
1184         while (decl_stack->cnt) {
1185                 id = decl_stack->ids[decl_stack->cnt - 1];
1186                 t = btf__type_by_id(d->btf, id);
1187                 if (!btf_is_mod(t))
1188                         return;
1189                 decl_stack->cnt--;
1190         }
1191 }
1192
1193 static void btf_dump_emit_name(const struct btf_dump *d,
1194                                const char *name, bool last_was_ptr)
1195 {
1196         bool separate = name[0] && !last_was_ptr;
1197
1198         btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1199 }
1200
1201 static void btf_dump_emit_type_chain(struct btf_dump *d,
1202                                      struct id_stack *decls,
1203                                      const char *fname, int lvl)
1204 {
1205         /*
1206          * last_was_ptr is used to determine if we need to separate pointer
1207          * asterisk (*) from previous part of type signature with space, so
1208          * that we get `int ***`, instead of `int * * *`. We default to true
1209          * for cases where we have single pointer in a chain. E.g., in ptr ->
1210          * func_proto case. func_proto will start a new emit_type_chain call
1211          * with just ptr, which should be emitted as (*) or (*<fname>), so we
1212          * don't want to prepend space for that last pointer.
1213          */
1214         bool last_was_ptr = true;
1215         const struct btf_type *t;
1216         const char *name;
1217         __u16 kind;
1218         __u32 id;
1219
1220         while (decls->cnt) {
1221                 id = decls->ids[--decls->cnt];
1222                 if (id == 0) {
1223                         /* VOID is a special snowflake */
1224                         btf_dump_emit_mods(d, decls);
1225                         btf_dump_printf(d, "void");
1226                         last_was_ptr = false;
1227                         continue;
1228                 }
1229
1230                 t = btf__type_by_id(d->btf, id);
1231                 kind = btf_kind(t);
1232
1233                 switch (kind) {
1234                 case BTF_KIND_INT:
1235                         btf_dump_emit_mods(d, decls);
1236                         name = btf_name_of(d, t->name_off);
1237                         btf_dump_printf(d, "%s", name);
1238                         break;
1239                 case BTF_KIND_STRUCT:
1240                 case BTF_KIND_UNION:
1241                         btf_dump_emit_mods(d, decls);
1242                         /* inline anonymous struct/union */
1243                         if (t->name_off == 0)
1244                                 btf_dump_emit_struct_def(d, id, t, lvl);
1245                         else
1246                                 btf_dump_emit_struct_fwd(d, id, t);
1247                         break;
1248                 case BTF_KIND_ENUM:
1249                         btf_dump_emit_mods(d, decls);
1250                         /* inline anonymous enum */
1251                         if (t->name_off == 0)
1252                                 btf_dump_emit_enum_def(d, id, t, lvl);
1253                         else
1254                                 btf_dump_emit_enum_fwd(d, id, t);
1255                         break;
1256                 case BTF_KIND_FWD:
1257                         btf_dump_emit_mods(d, decls);
1258                         btf_dump_emit_fwd_def(d, id, t);
1259                         break;
1260                 case BTF_KIND_TYPEDEF:
1261                         btf_dump_emit_mods(d, decls);
1262                         btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1263                         break;
1264                 case BTF_KIND_PTR:
1265                         btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1266                         break;
1267                 case BTF_KIND_VOLATILE:
1268                         btf_dump_printf(d, " volatile");
1269                         break;
1270                 case BTF_KIND_CONST:
1271                         btf_dump_printf(d, " const");
1272                         break;
1273                 case BTF_KIND_RESTRICT:
1274                         btf_dump_printf(d, " restrict");
1275                         break;
1276                 case BTF_KIND_ARRAY: {
1277                         const struct btf_array *a = btf_array(t);
1278                         const struct btf_type *next_t;
1279                         __u32 next_id;
1280                         bool multidim;
1281                         /*
1282                          * GCC has a bug
1283                          * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1284                          * which causes it to emit extra const/volatile
1285                          * modifiers for an array, if array's element type has
1286                          * const/volatile modifiers. Clang doesn't do that.
1287                          * In general, it doesn't seem very meaningful to have
1288                          * a const/volatile modifier for array, so we are
1289                          * going to silently skip them here.
1290                          */
1291                         btf_dump_drop_mods(d, decls);
1292
1293                         if (decls->cnt == 0) {
1294                                 btf_dump_emit_name(d, fname, last_was_ptr);
1295                                 btf_dump_printf(d, "[%u]", a->nelems);
1296                                 return;
1297                         }
1298
1299                         next_id = decls->ids[decls->cnt - 1];
1300                         next_t = btf__type_by_id(d->btf, next_id);
1301                         multidim = btf_is_array(next_t);
1302                         /* we need space if we have named non-pointer */
1303                         if (fname[0] && !last_was_ptr)
1304                                 btf_dump_printf(d, " ");
1305                         /* no parentheses for multi-dimensional array */
1306                         if (!multidim)
1307                                 btf_dump_printf(d, "(");
1308                         btf_dump_emit_type_chain(d, decls, fname, lvl);
1309                         if (!multidim)
1310                                 btf_dump_printf(d, ")");
1311                         btf_dump_printf(d, "[%u]", a->nelems);
1312                         return;
1313                 }
1314                 case BTF_KIND_FUNC_PROTO: {
1315                         const struct btf_param *p = btf_params(t);
1316                         __u16 vlen = btf_vlen(t);
1317                         int i;
1318
1319                         /*
1320                          * GCC emits extra volatile qualifier for
1321                          * __attribute__((noreturn)) function pointers. Clang
1322                          * doesn't do it. It's a GCC quirk for backwards
1323                          * compatibility with code written for GCC <2.5. So,
1324                          * similarly to extra qualifiers for array, just drop
1325                          * them, instead of handling them.
1326                          */
1327                         btf_dump_drop_mods(d, decls);
1328                         if (decls->cnt) {
1329                                 btf_dump_printf(d, " (");
1330                                 btf_dump_emit_type_chain(d, decls, fname, lvl);
1331                                 btf_dump_printf(d, ")");
1332                         } else {
1333                                 btf_dump_emit_name(d, fname, last_was_ptr);
1334                         }
1335                         btf_dump_printf(d, "(");
1336                         /*
1337                          * Clang for BPF target generates func_proto with no
1338                          * args as a func_proto with a single void arg (e.g.,
1339                          * `int (*f)(void)` vs just `int (*f)()`). We are
1340                          * going to pretend there are no args for such case.
1341                          */
1342                         if (vlen == 1 && p->type == 0) {
1343                                 btf_dump_printf(d, ")");
1344                                 return;
1345                         }
1346
1347                         for (i = 0; i < vlen; i++, p++) {
1348                                 if (i > 0)
1349                                         btf_dump_printf(d, ", ");
1350
1351                                 /* last arg of type void is vararg */
1352                                 if (i == vlen - 1 && p->type == 0) {
1353                                         btf_dump_printf(d, "...");
1354                                         break;
1355                                 }
1356
1357                                 name = btf_name_of(d, p->name_off);
1358                                 btf_dump_emit_type_decl(d, p->type, name, lvl);
1359                         }
1360
1361                         btf_dump_printf(d, ")");
1362                         return;
1363                 }
1364                 default:
1365                         pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1366                                 kind, id);
1367                         return;
1368                 }
1369
1370                 last_was_ptr = kind == BTF_KIND_PTR;
1371         }
1372
1373         btf_dump_emit_name(d, fname, last_was_ptr);
1374 }
1375
1376 /* return number of duplicates (occurrences) of a given name */
1377 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1378                                  const char *orig_name)
1379 {
1380         size_t dup_cnt = 0;
1381
1382         hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1383         dup_cnt++;
1384         hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1385
1386         return dup_cnt;
1387 }
1388
1389 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1390                                          struct hashmap *name_map)
1391 {
1392         struct btf_dump_type_aux_state *s = &d->type_states[id];
1393         const struct btf_type *t = btf__type_by_id(d->btf, id);
1394         const char *orig_name = btf_name_of(d, t->name_off);
1395         const char **cached_name = &d->cached_names[id];
1396         size_t dup_cnt;
1397
1398         if (t->name_off == 0)
1399                 return "";
1400
1401         if (s->name_resolved)
1402                 return *cached_name ? *cached_name : orig_name;
1403
1404         dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1405         if (dup_cnt > 1) {
1406                 const size_t max_len = 256;
1407                 char new_name[max_len];
1408
1409                 snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1410                 *cached_name = strdup(new_name);
1411         }
1412
1413         s->name_resolved = 1;
1414         return *cached_name ? *cached_name : orig_name;
1415 }
1416
1417 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1418 {
1419         return btf_dump_resolve_name(d, id, d->type_names);
1420 }
1421
1422 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1423 {
1424         return btf_dump_resolve_name(d, id, d->ident_names);
1425 }