Linux Audio

Check our new training course

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