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