xref: /openbmc/linux/tools/lib/bpf/btf_dump.c (revision cef69974)
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 	if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1509 		s->name_resolved = 1;
1510 		return orig_name;
1511 	}
1512 
1513 	dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1514 	if (dup_cnt > 1) {
1515 		const size_t max_len = 256;
1516 		char new_name[max_len];
1517 
1518 		snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1519 		*cached_name = strdup(new_name);
1520 	}
1521 
1522 	s->name_resolved = 1;
1523 	return *cached_name ? *cached_name : orig_name;
1524 }
1525 
1526 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1527 {
1528 	return btf_dump_resolve_name(d, id, d->type_names);
1529 }
1530 
1531 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1532 {
1533 	return btf_dump_resolve_name(d, id, d->ident_names);
1534 }
1535 
1536 static int btf_dump_dump_type_data(struct btf_dump *d,
1537 				   const char *fname,
1538 				   const struct btf_type *t,
1539 				   __u32 id,
1540 				   const void *data,
1541 				   __u8 bits_offset,
1542 				   __u8 bit_sz);
1543 
1544 static const char *btf_dump_data_newline(struct btf_dump *d)
1545 {
1546 	return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1547 }
1548 
1549 static const char *btf_dump_data_delim(struct btf_dump *d)
1550 {
1551 	return d->typed_dump->depth == 0 ? "" : ",";
1552 }
1553 
1554 static void btf_dump_data_pfx(struct btf_dump *d)
1555 {
1556 	int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1557 
1558 	if (d->typed_dump->compact)
1559 		return;
1560 
1561 	for (i = 0; i < lvl; i++)
1562 		btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1563 }
1564 
1565 /* A macro is used here as btf_type_value[s]() appends format specifiers
1566  * to the format specifier passed in; these do the work of appending
1567  * delimiters etc while the caller simply has to specify the type values
1568  * in the format specifier + value(s).
1569  */
1570 #define btf_dump_type_values(d, fmt, ...)				\
1571 	btf_dump_printf(d, fmt "%s%s",					\
1572 			##__VA_ARGS__,					\
1573 			btf_dump_data_delim(d),				\
1574 			btf_dump_data_newline(d))
1575 
1576 static int btf_dump_unsupported_data(struct btf_dump *d,
1577 				     const struct btf_type *t,
1578 				     __u32 id)
1579 {
1580 	btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1581 	return -ENOTSUP;
1582 }
1583 
1584 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1585 				       const struct btf_type *t,
1586 				       const void *data,
1587 				       __u8 bits_offset,
1588 				       __u8 bit_sz,
1589 				       __u64 *value)
1590 {
1591 	__u16 left_shift_bits, right_shift_bits;
1592 	const __u8 *bytes = data;
1593 	__u8 nr_copy_bits;
1594 	__u64 num = 0;
1595 	int i;
1596 
1597 	/* Maximum supported bitfield size is 64 bits */
1598 	if (t->size > 8) {
1599 		pr_warn("unexpected bitfield size %d\n", t->size);
1600 		return -EINVAL;
1601 	}
1602 
1603 	/* Bitfield value retrieval is done in two steps; first relevant bytes are
1604 	 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1605 	 */
1606 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1607 	for (i = t->size - 1; i >= 0; i--)
1608 		num = num * 256 + bytes[i];
1609 	nr_copy_bits = bit_sz + bits_offset;
1610 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1611 	for (i = 0; i < t->size; i++)
1612 		num = num * 256 + bytes[i];
1613 	nr_copy_bits = t->size * 8 - bits_offset;
1614 #else
1615 # error "Unrecognized __BYTE_ORDER__"
1616 #endif
1617 	left_shift_bits = 64 - nr_copy_bits;
1618 	right_shift_bits = 64 - bit_sz;
1619 
1620 	*value = (num << left_shift_bits) >> right_shift_bits;
1621 
1622 	return 0;
1623 }
1624 
1625 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1626 					const struct btf_type *t,
1627 					const void *data,
1628 					__u8 bits_offset,
1629 					__u8 bit_sz)
1630 {
1631 	__u64 check_num;
1632 	int err;
1633 
1634 	err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1635 	if (err)
1636 		return err;
1637 	if (check_num == 0)
1638 		return -ENODATA;
1639 	return 0;
1640 }
1641 
1642 static int btf_dump_bitfield_data(struct btf_dump *d,
1643 				  const struct btf_type *t,
1644 				  const void *data,
1645 				  __u8 bits_offset,
1646 				  __u8 bit_sz)
1647 {
1648 	__u64 print_num;
1649 	int err;
1650 
1651 	err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1652 	if (err)
1653 		return err;
1654 
1655 	btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1656 
1657 	return 0;
1658 }
1659 
1660 /* ints, floats and ptrs */
1661 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1662 					 const struct btf_type *t,
1663 					 __u32 id,
1664 					 const void *data)
1665 {
1666 	static __u8 bytecmp[16] = {};
1667 	int nr_bytes;
1668 
1669 	/* For pointer types, pointer size is not defined on a per-type basis.
1670 	 * On dump creation however, we store the pointer size.
1671 	 */
1672 	if (btf_kind(t) == BTF_KIND_PTR)
1673 		nr_bytes = d->ptr_sz;
1674 	else
1675 		nr_bytes = t->size;
1676 
1677 	if (nr_bytes < 1 || nr_bytes > 16) {
1678 		pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1679 		return -EINVAL;
1680 	}
1681 
1682 	if (memcmp(data, bytecmp, nr_bytes) == 0)
1683 		return -ENODATA;
1684 	return 0;
1685 }
1686 
1687 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1688 			   const void *data)
1689 {
1690 	int alignment = btf__align_of(btf, type_id);
1691 
1692 	if (alignment == 0)
1693 		return false;
1694 
1695 	return ((uintptr_t)data) % alignment == 0;
1696 }
1697 
1698 static int btf_dump_int_data(struct btf_dump *d,
1699 			     const struct btf_type *t,
1700 			     __u32 type_id,
1701 			     const void *data,
1702 			     __u8 bits_offset)
1703 {
1704 	__u8 encoding = btf_int_encoding(t);
1705 	bool sign = encoding & BTF_INT_SIGNED;
1706 	char buf[16] __attribute__((aligned(16)));
1707 	int sz = t->size;
1708 
1709 	if (sz == 0 || sz > sizeof(buf)) {
1710 		pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1711 		return -EINVAL;
1712 	}
1713 
1714 	/* handle packed int data - accesses of integers not aligned on
1715 	 * int boundaries can cause problems on some platforms.
1716 	 */
1717 	if (!ptr_is_aligned(d->btf, type_id, data)) {
1718 		memcpy(buf, data, sz);
1719 		data = buf;
1720 	}
1721 
1722 	switch (sz) {
1723 	case 16: {
1724 		const __u64 *ints = data;
1725 		__u64 lsi, msi;
1726 
1727 		/* avoid use of __int128 as some 32-bit platforms do not
1728 		 * support it.
1729 		 */
1730 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1731 		lsi = ints[0];
1732 		msi = ints[1];
1733 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1734 		lsi = ints[1];
1735 		msi = ints[0];
1736 #else
1737 # error "Unrecognized __BYTE_ORDER__"
1738 #endif
1739 		if (msi == 0)
1740 			btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
1741 		else
1742 			btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
1743 					     (unsigned long long)lsi);
1744 		break;
1745 	}
1746 	case 8:
1747 		if (sign)
1748 			btf_dump_type_values(d, "%lld", *(long long *)data);
1749 		else
1750 			btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
1751 		break;
1752 	case 4:
1753 		if (sign)
1754 			btf_dump_type_values(d, "%d", *(__s32 *)data);
1755 		else
1756 			btf_dump_type_values(d, "%u", *(__u32 *)data);
1757 		break;
1758 	case 2:
1759 		if (sign)
1760 			btf_dump_type_values(d, "%d", *(__s16 *)data);
1761 		else
1762 			btf_dump_type_values(d, "%u", *(__u16 *)data);
1763 		break;
1764 	case 1:
1765 		if (d->typed_dump->is_array_char) {
1766 			/* check for null terminator */
1767 			if (d->typed_dump->is_array_terminated)
1768 				break;
1769 			if (*(char *)data == '\0') {
1770 				d->typed_dump->is_array_terminated = true;
1771 				break;
1772 			}
1773 			if (isprint(*(char *)data)) {
1774 				btf_dump_type_values(d, "'%c'", *(char *)data);
1775 				break;
1776 			}
1777 		}
1778 		if (sign)
1779 			btf_dump_type_values(d, "%d", *(__s8 *)data);
1780 		else
1781 			btf_dump_type_values(d, "%u", *(__u8 *)data);
1782 		break;
1783 	default:
1784 		pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
1785 		return -EINVAL;
1786 	}
1787 	return 0;
1788 }
1789 
1790 union float_data {
1791 	long double ld;
1792 	double d;
1793 	float f;
1794 };
1795 
1796 static int btf_dump_float_data(struct btf_dump *d,
1797 			       const struct btf_type *t,
1798 			       __u32 type_id,
1799 			       const void *data)
1800 {
1801 	const union float_data *flp = data;
1802 	union float_data fl;
1803 	int sz = t->size;
1804 
1805 	/* handle unaligned data; copy to local union */
1806 	if (!ptr_is_aligned(d->btf, type_id, data)) {
1807 		memcpy(&fl, data, sz);
1808 		flp = &fl;
1809 	}
1810 
1811 	switch (sz) {
1812 	case 16:
1813 		btf_dump_type_values(d, "%Lf", flp->ld);
1814 		break;
1815 	case 8:
1816 		btf_dump_type_values(d, "%lf", flp->d);
1817 		break;
1818 	case 4:
1819 		btf_dump_type_values(d, "%f", flp->f);
1820 		break;
1821 	default:
1822 		pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1823 		return -EINVAL;
1824 	}
1825 	return 0;
1826 }
1827 
1828 static int btf_dump_var_data(struct btf_dump *d,
1829 			     const struct btf_type *v,
1830 			     __u32 id,
1831 			     const void *data)
1832 {
1833 	enum btf_func_linkage linkage = btf_var(v)->linkage;
1834 	const struct btf_type *t;
1835 	const char *l;
1836 	__u32 type_id;
1837 
1838 	switch (linkage) {
1839 	case BTF_FUNC_STATIC:
1840 		l = "static ";
1841 		break;
1842 	case BTF_FUNC_EXTERN:
1843 		l = "extern ";
1844 		break;
1845 	case BTF_FUNC_GLOBAL:
1846 	default:
1847 		l = "";
1848 		break;
1849 	}
1850 
1851 	/* format of output here is [linkage] [type] [varname] = (type)value,
1852 	 * for example "static int cpu_profile_flip = (int)1"
1853 	 */
1854 	btf_dump_printf(d, "%s", l);
1855 	type_id = v->type;
1856 	t = btf__type_by_id(d->btf, type_id);
1857 	btf_dump_emit_type_cast(d, type_id, false);
1858 	btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
1859 	return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
1860 }
1861 
1862 static int btf_dump_array_data(struct btf_dump *d,
1863 			       const struct btf_type *t,
1864 			       __u32 id,
1865 			       const void *data)
1866 {
1867 	const struct btf_array *array = btf_array(t);
1868 	const struct btf_type *elem_type;
1869 	__u32 i, elem_type_id;
1870 	__s64 elem_size;
1871 	bool is_array_member;
1872 
1873 	elem_type_id = array->type;
1874 	elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
1875 	elem_size = btf__resolve_size(d->btf, elem_type_id);
1876 	if (elem_size <= 0) {
1877 		pr_warn("unexpected elem size %zd for array type [%u]\n",
1878 			(ssize_t)elem_size, id);
1879 		return -EINVAL;
1880 	}
1881 
1882 	if (btf_is_int(elem_type)) {
1883 		/*
1884 		 * BTF_INT_CHAR encoding never seems to be set for
1885 		 * char arrays, so if size is 1 and element is
1886 		 * printable as a char, we'll do that.
1887 		 */
1888 		if (elem_size == 1)
1889 			d->typed_dump->is_array_char = true;
1890 	}
1891 
1892 	/* note that we increment depth before calling btf_dump_print() below;
1893 	 * this is intentional.  btf_dump_data_newline() will not print a
1894 	 * newline for depth 0 (since this leaves us with trailing newlines
1895 	 * at the end of typed display), so depth is incremented first.
1896 	 * For similar reasons, we decrement depth before showing the closing
1897 	 * parenthesis.
1898 	 */
1899 	d->typed_dump->depth++;
1900 	btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
1901 
1902 	/* may be a multidimensional array, so store current "is array member"
1903 	 * status so we can restore it correctly later.
1904 	 */
1905 	is_array_member = d->typed_dump->is_array_member;
1906 	d->typed_dump->is_array_member = true;
1907 	for (i = 0; i < array->nelems; i++, data += elem_size) {
1908 		if (d->typed_dump->is_array_terminated)
1909 			break;
1910 		btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
1911 	}
1912 	d->typed_dump->is_array_member = is_array_member;
1913 	d->typed_dump->depth--;
1914 	btf_dump_data_pfx(d);
1915 	btf_dump_type_values(d, "]");
1916 
1917 	return 0;
1918 }
1919 
1920 static int btf_dump_struct_data(struct btf_dump *d,
1921 				const struct btf_type *t,
1922 				__u32 id,
1923 				const void *data)
1924 {
1925 	const struct btf_member *m = btf_members(t);
1926 	__u16 n = btf_vlen(t);
1927 	int i, err;
1928 
1929 	/* note that we increment depth before calling btf_dump_print() below;
1930 	 * this is intentional.  btf_dump_data_newline() will not print a
1931 	 * newline for depth 0 (since this leaves us with trailing newlines
1932 	 * at the end of typed display), so depth is incremented first.
1933 	 * For similar reasons, we decrement depth before showing the closing
1934 	 * parenthesis.
1935 	 */
1936 	d->typed_dump->depth++;
1937 	btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
1938 
1939 	for (i = 0; i < n; i++, m++) {
1940 		const struct btf_type *mtype;
1941 		const char *mname;
1942 		__u32 moffset;
1943 		__u8 bit_sz;
1944 
1945 		mtype = btf__type_by_id(d->btf, m->type);
1946 		mname = btf_name_of(d, m->name_off);
1947 		moffset = btf_member_bit_offset(t, i);
1948 
1949 		bit_sz = btf_member_bitfield_size(t, i);
1950 		err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
1951 					      moffset % 8, bit_sz);
1952 		if (err < 0)
1953 			return err;
1954 	}
1955 	d->typed_dump->depth--;
1956 	btf_dump_data_pfx(d);
1957 	btf_dump_type_values(d, "}");
1958 	return err;
1959 }
1960 
1961 union ptr_data {
1962 	unsigned int p;
1963 	unsigned long long lp;
1964 };
1965 
1966 static int btf_dump_ptr_data(struct btf_dump *d,
1967 			      const struct btf_type *t,
1968 			      __u32 id,
1969 			      const void *data)
1970 {
1971 	if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
1972 		btf_dump_type_values(d, "%p", *(void **)data);
1973 	} else {
1974 		union ptr_data pt;
1975 
1976 		memcpy(&pt, data, d->ptr_sz);
1977 		if (d->ptr_sz == 4)
1978 			btf_dump_type_values(d, "0x%x", pt.p);
1979 		else
1980 			btf_dump_type_values(d, "0x%llx", pt.lp);
1981 	}
1982 	return 0;
1983 }
1984 
1985 static int btf_dump_get_enum_value(struct btf_dump *d,
1986 				   const struct btf_type *t,
1987 				   const void *data,
1988 				   __u32 id,
1989 				   __s64 *value)
1990 {
1991 	/* handle unaligned enum value */
1992 	if (!ptr_is_aligned(d->btf, id, data)) {
1993 		__u64 val;
1994 		int err;
1995 
1996 		err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
1997 		if (err)
1998 			return err;
1999 		*value = (__s64)val;
2000 		return 0;
2001 	}
2002 
2003 	switch (t->size) {
2004 	case 8:
2005 		*value = *(__s64 *)data;
2006 		return 0;
2007 	case 4:
2008 		*value = *(__s32 *)data;
2009 		return 0;
2010 	case 2:
2011 		*value = *(__s16 *)data;
2012 		return 0;
2013 	case 1:
2014 		*value = *(__s8 *)data;
2015 		return 0;
2016 	default:
2017 		pr_warn("unexpected size %d for enum, id:[%u]\n", t->size, id);
2018 		return -EINVAL;
2019 	}
2020 }
2021 
2022 static int btf_dump_enum_data(struct btf_dump *d,
2023 			      const struct btf_type *t,
2024 			      __u32 id,
2025 			      const void *data)
2026 {
2027 	const struct btf_enum *e;
2028 	__s64 value;
2029 	int i, err;
2030 
2031 	err = btf_dump_get_enum_value(d, t, data, id, &value);
2032 	if (err)
2033 		return err;
2034 
2035 	for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2036 		if (value != e->val)
2037 			continue;
2038 		btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2039 		return 0;
2040 	}
2041 
2042 	btf_dump_type_values(d, "%d", value);
2043 	return 0;
2044 }
2045 
2046 static int btf_dump_datasec_data(struct btf_dump *d,
2047 				 const struct btf_type *t,
2048 				 __u32 id,
2049 				 const void *data)
2050 {
2051 	const struct btf_var_secinfo *vsi;
2052 	const struct btf_type *var;
2053 	__u32 i;
2054 	int err;
2055 
2056 	btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2057 
2058 	for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2059 		var = btf__type_by_id(d->btf, vsi->type);
2060 		err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2061 		if (err < 0)
2062 			return err;
2063 		btf_dump_printf(d, ";");
2064 	}
2065 	return 0;
2066 }
2067 
2068 /* return size of type, or if base type overflows, return -E2BIG. */
2069 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2070 					     const struct btf_type *t,
2071 					     __u32 id,
2072 					     const void *data,
2073 					     __u8 bits_offset)
2074 {
2075 	__s64 size = btf__resolve_size(d->btf, id);
2076 
2077 	if (size < 0 || size >= INT_MAX) {
2078 		pr_warn("unexpected size [%zu] for id [%u]\n",
2079 			(size_t)size, id);
2080 		return -EINVAL;
2081 	}
2082 
2083 	/* Only do overflow checking for base types; we do not want to
2084 	 * avoid showing part of a struct, union or array, even if we
2085 	 * do not have enough data to show the full object.  By
2086 	 * restricting overflow checking to base types we can ensure
2087 	 * that partial display succeeds, while avoiding overflowing
2088 	 * and using bogus data for display.
2089 	 */
2090 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2091 	if (!t) {
2092 		pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2093 			id);
2094 		return -EINVAL;
2095 	}
2096 
2097 	switch (btf_kind(t)) {
2098 	case BTF_KIND_INT:
2099 	case BTF_KIND_FLOAT:
2100 	case BTF_KIND_PTR:
2101 	case BTF_KIND_ENUM:
2102 		if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2103 			return -E2BIG;
2104 		break;
2105 	default:
2106 		break;
2107 	}
2108 	return (int)size;
2109 }
2110 
2111 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2112 					 const struct btf_type *t,
2113 					 __u32 id,
2114 					 const void *data,
2115 					 __u8 bits_offset,
2116 					 __u8 bit_sz)
2117 {
2118 	__s64 value;
2119 	int i, err;
2120 
2121 	/* toplevel exceptions; we show zero values if
2122 	 * - we ask for them (emit_zeros)
2123 	 * - if we are at top-level so we see "struct empty { }"
2124 	 * - or if we are an array member and the array is non-empty and
2125 	 *   not a char array; we don't want to be in a situation where we
2126 	 *   have an integer array 0, 1, 0, 1 and only show non-zero values.
2127 	 *   If the array contains zeroes only, or is a char array starting
2128 	 *   with a '\0', the array-level check_zero() will prevent showing it;
2129 	 *   we are concerned with determining zero value at the array member
2130 	 *   level here.
2131 	 */
2132 	if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2133 	    (d->typed_dump->is_array_member &&
2134 	     !d->typed_dump->is_array_char))
2135 		return 0;
2136 
2137 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2138 
2139 	switch (btf_kind(t)) {
2140 	case BTF_KIND_INT:
2141 		if (bit_sz)
2142 			return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2143 		return btf_dump_base_type_check_zero(d, t, id, data);
2144 	case BTF_KIND_FLOAT:
2145 	case BTF_KIND_PTR:
2146 		return btf_dump_base_type_check_zero(d, t, id, data);
2147 	case BTF_KIND_ARRAY: {
2148 		const struct btf_array *array = btf_array(t);
2149 		const struct btf_type *elem_type;
2150 		__u32 elem_type_id, elem_size;
2151 		bool ischar;
2152 
2153 		elem_type_id = array->type;
2154 		elem_size = btf__resolve_size(d->btf, elem_type_id);
2155 		elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2156 
2157 		ischar = btf_is_int(elem_type) && elem_size == 1;
2158 
2159 		/* check all elements; if _any_ element is nonzero, all
2160 		 * of array is displayed.  We make an exception however
2161 		 * for char arrays where the first element is 0; these
2162 		 * are considered zeroed also, even if later elements are
2163 		 * non-zero because the string is terminated.
2164 		 */
2165 		for (i = 0; i < array->nelems; i++) {
2166 			if (i == 0 && ischar && *(char *)data == 0)
2167 				return -ENODATA;
2168 			err = btf_dump_type_data_check_zero(d, elem_type,
2169 							    elem_type_id,
2170 							    data +
2171 							    (i * elem_size),
2172 							    bits_offset, 0);
2173 			if (err != -ENODATA)
2174 				return err;
2175 		}
2176 		return -ENODATA;
2177 	}
2178 	case BTF_KIND_STRUCT:
2179 	case BTF_KIND_UNION: {
2180 		const struct btf_member *m = btf_members(t);
2181 		__u16 n = btf_vlen(t);
2182 
2183 		/* if any struct/union member is non-zero, the struct/union
2184 		 * is considered non-zero and dumped.
2185 		 */
2186 		for (i = 0; i < n; i++, m++) {
2187 			const struct btf_type *mtype;
2188 			__u32 moffset;
2189 
2190 			mtype = btf__type_by_id(d->btf, m->type);
2191 			moffset = btf_member_bit_offset(t, i);
2192 
2193 			/* btf_int_bits() does not store member bitfield size;
2194 			 * bitfield size needs to be stored here so int display
2195 			 * of member can retrieve it.
2196 			 */
2197 			bit_sz = btf_member_bitfield_size(t, i);
2198 			err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2199 							    moffset % 8, bit_sz);
2200 			if (err != ENODATA)
2201 				return err;
2202 		}
2203 		return -ENODATA;
2204 	}
2205 	case BTF_KIND_ENUM:
2206 		err = btf_dump_get_enum_value(d, t, data, id, &value);
2207 		if (err)
2208 			return err;
2209 		if (value == 0)
2210 			return -ENODATA;
2211 		return 0;
2212 	default:
2213 		return 0;
2214 	}
2215 }
2216 
2217 /* returns size of data dumped, or error. */
2218 static int btf_dump_dump_type_data(struct btf_dump *d,
2219 				   const char *fname,
2220 				   const struct btf_type *t,
2221 				   __u32 id,
2222 				   const void *data,
2223 				   __u8 bits_offset,
2224 				   __u8 bit_sz)
2225 {
2226 	int size, err = 0;
2227 
2228 	size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset);
2229 	if (size < 0)
2230 		return size;
2231 	err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2232 	if (err) {
2233 		/* zeroed data is expected and not an error, so simply skip
2234 		 * dumping such data.  Record other errors however.
2235 		 */
2236 		if (err == -ENODATA)
2237 			return size;
2238 		return err;
2239 	}
2240 	btf_dump_data_pfx(d);
2241 
2242 	if (!d->typed_dump->skip_names) {
2243 		if (fname && strlen(fname) > 0)
2244 			btf_dump_printf(d, ".%s = ", fname);
2245 		btf_dump_emit_type_cast(d, id, true);
2246 	}
2247 
2248 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2249 
2250 	switch (btf_kind(t)) {
2251 	case BTF_KIND_UNKN:
2252 	case BTF_KIND_FWD:
2253 	case BTF_KIND_FUNC:
2254 	case BTF_KIND_FUNC_PROTO:
2255 	case BTF_KIND_DECL_TAG:
2256 		err = btf_dump_unsupported_data(d, t, id);
2257 		break;
2258 	case BTF_KIND_INT:
2259 		if (bit_sz)
2260 			err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2261 		else
2262 			err = btf_dump_int_data(d, t, id, data, bits_offset);
2263 		break;
2264 	case BTF_KIND_FLOAT:
2265 		err = btf_dump_float_data(d, t, id, data);
2266 		break;
2267 	case BTF_KIND_PTR:
2268 		err = btf_dump_ptr_data(d, t, id, data);
2269 		break;
2270 	case BTF_KIND_ARRAY:
2271 		err = btf_dump_array_data(d, t, id, data);
2272 		break;
2273 	case BTF_KIND_STRUCT:
2274 	case BTF_KIND_UNION:
2275 		err = btf_dump_struct_data(d, t, id, data);
2276 		break;
2277 	case BTF_KIND_ENUM:
2278 		/* handle bitfield and int enum values */
2279 		if (bit_sz) {
2280 			__u64 print_num;
2281 			__s64 enum_val;
2282 
2283 			err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2284 							  &print_num);
2285 			if (err)
2286 				break;
2287 			enum_val = (__s64)print_num;
2288 			err = btf_dump_enum_data(d, t, id, &enum_val);
2289 		} else
2290 			err = btf_dump_enum_data(d, t, id, data);
2291 		break;
2292 	case BTF_KIND_VAR:
2293 		err = btf_dump_var_data(d, t, id, data);
2294 		break;
2295 	case BTF_KIND_DATASEC:
2296 		err = btf_dump_datasec_data(d, t, id, data);
2297 		break;
2298 	default:
2299 		pr_warn("unexpected kind [%u] for id [%u]\n",
2300 			BTF_INFO_KIND(t->info), id);
2301 		return -EINVAL;
2302 	}
2303 	if (err < 0)
2304 		return err;
2305 	return size;
2306 }
2307 
2308 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2309 			     const void *data, size_t data_sz,
2310 			     const struct btf_dump_type_data_opts *opts)
2311 {
2312 	struct btf_dump_data typed_dump = {};
2313 	const struct btf_type *t;
2314 	int ret;
2315 
2316 	if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2317 		return libbpf_err(-EINVAL);
2318 
2319 	t = btf__type_by_id(d->btf, id);
2320 	if (!t)
2321 		return libbpf_err(-ENOENT);
2322 
2323 	d->typed_dump = &typed_dump;
2324 	d->typed_dump->data_end = data + data_sz;
2325 	d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2326 
2327 	/* default indent string is a tab */
2328 	if (!opts->indent_str)
2329 		d->typed_dump->indent_str[0] = '\t';
2330 	else
2331 		libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
2332 			       sizeof(d->typed_dump->indent_str));
2333 
2334 	d->typed_dump->compact = OPTS_GET(opts, compact, false);
2335 	d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2336 	d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2337 
2338 	ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2339 
2340 	d->typed_dump = NULL;
2341 
2342 	return libbpf_err(ret);
2343 }
2344