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