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