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