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