xref: /linux/tools/lib/bpf/btf_dump.c (revision 2b5440b31cafad2fb4b4a83efb780a6d7430a385)
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
1599 				btf_dump_printf(d, " __attribute__((btf_type_tag(\"%s\")))", name);
1600 			break;
1601 		case BTF_KIND_ARRAY: {
1602 			const struct btf_array *a = btf_array(t);
1603 			const struct btf_type *next_t;
1604 			__u32 next_id;
1605 			bool multidim;
1606 			/*
1607 			 * GCC has a bug
1608 			 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1609 			 * which causes it to emit extra const/volatile
1610 			 * modifiers for an array, if array's element type has
1611 			 * const/volatile modifiers. Clang doesn't do that.
1612 			 * In general, it doesn't seem very meaningful to have
1613 			 * a const/volatile modifier for array, so we are
1614 			 * going to silently skip them here.
1615 			 */
1616 			btf_dump_drop_mods(d, decls);
1617 
1618 			if (decls->cnt == 0) {
1619 				btf_dump_emit_name(d, fname, last_was_ptr);
1620 				btf_dump_printf(d, "[%u]", a->nelems);
1621 				return;
1622 			}
1623 
1624 			next_id = decls->ids[decls->cnt - 1];
1625 			next_t = btf__type_by_id(d->btf, next_id);
1626 			multidim = btf_is_array(next_t);
1627 			/* we need space if we have named non-pointer */
1628 			if (fname[0] && !last_was_ptr)
1629 				btf_dump_printf(d, " ");
1630 			/* no parentheses for multi-dimensional array */
1631 			if (!multidim)
1632 				btf_dump_printf(d, "(");
1633 			btf_dump_emit_type_chain(d, decls, fname, lvl);
1634 			if (!multidim)
1635 				btf_dump_printf(d, ")");
1636 			btf_dump_printf(d, "[%u]", a->nelems);
1637 			return;
1638 		}
1639 		case BTF_KIND_FUNC_PROTO: {
1640 			const struct btf_param *p = btf_params(t);
1641 			__u32 vlen = btf_vlen(t);
1642 			int i;
1643 
1644 			/*
1645 			 * GCC emits extra volatile qualifier for
1646 			 * __attribute__((noreturn)) function pointers. Clang
1647 			 * doesn't do it. It's a GCC quirk for backwards
1648 			 * compatibility with code written for GCC <2.5. So,
1649 			 * similarly to extra qualifiers for array, just drop
1650 			 * them, instead of handling them.
1651 			 */
1652 			btf_dump_drop_mods(d, decls);
1653 			if (decls->cnt) {
1654 				btf_dump_printf(d, " (");
1655 				btf_dump_emit_type_chain(d, decls, fname, lvl);
1656 				btf_dump_printf(d, ")");
1657 			} else {
1658 				btf_dump_emit_name(d, fname, last_was_ptr);
1659 			}
1660 			btf_dump_printf(d, "(");
1661 			/*
1662 			 * Clang for BPF target generates func_proto with no
1663 			 * args as a func_proto with a single void arg (e.g.,
1664 			 * `int (*f)(void)` vs just `int (*f)()`). We are
1665 			 * going to emit valid empty args (void) syntax for
1666 			 * such case. Similarly and conveniently, valid
1667 			 * no args case can be special-cased here as well.
1668 			 */
1669 			if (vlen == 0 || (vlen == 1 && p->type == 0)) {
1670 				btf_dump_printf(d, "void)");
1671 				return;
1672 			}
1673 
1674 			for (i = 0; i < vlen; i++, p++) {
1675 				if (i > 0)
1676 					btf_dump_printf(d, ", ");
1677 
1678 				/* last arg of type void is vararg */
1679 				if (i == vlen - 1 && p->type == 0) {
1680 					btf_dump_printf(d, "...");
1681 					break;
1682 				}
1683 
1684 				name = btf_name_of(d, p->name_off);
1685 				btf_dump_emit_type_decl(d, p->type, name, lvl);
1686 			}
1687 
1688 			btf_dump_printf(d, ")");
1689 			return;
1690 		}
1691 		default:
1692 			pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1693 				kind, id);
1694 			return;
1695 		}
1696 
1697 		last_was_ptr = kind == BTF_KIND_PTR;
1698 	}
1699 
1700 	btf_dump_emit_name(d, fname, last_was_ptr);
1701 }
1702 
1703 /* show type name as (type_name) */
1704 static void btf_dump_emit_type_cast(struct btf_dump *d, __u32 id,
1705 				    bool top_level)
1706 {
1707 	const struct btf_type *t;
1708 
1709 	/* for array members, we don't bother emitting type name for each
1710 	 * member to avoid the redundancy of
1711 	 * .name = (char[4])[(char)'f',(char)'o',(char)'o',]
1712 	 */
1713 	if (d->typed_dump->is_array_member)
1714 		return;
1715 
1716 	/* avoid type name specification for variable/section; it will be done
1717 	 * for the associated variable value(s).
1718 	 */
1719 	t = btf__type_by_id(d->btf, id);
1720 	if (btf_is_var(t) || btf_is_datasec(t))
1721 		return;
1722 
1723 	if (top_level)
1724 		btf_dump_printf(d, "(");
1725 
1726 	d->skip_anon_defs = true;
1727 	d->strip_mods = true;
1728 	btf_dump_emit_type_decl(d, id, "", 0);
1729 	d->strip_mods = false;
1730 	d->skip_anon_defs = false;
1731 
1732 	if (top_level)
1733 		btf_dump_printf(d, ")");
1734 }
1735 
1736 /* return number of duplicates (occurrences) of a given name */
1737 static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1738 				 const char *orig_name)
1739 {
1740 	char *old_name, *new_name;
1741 	size_t dup_cnt = 0;
1742 	int err;
1743 
1744 	new_name = strdup(orig_name);
1745 	if (!new_name)
1746 		return 1;
1747 
1748 	(void)hashmap__find(name_map, orig_name, &dup_cnt);
1749 	dup_cnt++;
1750 
1751 	err = hashmap__set(name_map, new_name, dup_cnt, &old_name, NULL);
1752 	if (err)
1753 		free(new_name);
1754 
1755 	free(old_name);
1756 
1757 	return dup_cnt;
1758 }
1759 
1760 static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1761 					 struct hashmap *name_map)
1762 {
1763 	struct btf_dump_type_aux_state *s = &d->type_states[id];
1764 	const struct btf_type *t = btf__type_by_id(d->btf, id);
1765 	const char *orig_name = btf_name_of(d, t->name_off);
1766 	const char **cached_name = &d->cached_names[id];
1767 	size_t dup_cnt;
1768 
1769 	if (t->name_off == 0)
1770 		return "";
1771 
1772 	if (s->name_resolved)
1773 		return *cached_name ? *cached_name : orig_name;
1774 
1775 	if (btf_is_fwd(t) || (btf_is_enum(t) && btf_vlen(t) == 0)) {
1776 		s->name_resolved = 1;
1777 		return orig_name;
1778 	}
1779 
1780 	dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1781 	if (dup_cnt > 1) {
1782 		const size_t max_len = 256;
1783 		char new_name[max_len];
1784 
1785 		snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1786 		*cached_name = strdup(new_name);
1787 	}
1788 
1789 	s->name_resolved = 1;
1790 	return *cached_name ? *cached_name : orig_name;
1791 }
1792 
1793 static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1794 {
1795 	return btf_dump_resolve_name(d, id, d->type_names);
1796 }
1797 
1798 static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1799 {
1800 	return btf_dump_resolve_name(d, id, d->ident_names);
1801 }
1802 
1803 static int btf_dump_dump_type_data(struct btf_dump *d,
1804 				   const char *fname,
1805 				   const struct btf_type *t,
1806 				   __u32 id,
1807 				   const void *data,
1808 				   __u8 bits_offset,
1809 				   __u8 bit_sz);
1810 
1811 static const char *btf_dump_data_newline(struct btf_dump *d)
1812 {
1813 	return d->typed_dump->compact || d->typed_dump->depth == 0 ? "" : "\n";
1814 }
1815 
1816 static const char *btf_dump_data_delim(struct btf_dump *d)
1817 {
1818 	return d->typed_dump->depth == 0 ? "" : ",";
1819 }
1820 
1821 static void btf_dump_data_pfx(struct btf_dump *d)
1822 {
1823 	int i, lvl = d->typed_dump->indent_lvl + d->typed_dump->depth;
1824 
1825 	if (d->typed_dump->compact)
1826 		return;
1827 
1828 	for (i = 0; i < lvl; i++)
1829 		btf_dump_printf(d, "%s", d->typed_dump->indent_str);
1830 }
1831 
1832 /* A macro is used here as btf_type_value[s]() appends format specifiers
1833  * to the format specifier passed in; these do the work of appending
1834  * delimiters etc while the caller simply has to specify the type values
1835  * in the format specifier + value(s).
1836  */
1837 #define btf_dump_type_values(d, fmt, ...)				\
1838 	btf_dump_printf(d, fmt "%s%s",					\
1839 			##__VA_ARGS__,					\
1840 			btf_dump_data_delim(d),				\
1841 			btf_dump_data_newline(d))
1842 
1843 static int btf_dump_unsupported_data(struct btf_dump *d,
1844 				     const struct btf_type *t,
1845 				     __u32 id)
1846 {
1847 	btf_dump_printf(d, "<unsupported kind:%u>", btf_kind(t));
1848 	return -ENOTSUP;
1849 }
1850 
1851 static int btf_dump_get_bitfield_value(struct btf_dump *d,
1852 				       const struct btf_type *t,
1853 				       const void *data,
1854 				       __u8 bits_offset,
1855 				       __u8 bit_sz,
1856 				       __u64 *value)
1857 {
1858 	__u16 left_shift_bits, right_shift_bits;
1859 	const __u8 *bytes = data;
1860 	__u8 nr_copy_bits;
1861 	__u8 start_bit, nr_bytes;
1862 	__u64 num = 0;
1863 	int i;
1864 
1865 	/* Calculate how many bytes cover the bitfield */
1866 	start_bit = bits_offset % 8;
1867 	nr_bytes = (start_bit + bit_sz + 7) / 8;
1868 
1869 	/* Bound check */
1870 	if (data + nr_bytes > d->typed_dump->data_end)
1871 		return -E2BIG;
1872 
1873 	/* Maximum supported bitfield size is 64 bits */
1874 	if (t->size > 8) {
1875 		pr_warn("unexpected bitfield size %u\n", t->size);
1876 		return -EINVAL;
1877 	}
1878 
1879 	/* Bitfield value retrieval is done in two steps; first relevant bytes are
1880 	 * stored in num, then we left/right shift num to eliminate irrelevant bits.
1881 	 */
1882 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1883 	for (i = t->size - 1; i >= 0; i--)
1884 		num = num * 256 + bytes[i];
1885 	nr_copy_bits = bit_sz + bits_offset;
1886 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1887 	for (i = 0; i < t->size; i++)
1888 		num = num * 256 + bytes[i];
1889 	nr_copy_bits = t->size * 8 - bits_offset;
1890 #else
1891 # error "Unrecognized __BYTE_ORDER__"
1892 #endif
1893 	left_shift_bits = 64 - nr_copy_bits;
1894 	right_shift_bits = 64 - bit_sz;
1895 
1896 	*value = (num << left_shift_bits) >> right_shift_bits;
1897 
1898 	return 0;
1899 }
1900 
1901 static int btf_dump_bitfield_check_zero(struct btf_dump *d,
1902 					const struct btf_type *t,
1903 					const void *data,
1904 					__u8 bits_offset,
1905 					__u8 bit_sz)
1906 {
1907 	__u64 check_num;
1908 	int err;
1909 
1910 	err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &check_num);
1911 	if (err)
1912 		return err;
1913 	if (check_num == 0)
1914 		return -ENODATA;
1915 	return 0;
1916 }
1917 
1918 static int btf_dump_bitfield_data(struct btf_dump *d,
1919 				  const struct btf_type *t,
1920 				  const void *data,
1921 				  __u8 bits_offset,
1922 				  __u8 bit_sz)
1923 {
1924 	__u64 print_num;
1925 	int err;
1926 
1927 	err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz, &print_num);
1928 	if (err)
1929 		return err;
1930 
1931 	btf_dump_type_values(d, "0x%llx", (unsigned long long)print_num);
1932 
1933 	return 0;
1934 }
1935 
1936 /* ints, floats and ptrs */
1937 static int btf_dump_base_type_check_zero(struct btf_dump *d,
1938 					 const struct btf_type *t,
1939 					 __u32 id,
1940 					 const void *data)
1941 {
1942 	static __u8 bytecmp[16] = {};
1943 	int nr_bytes;
1944 
1945 	/* For pointer types, pointer size is not defined on a per-type basis.
1946 	 * On dump creation however, we store the pointer size.
1947 	 */
1948 	if (btf_kind(t) == BTF_KIND_PTR)
1949 		nr_bytes = d->ptr_sz;
1950 	else
1951 		nr_bytes = t->size;
1952 
1953 	if (nr_bytes < 1 || nr_bytes > 16) {
1954 		pr_warn("unexpected size %d for id [%u]\n", nr_bytes, id);
1955 		return -EINVAL;
1956 	}
1957 
1958 	if (memcmp(data, bytecmp, nr_bytes) == 0)
1959 		return -ENODATA;
1960 	return 0;
1961 }
1962 
1963 static bool ptr_is_aligned(const struct btf *btf, __u32 type_id,
1964 			   const void *data)
1965 {
1966 	int alignment = btf__align_of(btf, type_id);
1967 
1968 	if (alignment == 0)
1969 		return false;
1970 
1971 	return ((uintptr_t)data) % alignment == 0;
1972 }
1973 
1974 static int btf_dump_int_data(struct btf_dump *d,
1975 			     const struct btf_type *t,
1976 			     __u32 type_id,
1977 			     const void *data,
1978 			     __u8 bits_offset)
1979 {
1980 	__u8 encoding = btf_int_encoding(t);
1981 	bool sign = encoding & BTF_INT_SIGNED;
1982 	char buf[16] __attribute__((aligned(16)));
1983 	int sz = t->size;
1984 
1985 	if (sz == 0 || sz > sizeof(buf)) {
1986 		pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
1987 		return -EINVAL;
1988 	}
1989 
1990 	/* handle packed int data - accesses of integers not aligned on
1991 	 * int boundaries can cause problems on some platforms.
1992 	 */
1993 	if (!ptr_is_aligned(d->btf, type_id, data)) {
1994 		memcpy(buf, data, sz);
1995 		data = buf;
1996 	}
1997 
1998 	switch (sz) {
1999 	case 16: {
2000 		const __u64 *ints = data;
2001 		__u64 lsi, msi;
2002 
2003 		/* avoid use of __int128 as some 32-bit platforms do not
2004 		 * support it.
2005 		 */
2006 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
2007 		lsi = ints[0];
2008 		msi = ints[1];
2009 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
2010 		lsi = ints[1];
2011 		msi = ints[0];
2012 #else
2013 # error "Unrecognized __BYTE_ORDER__"
2014 #endif
2015 		if (msi == 0)
2016 			btf_dump_type_values(d, "0x%llx", (unsigned long long)lsi);
2017 		else
2018 			btf_dump_type_values(d, "0x%llx%016llx", (unsigned long long)msi,
2019 					     (unsigned long long)lsi);
2020 		break;
2021 	}
2022 	case 8:
2023 		if (sign)
2024 			btf_dump_type_values(d, "%lld", *(long long *)data);
2025 		else
2026 			btf_dump_type_values(d, "%llu", *(unsigned long long *)data);
2027 		break;
2028 	case 4:
2029 		if (sign)
2030 			btf_dump_type_values(d, "%d", *(__s32 *)data);
2031 		else
2032 			btf_dump_type_values(d, "%u", *(__u32 *)data);
2033 		break;
2034 	case 2:
2035 		if (sign)
2036 			btf_dump_type_values(d, "%d", *(__s16 *)data);
2037 		else
2038 			btf_dump_type_values(d, "%u", *(__u16 *)data);
2039 		break;
2040 	case 1:
2041 		if (d->typed_dump->is_array_char) {
2042 			/* check for null terminator */
2043 			if (d->typed_dump->is_array_terminated)
2044 				break;
2045 			if (*(char *)data == '\0') {
2046 				btf_dump_type_values(d, "'\\0'");
2047 				d->typed_dump->is_array_terminated = true;
2048 				break;
2049 			}
2050 			if (isprint(*(char *)data)) {
2051 				btf_dump_type_values(d, "'%c'", *(char *)data);
2052 				break;
2053 			}
2054 		}
2055 		if (sign)
2056 			btf_dump_type_values(d, "%d", *(__s8 *)data);
2057 		else
2058 			btf_dump_type_values(d, "%u", *(__u8 *)data);
2059 		break;
2060 	default:
2061 		pr_warn("unexpected sz %d for id [%u]\n", sz, type_id);
2062 		return -EINVAL;
2063 	}
2064 	return 0;
2065 }
2066 
2067 union float_data {
2068 	long double ld;
2069 	double d;
2070 	float f;
2071 };
2072 
2073 static int btf_dump_float_data(struct btf_dump *d,
2074 			       const struct btf_type *t,
2075 			       __u32 type_id,
2076 			       const void *data)
2077 {
2078 	const union float_data *flp = data;
2079 	union float_data fl;
2080 	int sz = t->size;
2081 
2082 	/* handle unaligned data; copy to local union */
2083 	if (!ptr_is_aligned(d->btf, type_id, data)) {
2084 		memcpy(&fl, data, sz);
2085 		flp = &fl;
2086 	}
2087 
2088 	switch (sz) {
2089 	case 16:
2090 		btf_dump_type_values(d, "%Lf", flp->ld);
2091 		break;
2092 	case 8:
2093 		btf_dump_type_values(d, "%lf", flp->d);
2094 		break;
2095 	case 4:
2096 		btf_dump_type_values(d, "%f", flp->f);
2097 		break;
2098 	default:
2099 		pr_warn("unexpected size %d for id [%u]\n", sz, type_id);
2100 		return -EINVAL;
2101 	}
2102 	return 0;
2103 }
2104 
2105 static int btf_dump_var_data(struct btf_dump *d,
2106 			     const struct btf_type *v,
2107 			     __u32 id,
2108 			     const void *data)
2109 {
2110 	enum btf_func_linkage linkage = btf_var(v)->linkage;
2111 	const struct btf_type *t;
2112 	const char *l;
2113 	__u32 type_id;
2114 
2115 	switch (linkage) {
2116 	case BTF_FUNC_STATIC:
2117 		l = "static ";
2118 		break;
2119 	case BTF_FUNC_EXTERN:
2120 		l = "extern ";
2121 		break;
2122 	case BTF_FUNC_GLOBAL:
2123 	default:
2124 		l = "";
2125 		break;
2126 	}
2127 
2128 	/* format of output here is [linkage] [type] [varname] = (type)value,
2129 	 * for example "static int cpu_profile_flip = (int)1"
2130 	 */
2131 	btf_dump_printf(d, "%s", l);
2132 	type_id = v->type;
2133 	t = btf__type_by_id(d->btf, type_id);
2134 	btf_dump_emit_type_cast(d, type_id, false);
2135 	btf_dump_printf(d, " %s = ", btf_name_of(d, v->name_off));
2136 	return btf_dump_dump_type_data(d, NULL, t, type_id, data, 0, 0);
2137 }
2138 
2139 static int btf_dump_string_data(struct btf_dump *d,
2140 				const struct btf_type *t,
2141 				__u32 id,
2142 				const void *data)
2143 {
2144 	const struct btf_array *array = btf_array(t);
2145 	const char *chars = data;
2146 	__u32 i;
2147 
2148 	/* Make sure it is a NUL-terminated string. */
2149 	for (i = 0; i < array->nelems; i++) {
2150 		if ((void *)(chars + i) >= d->typed_dump->data_end)
2151 			return -E2BIG;
2152 		if (chars[i] == '\0')
2153 			break;
2154 	}
2155 	if (i == array->nelems) {
2156 		/* The caller will print this as a regular array. */
2157 		return -EINVAL;
2158 	}
2159 
2160 	btf_dump_data_pfx(d);
2161 	btf_dump_printf(d, "\"");
2162 
2163 	for (i = 0; i < array->nelems; i++) {
2164 		char c = chars[i];
2165 
2166 		if (c == '\0') {
2167 			/*
2168 			 * When printing character arrays as strings, NUL bytes
2169 			 * are always treated as string terminators; they are
2170 			 * never printed.
2171 			 */
2172 			break;
2173 		}
2174 		if (isprint(c))
2175 			btf_dump_printf(d, "%c", c);
2176 		else
2177 			btf_dump_printf(d, "\\x%02x", (__u8)c);
2178 	}
2179 
2180 	btf_dump_printf(d, "\"");
2181 
2182 	return 0;
2183 }
2184 
2185 static int btf_dump_array_data(struct btf_dump *d,
2186 			       const struct btf_type *t,
2187 			       __u32 id,
2188 			       const void *data)
2189 {
2190 	const struct btf_array *array = btf_array(t);
2191 	const struct btf_type *elem_type;
2192 	__u32 i, elem_type_id;
2193 	__s64 elem_size;
2194 	bool is_array_member;
2195 	bool is_array_terminated;
2196 
2197 	elem_type_id = array->type;
2198 	elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2199 	elem_size = btf__resolve_size(d->btf, elem_type_id);
2200 	if (elem_size <= 0) {
2201 		pr_warn("unexpected elem size %zd for array type [%u]\n",
2202 			(ssize_t)elem_size, id);
2203 		return -EINVAL;
2204 	}
2205 
2206 	if (btf_is_int(elem_type)) {
2207 		/*
2208 		 * BTF_INT_CHAR encoding never seems to be set for
2209 		 * char arrays, so if size is 1 and element is
2210 		 * printable as a char, we'll do that.
2211 		 */
2212 		if (elem_size == 1) {
2213 			if (d->typed_dump->emit_strings &&
2214 			    btf_dump_string_data(d, t, id, data) == 0) {
2215 				return 0;
2216 			}
2217 			d->typed_dump->is_array_char = true;
2218 		}
2219 	}
2220 
2221 	/* note that we increment depth before calling btf_dump_print() below;
2222 	 * this is intentional.  btf_dump_data_newline() will not print a
2223 	 * newline for depth 0 (since this leaves us with trailing newlines
2224 	 * at the end of typed display), so depth is incremented first.
2225 	 * For similar reasons, we decrement depth before showing the closing
2226 	 * parenthesis.
2227 	 */
2228 	d->typed_dump->depth++;
2229 	btf_dump_printf(d, "[%s", btf_dump_data_newline(d));
2230 
2231 	/* may be a multidimensional array, so store current "is array member"
2232 	 * status so we can restore it correctly later.
2233 	 */
2234 	is_array_member = d->typed_dump->is_array_member;
2235 	d->typed_dump->is_array_member = true;
2236 	is_array_terminated = d->typed_dump->is_array_terminated;
2237 	d->typed_dump->is_array_terminated = false;
2238 	for (i = 0; i < array->nelems; i++, data += elem_size) {
2239 		if (d->typed_dump->is_array_terminated)
2240 			break;
2241 		btf_dump_dump_type_data(d, NULL, elem_type, elem_type_id, data, 0, 0);
2242 	}
2243 	d->typed_dump->is_array_member = is_array_member;
2244 	d->typed_dump->is_array_terminated = is_array_terminated;
2245 	d->typed_dump->depth--;
2246 	btf_dump_data_pfx(d);
2247 	btf_dump_type_values(d, "]");
2248 
2249 	return 0;
2250 }
2251 
2252 static int btf_dump_struct_data(struct btf_dump *d,
2253 				const struct btf_type *t,
2254 				__u32 id,
2255 				const void *data)
2256 {
2257 	const struct btf_member *m = btf_members(t);
2258 	__u32 n = btf_vlen(t);
2259 	int i, err = 0;
2260 
2261 	/* note that we increment depth before calling btf_dump_print() below;
2262 	 * this is intentional.  btf_dump_data_newline() will not print a
2263 	 * newline for depth 0 (since this leaves us with trailing newlines
2264 	 * at the end of typed display), so depth is incremented first.
2265 	 * For similar reasons, we decrement depth before showing the closing
2266 	 * parenthesis.
2267 	 */
2268 	d->typed_dump->depth++;
2269 	btf_dump_printf(d, "{%s", btf_dump_data_newline(d));
2270 
2271 	for (i = 0; i < n; i++, m++) {
2272 		const struct btf_type *mtype;
2273 		const char *mname;
2274 		__u32 moffset;
2275 		__u8 bit_sz;
2276 
2277 		mtype = btf__type_by_id(d->btf, m->type);
2278 		mname = btf_name_of(d, m->name_off);
2279 		moffset = btf_member_bit_offset(t, i);
2280 
2281 		bit_sz = btf_member_bitfield_size(t, i);
2282 		err = btf_dump_dump_type_data(d, mname, mtype, m->type, data + moffset / 8,
2283 					      moffset % 8, bit_sz);
2284 		if (err < 0)
2285 			return err;
2286 	}
2287 	d->typed_dump->depth--;
2288 	btf_dump_data_pfx(d);
2289 	btf_dump_type_values(d, "}");
2290 	return err;
2291 }
2292 
2293 union ptr_data {
2294 	unsigned int p;
2295 	unsigned long long lp;
2296 };
2297 
2298 static int btf_dump_ptr_data(struct btf_dump *d,
2299 			      const struct btf_type *t,
2300 			      __u32 id,
2301 			      const void *data)
2302 {
2303 	if (ptr_is_aligned(d->btf, id, data) && d->ptr_sz == sizeof(void *)) {
2304 		btf_dump_type_values(d, "%p", *(void **)data);
2305 	} else {
2306 		union ptr_data pt;
2307 
2308 		memcpy(&pt, data, d->ptr_sz);
2309 		if (d->ptr_sz == 4)
2310 			btf_dump_type_values(d, "0x%x", pt.p);
2311 		else
2312 			btf_dump_type_values(d, "0x%llx", pt.lp);
2313 	}
2314 	return 0;
2315 }
2316 
2317 static int btf_dump_get_enum_value(struct btf_dump *d,
2318 				   const struct btf_type *t,
2319 				   const void *data,
2320 				   __u32 id,
2321 				   __s64 *value)
2322 {
2323 	bool is_signed = btf_kflag(t);
2324 
2325 	if (!ptr_is_aligned(d->btf, id, data)) {
2326 		__u64 val;
2327 		int err;
2328 
2329 		err = btf_dump_get_bitfield_value(d, t, data, 0, 0, &val);
2330 		if (err)
2331 			return err;
2332 		*value = (__s64)val;
2333 		return 0;
2334 	}
2335 
2336 	switch (t->size) {
2337 	case 8:
2338 		*value = *(__s64 *)data;
2339 		return 0;
2340 	case 4:
2341 		*value = is_signed ? (__s64)*(__s32 *)data : *(__u32 *)data;
2342 		return 0;
2343 	case 2:
2344 		*value = is_signed ? *(__s16 *)data : *(__u16 *)data;
2345 		return 0;
2346 	case 1:
2347 		*value = is_signed ? *(__s8 *)data : *(__u8 *)data;
2348 		return 0;
2349 	default:
2350 		pr_warn("unexpected size %u for enum, id:[%u]\n", t->size, id);
2351 		return -EINVAL;
2352 	}
2353 }
2354 
2355 static int btf_dump_enum_data(struct btf_dump *d,
2356 			      const struct btf_type *t,
2357 			      __u32 id,
2358 			      const void *data)
2359 {
2360 	bool is_signed;
2361 	__s64 value;
2362 	int i, err;
2363 
2364 	err = btf_dump_get_enum_value(d, t, data, id, &value);
2365 	if (err)
2366 		return err;
2367 
2368 	is_signed = btf_kflag(t);
2369 	if (btf_is_enum(t)) {
2370 		const struct btf_enum *e;
2371 
2372 		for (i = 0, e = btf_enum(t); i < btf_vlen(t); i++, e++) {
2373 			if (value != e->val)
2374 				continue;
2375 			btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2376 			return 0;
2377 		}
2378 
2379 		btf_dump_type_values(d, is_signed ? "%d" : "%u", value);
2380 	} else {
2381 		const struct btf_enum64 *e;
2382 
2383 		for (i = 0, e = btf_enum64(t); i < btf_vlen(t); i++, e++) {
2384 			if (value != btf_enum64_value(e))
2385 				continue;
2386 			btf_dump_type_values(d, "%s", btf_name_of(d, e->name_off));
2387 			return 0;
2388 		}
2389 
2390 		btf_dump_type_values(d, is_signed ? "%lldLL" : "%lluULL",
2391 				     (unsigned long long)value);
2392 	}
2393 	return 0;
2394 }
2395 
2396 static int btf_dump_datasec_data(struct btf_dump *d,
2397 				 const struct btf_type *t,
2398 				 __u32 id,
2399 				 const void *data)
2400 {
2401 	const struct btf_var_secinfo *vsi;
2402 	const struct btf_type *var;
2403 	__u32 i;
2404 	int err;
2405 
2406 	btf_dump_type_values(d, "SEC(\"%s\") ", btf_name_of(d, t->name_off));
2407 
2408 	for (i = 0, vsi = btf_var_secinfos(t); i < btf_vlen(t); i++, vsi++) {
2409 		var = btf__type_by_id(d->btf, vsi->type);
2410 		err = btf_dump_dump_type_data(d, NULL, var, vsi->type, data + vsi->offset, 0, 0);
2411 		if (err < 0)
2412 			return err;
2413 		btf_dump_printf(d, ";");
2414 	}
2415 	return 0;
2416 }
2417 
2418 /* return size of type, or if base type overflows, return -E2BIG. */
2419 static int btf_dump_type_data_check_overflow(struct btf_dump *d,
2420 					     const struct btf_type *t,
2421 					     __u32 id,
2422 					     const void *data,
2423 					     __u8 bits_offset,
2424 					     __u8 bit_sz)
2425 {
2426 	__s64 size;
2427 
2428 	if (bit_sz) {
2429 		/* bits_offset is at most 7. bit_sz is at most 128. */
2430 		__u8 nr_bytes = (bits_offset + bit_sz + 7) / 8;
2431 
2432 		/* When bit_sz is non zero, it is called from
2433 		 * btf_dump_struct_data() where it only cares about
2434 		 * negative error value.
2435 		 * Return nr_bytes in success case to make it
2436 		 * consistent as the regular integer case below.
2437 		 */
2438 		return data + nr_bytes > d->typed_dump->data_end ? -E2BIG : nr_bytes;
2439 	}
2440 
2441 	size = btf__resolve_size(d->btf, id);
2442 
2443 	if (size < 0 || size >= INT_MAX) {
2444 		pr_warn("unexpected size [%zu] for id [%u]\n",
2445 			(size_t)size, id);
2446 		return -EINVAL;
2447 	}
2448 
2449 	/* Only do overflow checking for base types; we do not want to
2450 	 * avoid showing part of a struct, union or array, even if we
2451 	 * do not have enough data to show the full object.  By
2452 	 * restricting overflow checking to base types we can ensure
2453 	 * that partial display succeeds, while avoiding overflowing
2454 	 * and using bogus data for display.
2455 	 */
2456 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2457 	if (!t) {
2458 		pr_warn("unexpected error skipping mods/typedefs for id [%u]\n",
2459 			id);
2460 		return -EINVAL;
2461 	}
2462 
2463 	switch (btf_kind(t)) {
2464 	case BTF_KIND_INT:
2465 	case BTF_KIND_FLOAT:
2466 	case BTF_KIND_PTR:
2467 	case BTF_KIND_ENUM:
2468 	case BTF_KIND_ENUM64:
2469 		if (data + bits_offset / 8 + size > d->typed_dump->data_end)
2470 			return -E2BIG;
2471 		break;
2472 	default:
2473 		break;
2474 	}
2475 	return (int)size;
2476 }
2477 
2478 static int btf_dump_type_data_check_zero(struct btf_dump *d,
2479 					 const struct btf_type *t,
2480 					 __u32 id,
2481 					 const void *data,
2482 					 __u8 bits_offset,
2483 					 __u8 bit_sz)
2484 {
2485 	__s64 value;
2486 	int i, err;
2487 
2488 	/* toplevel exceptions; we show zero values if
2489 	 * - we ask for them (emit_zeros)
2490 	 * - if we are at top-level so we see "struct empty { }"
2491 	 * - or if we are an array member and the array is non-empty and
2492 	 *   not a char array; we don't want to be in a situation where we
2493 	 *   have an integer array 0, 1, 0, 1 and only show non-zero values.
2494 	 *   If the array contains zeroes only, or is a char array starting
2495 	 *   with a '\0', the array-level check_zero() will prevent showing it;
2496 	 *   we are concerned with determining zero value at the array member
2497 	 *   level here.
2498 	 */
2499 	if (d->typed_dump->emit_zeroes || d->typed_dump->depth == 0 ||
2500 	    (d->typed_dump->is_array_member &&
2501 	     !d->typed_dump->is_array_char))
2502 		return 0;
2503 
2504 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2505 
2506 	switch (btf_kind(t)) {
2507 	case BTF_KIND_INT:
2508 		if (bit_sz)
2509 			return btf_dump_bitfield_check_zero(d, t, data, bits_offset, bit_sz);
2510 		return btf_dump_base_type_check_zero(d, t, id, data);
2511 	case BTF_KIND_FLOAT:
2512 	case BTF_KIND_PTR:
2513 		return btf_dump_base_type_check_zero(d, t, id, data);
2514 	case BTF_KIND_ARRAY: {
2515 		const struct btf_array *array = btf_array(t);
2516 		const struct btf_type *elem_type;
2517 		__u32 elem_type_id, elem_size;
2518 		bool ischar;
2519 
2520 		elem_type_id = array->type;
2521 		elem_size = btf__resolve_size(d->btf, elem_type_id);
2522 		elem_type = skip_mods_and_typedefs(d->btf, elem_type_id, NULL);
2523 
2524 		ischar = btf_is_int(elem_type) && elem_size == 1;
2525 
2526 		/* check all elements; if _any_ element is nonzero, all
2527 		 * of array is displayed.  We make an exception however
2528 		 * for char arrays where the first element is 0; these
2529 		 * are considered zeroed also, even if later elements are
2530 		 * non-zero because the string is terminated.
2531 		 */
2532 		for (i = 0; i < array->nelems; i++) {
2533 			if (i == 0 && ischar && *(char *)data == 0)
2534 				return -ENODATA;
2535 			err = btf_dump_type_data_check_zero(d, elem_type,
2536 							    elem_type_id,
2537 							    data +
2538 							    (i * elem_size),
2539 							    bits_offset, 0);
2540 			if (err != -ENODATA)
2541 				return err;
2542 		}
2543 		return -ENODATA;
2544 	}
2545 	case BTF_KIND_STRUCT:
2546 	case BTF_KIND_UNION: {
2547 		const struct btf_member *m = btf_members(t);
2548 		__u32 n = btf_vlen(t);
2549 
2550 		/* if any struct/union member is non-zero, the struct/union
2551 		 * is considered non-zero and dumped.
2552 		 */
2553 		for (i = 0; i < n; i++, m++) {
2554 			const struct btf_type *mtype;
2555 			__u32 moffset;
2556 
2557 			mtype = btf__type_by_id(d->btf, m->type);
2558 			moffset = btf_member_bit_offset(t, i);
2559 
2560 			/* btf_int_bits() does not store member bitfield size;
2561 			 * bitfield size needs to be stored here so int display
2562 			 * of member can retrieve it.
2563 			 */
2564 			bit_sz = btf_member_bitfield_size(t, i);
2565 			err = btf_dump_type_data_check_zero(d, mtype, m->type, data + moffset / 8,
2566 							    moffset % 8, bit_sz);
2567 			if (err != ENODATA)
2568 				return err;
2569 		}
2570 		return -ENODATA;
2571 	}
2572 	case BTF_KIND_ENUM:
2573 	case BTF_KIND_ENUM64:
2574 		err = btf_dump_get_enum_value(d, t, data, id, &value);
2575 		if (err)
2576 			return err;
2577 		if (value == 0)
2578 			return -ENODATA;
2579 		return 0;
2580 	default:
2581 		return 0;
2582 	}
2583 }
2584 
2585 /* returns size of data dumped, or error. */
2586 static int btf_dump_dump_type_data(struct btf_dump *d,
2587 				   const char *fname,
2588 				   const struct btf_type *t,
2589 				   __u32 id,
2590 				   const void *data,
2591 				   __u8 bits_offset,
2592 				   __u8 bit_sz)
2593 {
2594 	int size, err = 0;
2595 
2596 	size = btf_dump_type_data_check_overflow(d, t, id, data, bits_offset, bit_sz);
2597 	if (size < 0)
2598 		return size;
2599 	err = btf_dump_type_data_check_zero(d, t, id, data, bits_offset, bit_sz);
2600 	if (err) {
2601 		/* zeroed data is expected and not an error, so simply skip
2602 		 * dumping such data.  Record other errors however.
2603 		 */
2604 		if (err == -ENODATA)
2605 			return size;
2606 		return err;
2607 	}
2608 	btf_dump_data_pfx(d);
2609 
2610 	if (!d->typed_dump->skip_names) {
2611 		if (fname && strlen(fname) > 0)
2612 			btf_dump_printf(d, ".%s = ", fname);
2613 		btf_dump_emit_type_cast(d, id, true);
2614 	}
2615 
2616 	t = skip_mods_and_typedefs(d->btf, id, NULL);
2617 
2618 	switch (btf_kind(t)) {
2619 	case BTF_KIND_UNKN:
2620 	case BTF_KIND_FWD:
2621 	case BTF_KIND_FUNC:
2622 	case BTF_KIND_FUNC_PROTO:
2623 	case BTF_KIND_DECL_TAG:
2624 	case BTF_KIND_LOC_PARAM:
2625 	case BTF_KIND_LOC_PROTO:
2626 	case BTF_KIND_LOCSEC:
2627 		err = btf_dump_unsupported_data(d, t, id);
2628 		break;
2629 	case BTF_KIND_INT:
2630 		if (bit_sz)
2631 			err = btf_dump_bitfield_data(d, t, data, bits_offset, bit_sz);
2632 		else
2633 			err = btf_dump_int_data(d, t, id, data, bits_offset);
2634 		break;
2635 	case BTF_KIND_FLOAT:
2636 		err = btf_dump_float_data(d, t, id, data);
2637 		break;
2638 	case BTF_KIND_PTR:
2639 		err = btf_dump_ptr_data(d, t, id, data);
2640 		break;
2641 	case BTF_KIND_ARRAY:
2642 		err = btf_dump_array_data(d, t, id, data);
2643 		break;
2644 	case BTF_KIND_STRUCT:
2645 	case BTF_KIND_UNION:
2646 		err = btf_dump_struct_data(d, t, id, data);
2647 		break;
2648 	case BTF_KIND_ENUM:
2649 	case BTF_KIND_ENUM64:
2650 		/* handle bitfield and int enum values */
2651 		if (bit_sz) {
2652 			__u64 print_num;
2653 			__s64 enum_val;
2654 
2655 			err = btf_dump_get_bitfield_value(d, t, data, bits_offset, bit_sz,
2656 							  &print_num);
2657 			if (err)
2658 				break;
2659 			enum_val = (__s64)print_num;
2660 			err = btf_dump_enum_data(d, t, id, &enum_val);
2661 		} else
2662 			err = btf_dump_enum_data(d, t, id, data);
2663 		break;
2664 	case BTF_KIND_VAR:
2665 		err = btf_dump_var_data(d, t, id, data);
2666 		break;
2667 	case BTF_KIND_DATASEC:
2668 		err = btf_dump_datasec_data(d, t, id, data);
2669 		break;
2670 	default:
2671 		pr_warn("unexpected kind [%u] for id [%u]\n",
2672 			BTF_INFO_KIND(t->info), id);
2673 		return -EINVAL;
2674 	}
2675 	if (err < 0)
2676 		return err;
2677 	return size;
2678 }
2679 
2680 int btf_dump__dump_type_data(struct btf_dump *d, __u32 id,
2681 			     const void *data, size_t data_sz,
2682 			     const struct btf_dump_type_data_opts *opts)
2683 {
2684 	struct btf_dump_data typed_dump = {};
2685 	const struct btf_type *t;
2686 	int ret;
2687 
2688 	if (!OPTS_VALID(opts, btf_dump_type_data_opts))
2689 		return libbpf_err(-EINVAL);
2690 
2691 	t = btf__type_by_id(d->btf, id);
2692 	if (!t)
2693 		return libbpf_err(-ENOENT);
2694 
2695 	d->typed_dump = &typed_dump;
2696 	d->typed_dump->data_end = data + data_sz;
2697 	d->typed_dump->indent_lvl = OPTS_GET(opts, indent_level, 0);
2698 
2699 	/* default indent string is a tab */
2700 	if (!OPTS_GET(opts, indent_str, NULL))
2701 		d->typed_dump->indent_str[0] = '\t';
2702 	else
2703 		libbpf_strlcpy(d->typed_dump->indent_str, opts->indent_str,
2704 			       sizeof(d->typed_dump->indent_str));
2705 
2706 	d->typed_dump->compact = OPTS_GET(opts, compact, false);
2707 	d->typed_dump->skip_names = OPTS_GET(opts, skip_names, false);
2708 	d->typed_dump->emit_zeroes = OPTS_GET(opts, emit_zeroes, false);
2709 	d->typed_dump->emit_strings = OPTS_GET(opts, emit_strings, false);
2710 
2711 	ret = btf_dump_dump_type_data(d, NULL, t, id, data, 0, 0);
2712 
2713 	d->typed_dump = NULL;
2714 
2715 	return libbpf_err(ret);
2716 }
2717