xref: /openbmc/linux/tools/lib/bpf/btf_dump.c (revision 827beb77)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * BTF-to-C type converter.
5  *
6  * Copyright (c) 2019 Facebook
7  */
8 
9 #include <stdbool.h>
10 #include <stddef.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ctype.h>
14 #include <endian.h>
15 #include <errno.h>
16 #include <linux/err.h>
17 #include <linux/btf.h>
18 #include <linux/kernel.h>
19 #include "btf.h"
20 #include "hashmap.h"
21 #include "libbpf.h"
22 #include "libbpf_internal.h"
23 
24 static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
25 static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
26 
27 static const char *pfx(int lvl)
28 {
29 	return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
30 }
31 
32 enum btf_dump_type_order_state {
33 	NOT_ORDERED,
34 	ORDERING,
35 	ORDERED,
36 };
37 
38 enum btf_dump_type_emit_state {
39 	NOT_EMITTED,
40 	EMITTING,
41 	EMITTED,
42 };
43 
44 /* per-type auxiliary state */
45 struct btf_dump_type_aux_state {
46 	/* topological sorting state */
47 	enum btf_dump_type_order_state order_state: 2;
48 	/* emitting state used to determine the need for forward declaration */
49 	enum btf_dump_type_emit_state emit_state: 2;
50 	/* whether forward declaration was already emitted */
51 	__u8 fwd_emitted: 1;
52 	/* whether unique non-duplicate name was already assigned */
53 	__u8 name_resolved: 1;
54 	/* whether type is referenced from any other type */
55 	__u8 referenced: 1;
56 };
57 
58 /* indent string length; one indent string is added for each indent level */
59 #define BTF_DATA_INDENT_STR_LEN			32
60 
61 /*
62  * Common internal data for BTF type data dump operations.
63  */
64 struct btf_dump_data {
65 	const void *data_end;		/* end of valid data to show */
66 	bool compact;
67 	bool skip_names;
68 	bool emit_zeroes;
69 	__u8 indent_lvl;	/* base indent level */
70 	char indent_str[BTF_DATA_INDENT_STR_LEN];
71 	/* below are used during iteration */
72 	int depth;
73 	bool is_array_member;
74 	bool is_array_terminated;
75 	bool is_array_char;
76 };
77 
78 struct btf_dump {
79 	const struct btf *btf;
80 	const struct btf_ext *btf_ext;
81 	btf_dump_printf_fn_t printf_fn;
82 	struct btf_dump_opts opts;
83 	int ptr_sz;
84 	bool strip_mods;
85 	bool skip_anon_defs;
86 	int last_id;
87 
88 	/* per-type auxiliary state */
89 	struct btf_dump_type_aux_state *type_states;
90 	size_t type_states_cap;
91 	/* per-type optional cached unique name, must be freed, if present */
92 	const char **cached_names;
93 	size_t cached_names_cap;
94 
95 	/* topo-sorted list of dependent type definitions */
96 	__u32 *emit_queue;
97 	int emit_queue_cap;
98 	int emit_queue_cnt;
99 
100 	/*
101 	 * stack of type declarations (e.g., chain of modifiers, arrays,
102 	 * funcs, etc)
103 	 */
104 	__u32 *decl_stack;
105 	int decl_stack_cap;
106 	int decl_stack_cnt;
107 
108 	/* maps struct/union/enum name to a number of name occurrences */
109 	struct hashmap *type_names;
110 	/*
111 	 * maps typedef identifiers and enum value names to a number of such
112 	 * name occurrences
113 	 */
114 	struct hashmap *ident_names;
115 	/*
116 	 * data for typed display; allocated if needed.
117 	 */
118 	struct btf_dump_data *typed_dump;
119 };
120 
121 static size_t str_hash_fn(const void *key, void *ctx)
122 {
123 	return str_hash(key);
124 }
125 
126 static bool str_equal_fn(const void *a, const void *b, void *ctx)
127 {
128 	return strcmp(a, b) == 0;
129 }
130 
131 static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
132 {
133 	return btf__name_by_offset(d->btf, name_off);
134 }
135 
136 static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
137 {
138 	va_list args;
139 
140 	va_start(args, fmt);
141 	d->printf_fn(d->opts.ctx, fmt, args);
142 	va_end(args);
143 }
144 
145 static int btf_dump_mark_referenced(struct btf_dump *d);
146 static int btf_dump_resize(struct btf_dump *d);
147 
148 struct btf_dump *btf_dump__new(const struct btf *btf,
149 			       const struct btf_ext *btf_ext,
150 			       const struct btf_dump_opts *opts,
151 			       btf_dump_printf_fn_t printf_fn)
152 {
153 	struct btf_dump *d;
154 	int err;
155 
156 	d = calloc(1, sizeof(struct btf_dump));
157 	if (!d)
158 		return libbpf_err_ptr(-ENOMEM);
159 
160 	d->btf = btf;
161 	d->btf_ext = btf_ext;
162 	d->printf_fn = printf_fn;
163 	d->opts.ctx = opts ? opts->ctx : NULL;
164 	d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
165 
166 	d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
167 	if (IS_ERR(d->type_names)) {
168 		err = PTR_ERR(d->type_names);
169 		d->type_names = NULL;
170 		goto err;
171 	}
172 	d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
173 	if (IS_ERR(d->ident_names)) {
174 		err = PTR_ERR(d->ident_names);
175 		d->ident_names = NULL;
176 		goto err;
177 	}
178 
179 	err = btf_dump_resize(d);
180 	if (err)
181 		goto err;
182 
183 	return d;
184 err:
185 	btf_dump__free(d);
186 	return libbpf_err_ptr(err);
187 }
188 
189 static int btf_dump_resize(struct btf_dump *d)
190 {
191 	int err, last_id = btf__type_cnt(d->btf) - 1;
192 
193 	if (last_id <= d->last_id)
194 		return 0;
195 
196 	if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
197 			      sizeof(*d->type_states), last_id + 1))
198 		return -ENOMEM;
199 	if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
200 			      sizeof(*d->cached_names), last_id + 1))
201 		return -ENOMEM;
202 
203 	if (d->last_id == 0) {
204 		/* VOID is special */
205 		d->type_states[0].order_state = ORDERED;
206 		d->type_states[0].emit_state = EMITTED;
207 	}
208 
209 	/* eagerly determine referenced types for anon enums */
210 	err = btf_dump_mark_referenced(d);
211 	if (err)
212 		return err;
213 
214 	d->last_id = last_id;
215 	return 0;
216 }
217 
218 void btf_dump__free(struct btf_dump *d)
219 {
220 	int i;
221 
222 	if (IS_ERR_OR_NULL(d))
223 		return;
224 
225 	free(d->type_states);
226 	if (d->cached_names) {
227 		/* any set cached name is owned by us and should be freed */
228 		for (i = 0; i <= d->last_id; i++) {
229 			if (d->cached_names[i])
230 				free((void *)d->cached_names[i]);
231 		}
232 	}
233 	free(d->cached_names);
234 	free(d->emit_queue);
235 	free(d->decl_stack);
236 	hashmap__free(d->type_names);
237 	hashmap__free(d->ident_names);
238 
239 	free(d);
240 }
241 
242 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
243 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
244 
245 /*
246  * Dump BTF type in a compilable C syntax, including all the necessary
247  * dependent types, necessary for compilation. If some of the dependent types
248  * were already emitted as part of previous btf_dump__dump_type() invocation
249  * for another type, they won't be emitted again. This API allows callers to
250  * filter out BTF types according to user-defined criterias and emitted only
251  * minimal subset of types, necessary to compile everything. Full struct/union
252  * definitions will still be emitted, even if the only usage is through
253  * pointer and could be satisfied with just a forward declaration.
254  *
255  * Dumping is done in two high-level passes:
256  *   1. Topologically sort type definitions to satisfy C rules of compilation.
257  *   2. Emit type definitions in C syntax.
258  *
259  * Returns 0 on success; <0, otherwise.
260  */
261 int btf_dump__dump_type(struct btf_dump *d, __u32 id)
262 {
263 	int err, i;
264 
265 	if (id >= btf__type_cnt(d->btf))
266 		return libbpf_err(-EINVAL);
267 
268 	err = btf_dump_resize(d);
269 	if (err)
270 		return libbpf_err(err);
271 
272 	d->emit_queue_cnt = 0;
273 	err = btf_dump_order_type(d, id, false);
274 	if (err < 0)
275 		return libbpf_err(err);
276 
277 	for (i = 0; i < d->emit_queue_cnt; i++)
278 		btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
279 
280 	return 0;
281 }
282 
283 /*
284  * Mark all types that are referenced from any other type. This is used to
285  * determine top-level anonymous enums that need to be emitted as an
286  * independent type declarations.
287  * Anonymous enums come in two flavors: either embedded in a struct's field
288  * definition, in which case they have to be declared inline as part of field
289  * type declaration; or as a top-level anonymous enum, typically used for
290  * declaring global constants. It's impossible to distinguish between two
291  * without knowning whether given enum type was referenced from other type:
292  * top-level anonymous enum won't be referenced by anything, while embedded
293  * one will.
294  */
295 static int btf_dump_mark_referenced(struct btf_dump *d)
296 {
297 	int i, j, n = btf__type_cnt(d->btf);
298 	const struct btf_type *t;
299 	__u16 vlen;
300 
301 	for (i = d->last_id + 1; i < n; i++) {
302 		t = btf__type_by_id(d->btf, i);
303 		vlen = btf_vlen(t);
304 
305 		switch (btf_kind(t)) {
306 		case BTF_KIND_INT:
307 		case BTF_KIND_ENUM:
308 		case BTF_KIND_FWD:
309 		case BTF_KIND_FLOAT:
310 			break;
311 
312 		case BTF_KIND_VOLATILE:
313 		case BTF_KIND_CONST:
314 		case BTF_KIND_RESTRICT:
315 		case BTF_KIND_PTR:
316 		case BTF_KIND_TYPEDEF:
317 		case BTF_KIND_FUNC:
318 		case BTF_KIND_VAR:
319 		case BTF_KIND_DECL_TAG:
320 			d->type_states[t->type].referenced = 1;
321 			break;
322 
323 		case BTF_KIND_ARRAY: {
324 			const struct btf_array *a = btf_array(t);
325 
326 			d->type_states[a->index_type].referenced = 1;
327 			d->type_states[a->type].referenced = 1;
328 			break;
329 		}
330 		case BTF_KIND_STRUCT:
331 		case BTF_KIND_UNION: {
332 			const struct btf_member *m = btf_members(t);
333 
334 			for (j = 0; j < vlen; j++, m++)
335 				d->type_states[m->type].referenced = 1;
336 			break;
337 		}
338 		case BTF_KIND_FUNC_PROTO: {
339 			const struct btf_param *p = btf_params(t);
340 
341 			for (j = 0; j < vlen; j++, p++)
342 				d->type_states[p->type].referenced = 1;
343 			break;
344 		}
345 		case BTF_KIND_DATASEC: {
346 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
347 
348 			for (j = 0; j < vlen; j++, v++)
349 				d->type_states[v->type].referenced = 1;
350 			break;
351 		}
352 		default:
353 			return -EINVAL;
354 		}
355 	}
356 	return 0;
357 }
358 
359 static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
360 {
361 	__u32 *new_queue;
362 	size_t new_cap;
363 
364 	if (d->emit_queue_cnt >= d->emit_queue_cap) {
365 		new_cap = max(16, d->emit_queue_cap * 3 / 2);
366 		new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
367 		if (!new_queue)
368 			return -ENOMEM;
369 		d->emit_queue = new_queue;
370 		d->emit_queue_cap = new_cap;
371 	}
372 
373 	d->emit_queue[d->emit_queue_cnt++] = id;
374 	return 0;
375 }
376 
377 /*
378  * Determine order of emitting dependent types and specified type to satisfy
379  * C compilation rules.  This is done through topological sorting with an
380  * additional complication which comes from C rules. The main idea for C is
381  * that if some type is "embedded" into a struct/union, it's size needs to be
382  * known at the time of definition of containing type. E.g., for:
383  *
384  *	struct A {};
385  *	struct B { struct A x; }
386  *
387  * struct A *HAS* to be defined before struct B, because it's "embedded",
388  * i.e., it is part of struct B layout. But in the following case:
389  *
390  *	struct A;
391  *	struct B { struct A *x; }
392  *	struct A {};
393  *
394  * it's enough to just have a forward declaration of struct A at the time of
395  * struct B definition, as struct B has a pointer to struct A, so the size of
396  * field x is known without knowing struct A size: it's sizeof(void *).
397  *
398  * Unfortunately, there are some trickier cases we need to handle, e.g.:
399  *
400  *	struct A {}; // if this was forward-declaration: compilation error
401  *	struct B {
402  *		struct { // anonymous struct
403  *			struct A y;
404  *		} *x;
405  *	};
406  *
407  * In this case, struct B's field x is a pointer, so it's size is known
408  * regardless of the size of (anonymous) struct it points to. But because this
409  * struct is anonymous and thus defined inline inside struct B, *and* it
410  * embeds struct A, compiler requires full definition of struct A to be known
411  * before struct B can be defined. This creates a transitive dependency
412  * between struct A and struct B. If struct A was forward-declared before
413  * struct B definition and fully defined after struct B definition, that would
414  * trigger compilation error.
415  *
416  * All this means that while we are doing topological sorting on BTF type
417  * graph, we need to determine relationships between different types (graph
418  * nodes):
419  *   - weak link (relationship) between X and Y, if Y *CAN* be
420  *   forward-declared at the point of X definition;
421  *   - strong link, if Y *HAS* to be fully-defined before X can be defined.
422  *
423  * The rule is as follows. Given a chain of BTF types from X to Y, if there is
424  * BTF_KIND_PTR type in the chain and at least one non-anonymous type
425  * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
426  * Weak/strong relationship is determined recursively during DFS traversal and
427  * is returned as a result from btf_dump_order_type().
428  *
429  * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
430  * but it is not guaranteeing that no extraneous forward declarations will be
431  * emitted.
432  *
433  * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
434  * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
435  * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
436  * entire graph path, so depending where from one came to that BTF type, it
437  * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
438  * once they are processed, there is no need to do it again, so they are
439  * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
440  * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
441  * in any case, once those are processed, no need to do it again, as the
442  * result won't change.
443  *
444  * Returns:
445  *   - 1, if type is part of strong link (so there is strong topological
446  *   ordering requirements);
447  *   - 0, if type is part of weak link (so can be satisfied through forward
448  *   declaration);
449  *   - <0, on error (e.g., unsatisfiable type loop detected).
450  */
451 static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
452 {
453 	/*
454 	 * Order state is used to detect strong link cycles, but only for BTF
455 	 * kinds that are or could be an independent definition (i.e.,
456 	 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
457 	 * func_protos, modifiers are just means to get to these definitions.
458 	 * Int/void don't need definitions, they are assumed to be always
459 	 * properly defined.  We also ignore datasec, var, and funcs for now.
460 	 * So for all non-defining kinds, we never even set ordering state,
461 	 * for defining kinds we set ORDERING and subsequently ORDERED if it
462 	 * forms a strong link.
463 	 */
464 	struct btf_dump_type_aux_state *tstate = &d->type_states[id];
465 	const struct btf_type *t;
466 	__u16 vlen;
467 	int err, i;
468 
469 	/* return true, letting typedefs know that it's ok to be emitted */
470 	if (tstate->order_state == ORDERED)
471 		return 1;
472 
473 	t = btf__type_by_id(d->btf, id);
474 
475 	if (tstate->order_state == ORDERING) {
476 		/* type loop, but resolvable through fwd declaration */
477 		if (btf_is_composite(t) && through_ptr && t->name_off != 0)
478 			return 0;
479 		pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
480 		return -ELOOP;
481 	}
482 
483 	switch (btf_kind(t)) {
484 	case BTF_KIND_INT:
485 	case BTF_KIND_FLOAT:
486 		tstate->order_state = ORDERED;
487 		return 0;
488 
489 	case BTF_KIND_PTR:
490 		err = btf_dump_order_type(d, t->type, true);
491 		tstate->order_state = ORDERED;
492 		return err;
493 
494 	case BTF_KIND_ARRAY:
495 		return btf_dump_order_type(d, btf_array(t)->type, false);
496 
497 	case BTF_KIND_STRUCT:
498 	case BTF_KIND_UNION: {
499 		const struct btf_member *m = btf_members(t);
500 		/*
501 		 * struct/union is part of strong link, only if it's embedded
502 		 * (so no ptr in a path) or it's anonymous (so has to be
503 		 * defined inline, even if declared through ptr)
504 		 */
505 		if (through_ptr && t->name_off != 0)
506 			return 0;
507 
508 		tstate->order_state = ORDERING;
509 
510 		vlen = btf_vlen(t);
511 		for (i = 0; i < vlen; i++, m++) {
512 			err = btf_dump_order_type(d, m->type, false);
513 			if (err < 0)
514 				return err;
515 		}
516 
517 		if (t->name_off != 0) {
518 			err = btf_dump_add_emit_queue_id(d, id);
519 			if (err < 0)
520 				return err;
521 		}
522 
523 		tstate->order_state = ORDERED;
524 		return 1;
525 	}
526 	case BTF_KIND_ENUM:
527 	case BTF_KIND_FWD:
528 		/*
529 		 * non-anonymous or non-referenced enums are top-level
530 		 * declarations and should be emitted. Same logic can be
531 		 * applied to FWDs, it won't hurt anyways.
532 		 */
533 		if (t->name_off != 0 || !tstate->referenced) {
534 			err = btf_dump_add_emit_queue_id(d, id);
535 			if (err)
536 				return err;
537 		}
538 		tstate->order_state = ORDERED;
539 		return 1;
540 
541 	case BTF_KIND_TYPEDEF: {
542 		int is_strong;
543 
544 		is_strong = btf_dump_order_type(d, t->type, through_ptr);
545 		if (is_strong < 0)
546 			return is_strong;
547 
548 		/* typedef is similar to struct/union w.r.t. fwd-decls */
549 		if (through_ptr && !is_strong)
550 			return 0;
551 
552 		/* typedef is always a named definition */
553 		err = btf_dump_add_emit_queue_id(d, id);
554 		if (err)
555 			return err;
556 
557 		d->type_states[id].order_state = ORDERED;
558 		return 1;
559 	}
560 	case BTF_KIND_VOLATILE:
561 	case BTF_KIND_CONST:
562 	case BTF_KIND_RESTRICT:
563 		return btf_dump_order_type(d, t->type, through_ptr);
564 
565 	case BTF_KIND_FUNC_PROTO: {
566 		const struct btf_param *p = btf_params(t);
567 		bool is_strong;
568 
569 		err = btf_dump_order_type(d, t->type, through_ptr);
570 		if (err < 0)
571 			return err;
572 		is_strong = err > 0;
573 
574 		vlen = btf_vlen(t);
575 		for (i = 0; i < vlen; i++, p++) {
576 			err = btf_dump_order_type(d, p->type, through_ptr);
577 			if (err < 0)
578 				return err;
579 			if (err > 0)
580 				is_strong = true;
581 		}
582 		return is_strong;
583 	}
584 	case BTF_KIND_FUNC:
585 	case BTF_KIND_VAR:
586 	case BTF_KIND_DATASEC:
587 	case BTF_KIND_DECL_TAG:
588 		d->type_states[id].order_state = ORDERED;
589 		return 0;
590 
591 	default:
592 		return -EINVAL;
593 	}
594 }
595 
596 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
597 					  const struct btf_type *t);
598 
599 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
600 				     const struct btf_type *t);
601 static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
602 				     const struct btf_type *t, int lvl);
603 
604 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
605 				   const struct btf_type *t);
606 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
607 				   const struct btf_type *t, int lvl);
608 
609 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
610 				  const struct btf_type *t);
611 
612 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
613 				      const struct btf_type *t, int lvl);
614 
615 /* a local view into a shared stack */
616 struct id_stack {
617 	const __u32 *ids;
618 	int cnt;
619 };
620 
621 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
622 				    const char *fname, int lvl);
623 static void btf_dump_emit_type_chain(struct btf_dump *d,
624 				     struct id_stack *decl_stack,
625 				     const char *fname, int lvl);
626 
627 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
628 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
629 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
630 				 const char *orig_name);
631 
632 static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
633 {
634 	const struct btf_type *t = btf__type_by_id(d->btf, id);
635 
636 	/* __builtin_va_list is a compiler built-in, which causes compilation
637 	 * errors, when compiling w/ different compiler, then used to compile
638 	 * original code (e.g., GCC to compile kernel, Clang to use generated
639 	 * C header from BTF). As it is built-in, it should be already defined
640 	 * properly internally in compiler.
641 	 */
642 	if (t->name_off == 0)
643 		return false;
644 	return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
645 }
646 
647 /*
648  * Emit C-syntax definitions of types from chains of BTF types.
649  *
650  * High-level handling of determining necessary forward declarations are handled
651  * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
652  * declarations/definitions in C syntax  are handled by a combo of
653  * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
654  * corresponding btf_dump_emit_*_{def,fwd}() functions.
655  *
656  * We also keep track of "containing struct/union type ID" to determine when
657  * we reference it from inside and thus can avoid emitting unnecessary forward
658  * declaration.
659  *
660  * This algorithm is designed in such a way, that even if some error occurs
661  * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
662  * that doesn't comply to C rules completely), algorithm will try to proceed
663  * and produce as much meaningful output as possible.
664  */
665 static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
666 {
667 	struct btf_dump_type_aux_state *tstate = &d->type_states[id];
668 	bool top_level_def = cont_id == 0;
669 	const struct btf_type *t;
670 	__u16 kind;
671 
672 	if (tstate->emit_state == EMITTED)
673 		return;
674 
675 	t = btf__type_by_id(d->btf, id);
676 	kind = btf_kind(t);
677 
678 	if (tstate->emit_state == EMITTING) {
679 		if (tstate->fwd_emitted)
680 			return;
681 
682 		switch (kind) {
683 		case BTF_KIND_STRUCT:
684 		case BTF_KIND_UNION:
685 			/*
686 			 * if we are referencing a struct/union that we are
687 			 * part of - then no need for fwd declaration
688 			 */
689 			if (id == cont_id)
690 				return;
691 			if (t->name_off == 0) {
692 				pr_warn("anonymous struct/union loop, id:[%u]\n",
693 					id);
694 				return;
695 			}
696 			btf_dump_emit_struct_fwd(d, id, t);
697 			btf_dump_printf(d, ";\n\n");
698 			tstate->fwd_emitted = 1;
699 			break;
700 		case BTF_KIND_TYPEDEF:
701 			/*
702 			 * for typedef fwd_emitted means typedef definition
703 			 * was emitted, but it can be used only for "weak"
704 			 * references through pointer only, not for embedding
705 			 */
706 			if (!btf_dump_is_blacklisted(d, id)) {
707 				btf_dump_emit_typedef_def(d, id, t, 0);
708 				btf_dump_printf(d, ";\n\n");
709 			}
710 			tstate->fwd_emitted = 1;
711 			break;
712 		default:
713 			break;
714 		}
715 
716 		return;
717 	}
718 
719 	switch (kind) {
720 	case BTF_KIND_INT:
721 		/* Emit type alias definitions if necessary */
722 		btf_dump_emit_missing_aliases(d, id, t);
723 
724 		tstate->emit_state = EMITTED;
725 		break;
726 	case BTF_KIND_ENUM:
727 		if (top_level_def) {
728 			btf_dump_emit_enum_def(d, id, t, 0);
729 			btf_dump_printf(d, ";\n\n");
730 		}
731 		tstate->emit_state = EMITTED;
732 		break;
733 	case BTF_KIND_PTR:
734 	case BTF_KIND_VOLATILE:
735 	case BTF_KIND_CONST:
736 	case BTF_KIND_RESTRICT:
737 		btf_dump_emit_type(d, t->type, cont_id);
738 		break;
739 	case BTF_KIND_ARRAY:
740 		btf_dump_emit_type(d, btf_array(t)->type, cont_id);
741 		break;
742 	case BTF_KIND_FWD:
743 		btf_dump_emit_fwd_def(d, id, t);
744 		btf_dump_printf(d, ";\n\n");
745 		tstate->emit_state = EMITTED;
746 		break;
747 	case BTF_KIND_TYPEDEF:
748 		tstate->emit_state = EMITTING;
749 		btf_dump_emit_type(d, t->type, id);
750 		/*
751 		 * typedef can server as both definition and forward
752 		 * declaration; at this stage someone depends on
753 		 * typedef as a forward declaration (refers to it
754 		 * through pointer), so unless we already did it,
755 		 * emit typedef as a forward declaration
756 		 */
757 		if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
758 			btf_dump_emit_typedef_def(d, id, t, 0);
759 			btf_dump_printf(d, ";\n\n");
760 		}
761 		tstate->emit_state = EMITTED;
762 		break;
763 	case BTF_KIND_STRUCT:
764 	case BTF_KIND_UNION:
765 		tstate->emit_state = EMITTING;
766 		/* if it's a top-level struct/union definition or struct/union
767 		 * is anonymous, then in C we'll be emitting all fields and
768 		 * their types (as opposed to just `struct X`), so we need to
769 		 * make sure that all types, referenced from struct/union
770 		 * members have necessary forward-declarations, where
771 		 * applicable
772 		 */
773 		if (top_level_def || t->name_off == 0) {
774 			const struct btf_member *m = btf_members(t);
775 			__u16 vlen = btf_vlen(t);
776 			int i, new_cont_id;
777 
778 			new_cont_id = t->name_off == 0 ? cont_id : id;
779 			for (i = 0; i < vlen; i++, m++)
780 				btf_dump_emit_type(d, m->type, new_cont_id);
781 		} else if (!tstate->fwd_emitted && id != cont_id) {
782 			btf_dump_emit_struct_fwd(d, id, t);
783 			btf_dump_printf(d, ";\n\n");
784 			tstate->fwd_emitted = 1;
785 		}
786 
787 		if (top_level_def) {
788 			btf_dump_emit_struct_def(d, id, t, 0);
789 			btf_dump_printf(d, ";\n\n");
790 			tstate->emit_state = EMITTED;
791 		} else {
792 			tstate->emit_state = NOT_EMITTED;
793 		}
794 		break;
795 	case BTF_KIND_FUNC_PROTO: {
796 		const struct btf_param *p = btf_params(t);
797 		__u16 n = btf_vlen(t);
798 		int i;
799 
800 		btf_dump_emit_type(d, t->type, cont_id);
801 		for (i = 0; i < n; i++, p++)
802 			btf_dump_emit_type(d, p->type, cont_id);
803 
804 		break;
805 	}
806 	default:
807 		break;
808 	}
809 }
810 
811 static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
812 				 const struct btf_type *t)
813 {
814 	const struct btf_member *m;
815 	int align, i, bit_sz;
816 	__u16 vlen;
817 
818 	align = btf__align_of(btf, id);
819 	/* size of a non-packed struct has to be a multiple of its alignment*/
820 	if (align && t->size % align)
821 		return true;
822 
823 	m = btf_members(t);
824 	vlen = btf_vlen(t);
825 	/* all non-bitfield fields have to be naturally aligned */
826 	for (i = 0; i < vlen; i++, m++) {
827 		align = btf__align_of(btf, m->type);
828 		bit_sz = btf_member_bitfield_size(t, i);
829 		if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
830 			return true;
831 	}
832 
833 	/*
834 	 * if original struct was marked as packed, but its layout is
835 	 * naturally aligned, we'll detect that it's not packed
836 	 */
837 	return false;
838 }
839 
840 static int chip_away_bits(int total, int at_most)
841 {
842 	return total % at_most ? : at_most;
843 }
844 
845 static void btf_dump_emit_bit_padding(const struct btf_dump *d,
846 				      int cur_off, int m_off, int m_bit_sz,
847 				      int align, int lvl)
848 {
849 	int off_diff = m_off - cur_off;
850 	int ptr_bits = d->ptr_sz * 8;
851 
852 	if (off_diff <= 0)
853 		/* no gap */
854 		return;
855 	if (m_bit_sz == 0 && off_diff < align * 8)
856 		/* natural padding will take care of a gap */
857 		return;
858 
859 	while (off_diff > 0) {
860 		const char *pad_type;
861 		int pad_bits;
862 
863 		if (ptr_bits > 32 && off_diff > 32) {
864 			pad_type = "long";
865 			pad_bits = chip_away_bits(off_diff, ptr_bits);
866 		} else if (off_diff > 16) {
867 			pad_type = "int";
868 			pad_bits = chip_away_bits(off_diff, 32);
869 		} else if (off_diff > 8) {
870 			pad_type = "short";
871 			pad_bits = chip_away_bits(off_diff, 16);
872 		} else {
873 			pad_type = "char";
874 			pad_bits = chip_away_bits(off_diff, 8);
875 		}
876 		btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
877 		off_diff -= pad_bits;
878 	}
879 }
880 
881 static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
882 				     const struct btf_type *t)
883 {
884 	btf_dump_printf(d, "%s%s%s",
885 			btf_is_struct(t) ? "struct" : "union",
886 			t->name_off ? " " : "",
887 			btf_dump_type_name(d, id));
888 }
889 
890 static void btf_dump_emit_struct_def(struct btf_dump *d,
891 				     __u32 id,
892 				     const struct btf_type *t,
893 				     int lvl)
894 {
895 	const struct btf_member *m = btf_members(t);
896 	bool is_struct = btf_is_struct(t);
897 	int align, i, packed, off = 0;
898 	__u16 vlen = btf_vlen(t);
899 
900 	packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
901 
902 	btf_dump_printf(d, "%s%s%s {",
903 			is_struct ? "struct" : "union",
904 			t->name_off ? " " : "",
905 			btf_dump_type_name(d, id));
906 
907 	for (i = 0; i < vlen; i++, m++) {
908 		const char *fname;
909 		int m_off, m_sz;
910 
911 		fname = btf_name_of(d, m->name_off);
912 		m_sz = btf_member_bitfield_size(t, i);
913 		m_off = btf_member_bit_offset(t, i);
914 		align = packed ? 1 : btf__align_of(d->btf, m->type);
915 
916 		btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
917 		btf_dump_printf(d, "\n%s", pfx(lvl + 1));
918 		btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
919 
920 		if (m_sz) {
921 			btf_dump_printf(d, ": %d", m_sz);
922 			off = m_off + m_sz;
923 		} else {
924 			m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
925 			off = m_off + m_sz * 8;
926 		}
927 		btf_dump_printf(d, ";");
928 	}
929 
930 	/* pad at the end, if necessary */
931 	if (is_struct) {
932 		align = packed ? 1 : btf__align_of(d->btf, id);
933 		btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
934 					  lvl + 1);
935 	}
936 
937 	if (vlen)
938 		btf_dump_printf(d, "\n");
939 	btf_dump_printf(d, "%s}", pfx(lvl));
940 	if (packed)
941 		btf_dump_printf(d, " __attribute__((packed))");
942 }
943 
944 static const char *missing_base_types[][2] = {
945 	/*
946 	 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
947 	 * SIMD intrinsics. Alias them to standard base types.
948 	 */
949 	{ "__Poly8_t",		"unsigned char" },
950 	{ "__Poly16_t",		"unsigned short" },
951 	{ "__Poly64_t",		"unsigned long long" },
952 	{ "__Poly128_t",	"unsigned __int128" },
953 };
954 
955 static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
956 					  const struct btf_type *t)
957 {
958 	const char *name = btf_dump_type_name(d, id);
959 	int i;
960 
961 	for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
962 		if (strcmp(name, missing_base_types[i][0]) == 0) {
963 			btf_dump_printf(d, "typedef %s %s;\n\n",
964 					missing_base_types[i][1], name);
965 			break;
966 		}
967 	}
968 }
969 
970 static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
971 				   const struct btf_type *t)
972 {
973 	btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
974 }
975 
976 static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
977 				   const struct btf_type *t,
978 				   int lvl)
979 {
980 	const struct btf_enum *v = btf_enum(t);
981 	__u16 vlen = btf_vlen(t);
982 	const char *name;
983 	size_t dup_cnt;
984 	int i;
985 
986 	btf_dump_printf(d, "enum%s%s",
987 			t->name_off ? " " : "",
988 			btf_dump_type_name(d, id));
989 
990 	if (vlen) {
991 		btf_dump_printf(d, " {");
992 		for (i = 0; i < vlen; i++, v++) {
993 			name = btf_name_of(d, v->name_off);
994 			/* enumerators share namespace with typedef idents */
995 			dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
996 			if (dup_cnt > 1) {
997 				btf_dump_printf(d, "\n%s%s___%zu = %u,",
998 						pfx(lvl + 1), name, dup_cnt,
999 						(__u32)v->val);
1000 			} else {
1001 				btf_dump_printf(d, "\n%s%s = %u,",
1002 						pfx(lvl + 1), name,
1003 						(__u32)v->val);
1004 			}
1005 		}
1006 		btf_dump_printf(d, "\n%s}", pfx(lvl));
1007 	}
1008 }
1009 
1010 static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
1011 				  const struct btf_type *t)
1012 {
1013 	const char *name = btf_dump_type_name(d, id);
1014 
1015 	if (btf_kflag(t))
1016 		btf_dump_printf(d, "union %s", name);
1017 	else
1018 		btf_dump_printf(d, "struct %s", name);
1019 }
1020 
1021 static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
1022 				     const struct btf_type *t, int lvl)
1023 {
1024 	const char *name = btf_dump_ident_name(d, id);
1025 
1026 	/*
1027 	 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
1028 	 * pointing to VOID. This generates warnings from btf_dump() and
1029 	 * results in uncompilable header file, so we are fixing it up here
1030 	 * with valid typedef into __builtin_va_list.
1031 	 */
1032 	if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1033 		btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1034 		return;
1035 	}
1036 
1037 	btf_dump_printf(d, "typedef ");
1038 	btf_dump_emit_type_decl(d, t->type, name, lvl);
1039 }
1040 
1041 static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1042 {
1043 	__u32 *new_stack;
1044 	size_t new_cap;
1045 
1046 	if (d->decl_stack_cnt >= d->decl_stack_cap) {
1047 		new_cap = max(16, d->decl_stack_cap * 3 / 2);
1048 		new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
1049 		if (!new_stack)
1050 			return -ENOMEM;
1051 		d->decl_stack = new_stack;
1052 		d->decl_stack_cap = new_cap;
1053 	}
1054 
1055 	d->decl_stack[d->decl_stack_cnt++] = id;
1056 
1057 	return 0;
1058 }
1059 
1060 /*
1061  * Emit type declaration (e.g., field type declaration in a struct or argument
1062  * declaration in function prototype) in correct C syntax.
1063  *
1064  * For most types it's trivial, but there are few quirky type declaration
1065  * cases worth mentioning:
1066  *   - function prototypes (especially nesting of function prototypes);
1067  *   - arrays;
1068  *   - const/volatile/restrict for pointers vs other types.
1069  *
1070  * For a good discussion of *PARSING* C syntax (as a human), see
1071  * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1072  * Ch.3 "Unscrambling Declarations in C".
1073  *
1074  * It won't help with BTF to C conversion much, though, as it's an opposite
1075  * problem. So we came up with this algorithm in reverse to van der Linden's
1076  * parsing algorithm. It goes from structured BTF representation of type
1077  * declaration to a valid compilable C syntax.
1078  *
1079  * For instance, consider this C typedef:
1080  *	typedef const int * const * arr[10] arr_t;
1081  * It will be represented in BTF with this chain of BTF types:
1082  *	[typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1083  *
1084  * Notice how [const] modifier always goes before type it modifies in BTF type
1085  * graph, but in C syntax, const/volatile/restrict modifiers are written to
1086  * the right of pointers, but to the left of other types. There are also other
1087  * quirks, like function pointers, arrays of them, functions returning other
1088  * functions, etc.
1089  *
1090  * We handle that by pushing all the types to a stack, until we hit "terminal"
1091  * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1092  * top of a stack, modifiers are handled differently. Array/function pointers
1093  * have also wildly different syntax and how nesting of them are done. See
1094  * code for authoritative definition.
1095  *
1096  * To avoid allocating new stack for each independent chain of BTF types, we
1097  * share one bigger stack, with each chain working only on its own local view
1098  * of a stack frame. Some care is required to "pop" stack frames after
1099  * processing type declaration chain.
1100  */
1101 int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1102 			     const struct btf_dump_emit_type_decl_opts *opts)
1103 {
1104 	const char *fname;
1105 	int lvl, err;
1106 
1107 	if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1108 		return libbpf_err(-EINVAL);
1109 
1110 	err = btf_dump_resize(d);
1111 	if (err)
1112 		return libbpf_err(err);
1113 
1114 	fname = OPTS_GET(opts, field_name, "");
1115 	lvl = OPTS_GET(opts, indent_level, 0);
1116 	d->strip_mods = OPTS_GET(opts, strip_mods, false);
1117 	btf_dump_emit_type_decl(d, id, fname, lvl);
1118 	d->strip_mods = false;
1119 	return 0;
1120 }
1121 
1122 static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1123 				    const char *fname, int lvl)
1124 {
1125 	struct id_stack decl_stack;
1126 	const struct btf_type *t;
1127 	int err, stack_start;
1128 
1129 	stack_start = d->decl_stack_cnt;
1130 	for (;;) {
1131 		t = btf__type_by_id(d->btf, id);
1132 		if (d->strip_mods && btf_is_mod(t))
1133 			goto skip_mod;
1134 
1135 		err = btf_dump_push_decl_stack_id(d, id);
1136 		if (err < 0) {
1137 			/*
1138 			 * if we don't have enough memory for entire type decl
1139 			 * chain, restore stack, emit warning, and try to
1140 			 * proceed nevertheless
1141 			 */
1142 			pr_warn("not enough memory for decl stack:%d", err);
1143 			d->decl_stack_cnt = stack_start;
1144 			return;
1145 		}
1146 skip_mod:
1147 		/* VOID */
1148 		if (id == 0)
1149 			break;
1150 
1151 		switch (btf_kind(t)) {
1152 		case BTF_KIND_PTR:
1153 		case BTF_KIND_VOLATILE:
1154 		case BTF_KIND_CONST:
1155 		case BTF_KIND_RESTRICT:
1156 		case BTF_KIND_FUNC_PROTO:
1157 			id = t->type;
1158 			break;
1159 		case BTF_KIND_ARRAY:
1160 			id = btf_array(t)->type;
1161 			break;
1162 		case BTF_KIND_INT:
1163 		case BTF_KIND_ENUM:
1164 		case BTF_KIND_FWD:
1165 		case BTF_KIND_STRUCT:
1166 		case BTF_KIND_UNION:
1167 		case BTF_KIND_TYPEDEF:
1168 		case BTF_KIND_FLOAT:
1169 			goto done;
1170 		default:
1171 			pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1172 				btf_kind(t), id);
1173 			goto done;
1174 		}
1175 	}
1176 done:
1177 	/*
1178 	 * We might be inside a chain of declarations (e.g., array of function
1179 	 * pointers returning anonymous (so inlined) structs, having another
1180 	 * array field). Each of those needs its own "stack frame" to handle
1181 	 * emitting of declarations. Those stack frames are non-overlapping
1182 	 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1183 	 * handle this set of nested stacks, we create a view corresponding to
1184 	 * our own "stack frame" and work with it as an independent stack.
1185 	 * We'll need to clean up after emit_type_chain() returns, though.
1186 	 */
1187 	decl_stack.ids = d->decl_stack + stack_start;
1188 	decl_stack.cnt = d->decl_stack_cnt - stack_start;
1189 	btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1190 	/*
1191 	 * emit_type_chain() guarantees that it will pop its entire decl_stack
1192 	 * frame before returning. But it works with a read-only view into
1193 	 * decl_stack, so it doesn't actually pop anything from the
1194 	 * perspective of shared btf_dump->decl_stack, per se. We need to
1195 	 * reset decl_stack state to how it was before us to avoid it growing
1196 	 * all the time.
1197 	 */
1198 	d->decl_stack_cnt = stack_start;
1199 }
1200 
1201 static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1202 {
1203 	const struct btf_type *t;
1204 	__u32 id;
1205 
1206 	while (decl_stack->cnt) {
1207 		id = decl_stack->ids[decl_stack->cnt - 1];
1208 		t = btf__type_by_id(d->btf, id);
1209 
1210 		switch (btf_kind(t)) {
1211 		case BTF_KIND_VOLATILE:
1212 			btf_dump_printf(d, "volatile ");
1213 			break;
1214 		case BTF_KIND_CONST:
1215 			btf_dump_printf(d, "const ");
1216 			break;
1217 		case BTF_KIND_RESTRICT:
1218 			btf_dump_printf(d, "restrict ");
1219 			break;
1220 		default:
1221 			return;
1222 		}
1223 		decl_stack->cnt--;
1224 	}
1225 }
1226 
1227 static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1228 {
1229 	const struct btf_type *t;
1230 	__u32 id;
1231 
1232 	while (decl_stack->cnt) {
1233 		id = decl_stack->ids[decl_stack->cnt - 1];
1234 		t = btf__type_by_id(d->btf, id);
1235 		if (!btf_is_mod(t))
1236 			return;
1237 		decl_stack->cnt--;
1238 	}
1239 }
1240 
1241 static void btf_dump_emit_name(const struct btf_dump *d,
1242 			       const char *name, bool last_was_ptr)
1243 {
1244 	bool separate = name[0] && !last_was_ptr;
1245 
1246 	btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1247 }
1248 
1249 static void btf_dump_emit_type_chain(struct btf_dump *d,
1250 				     struct id_stack *decls,
1251 				     const char *fname, int lvl)
1252 {
1253 	/*
1254 	 * last_was_ptr is used to determine if we need to separate pointer
1255 	 * asterisk (*) from previous part of type signature with space, so
1256 	 * that we get `int ***`, instead of `int * * *`. We default to true
1257 	 * for cases where we have single pointer in a chain. E.g., in ptr ->
1258 	 * func_proto case. func_proto will start a new emit_type_chain call
1259 	 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1260 	 * don't want to prepend space for that last pointer.
1261 	 */
1262 	bool last_was_ptr = true;
1263 	const struct btf_type *t;
1264 	const char *name;
1265 	__u16 kind;
1266 	__u32 id;
1267 
1268 	while (decls->cnt) {
1269 		id = decls->ids[--decls->cnt];
1270 		if (id == 0) {
1271 			/* VOID is a special snowflake */
1272 			btf_dump_emit_mods(d, decls);
1273 			btf_dump_printf(d, "void");
1274 			last_was_ptr = false;
1275 			continue;
1276 		}
1277 
1278 		t = btf__type_by_id(d->btf, id);
1279 		kind = btf_kind(t);
1280 
1281 		switch (kind) {
1282 		case BTF_KIND_INT:
1283 		case BTF_KIND_FLOAT:
1284 			btf_dump_emit_mods(d, decls);
1285 			name = btf_name_of(d, t->name_off);
1286 			btf_dump_printf(d, "%s", name);
1287 			break;
1288 		case BTF_KIND_STRUCT:
1289 		case BTF_KIND_UNION:
1290 			btf_dump_emit_mods(d, decls);
1291 			/* inline anonymous struct/union */
1292 			if (t->name_off == 0 && !d->skip_anon_defs)
1293 				btf_dump_emit_struct_def(d, id, t, lvl);
1294 			else
1295 				btf_dump_emit_struct_fwd(d, id, t);
1296 			break;
1297 		case BTF_KIND_ENUM:
1298 			btf_dump_emit_mods(d, decls);
1299 			/* inline anonymous enum */
1300 			if (t->name_off == 0 && !d->skip_anon_defs)
1301 				btf_dump_emit_enum_def(d, id, t, lvl);
1302 			else
1303 				btf_dump_emit_enum_fwd(d, id, t);
1304 			break;
1305 		case BTF_KIND_FWD:
1306 			btf_dump_emit_mods(d, decls);
1307 			btf_dump_emit_fwd_def(d, id, t);
1308 			break;
1309 		case BTF_KIND_TYPEDEF:
1310 			btf_dump_emit_mods(d, decls);
1311 			btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1312 			break;
1313 		case BTF_KIND_PTR:
1314 			btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1315 			break;
1316 		case BTF_KIND_VOLATILE:
1317 			btf_dump_printf(d, " volatile");
1318 			break;
1319 		case BTF_KIND_CONST:
1320 			btf_dump_printf(d, " const");
1321 			break;
1322 		case BTF_KIND_RESTRICT:
1323 			btf_dump_printf(d, " restrict");
1324 			break;
1325 		case BTF_KIND_ARRAY: {
1326 			const struct btf_array *a = btf_array(t);
1327 			const struct btf_type *next_t;
1328 			__u32 next_id;
1329 			bool multidim;
1330 			/*
1331 			 * GCC has a bug
1332 			 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1333 			 * which causes it to emit extra const/volatile
1334 			 * modifiers for an array, if array's element type has
1335 			 * const/volatile modifiers. Clang doesn't do that.
1336 			 * In general, it doesn't seem very meaningful to have
1337 			 * a const/volatile modifier for array, so we are
1338 			 * going to silently skip them here.
1339 			 */
1340 			btf_dump_drop_mods(d, decls);
1341 
1342 			if (decls->cnt == 0) {
1343 				btf_dump_emit_name(d, fname, last_was_ptr);
1344 				btf_dump_printf(d, "[%u]", a->nelems);
1345 				return;
1346 			}
1347 
1348 			next_id = decls->ids[decls->cnt - 1];
1349 			next_t = btf__type_by_id(d->btf, next_id);
1350 			multidim = btf_is_array(next_t);
1351 			/* we need space if we have named non-pointer */
1352 			if (fname[0] && !last_was_ptr)
1353 				btf_dump_printf(d, " ");
1354 			/* no parentheses for multi-dimensional array */
1355 			if (!multidim)
1356 				btf_dump_printf(d, "(");
1357 			btf_dump_emit_type_chain(d, decls, fname, lvl);
1358 			if (!multidim)
1359 				btf_dump_printf(d, ")");
1360 			btf_dump_printf(d, "[%u]", a->nelems);
1361 			return;
1362 		}
1363 		case BTF_KIND_FUNC_PROTO: {
1364 			const struct btf_param *p = btf_params(t);
1365 			__u16 vlen = btf_vlen(t);
1366 			int i;
1367 
1368 			/*
1369 			 * GCC emits extra volatile qualifier for
1370 			 * __attribute__((noreturn)) function pointers. Clang
1371 			 * doesn't do it. It's a GCC quirk for backwards
1372 			 * compatibility with code written for GCC <2.5. So,
1373 			 * similarly to extra qualifiers for array, just drop
1374 			 * them, instead of handling them.
1375 			 */
1376 			btf_dump_drop_mods(d, decls);
1377 			if (decls->cnt) {
1378 				btf_dump_printf(d, " (");
1379 				btf_dump_emit_type_chain(d, decls, fname, lvl);
1380 				btf_dump_printf(d, ")");
1381 			} else {
1382 				btf_dump_emit_name(d, fname, last_was_ptr);
1383 			}
1384 			btf_dump_printf(d, "(");
1385 			/*
1386 			 * Clang for BPF target generates func_proto with no
1387 			 * args as a func_proto with a single void arg (e.g.,
1388 			 * `int (*f)(void)` vs just `int (*f)()`). We are
1389 			 * going to pretend there are no args for such case.
1390 			 */
1391 			if (vlen == 1 && p->type == 0) {
1392 				btf_dump_printf(d, ")");
1393 				return;
1394 			}
1395 
1396 			for (i = 0; i < vlen; i++, p++) {
1397 				if (i > 0)
1398 					btf_dump_printf(d, ", ");
1399 
1400 				/* last arg of type void is vararg */
1401 				if (i == vlen - 1 && p->type == 0) {
1402 					btf_dump_printf(d, "...");
1403 					break;
1404 				}
1405 
1406 				name = btf_name_of(d, p->name_off);
1407 				btf_dump_emit_type_decl(d, p->type, name, lvl);
1408 			}
1409 
1410 			btf_dump_printf(d, ")");
1411 			return;
1412 		}
1413 		default:
1414 			pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1415 				kind, id);
1416 			return;
1417 		}
1418 
1419 		last_was_ptr = kind == BTF_KIND_PTR;
1420 	}
1421 
1422 	btf_dump_emit_name(d, fname, last_was_ptr);
1423 }
1424 
1425 /* show type name as (type_name) */
1426 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1427 				    bool top_level)
1428 {
1429 	const struct btf_type *t;
1430 
1431 	/* for array members, we don't bother emitting type name for each
1432 	 * member to avoid the redundancy of
1433 	 * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
1434 	 */
1435 	if (d->typed_dump->is_array_member)
1436 		return;
1437 
1438 	/* avoid type name specification for variable/section; it will be done
1439 	 * for the associated variable value(s).
1440 	 */
1441 	t = btf__type_by_id(d->btf, id);
1442 	if (btf_is_var(t) || btf_is_datasec(t))
1443 		return;
1444 
1445 	if (top_level)
1446 		btf_dump_printf(d, "(");
1447 
1448 	d->skip_anon_defs = true;
1449 	d->strip_mods = true;
1450 	btf_dump_emit_type_decl(d, id, "", 0);
1451 	d->strip_mods = false;
1452 	d->skip_anon_defs = false;
1453 
1454 	if (top_level)
1455 		btf_dump_printf(d, ")");
1456 }
1457 
1458 /* return number of duplicates (occurrences) of a given name */
1459 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1460 				 const char *orig_name)
1461 {
1462 	size_t dup_cnt = 0;
1463 
1464 	hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1465 	dup_cnt++;
1466 	hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1467 
1468 	return dup_cnt;
1469 }
1470 
1471 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1472 					 struct hashmap *name_map)
1473 {
1474 	struct btf_dump_type_aux_state *s = &d->type_states[id];
1475 	const struct btf_type *t = btf__type_by_id(d->btf, id);
1476 	const char *orig_name = btf_name_of(d, t->name_off);
1477 	const char **cached_name = &d->cached_names[id];
1478 	size_t dup_cnt;
1479 
1480 	if (t->name_off == 0)
1481 		return "";
1482 
1483 	if (s->name_resolved)
1484 		return *cached_name ? *cached_name : orig_name;
1485 
1486 	dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1487 	if (dup_cnt > 1) {
1488 		const size_t max_len = 256;
1489 		char new_name[max_len];
1490 
1491 		snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1492 		*cached_name = strdup(new_name);
1493 	}
1494 
1495 	s->name_resolved = 1;
1496 	return *cached_name ? *cached_name : orig_name;
1497 }
1498 
1499 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1500 {
1501 	return btf_dump_resolve_name(d, id, d->type_names);
1502 }
1503 
1504 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1505 {
1506 	return btf_dump_resolve_name(d, id, d->ident_names);
1507 }
1508 
1509 static int btf_dump_dump_type_data(struct btf_dump *d,
1510 				   const char *fname,
1511 				   const struct btf_type *t,
1512 				   __u32 id,
1513 				   const void *data,
1514 				   __u8 bits_offset,
1515 				   __u8 bit_sz);
1516 
1517 static const char *btf_dump_data_newline(struct btf_dump *d)
1518 {
1519 	return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1520 }
1521 
1522 static const char *btf_dump_data_delim(struct btf_dump *d)
1523 {
1524 	return d->typed_dump->depth == 0 ? "" : ",";
1525 }
1526 
1527 static void btf_dump_data_pfx(struct btf_dump *d)
1528 {
1529 	int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1530 
1531 	if (d->typed_dump->compact)
1532 		return;
1533 
1534 	for (i = 0; i < lvl; i++)
1535 		btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1536 }
1537 
1538 /* A macro is used here as btf_type_value[s]() appends format specifiers
1539  * to the format specifier passed in; these do the work of appending
1540  * delimiters etc while the caller simply has to specify the type values
1541  * in the format specifier + value(s).
1542  */
1543 #define btf_dump_type_values(d, fmt, ...)				\
1544 	btf_dump_printf(d, fmt "%s%s",					\
1545 			##__VA_ARGS__,					\
1546 			btf_dump_data_delim(d),				\
1547 			btf_dump_data_newline(d))
1548 
1549 static int btf_dump_unsupported_data(struct btf_dump *d,
1550 				     const struct btf_type *t,
1551 				     __u32 id)
1552 {
1553 	btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1554 	return -ENOTSUP;
1555 }
1556 
1557 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1558 				       const struct btf_type *t,
1559 				       const void *data,
1560 				       __u8 bits_offset,
1561 				       __u8 bit_sz,
1562 				       __u64 *value)
1563 {
1564 	__u16 left_shift_bits, right_shift_bits;
1565 	const __u8 *bytes = data;
1566 	__u8 nr_copy_bits;
1567 	__u64 num = 0;
1568 	int i;
1569 
1570 	/* Maximum supported bitfield size is 64 bits */
1571 	if (t->size > 8) {
1572 		pr_warn("unexpected bitfield size %d\n", t->size);
1573 		return -EINVAL;
1574 	}
1575 
1576 	/* Bitfield value retrieval is done in two steps; first relevant bytes are
1577 	 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1578 	 */
1579 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1580 	for (i = t->size - 1; i >= 0; i--)
1581 		num = num * 256 + bytes[i];
1582 	nr_copy_bits = bit_sz + bits_offset;
1583 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1584 	for (i = 0; i < t->size; i++)
1585 		num = num * 256 + bytes[i];
1586 	nr_copy_bits = t->size * 8 - bits_offset;
1587 #else
1588 # error "Unrecognized __BYTE_ORDER__"
1589 #endif
1590 	left_shift_bits = 64 - nr_copy_bits;
1591 	right_shift_bits = 64 - bit_sz;
1592 
1593 	*value = (num << left_shift_bits) >> right_shift_bits;
1594 
1595 	return 0;
1596 }
1597 
1598 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1599 					const struct btf_type *t,
1600 					const void *data,
1601 					__u8 bits_offset,
1602 					__u8 bit_sz)
1603 {
1604 	__u64 check_num;
1605 	int err;
1606 
1607 	err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1608 	if (err)
1609 		return err;
1610 	if (check_num == 0)
1611 		return -ENODATA;
1612 	return 0;
1613 }
1614 
1615 static int btf_dump_bitfield_data(struct btf_dump *d,
1616 				  const struct btf_type *t,
1617 				  const void *data,
1618 				  __u8 bits_offset,
1619 				  __u8 bit_sz)
1620 {
1621 	__u64 print_num;
1622 	int err;
1623 
1624 	err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1625 	if (err)
1626 		return err;
1627 
1628 	btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1629 
1630 	return 0;
1631 }
1632 
1633 /* ints, floats and ptrs */
1634 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1635 					 const struct btf_type *t,
1636 					 __u32 id,
1637 					 const void *data)
1638 {
1639 	static __u8 bytecmp[16] = {};
1640 	int nr_bytes;
1641 
1642 	/* For pointer types, pointer size is not defined on a per-type basis.
1643 	 * On dump creation however, we store the pointer size.
1644 	 */
1645 	if (btf_kind(t) == BTF_KIND_PTR)
1646 		nr_bytes = d->ptr_sz;
1647 	else
1648 		nr_bytes = t->size;
1649 
1650 	if (nr_bytes < 1 || nr_bytes > 16) {
1651 		pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1652 		return -EINVAL;
1653 	}
1654 
1655 	if (memcmp(data, bytecmp, nr_bytes) == 0)
1656 		return -ENODATA;
1657 	return 0;
1658 }
1659 
1660 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1661 			   const void *data)
1662 {
1663 	int alignment = btf__align_of(btf, type_id);
1664 
1665 	if (alignment == 0)
1666 		return false;
1667 
1668 	return ((uintptr_t)data) % alignment == 0;
1669 }
1670 
1671 static int btf_dump_int_data(struct btf_dump *d,
1672 			     const struct btf_type *t,
1673 			     __u32 type_id,
1674 			     const void *data,
1675 			     __u8 bits_offset)
1676 {
1677 	__u8 encoding = btf_int_encoding(t);
1678 	bool sign = encoding & BTF_INT_SIGNED;
1679 	char buf[16] __attribute__((aligned(16)));
1680 	int sz = t->size;
1681 
1682 	if (sz == 0 || sz > sizeof(buf)) {
1683 		pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1684 		return -EINVAL;
1685 	}
1686 
1687 	/* handle packed int data - accesses of integers not aligned on
1688 	 * int boundaries can cause problems on some platforms.
1689 	 */
1690 	if (!ptr_is_aligned(d->btf, type_id, data)) {
1691 		memcpy(buf, data, sz);
1692 		data = buf;
1693 	}
1694 
1695 	switch (sz) {
1696 	case 16: {
1697 		const __u64 *ints = data;
1698 		__u64 lsi, msi;
1699 
1700 		/* avoid use of __int128 as some 32-bit platforms do not
1701 		 * support it.
1702 		 */
1703 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1704 		lsi = ints[0];
1705 		msi = ints[1];
1706 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1707 		lsi = ints[1];
1708 		msi = ints[0];
1709 #else
1710 # error "Unrecognized __BYTE_ORDER__"
1711 #endif
1712 		if (msi == 0)
1713 			btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1714 		else
1715 			btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1716 					     (unsigned long long)lsi);
1717 		break;
1718 	}
1719 	case 8:
1720 		if (sign)
1721 			btf_dump_type_values(d, "%lld", *(long long *)data);
1722 		else
1723 			btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1724 		break;
1725 	case 4:
1726 		if (sign)
1727 			btf_dump_type_values(d, "%d", *(__s32 *)data);
1728 		else
1729 			btf_dump_type_values(d, "%u", *(__u32 *)data);
1730 		break;
1731 	case 2:
1732 		if (sign)
1733 			btf_dump_type_values(d, "%d", *(__s16 *)data);
1734 		else
1735 			btf_dump_type_values(d, "%u", *(__u16 *)data);
1736 		break;
1737 	case 1:
1738 		if (d->typed_dump->is_array_char) {
1739 			/* check for null terminator */
1740 			if (d->typed_dump->is_array_terminated)
1741 				break;
1742 			if (*(char *)data == '\0') {
1743 				d->typed_dump->is_array_terminated = true;
1744 				break;
1745 			}
1746 			if (isprint(*(char *)data)) {
1747 				btf_dump_type_values(d, "'%c'", *(char *)data);
1748 				break;
1749 			}
1750 		}
1751 		if (sign)
1752 			btf_dump_type_values(d, "%d", *(__s8 *)data);
1753 		else
1754 			btf_dump_type_values(d, "%u", *(__u8 *)data);
1755 		break;
1756 	default:
1757 		pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1758 		return -EINVAL;
1759 	}
1760 	return 0;
1761 }
1762 
1763 union float_data {
1764 	long double ld;
1765 	double d;
1766 	float f;
1767 };
1768 
1769 static int btf_dump_float_data(struct btf_dump *d,
1770 			       const struct btf_type *t,
1771 			       __u32 type_id,
1772 			       const void *data)
1773 {
1774 	const union float_data *flp = data;
1775 	union float_data fl;
1776 	int sz = t->size;
1777 
1778 	/* handle unaligned data; copy to local union */
1779 	if (!ptr_is_aligned(d->btf, type_id, data)) {
1780 		memcpy(&fl, data, sz);
1781 		flp = &fl;
1782 	}
1783 
1784 	switch (sz) {
1785 	case 16:
1786 		btf_dump_type_values(d, "%Lf", flp->ld);
1787 		break;
1788 	case 8:
1789 		btf_dump_type_values(d, "%lf", flp->d);
1790 		break;
1791 	case 4:
1792 		btf_dump_type_values(d, "%f", flp->f);
1793 		break;
1794 	default:
1795 		pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1796 		return -EINVAL;
1797 	}
1798 	return 0;
1799 }
1800 
1801 static int btf_dump_var_data(struct btf_dump *d,
1802 			     const struct btf_type *v,
1803 			     __u32 id,
1804 			     const void *data)
1805 {
1806 	enum btf_func_linkage linkage = btf_var(v)->linkage;
1807 	const struct btf_type *t;
1808 	const char *l;
1809 	__u32 type_id;
1810 
1811 	switch (linkage) {
1812 	case BTF_FUNC_STATIC:
1813 		l = "static ";
1814 		break;
1815 	case BTF_FUNC_EXTERN:
1816 		l = "extern ";
1817 		break;
1818 	case BTF_FUNC_GLOBAL:
1819 	default:
1820 		l = "";
1821 		break;
1822 	}
1823 
1824 	/* format of output here is [linkage] [type] [varname] = (type)value,
1825 	 * for example "static int cpu_profile_flip = (int)1"
1826 	 */
1827 	btf_dump_printf(d, "%s", l);
1828 	type_id = v->type;
1829 	t = btf__type_by_id(d->btf, type_id);
1830 	btf_dump_emit_type_cast(d, type_id, false);
1831 	btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
1832 	return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
1833 }
1834 
1835 static int btf_dump_array_data(struct btf_dump *d,
1836 			       const struct btf_type *t,
1837 			       __u32 id,
1838 			       const void *data)
1839 {
1840 	const struct btf_array *array = btf_array(t);
1841 	const struct btf_type *elem_type;
1842 	__u32 i, elem_size = 0, elem_type_id;
1843 	bool is_array_member;
1844 
1845 	elem_type_id = array->type;
1846 	elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
1847 	elem_size = btf__resolve_size(d->btf, elem_type_id);
1848 	if (elem_size <= 0) {
1849 		pr_warn("unexpected elem size %d for array type [%u]\n", elem_size, id);
1850 		return -EINVAL;
1851 	}
1852 
1853 	if (btf_is_int(elem_type)) {
1854 		/*
1855 		 * BTF_INT_CHAR encoding never seems to be set for
1856 		 * char arrays, so if size is 1 and element is
1857 		 * printable as a char, we'll do that.
1858 		 */
1859 		if (elem_size == 1)
1860 			d->typed_dump->is_array_char = true;
1861 	}
1862 
1863 	/* note that we increment depth before calling btf_dump_print() below;
1864 	 * this is intentional.  btf_dump_data_newline() will not print a
1865 	 * newline for depth 0 (since this leaves us with trailing newlines
1866 	 * at the end of typed display), so depth is incremented first.
1867 	 * For similar reasons, we decrement depth before showing the closing
1868 	 * parenthesis.
1869 	 */
1870 	d->typed_dump->depth++;
1871 	btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
1872 
1873 	/* may be a multidimensional array, so store current "is array member"
1874 	 * status so we can restore it correctly later.
1875 	 */
1876 	is_array_member = d->typed_dump->is_array_member;
1877 	d->typed_dump->is_array_member = true;
1878 	for (i = 0; i < array->nelems; i++, data += elem_size) {
1879 		if (d->typed_dump->is_array_terminated)
1880 			break;
1881 		btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
1882 	}
1883 	d->typed_dump->is_array_member = is_array_member;
1884 	d->typed_dump->depth--;
1885 	btf_dump_data_pfx(d);
1886 	btf_dump_type_values(d, "]");
1887 
1888 	return 0;
1889 }
1890 
1891 static int btf_dump_struct_data(struct btf_dump *d,
1892 				const struct btf_type *t,
1893 				__u32 id,
1894 				const void *data)
1895 {
1896 	const struct btf_member *m = btf_members(t);
1897 	__u16 n = btf_vlen(t);
1898 	int i, err;
1899 
1900 	/* note that we increment depth before calling btf_dump_print() below;
1901 	 * this is intentional.  btf_dump_data_newline() will not print a
1902 	 * newline for depth 0 (since this leaves us with trailing newlines
1903 	 * at the end of typed display), so depth is incremented first.
1904 	 * For similar reasons, we decrement depth before showing the closing
1905 	 * parenthesis.
1906 	 */
1907 	d->typed_dump->depth++;
1908 	btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
1909 
1910 	for (i = 0; i < n; i++, m++) {
1911 		const struct btf_type *mtype;
1912 		const char *mname;
1913 		__u32 moffset;
1914 		__u8 bit_sz;
1915 
1916 		mtype = btf__type_by_id(d->btf, m->type);
1917 		mname = btf_name_of(d, m->name_off);
1918 		moffset = btf_member_bit_offset(t, i);
1919 
1920 		bit_sz = btf_member_bitfield_size(t, i);
1921 		err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
1922 					      moffset % 8, bit_sz);
1923 		if (err < 0)
1924 			return err;
1925 	}
1926 	d->typed_dump->depth--;
1927 	btf_dump_data_pfx(d);
1928 	btf_dump_type_values(d, "}");
1929 	return err;
1930 }
1931 
1932 union ptr_data {
1933 	unsigned int p;
1934 	unsigned long long lp;
1935 };
1936 
1937 static int btf_dump_ptr_data(struct btf_dump *d,
1938 			      const struct btf_type *t,
1939 			      __u32 id,
1940 			      const void *data)
1941 {
1942 	if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
1943 		btf_dump_type_values(d, "%p", *(void **)data);
1944 	} else {
1945 		union ptr_data pt;
1946 
1947 		memcpy(&pt, data, d->ptr_sz);
1948 		if (d->ptr_sz == 4)
1949 			btf_dump_type_values(d, "0x%x", pt.p);
1950 		else
1951 			btf_dump_type_values(d, "0x%llx", pt.lp);
1952 	}
1953 	return 0;
1954 }
1955 
1956 static int btf_dump_get_enum_value(struct btf_dump *d,
1957 				   const struct btf_type *t,
1958 				   const void *data,
1959 				   __u32 id,
1960 				   __s64 *value)
1961 {
1962 	/* handle unaligned enum value */
1963 	if (!ptr_is_aligned(d->btf, id, data)) {
1964 		__u64 val;
1965 		int err;
1966 
1967 		err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
1968 		if (err)
1969 			return err;
1970 		*value = (__s64)val;
1971 		return 0;
1972 	}
1973 
1974 	switch (t->size) {
1975 	case 8:
1976 		*value = *(__s64 *)data;
1977 		return 0;
1978 	case 4:
1979 		*value = *(__s32 *)data;
1980 		return 0;
1981 	case 2:
1982 		*value = *(__s16 *)data;
1983 		return 0;
1984 	case 1:
1985 		*value = *(__s8 *)data;
1986 		return 0;
1987 	default:
1988 		pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
1989 		return -EINVAL;
1990 	}
1991 }
1992 
1993 static int btf_dump_enum_data(struct btf_dump *d,
1994 			      const struct btf_type *t,
1995 			      __u32 id,
1996 			      const void *data)
1997 {
1998 	const struct btf_enum *e;
1999 	__s64 value;
2000 	int i, err;
2001 
2002 	err = btf_dump_get_enum_value(d, t, data, id, &value);
2003 	if (err)
2004 		return err;
2005 
2006 	for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2007 		if (value != e->val)
2008 			continue;
2009 		btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2010 		return 0;
2011 	}
2012 
2013 	btf_dump_type_values(d, "%d", value);
2014 	return 0;
2015 }
2016 
2017 static int btf_dump_datasec_data(struct btf_dump *d,
2018 				 const struct btf_type *t,
2019 				 __u32 id,
2020 				 const void *data)
2021 {
2022 	const struct btf_var_secinfo *vsi;
2023 	const struct btf_type *var;
2024 	__u32 i;
2025 	int err;
2026 
2027 	btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2028 
2029 	for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2030 		var = btf__type_by_id(d->btf, vsi->type);
2031 		err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2032 		if (err < 0)
2033 			return err;
2034 		btf_dump_printf(d, ";");
2035 	}
2036 	return 0;
2037 }
2038 
2039 /* return size of type, or if base type overflows, return -E2BIG. */
2040 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2041 					     const struct btf_type *t,
2042 					     __u32 id,
2043 					     const void *data,
2044 					     __u8 bits_offset)
2045 {
2046 	__s64 size = btf__resolve_size(d->btf, id);
2047 
2048 	if (size < 0 || size >= INT_MAX) {
2049 		pr_warn("unexpected size [%zu] for id [%u]\n",
2050 			(size_t)size, id);
2051 		return -EINVAL;
2052 	}
2053 
2054 	/* Only do overflow checking for base types; we do not want to
2055 	 * avoid showing part of a struct, union or array, even if we
2056 	 * do not have enough data to show the full object.  By
2057 	 * restricting overflow checking to base types we can ensure
2058 	 * that partial display succeeds, while avoiding overflowing
2059 	 * and using bogus data for display.
2060 	 */
2061 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2062 	if (!t) {
2063 		pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2064 			id);
2065 		return -EINVAL;
2066 	}
2067 
2068 	switch (btf_kind(t)) {
2069 	case BTF_KIND_INT:
2070 	case BTF_KIND_FLOAT:
2071 	case BTF_KIND_PTR:
2072 	case BTF_KIND_ENUM:
2073 		if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2074 			return -E2BIG;
2075 		break;
2076 	default:
2077 		break;
2078 	}
2079 	return (int)size;
2080 }
2081 
2082 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2083 					 const struct btf_type *t,
2084 					 __u32 id,
2085 					 const void *data,
2086 					 __u8 bits_offset,
2087 					 __u8 bit_sz)
2088 {
2089 	__s64 value;
2090 	int i, err;
2091 
2092 	/* toplevel exceptions; we show zero values if
2093 	 * - we ask for them (emit_zeros)
2094 	 * - if we are at top-level so we see "struct empty { }"
2095 	 * - or if we are an array member and the array is non-empty and
2096 	 *   not a char array; we don't want to be in a situation where we
2097 	 *   have an integer array 0, 1, 0, 1 and only show non-zero values.
2098 	 *   If the array contains zeroes only, or is a char array starting
2099 	 *   with a '\0', the array-level check_zero() will prevent showing it;
2100 	 *   we are concerned with determining zero value at the array member
2101 	 *   level here.
2102 	 */
2103 	if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2104 	    (d->typed_dump->is_array_member &&
2105 	     !d->typed_dump->is_array_char))
2106 		return 0;
2107 
2108 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2109 
2110 	switch (btf_kind(t)) {
2111 	case BTF_KIND_INT:
2112 		if (bit_sz)
2113 			return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2114 		return btf_dump_base_type_check_zero(d, t, id, data);
2115 	case BTF_KIND_FLOAT:
2116 	case BTF_KIND_PTR:
2117 		return btf_dump_base_type_check_zero(d, t, id, data);
2118 	case BTF_KIND_ARRAY: {
2119 		const struct btf_array *array = btf_array(t);
2120 		const struct btf_type *elem_type;
2121 		__u32 elem_type_id, elem_size;
2122 		bool ischar;
2123 
2124 		elem_type_id = array->type;
2125 		elem_size = btf__resolve_size(d->btf, elem_type_id);
2126 		elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2127 
2128 		ischar = btf_is_int(elem_type) && elem_size == 1;
2129 
2130 		/* check all elements; if _any_ element is nonzero, all
2131 		 * of array is displayed.  We make an exception however
2132 		 * for char arrays where the first element is 0; these
2133 		 * are considered zeroed also, even if later elements are
2134 		 * non-zero because the string is terminated.
2135 		 */
2136 		for (i = 0; i < array->nelems; i++) {
2137 			if (i == 0 && ischar && *(char *)data == 0)
2138 				return -ENODATA;
2139 			err = btf_dump_type_data_check_zero(d, elem_type,
2140 							    elem_type_id,
2141 							    data +
2142 							    (i * elem_size),
2143 							    bits_offset, 0);
2144 			if (err != -ENODATA)
2145 				return err;
2146 		}
2147 		return -ENODATA;
2148 	}
2149 	case BTF_KIND_STRUCT:
2150 	case BTF_KIND_UNION: {
2151 		const struct btf_member *m = btf_members(t);
2152 		__u16 n = btf_vlen(t);
2153 
2154 		/* if any struct/union member is non-zero, the struct/union
2155 		 * is considered non-zero and dumped.
2156 		 */
2157 		for (i = 0; i < n; i++, m++) {
2158 			const struct btf_type *mtype;
2159 			__u32 moffset;
2160 
2161 			mtype = btf__type_by_id(d->btf, m->type);
2162 			moffset = btf_member_bit_offset(t, i);
2163 
2164 			/* btf_int_bits() does not store member bitfield size;
2165 			 * bitfield size needs to be stored here so int display
2166 			 * of member can retrieve it.
2167 			 */
2168 			bit_sz = btf_member_bitfield_size(t, i);
2169 			err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2170 							    moffset % 8, bit_sz);
2171 			if (err != ENODATA)
2172 				return err;
2173 		}
2174 		return -ENODATA;
2175 	}
2176 	case BTF_KIND_ENUM:
2177 		err = btf_dump_get_enum_value(d, t, data, id, &value);
2178 		if (err)
2179 			return err;
2180 		if (value == 0)
2181 			return -ENODATA;
2182 		return 0;
2183 	default:
2184 		return 0;
2185 	}
2186 }
2187 
2188 /* returns size of data dumped, or error. */
2189 static int btf_dump_dump_type_data(struct btf_dump *d,
2190 				   const char *fname,
2191 				   const struct btf_type *t,
2192 				   __u32 id,
2193 				   const void *data,
2194 				   __u8 bits_offset,
2195 				   __u8 bit_sz)
2196 {
2197 	int size, err;
2198 
2199 	size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2200 	if (size < 0)
2201 		return size;
2202 	err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2203 	if (err) {
2204 		/* zeroed data is expected and not an error, so simply skip
2205 		 * dumping such data.  Record other errors however.
2206 		 */
2207 		if (err == -ENODATA)
2208 			return size;
2209 		return err;
2210 	}
2211 	btf_dump_data_pfx(d);
2212 
2213 	if (!d->typed_dump->skip_names) {
2214 		if (fname && strlen(fname) > 0)
2215 			btf_dump_printf(d, ".%s = ", fname);
2216 		btf_dump_emit_type_cast(d, id, true);
2217 	}
2218 
2219 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2220 
2221 	switch (btf_kind(t)) {
2222 	case BTF_KIND_UNKN:
2223 	case BTF_KIND_FWD:
2224 	case BTF_KIND_FUNC:
2225 	case BTF_KIND_FUNC_PROTO:
2226 	case BTF_KIND_DECL_TAG:
2227 		err = btf_dump_unsupported_data(d, t, id);
2228 		break;
2229 	case BTF_KIND_INT:
2230 		if (bit_sz)
2231 			err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2232 		else
2233 			err = btf_dump_int_data(d, t, id, data, bits_offset);
2234 		break;
2235 	case BTF_KIND_FLOAT:
2236 		err = btf_dump_float_data(d, t, id, data);
2237 		break;
2238 	case BTF_KIND_PTR:
2239 		err = btf_dump_ptr_data(d, t, id, data);
2240 		break;
2241 	case BTF_KIND_ARRAY:
2242 		err = btf_dump_array_data(d, t, id, data);
2243 		break;
2244 	case BTF_KIND_STRUCT:
2245 	case BTF_KIND_UNION:
2246 		err = btf_dump_struct_data(d, t, id, data);
2247 		break;
2248 	case BTF_KIND_ENUM:
2249 		/* handle bitfield and int enum values */
2250 		if (bit_sz) {
2251 			__u64 print_num;
2252 			__s64 enum_val;
2253 
2254 			err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2255 							  &print_num);
2256 			if (err)
2257 				break;
2258 			enum_val = (__s64)print_num;
2259 			err = btf_dump_enum_data(d, t, id, &enum_val);
2260 		} else
2261 			err = btf_dump_enum_data(d, t, id, data);
2262 		break;
2263 	case BTF_KIND_VAR:
2264 		err = btf_dump_var_data(d, t, id, data);
2265 		break;
2266 	case BTF_KIND_DATASEC:
2267 		err = btf_dump_datasec_data(d, t, id, data);
2268 		break;
2269 	default:
2270 		pr_warn("unexpected kind [%u] for id [%u]\n",
2271 			BTF_INFO_KIND(t->info), id);
2272 		return -EINVAL;
2273 	}
2274 	if (err < 0)
2275 		return err;
2276 	return size;
2277 }
2278 
2279 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2280 			     const void *data, size_t data_sz,
2281 			     const struct btf_dump_type_data_opts *opts)
2282 {
2283 	struct btf_dump_data typed_dump = {};
2284 	const struct btf_type *t;
2285 	int ret;
2286 
2287 	if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2288 		return libbpf_err(-EINVAL);
2289 
2290 	t = btf__type_by_id(d->btf, id);
2291 	if (!t)
2292 		return libbpf_err(-ENOENT);
2293 
2294 	d->typed_dump = &typed_dump;
2295 	d->typed_dump->data_end = data + data_sz;
2296 	d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2297 
2298 	/* default indent string is a tab */
2299 	if (!opts->indent_str)
2300 		d->typed_dump->indent_str[0] = '\t';
2301 	else
2302 		strncat(d->typed_dump->indent_str, opts->indent_str,
2303 			sizeof(d->typed_dump->indent_str) - 1);
2304 
2305 	d->typed_dump->compact = OPTS_GET(opts, compact, false);
2306 	d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2307 	d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2308 
2309 	ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2310 
2311 	d->typed_dump = NULL;
2312 
2313 	return libbpf_err(ret);
2314 }
2315