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