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