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