Linux Audio

Check our new training course

Loading...
v5.14.15
   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 <linux/kernel.h>
  17#include "btf.h"
  18#include "hashmap.h"
  19#include "libbpf.h"
  20#include "libbpf_internal.h"
  21
 
 
 
  22static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
  23static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
  24
  25static const char *pfx(int lvl)
  26{
  27	return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
  28}
  29
  30enum btf_dump_type_order_state {
  31	NOT_ORDERED,
  32	ORDERING,
  33	ORDERED,
  34};
  35
  36enum btf_dump_type_emit_state {
  37	NOT_EMITTED,
  38	EMITTING,
  39	EMITTED,
  40};
  41
  42/* per-type auxiliary state */
  43struct btf_dump_type_aux_state {
  44	/* topological sorting state */
  45	enum btf_dump_type_order_state order_state: 2;
  46	/* emitting state used to determine the need for forward declaration */
  47	enum btf_dump_type_emit_state emit_state: 2;
  48	/* whether forward declaration was already emitted */
  49	__u8 fwd_emitted: 1;
  50	/* whether unique non-duplicate name was already assigned */
  51	__u8 name_resolved: 1;
  52	/* whether type is referenced from any other type */
  53	__u8 referenced: 1;
  54};
  55
  56struct btf_dump {
  57	const struct btf *btf;
  58	const struct btf_ext *btf_ext;
  59	btf_dump_printf_fn_t printf_fn;
  60	struct btf_dump_opts opts;
  61	int ptr_sz;
  62	bool strip_mods;
  63	int last_id;
  64
  65	/* per-type auxiliary state */
  66	struct btf_dump_type_aux_state *type_states;
  67	size_t type_states_cap;
  68	/* per-type optional cached unique name, must be freed, if present */
  69	const char **cached_names;
  70	size_t cached_names_cap;
  71
  72	/* topo-sorted list of dependent type definitions */
  73	__u32 *emit_queue;
  74	int emit_queue_cap;
  75	int emit_queue_cnt;
  76
  77	/*
  78	 * stack of type declarations (e.g., chain of modifiers, arrays,
  79	 * funcs, etc)
  80	 */
  81	__u32 *decl_stack;
  82	int decl_stack_cap;
  83	int decl_stack_cnt;
  84
  85	/* maps struct/union/enum name to a number of name occurrences */
  86	struct hashmap *type_names;
  87	/*
  88	 * maps typedef identifiers and enum value names to a number of such
  89	 * name occurrences
  90	 */
  91	struct hashmap *ident_names;
  92};
  93
  94static size_t str_hash_fn(const void *key, void *ctx)
  95{
  96	return str_hash(key);
 
 
 
 
 
 
 
  97}
  98
  99static bool str_equal_fn(const void *a, const void *b, void *ctx)
 100{
 101	return strcmp(a, b) == 0;
 102}
 103
 104static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
 105{
 106	return btf__name_by_offset(d->btf, name_off);
 107}
 108
 109static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
 110{
 111	va_list args;
 112
 113	va_start(args, fmt);
 114	d->printf_fn(d->opts.ctx, fmt, args);
 115	va_end(args);
 116}
 117
 118static int btf_dump_mark_referenced(struct btf_dump *d);
 119static int btf_dump_resize(struct btf_dump *d);
 120
 121struct btf_dump *btf_dump__new(const struct btf *btf,
 122			       const struct btf_ext *btf_ext,
 123			       const struct btf_dump_opts *opts,
 124			       btf_dump_printf_fn_t printf_fn)
 125{
 126	struct btf_dump *d;
 127	int err;
 128
 129	d = calloc(1, sizeof(struct btf_dump));
 130	if (!d)
 131		return libbpf_err_ptr(-ENOMEM);
 132
 133	d->btf = btf;
 134	d->btf_ext = btf_ext;
 135	d->printf_fn = printf_fn;
 136	d->opts.ctx = opts ? opts->ctx : NULL;
 137	d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
 138
 139	d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
 140	if (IS_ERR(d->type_names)) {
 141		err = PTR_ERR(d->type_names);
 142		d->type_names = NULL;
 143		goto err;
 144	}
 145	d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
 146	if (IS_ERR(d->ident_names)) {
 147		err = PTR_ERR(d->ident_names);
 148		d->ident_names = NULL;
 149		goto err;
 150	}
 151
 152	err = btf_dump_resize(d);
 153	if (err)
 
 
 
 
 
 
 
 154		goto err;
 155
 156	return d;
 157err:
 158	btf_dump__free(d);
 159	return libbpf_err_ptr(err);
 160}
 161
 162static int btf_dump_resize(struct btf_dump *d)
 163{
 164	int err, last_id = btf__get_nr_types(d->btf);
 165
 166	if (last_id <= d->last_id)
 167		return 0;
 168
 169	if (libbpf_ensure_mem((void **)&d->type_states, &d->type_states_cap,
 170			      sizeof(*d->type_states), last_id + 1))
 171		return -ENOMEM;
 172	if (libbpf_ensure_mem((void **)&d->cached_names, &d->cached_names_cap,
 173			      sizeof(*d->cached_names), last_id + 1))
 174		return -ENOMEM;
 175
 176	if (d->last_id == 0) {
 177		/* VOID is special */
 178		d->type_states[0].order_state = ORDERED;
 179		d->type_states[0].emit_state = EMITTED;
 180	}
 181
 
 
 
 
 182	/* eagerly determine referenced types for anon enums */
 183	err = btf_dump_mark_referenced(d);
 184	if (err)
 185		return err;
 186
 187	d->last_id = last_id;
 188	return 0;
 
 
 189}
 190
 191void btf_dump__free(struct btf_dump *d)
 192{
 193	int i;
 194
 195	if (IS_ERR_OR_NULL(d))
 196		return;
 197
 198	free(d->type_states);
 199	if (d->cached_names) {
 200		/* any set cached name is owned by us and should be freed */
 201		for (i = 0; i <= d->last_id; i++) {
 202			if (d->cached_names[i])
 203				free((void *)d->cached_names[i]);
 204		}
 205	}
 206	free(d->cached_names);
 207	free(d->emit_queue);
 208	free(d->decl_stack);
 209	hashmap__free(d->type_names);
 210	hashmap__free(d->ident_names);
 211
 212	free(d);
 213}
 214
 215static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
 216static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
 217
 218/*
 219 * Dump BTF type in a compilable C syntax, including all the necessary
 220 * dependent types, necessary for compilation. If some of the dependent types
 221 * were already emitted as part of previous btf_dump__dump_type() invocation
 222 * for another type, they won't be emitted again. This API allows callers to
 223 * filter out BTF types according to user-defined criterias and emitted only
 224 * minimal subset of types, necessary to compile everything. Full struct/union
 225 * definitions will still be emitted, even if the only usage is through
 226 * pointer and could be satisfied with just a forward declaration.
 227 *
 228 * Dumping is done in two high-level passes:
 229 *   1. Topologically sort type definitions to satisfy C rules of compilation.
 230 *   2. Emit type definitions in C syntax.
 231 *
 232 * Returns 0 on success; <0, otherwise.
 233 */
 234int btf_dump__dump_type(struct btf_dump *d, __u32 id)
 235{
 236	int err, i;
 237
 238	if (id > btf__get_nr_types(d->btf))
 239		return libbpf_err(-EINVAL);
 240
 241	err = btf_dump_resize(d);
 242	if (err)
 243		return libbpf_err(err);
 244
 245	d->emit_queue_cnt = 0;
 246	err = btf_dump_order_type(d, id, false);
 247	if (err < 0)
 248		return libbpf_err(err);
 249
 250	for (i = 0; i < d->emit_queue_cnt; i++)
 251		btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
 252
 253	return 0;
 254}
 255
 256/*
 257 * Mark all types that are referenced from any other type. This is used to
 258 * determine top-level anonymous enums that need to be emitted as an
 259 * independent type declarations.
 260 * Anonymous enums come in two flavors: either embedded in a struct's field
 261 * definition, in which case they have to be declared inline as part of field
 262 * type declaration; or as a top-level anonymous enum, typically used for
 263 * declaring global constants. It's impossible to distinguish between two
 264 * without knowning whether given enum type was referenced from other type:
 265 * top-level anonymous enum won't be referenced by anything, while embedded
 266 * one will.
 267 */
 268static int btf_dump_mark_referenced(struct btf_dump *d)
 269{
 270	int i, j, n = btf__get_nr_types(d->btf);
 271	const struct btf_type *t;
 272	__u16 vlen;
 273
 274	for (i = d->last_id + 1; i <= n; i++) {
 275		t = btf__type_by_id(d->btf, i);
 276		vlen = btf_vlen(t);
 277
 278		switch (btf_kind(t)) {
 279		case BTF_KIND_INT:
 280		case BTF_KIND_ENUM:
 281		case BTF_KIND_FWD:
 282		case BTF_KIND_FLOAT:
 283			break;
 284
 285		case BTF_KIND_VOLATILE:
 286		case BTF_KIND_CONST:
 287		case BTF_KIND_RESTRICT:
 288		case BTF_KIND_PTR:
 289		case BTF_KIND_TYPEDEF:
 290		case BTF_KIND_FUNC:
 291		case BTF_KIND_VAR:
 292			d->type_states[t->type].referenced = 1;
 293			break;
 294
 295		case BTF_KIND_ARRAY: {
 296			const struct btf_array *a = btf_array(t);
 297
 298			d->type_states[a->index_type].referenced = 1;
 299			d->type_states[a->type].referenced = 1;
 300			break;
 301		}
 302		case BTF_KIND_STRUCT:
 303		case BTF_KIND_UNION: {
 304			const struct btf_member *m = btf_members(t);
 305
 306			for (j = 0; j < vlen; j++, m++)
 307				d->type_states[m->type].referenced = 1;
 308			break;
 309		}
 310		case BTF_KIND_FUNC_PROTO: {
 311			const struct btf_param *p = btf_params(t);
 312
 313			for (j = 0; j < vlen; j++, p++)
 314				d->type_states[p->type].referenced = 1;
 315			break;
 316		}
 317		case BTF_KIND_DATASEC: {
 318			const struct btf_var_secinfo *v = btf_var_secinfos(t);
 319
 320			for (j = 0; j < vlen; j++, v++)
 321				d->type_states[v->type].referenced = 1;
 322			break;
 323		}
 324		default:
 325			return -EINVAL;
 326		}
 327	}
 328	return 0;
 329}
 330
 331static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
 332{
 333	__u32 *new_queue;
 334	size_t new_cap;
 335
 336	if (d->emit_queue_cnt >= d->emit_queue_cap) {
 337		new_cap = max(16, d->emit_queue_cap * 3 / 2);
 338		new_queue = libbpf_reallocarray(d->emit_queue, new_cap, sizeof(new_queue[0]));
 
 339		if (!new_queue)
 340			return -ENOMEM;
 341		d->emit_queue = new_queue;
 342		d->emit_queue_cap = new_cap;
 343	}
 344
 345	d->emit_queue[d->emit_queue_cnt++] = id;
 346	return 0;
 347}
 348
 349/*
 350 * Determine order of emitting dependent types and specified type to satisfy
 351 * C compilation rules.  This is done through topological sorting with an
 352 * additional complication which comes from C rules. The main idea for C is
 353 * that if some type is "embedded" into a struct/union, it's size needs to be
 354 * known at the time of definition of containing type. E.g., for:
 355 *
 356 *	struct A {};
 357 *	struct B { struct A x; }
 358 *
 359 * struct A *HAS* to be defined before struct B, because it's "embedded",
 360 * i.e., it is part of struct B layout. But in the following case:
 361 *
 362 *	struct A;
 363 *	struct B { struct A *x; }
 364 *	struct A {};
 365 *
 366 * it's enough to just have a forward declaration of struct A at the time of
 367 * struct B definition, as struct B has a pointer to struct A, so the size of
 368 * field x is known without knowing struct A size: it's sizeof(void *).
 369 *
 370 * Unfortunately, there are some trickier cases we need to handle, e.g.:
 371 *
 372 *	struct A {}; // if this was forward-declaration: compilation error
 373 *	struct B {
 374 *		struct { // anonymous struct
 375 *			struct A y;
 376 *		} *x;
 377 *	};
 378 *
 379 * In this case, struct B's field x is a pointer, so it's size is known
 380 * regardless of the size of (anonymous) struct it points to. But because this
 381 * struct is anonymous and thus defined inline inside struct B, *and* it
 382 * embeds struct A, compiler requires full definition of struct A to be known
 383 * before struct B can be defined. This creates a transitive dependency
 384 * between struct A and struct B. If struct A was forward-declared before
 385 * struct B definition and fully defined after struct B definition, that would
 386 * trigger compilation error.
 387 *
 388 * All this means that while we are doing topological sorting on BTF type
 389 * graph, we need to determine relationships between different types (graph
 390 * nodes):
 391 *   - weak link (relationship) between X and Y, if Y *CAN* be
 392 *   forward-declared at the point of X definition;
 393 *   - strong link, if Y *HAS* to be fully-defined before X can be defined.
 394 *
 395 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
 396 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
 397 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
 398 * Weak/strong relationship is determined recursively during DFS traversal and
 399 * is returned as a result from btf_dump_order_type().
 400 *
 401 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
 402 * but it is not guaranteeing that no extraneous forward declarations will be
 403 * emitted.
 404 *
 405 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
 406 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
 407 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
 408 * entire graph path, so depending where from one came to that BTF type, it
 409 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
 410 * once they are processed, there is no need to do it again, so they are
 411 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
 412 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
 413 * in any case, once those are processed, no need to do it again, as the
 414 * result won't change.
 415 *
 416 * Returns:
 417 *   - 1, if type is part of strong link (so there is strong topological
 418 *   ordering requirements);
 419 *   - 0, if type is part of weak link (so can be satisfied through forward
 420 *   declaration);
 421 *   - <0, on error (e.g., unsatisfiable type loop detected).
 422 */
 423static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
 424{
 425	/*
 426	 * Order state is used to detect strong link cycles, but only for BTF
 427	 * kinds that are or could be an independent definition (i.e.,
 428	 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
 429	 * func_protos, modifiers are just means to get to these definitions.
 430	 * Int/void don't need definitions, they are assumed to be always
 431	 * properly defined.  We also ignore datasec, var, and funcs for now.
 432	 * So for all non-defining kinds, we never even set ordering state,
 433	 * for defining kinds we set ORDERING and subsequently ORDERED if it
 434	 * forms a strong link.
 435	 */
 436	struct btf_dump_type_aux_state *tstate = &d->type_states[id];
 437	const struct btf_type *t;
 438	__u16 vlen;
 439	int err, i;
 440
 441	/* return true, letting typedefs know that it's ok to be emitted */
 442	if (tstate->order_state == ORDERED)
 443		return 1;
 444
 445	t = btf__type_by_id(d->btf, id);
 446
 447	if (tstate->order_state == ORDERING) {
 448		/* type loop, but resolvable through fwd declaration */
 449		if (btf_is_composite(t) && through_ptr && t->name_off != 0)
 450			return 0;
 451		pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
 452		return -ELOOP;
 453	}
 454
 455	switch (btf_kind(t)) {
 456	case BTF_KIND_INT:
 457	case BTF_KIND_FLOAT:
 458		tstate->order_state = ORDERED;
 459		return 0;
 460
 461	case BTF_KIND_PTR:
 462		err = btf_dump_order_type(d, t->type, true);
 463		tstate->order_state = ORDERED;
 464		return err;
 465
 466	case BTF_KIND_ARRAY:
 467		return btf_dump_order_type(d, btf_array(t)->type, false);
 468
 469	case BTF_KIND_STRUCT:
 470	case BTF_KIND_UNION: {
 471		const struct btf_member *m = btf_members(t);
 472		/*
 473		 * struct/union is part of strong link, only if it's embedded
 474		 * (so no ptr in a path) or it's anonymous (so has to be
 475		 * defined inline, even if declared through ptr)
 476		 */
 477		if (through_ptr && t->name_off != 0)
 478			return 0;
 479
 480		tstate->order_state = ORDERING;
 481
 482		vlen = btf_vlen(t);
 483		for (i = 0; i < vlen; i++, m++) {
 484			err = btf_dump_order_type(d, m->type, false);
 485			if (err < 0)
 486				return err;
 487		}
 488
 489		if (t->name_off != 0) {
 490			err = btf_dump_add_emit_queue_id(d, id);
 491			if (err < 0)
 492				return err;
 493		}
 494
 495		tstate->order_state = ORDERED;
 496		return 1;
 497	}
 498	case BTF_KIND_ENUM:
 499	case BTF_KIND_FWD:
 500		/*
 501		 * non-anonymous or non-referenced enums are top-level
 502		 * declarations and should be emitted. Same logic can be
 503		 * applied to FWDs, it won't hurt anyways.
 504		 */
 505		if (t->name_off != 0 || !tstate->referenced) {
 506			err = btf_dump_add_emit_queue_id(d, id);
 507			if (err)
 508				return err;
 509		}
 510		tstate->order_state = ORDERED;
 511		return 1;
 512
 513	case BTF_KIND_TYPEDEF: {
 514		int is_strong;
 515
 516		is_strong = btf_dump_order_type(d, t->type, through_ptr);
 517		if (is_strong < 0)
 518			return is_strong;
 519
 520		/* typedef is similar to struct/union w.r.t. fwd-decls */
 521		if (through_ptr && !is_strong)
 522			return 0;
 523
 524		/* typedef is always a named definition */
 525		err = btf_dump_add_emit_queue_id(d, id);
 526		if (err)
 527			return err;
 528
 529		d->type_states[id].order_state = ORDERED;
 530		return 1;
 531	}
 532	case BTF_KIND_VOLATILE:
 533	case BTF_KIND_CONST:
 534	case BTF_KIND_RESTRICT:
 535		return btf_dump_order_type(d, t->type, through_ptr);
 536
 537	case BTF_KIND_FUNC_PROTO: {
 538		const struct btf_param *p = btf_params(t);
 539		bool is_strong;
 540
 541		err = btf_dump_order_type(d, t->type, through_ptr);
 542		if (err < 0)
 543			return err;
 544		is_strong = err > 0;
 545
 546		vlen = btf_vlen(t);
 547		for (i = 0; i < vlen; i++, p++) {
 548			err = btf_dump_order_type(d, p->type, through_ptr);
 549			if (err < 0)
 550				return err;
 551			if (err > 0)
 552				is_strong = true;
 553		}
 554		return is_strong;
 555	}
 556	case BTF_KIND_FUNC:
 557	case BTF_KIND_VAR:
 558	case BTF_KIND_DATASEC:
 559		d->type_states[id].order_state = ORDERED;
 560		return 0;
 561
 562	default:
 563		return -EINVAL;
 564	}
 565}
 566
 567static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
 568					  const struct btf_type *t);
 569
 570static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
 571				     const struct btf_type *t);
 572static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
 573				     const struct btf_type *t, int lvl);
 574
 575static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
 576				   const struct btf_type *t);
 577static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
 578				   const struct btf_type *t, int lvl);
 579
 580static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
 581				  const struct btf_type *t);
 582
 583static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
 584				      const struct btf_type *t, int lvl);
 585
 586/* a local view into a shared stack */
 587struct id_stack {
 588	const __u32 *ids;
 589	int cnt;
 590};
 591
 592static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
 593				    const char *fname, int lvl);
 594static void btf_dump_emit_type_chain(struct btf_dump *d,
 595				     struct id_stack *decl_stack,
 596				     const char *fname, int lvl);
 597
 598static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
 599static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
 600static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
 601				 const char *orig_name);
 602
 603static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
 604{
 605	const struct btf_type *t = btf__type_by_id(d->btf, id);
 606
 607	/* __builtin_va_list is a compiler built-in, which causes compilation
 608	 * errors, when compiling w/ different compiler, then used to compile
 609	 * original code (e.g., GCC to compile kernel, Clang to use generated
 610	 * C header from BTF). As it is built-in, it should be already defined
 611	 * properly internally in compiler.
 612	 */
 613	if (t->name_off == 0)
 614		return false;
 615	return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
 616}
 617
 618/*
 619 * Emit C-syntax definitions of types from chains of BTF types.
 620 *
 621 * High-level handling of determining necessary forward declarations are handled
 622 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
 623 * declarations/definitions in C syntax  are handled by a combo of
 624 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
 625 * corresponding btf_dump_emit_*_{def,fwd}() functions.
 626 *
 627 * We also keep track of "containing struct/union type ID" to determine when
 628 * we reference it from inside and thus can avoid emitting unnecessary forward
 629 * declaration.
 630 *
 631 * This algorithm is designed in such a way, that even if some error occurs
 632 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
 633 * that doesn't comply to C rules completely), algorithm will try to proceed
 634 * and produce as much meaningful output as possible.
 635 */
 636static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
 637{
 638	struct btf_dump_type_aux_state *tstate = &d->type_states[id];
 639	bool top_level_def = cont_id == 0;
 640	const struct btf_type *t;
 641	__u16 kind;
 642
 643	if (tstate->emit_state == EMITTED)
 644		return;
 645
 646	t = btf__type_by_id(d->btf, id);
 647	kind = btf_kind(t);
 648
 649	if (tstate->emit_state == EMITTING) {
 650		if (tstate->fwd_emitted)
 651			return;
 652
 653		switch (kind) {
 654		case BTF_KIND_STRUCT:
 655		case BTF_KIND_UNION:
 656			/*
 657			 * if we are referencing a struct/union that we are
 658			 * part of - then no need for fwd declaration
 659			 */
 660			if (id == cont_id)
 661				return;
 662			if (t->name_off == 0) {
 663				pr_warn("anonymous struct/union loop, id:[%u]\n",
 664					id);
 665				return;
 666			}
 667			btf_dump_emit_struct_fwd(d, id, t);
 668			btf_dump_printf(d, ";\n\n");
 669			tstate->fwd_emitted = 1;
 670			break;
 671		case BTF_KIND_TYPEDEF:
 672			/*
 673			 * for typedef fwd_emitted means typedef definition
 674			 * was emitted, but it can be used only for "weak"
 675			 * references through pointer only, not for embedding
 676			 */
 677			if (!btf_dump_is_blacklisted(d, id)) {
 678				btf_dump_emit_typedef_def(d, id, t, 0);
 679				btf_dump_printf(d, ";\n\n");
 680			}
 681			tstate->fwd_emitted = 1;
 682			break;
 683		default:
 684			break;
 685		}
 686
 687		return;
 688	}
 689
 690	switch (kind) {
 691	case BTF_KIND_INT:
 692		/* Emit type alias definitions if necessary */
 693		btf_dump_emit_missing_aliases(d, id, t);
 694
 695		tstate->emit_state = EMITTED;
 696		break;
 697	case BTF_KIND_ENUM:
 698		if (top_level_def) {
 699			btf_dump_emit_enum_def(d, id, t, 0);
 700			btf_dump_printf(d, ";\n\n");
 701		}
 702		tstate->emit_state = EMITTED;
 703		break;
 704	case BTF_KIND_PTR:
 705	case BTF_KIND_VOLATILE:
 706	case BTF_KIND_CONST:
 707	case BTF_KIND_RESTRICT:
 708		btf_dump_emit_type(d, t->type, cont_id);
 709		break;
 710	case BTF_KIND_ARRAY:
 711		btf_dump_emit_type(d, btf_array(t)->type, cont_id);
 712		break;
 713	case BTF_KIND_FWD:
 714		btf_dump_emit_fwd_def(d, id, t);
 715		btf_dump_printf(d, ";\n\n");
 716		tstate->emit_state = EMITTED;
 717		break;
 718	case BTF_KIND_TYPEDEF:
 719		tstate->emit_state = EMITTING;
 720		btf_dump_emit_type(d, t->type, id);
 721		/*
 722		 * typedef can server as both definition and forward
 723		 * declaration; at this stage someone depends on
 724		 * typedef as a forward declaration (refers to it
 725		 * through pointer), so unless we already did it,
 726		 * emit typedef as a forward declaration
 727		 */
 728		if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
 729			btf_dump_emit_typedef_def(d, id, t, 0);
 730			btf_dump_printf(d, ";\n\n");
 731		}
 732		tstate->emit_state = EMITTED;
 733		break;
 734	case BTF_KIND_STRUCT:
 735	case BTF_KIND_UNION:
 736		tstate->emit_state = EMITTING;
 737		/* if it's a top-level struct/union definition or struct/union
 738		 * is anonymous, then in C we'll be emitting all fields and
 739		 * their types (as opposed to just `struct X`), so we need to
 740		 * make sure that all types, referenced from struct/union
 741		 * members have necessary forward-declarations, where
 742		 * applicable
 743		 */
 744		if (top_level_def || t->name_off == 0) {
 745			const struct btf_member *m = btf_members(t);
 746			__u16 vlen = btf_vlen(t);
 747			int i, new_cont_id;
 748
 749			new_cont_id = t->name_off == 0 ? cont_id : id;
 750			for (i = 0; i < vlen; i++, m++)
 751				btf_dump_emit_type(d, m->type, new_cont_id);
 752		} else if (!tstate->fwd_emitted && id != cont_id) {
 753			btf_dump_emit_struct_fwd(d, id, t);
 754			btf_dump_printf(d, ";\n\n");
 755			tstate->fwd_emitted = 1;
 756		}
 757
 758		if (top_level_def) {
 759			btf_dump_emit_struct_def(d, id, t, 0);
 760			btf_dump_printf(d, ";\n\n");
 761			tstate->emit_state = EMITTED;
 762		} else {
 763			tstate->emit_state = NOT_EMITTED;
 764		}
 765		break;
 766	case BTF_KIND_FUNC_PROTO: {
 767		const struct btf_param *p = btf_params(t);
 768		__u16 vlen = btf_vlen(t);
 769		int i;
 770
 771		btf_dump_emit_type(d, t->type, cont_id);
 772		for (i = 0; i < vlen; i++, p++)
 773			btf_dump_emit_type(d, p->type, cont_id);
 774
 775		break;
 776	}
 777	default:
 778		break;
 779	}
 780}
 781
 782static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
 783				 const struct btf_type *t)
 784{
 785	const struct btf_member *m;
 786	int align, i, bit_sz;
 787	__u16 vlen;
 788
 789	align = btf__align_of(btf, id);
 790	/* size of a non-packed struct has to be a multiple of its alignment*/
 791	if (align && t->size % align)
 792		return true;
 793
 794	m = btf_members(t);
 795	vlen = btf_vlen(t);
 796	/* all non-bitfield fields have to be naturally aligned */
 797	for (i = 0; i < vlen; i++, m++) {
 798		align = btf__align_of(btf, m->type);
 799		bit_sz = btf_member_bitfield_size(t, i);
 800		if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
 801			return true;
 802	}
 803
 804	/*
 805	 * if original struct was marked as packed, but its layout is
 806	 * naturally aligned, we'll detect that it's not packed
 807	 */
 808	return false;
 809}
 810
 811static int chip_away_bits(int total, int at_most)
 812{
 813	return total % at_most ? : at_most;
 814}
 815
 816static void btf_dump_emit_bit_padding(const struct btf_dump *d,
 817				      int cur_off, int m_off, int m_bit_sz,
 818				      int align, int lvl)
 819{
 820	int off_diff = m_off - cur_off;
 821	int ptr_bits = d->ptr_sz * 8;
 822
 823	if (off_diff <= 0)
 824		/* no gap */
 825		return;
 826	if (m_bit_sz == 0 && off_diff < align * 8)
 827		/* natural padding will take care of a gap */
 828		return;
 829
 830	while (off_diff > 0) {
 831		const char *pad_type;
 832		int pad_bits;
 833
 834		if (ptr_bits > 32 && off_diff > 32) {
 835			pad_type = "long";
 836			pad_bits = chip_away_bits(off_diff, ptr_bits);
 837		} else if (off_diff > 16) {
 838			pad_type = "int";
 839			pad_bits = chip_away_bits(off_diff, 32);
 840		} else if (off_diff > 8) {
 841			pad_type = "short";
 842			pad_bits = chip_away_bits(off_diff, 16);
 843		} else {
 844			pad_type = "char";
 845			pad_bits = chip_away_bits(off_diff, 8);
 846		}
 847		btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
 848		off_diff -= pad_bits;
 849	}
 850}
 851
 852static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
 853				     const struct btf_type *t)
 854{
 855	btf_dump_printf(d, "%s %s",
 856			btf_is_struct(t) ? "struct" : "union",
 857			btf_dump_type_name(d, id));
 858}
 859
 860static void btf_dump_emit_struct_def(struct btf_dump *d,
 861				     __u32 id,
 862				     const struct btf_type *t,
 863				     int lvl)
 864{
 865	const struct btf_member *m = btf_members(t);
 866	bool is_struct = btf_is_struct(t);
 867	int align, i, packed, off = 0;
 868	__u16 vlen = btf_vlen(t);
 869
 870	packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
 871
 872	btf_dump_printf(d, "%s%s%s {",
 873			is_struct ? "struct" : "union",
 874			t->name_off ? " " : "",
 875			btf_dump_type_name(d, id));
 876
 877	for (i = 0; i < vlen; i++, m++) {
 878		const char *fname;
 879		int m_off, m_sz;
 880
 881		fname = btf_name_of(d, m->name_off);
 882		m_sz = btf_member_bitfield_size(t, i);
 883		m_off = btf_member_bit_offset(t, i);
 884		align = packed ? 1 : btf__align_of(d->btf, m->type);
 885
 886		btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
 887		btf_dump_printf(d, "\n%s", pfx(lvl + 1));
 888		btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
 889
 890		if (m_sz) {
 891			btf_dump_printf(d, ": %d", m_sz);
 892			off = m_off + m_sz;
 893		} else {
 894			m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
 895			off = m_off + m_sz * 8;
 896		}
 897		btf_dump_printf(d, ";");
 898	}
 899
 900	/* pad at the end, if necessary */
 901	if (is_struct) {
 902		align = packed ? 1 : btf__align_of(d->btf, id);
 903		btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
 904					  lvl + 1);
 905	}
 906
 907	if (vlen)
 908		btf_dump_printf(d, "\n");
 909	btf_dump_printf(d, "%s}", pfx(lvl));
 910	if (packed)
 911		btf_dump_printf(d, " __attribute__((packed))");
 912}
 913
 914static const char *missing_base_types[][2] = {
 915	/*
 916	 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
 917	 * SIMD intrinsics. Alias them to standard base types.
 918	 */
 919	{ "__Poly8_t",		"unsigned char" },
 920	{ "__Poly16_t",		"unsigned short" },
 921	{ "__Poly64_t",		"unsigned long long" },
 922	{ "__Poly128_t",	"unsigned __int128" },
 923};
 924
 925static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
 926					  const struct btf_type *t)
 927{
 928	const char *name = btf_dump_type_name(d, id);
 929	int i;
 930
 931	for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
 932		if (strcmp(name, missing_base_types[i][0]) == 0) {
 933			btf_dump_printf(d, "typedef %s %s;\n\n",
 934					missing_base_types[i][1], name);
 935			break;
 936		}
 937	}
 938}
 939
 940static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
 941				   const struct btf_type *t)
 942{
 943	btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
 944}
 945
 946static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
 947				   const struct btf_type *t,
 948				   int lvl)
 949{
 950	const struct btf_enum *v = btf_enum(t);
 951	__u16 vlen = btf_vlen(t);
 952	const char *name;
 953	size_t dup_cnt;
 954	int i;
 955
 956	btf_dump_printf(d, "enum%s%s",
 957			t->name_off ? " " : "",
 958			btf_dump_type_name(d, id));
 959
 960	if (vlen) {
 961		btf_dump_printf(d, " {");
 962		for (i = 0; i < vlen; i++, v++) {
 963			name = btf_name_of(d, v->name_off);
 964			/* enumerators share namespace with typedef idents */
 965			dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
 966			if (dup_cnt > 1) {
 967				btf_dump_printf(d, "\n%s%s___%zu = %u,",
 968						pfx(lvl + 1), name, dup_cnt,
 969						(__u32)v->val);
 970			} else {
 971				btf_dump_printf(d, "\n%s%s = %u,",
 972						pfx(lvl + 1), name,
 973						(__u32)v->val);
 974			}
 975		}
 976		btf_dump_printf(d, "\n%s}", pfx(lvl));
 977	}
 978}
 979
 980static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
 981				  const struct btf_type *t)
 982{
 983	const char *name = btf_dump_type_name(d, id);
 984
 985	if (btf_kflag(t))
 986		btf_dump_printf(d, "union %s", name);
 987	else
 988		btf_dump_printf(d, "struct %s", name);
 989}
 990
 991static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
 992				     const struct btf_type *t, int lvl)
 993{
 994	const char *name = btf_dump_ident_name(d, id);
 995
 996	/*
 997	 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
 998	 * pointing to VOID. This generates warnings from btf_dump() and
 999	 * results in uncompilable header file, so we are fixing it up here
1000	 * with valid typedef into __builtin_va_list.
1001	 */
1002	if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
1003		btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
1004		return;
1005	}
1006
1007	btf_dump_printf(d, "typedef ");
1008	btf_dump_emit_type_decl(d, t->type, name, lvl);
1009}
1010
1011static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1012{
1013	__u32 *new_stack;
1014	size_t new_cap;
1015
1016	if (d->decl_stack_cnt >= d->decl_stack_cap) {
1017		new_cap = max(16, d->decl_stack_cap * 3 / 2);
1018		new_stack = libbpf_reallocarray(d->decl_stack, new_cap, sizeof(new_stack[0]));
 
1019		if (!new_stack)
1020			return -ENOMEM;
1021		d->decl_stack = new_stack;
1022		d->decl_stack_cap = new_cap;
1023	}
1024
1025	d->decl_stack[d->decl_stack_cnt++] = id;
1026
1027	return 0;
1028}
1029
1030/*
1031 * Emit type declaration (e.g., field type declaration in a struct or argument
1032 * declaration in function prototype) in correct C syntax.
1033 *
1034 * For most types it's trivial, but there are few quirky type declaration
1035 * cases worth mentioning:
1036 *   - function prototypes (especially nesting of function prototypes);
1037 *   - arrays;
1038 *   - const/volatile/restrict for pointers vs other types.
1039 *
1040 * For a good discussion of *PARSING* C syntax (as a human), see
1041 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1042 * Ch.3 "Unscrambling Declarations in C".
1043 *
1044 * It won't help with BTF to C conversion much, though, as it's an opposite
1045 * problem. So we came up with this algorithm in reverse to van der Linden's
1046 * parsing algorithm. It goes from structured BTF representation of type
1047 * declaration to a valid compilable C syntax.
1048 *
1049 * For instance, consider this C typedef:
1050 *	typedef const int * const * arr[10] arr_t;
1051 * It will be represented in BTF with this chain of BTF types:
1052 *	[typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1053 *
1054 * Notice how [const] modifier always goes before type it modifies in BTF type
1055 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1056 * the right of pointers, but to the left of other types. There are also other
1057 * quirks, like function pointers, arrays of them, functions returning other
1058 * functions, etc.
1059 *
1060 * We handle that by pushing all the types to a stack, until we hit "terminal"
1061 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1062 * top of a stack, modifiers are handled differently. Array/function pointers
1063 * have also wildly different syntax and how nesting of them are done. See
1064 * code for authoritative definition.
1065 *
1066 * To avoid allocating new stack for each independent chain of BTF types, we
1067 * share one bigger stack, with each chain working only on its own local view
1068 * of a stack frame. Some care is required to "pop" stack frames after
1069 * processing type declaration chain.
1070 */
1071int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1072			     const struct btf_dump_emit_type_decl_opts *opts)
1073{
1074	const char *fname;
1075	int lvl, err;
1076
1077	if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1078		return libbpf_err(-EINVAL);
1079
1080	err = btf_dump_resize(d);
1081	if (err)
1082		return libbpf_err(err);
1083
1084	fname = OPTS_GET(opts, field_name, "");
1085	lvl = OPTS_GET(opts, indent_level, 0);
1086	d->strip_mods = OPTS_GET(opts, strip_mods, false);
1087	btf_dump_emit_type_decl(d, id, fname, lvl);
1088	d->strip_mods = false;
1089	return 0;
1090}
1091
1092static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1093				    const char *fname, int lvl)
1094{
1095	struct id_stack decl_stack;
1096	const struct btf_type *t;
1097	int err, stack_start;
1098
1099	stack_start = d->decl_stack_cnt;
1100	for (;;) {
1101		t = btf__type_by_id(d->btf, id);
1102		if (d->strip_mods && btf_is_mod(t))
1103			goto skip_mod;
1104
1105		err = btf_dump_push_decl_stack_id(d, id);
1106		if (err < 0) {
1107			/*
1108			 * if we don't have enough memory for entire type decl
1109			 * chain, restore stack, emit warning, and try to
1110			 * proceed nevertheless
1111			 */
1112			pr_warn("not enough memory for decl stack:%d", err);
1113			d->decl_stack_cnt = stack_start;
1114			return;
1115		}
1116skip_mod:
1117		/* VOID */
1118		if (id == 0)
1119			break;
1120
1121		switch (btf_kind(t)) {
1122		case BTF_KIND_PTR:
1123		case BTF_KIND_VOLATILE:
1124		case BTF_KIND_CONST:
1125		case BTF_KIND_RESTRICT:
1126		case BTF_KIND_FUNC_PROTO:
1127			id = t->type;
1128			break;
1129		case BTF_KIND_ARRAY:
1130			id = btf_array(t)->type;
1131			break;
1132		case BTF_KIND_INT:
1133		case BTF_KIND_ENUM:
1134		case BTF_KIND_FWD:
1135		case BTF_KIND_STRUCT:
1136		case BTF_KIND_UNION:
1137		case BTF_KIND_TYPEDEF:
1138		case BTF_KIND_FLOAT:
1139			goto done;
1140		default:
1141			pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1142				btf_kind(t), id);
1143			goto done;
1144		}
1145	}
1146done:
1147	/*
1148	 * We might be inside a chain of declarations (e.g., array of function
1149	 * pointers returning anonymous (so inlined) structs, having another
1150	 * array field). Each of those needs its own "stack frame" to handle
1151	 * emitting of declarations. Those stack frames are non-overlapping
1152	 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1153	 * handle this set of nested stacks, we create a view corresponding to
1154	 * our own "stack frame" and work with it as an independent stack.
1155	 * We'll need to clean up after emit_type_chain() returns, though.
1156	 */
1157	decl_stack.ids = d->decl_stack + stack_start;
1158	decl_stack.cnt = d->decl_stack_cnt - stack_start;
1159	btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1160	/*
1161	 * emit_type_chain() guarantees that it will pop its entire decl_stack
1162	 * frame before returning. But it works with a read-only view into
1163	 * decl_stack, so it doesn't actually pop anything from the
1164	 * perspective of shared btf_dump->decl_stack, per se. We need to
1165	 * reset decl_stack state to how it was before us to avoid it growing
1166	 * all the time.
1167	 */
1168	d->decl_stack_cnt = stack_start;
1169}
1170
1171static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1172{
1173	const struct btf_type *t;
1174	__u32 id;
1175
1176	while (decl_stack->cnt) {
1177		id = decl_stack->ids[decl_stack->cnt - 1];
1178		t = btf__type_by_id(d->btf, id);
1179
1180		switch (btf_kind(t)) {
1181		case BTF_KIND_VOLATILE:
1182			btf_dump_printf(d, "volatile ");
1183			break;
1184		case BTF_KIND_CONST:
1185			btf_dump_printf(d, "const ");
1186			break;
1187		case BTF_KIND_RESTRICT:
1188			btf_dump_printf(d, "restrict ");
1189			break;
1190		default:
1191			return;
1192		}
1193		decl_stack->cnt--;
1194	}
1195}
1196
1197static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1198{
1199	const struct btf_type *t;
1200	__u32 id;
1201
1202	while (decl_stack->cnt) {
1203		id = decl_stack->ids[decl_stack->cnt - 1];
1204		t = btf__type_by_id(d->btf, id);
1205		if (!btf_is_mod(t))
1206			return;
1207		decl_stack->cnt--;
1208	}
1209}
1210
1211static void btf_dump_emit_name(const struct btf_dump *d,
1212			       const char *name, bool last_was_ptr)
1213{
1214	bool separate = name[0] && !last_was_ptr;
1215
1216	btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1217}
1218
1219static void btf_dump_emit_type_chain(struct btf_dump *d,
1220				     struct id_stack *decls,
1221				     const char *fname, int lvl)
1222{
1223	/*
1224	 * last_was_ptr is used to determine if we need to separate pointer
1225	 * asterisk (*) from previous part of type signature with space, so
1226	 * that we get `int ***`, instead of `int * * *`. We default to true
1227	 * for cases where we have single pointer in a chain. E.g., in ptr ->
1228	 * func_proto case. func_proto will start a new emit_type_chain call
1229	 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1230	 * don't want to prepend space for that last pointer.
1231	 */
1232	bool last_was_ptr = true;
1233	const struct btf_type *t;
1234	const char *name;
1235	__u16 kind;
1236	__u32 id;
1237
1238	while (decls->cnt) {
1239		id = decls->ids[--decls->cnt];
1240		if (id == 0) {
1241			/* VOID is a special snowflake */
1242			btf_dump_emit_mods(d, decls);
1243			btf_dump_printf(d, "void");
1244			last_was_ptr = false;
1245			continue;
1246		}
1247
1248		t = btf__type_by_id(d->btf, id);
1249		kind = btf_kind(t);
1250
1251		switch (kind) {
1252		case BTF_KIND_INT:
1253		case BTF_KIND_FLOAT:
1254			btf_dump_emit_mods(d, decls);
1255			name = btf_name_of(d, t->name_off);
1256			btf_dump_printf(d, "%s", name);
1257			break;
1258		case BTF_KIND_STRUCT:
1259		case BTF_KIND_UNION:
1260			btf_dump_emit_mods(d, decls);
1261			/* inline anonymous struct/union */
1262			if (t->name_off == 0)
1263				btf_dump_emit_struct_def(d, id, t, lvl);
1264			else
1265				btf_dump_emit_struct_fwd(d, id, t);
1266			break;
1267		case BTF_KIND_ENUM:
1268			btf_dump_emit_mods(d, decls);
1269			/* inline anonymous enum */
1270			if (t->name_off == 0)
1271				btf_dump_emit_enum_def(d, id, t, lvl);
1272			else
1273				btf_dump_emit_enum_fwd(d, id, t);
1274			break;
1275		case BTF_KIND_FWD:
1276			btf_dump_emit_mods(d, decls);
1277			btf_dump_emit_fwd_def(d, id, t);
1278			break;
1279		case BTF_KIND_TYPEDEF:
1280			btf_dump_emit_mods(d, decls);
1281			btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1282			break;
1283		case BTF_KIND_PTR:
1284			btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1285			break;
1286		case BTF_KIND_VOLATILE:
1287			btf_dump_printf(d, " volatile");
1288			break;
1289		case BTF_KIND_CONST:
1290			btf_dump_printf(d, " const");
1291			break;
1292		case BTF_KIND_RESTRICT:
1293			btf_dump_printf(d, " restrict");
1294			break;
1295		case BTF_KIND_ARRAY: {
1296			const struct btf_array *a = btf_array(t);
1297			const struct btf_type *next_t;
1298			__u32 next_id;
1299			bool multidim;
1300			/*
1301			 * GCC has a bug
1302			 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1303			 * which causes it to emit extra const/volatile
1304			 * modifiers for an array, if array's element type has
1305			 * const/volatile modifiers. Clang doesn't do that.
1306			 * In general, it doesn't seem very meaningful to have
1307			 * a const/volatile modifier for array, so we are
1308			 * going to silently skip them here.
1309			 */
1310			btf_dump_drop_mods(d, decls);
1311
1312			if (decls->cnt == 0) {
1313				btf_dump_emit_name(d, fname, last_was_ptr);
1314				btf_dump_printf(d, "[%u]", a->nelems);
1315				return;
1316			}
1317
1318			next_id = decls->ids[decls->cnt - 1];
1319			next_t = btf__type_by_id(d->btf, next_id);
1320			multidim = btf_is_array(next_t);
1321			/* we need space if we have named non-pointer */
1322			if (fname[0] && !last_was_ptr)
1323				btf_dump_printf(d, " ");
1324			/* no parentheses for multi-dimensional array */
1325			if (!multidim)
1326				btf_dump_printf(d, "(");
1327			btf_dump_emit_type_chain(d, decls, fname, lvl);
1328			if (!multidim)
1329				btf_dump_printf(d, ")");
1330			btf_dump_printf(d, "[%u]", a->nelems);
1331			return;
1332		}
1333		case BTF_KIND_FUNC_PROTO: {
1334			const struct btf_param *p = btf_params(t);
1335			__u16 vlen = btf_vlen(t);
1336			int i;
1337
1338			/*
1339			 * GCC emits extra volatile qualifier for
1340			 * __attribute__((noreturn)) function pointers. Clang
1341			 * doesn't do it. It's a GCC quirk for backwards
1342			 * compatibility with code written for GCC <2.5. So,
1343			 * similarly to extra qualifiers for array, just drop
1344			 * them, instead of handling them.
1345			 */
1346			btf_dump_drop_mods(d, decls);
1347			if (decls->cnt) {
1348				btf_dump_printf(d, " (");
1349				btf_dump_emit_type_chain(d, decls, fname, lvl);
1350				btf_dump_printf(d, ")");
1351			} else {
1352				btf_dump_emit_name(d, fname, last_was_ptr);
1353			}
1354			btf_dump_printf(d, "(");
1355			/*
1356			 * Clang for BPF target generates func_proto with no
1357			 * args as a func_proto with a single void arg (e.g.,
1358			 * `int (*f)(void)` vs just `int (*f)()`). We are
1359			 * going to pretend there are no args for such case.
1360			 */
1361			if (vlen == 1 && p->type == 0) {
1362				btf_dump_printf(d, ")");
1363				return;
1364			}
1365
1366			for (i = 0; i < vlen; i++, p++) {
1367				if (i > 0)
1368					btf_dump_printf(d, ", ");
1369
1370				/* last arg of type void is vararg */
1371				if (i == vlen - 1 && p->type == 0) {
1372					btf_dump_printf(d, "...");
1373					break;
1374				}
1375
1376				name = btf_name_of(d, p->name_off);
1377				btf_dump_emit_type_decl(d, p->type, name, lvl);
1378			}
1379
1380			btf_dump_printf(d, ")");
1381			return;
1382		}
1383		default:
1384			pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1385				kind, id);
1386			return;
1387		}
1388
1389		last_was_ptr = kind == BTF_KIND_PTR;
1390	}
1391
1392	btf_dump_emit_name(d, fname, last_was_ptr);
1393}
1394
1395/* return number of duplicates (occurrences) of a given name */
1396static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1397				 const char *orig_name)
1398{
1399	size_t dup_cnt = 0;
1400
1401	hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1402	dup_cnt++;
1403	hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1404
1405	return dup_cnt;
1406}
1407
1408static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1409					 struct hashmap *name_map)
1410{
1411	struct btf_dump_type_aux_state *s = &d->type_states[id];
1412	const struct btf_type *t = btf__type_by_id(d->btf, id);
1413	const char *orig_name = btf_name_of(d, t->name_off);
1414	const char **cached_name = &d->cached_names[id];
1415	size_t dup_cnt;
1416
1417	if (t->name_off == 0)
1418		return "";
1419
1420	if (s->name_resolved)
1421		return *cached_name ? *cached_name : orig_name;
1422
1423	dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1424	if (dup_cnt > 1) {
1425		const size_t max_len = 256;
1426		char new_name[max_len];
1427
1428		snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1429		*cached_name = strdup(new_name);
1430	}
1431
1432	s->name_resolved = 1;
1433	return *cached_name ? *cached_name : orig_name;
1434}
1435
1436static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1437{
1438	return btf_dump_resolve_name(d, id, d->type_names);
1439}
1440
1441static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1442{
1443	return btf_dump_resolve_name(d, id, d->ident_names);
1444}
v5.9
   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 <linux/kernel.h>
  17#include "btf.h"
  18#include "hashmap.h"
  19#include "libbpf.h"
  20#include "libbpf_internal.h"
  21
  22/* make sure libbpf doesn't use kernel-only integer typedefs */
  23#pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
  24
  25static const char PREFIXES[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t";
  26static const size_t PREFIX_CNT = sizeof(PREFIXES) - 1;
  27
  28static const char *pfx(int lvl)
  29{
  30	return lvl >= PREFIX_CNT ? PREFIXES : &PREFIXES[PREFIX_CNT - lvl];
  31}
  32
  33enum btf_dump_type_order_state {
  34	NOT_ORDERED,
  35	ORDERING,
  36	ORDERED,
  37};
  38
  39enum btf_dump_type_emit_state {
  40	NOT_EMITTED,
  41	EMITTING,
  42	EMITTED,
  43};
  44
  45/* per-type auxiliary state */
  46struct btf_dump_type_aux_state {
  47	/* topological sorting state */
  48	enum btf_dump_type_order_state order_state: 2;
  49	/* emitting state used to determine the need for forward declaration */
  50	enum btf_dump_type_emit_state emit_state: 2;
  51	/* whether forward declaration was already emitted */
  52	__u8 fwd_emitted: 1;
  53	/* whether unique non-duplicate name was already assigned */
  54	__u8 name_resolved: 1;
  55	/* whether type is referenced from any other type */
  56	__u8 referenced: 1;
  57};
  58
  59struct btf_dump {
  60	const struct btf *btf;
  61	const struct btf_ext *btf_ext;
  62	btf_dump_printf_fn_t printf_fn;
  63	struct btf_dump_opts opts;
  64	int ptr_sz;
  65	bool strip_mods;
 
  66
  67	/* per-type auxiliary state */
  68	struct btf_dump_type_aux_state *type_states;
 
  69	/* per-type optional cached unique name, must be freed, if present */
  70	const char **cached_names;
 
  71
  72	/* topo-sorted list of dependent type definitions */
  73	__u32 *emit_queue;
  74	int emit_queue_cap;
  75	int emit_queue_cnt;
  76
  77	/*
  78	 * stack of type declarations (e.g., chain of modifiers, arrays,
  79	 * funcs, etc)
  80	 */
  81	__u32 *decl_stack;
  82	int decl_stack_cap;
  83	int decl_stack_cnt;
  84
  85	/* maps struct/union/enum name to a number of name occurrences */
  86	struct hashmap *type_names;
  87	/*
  88	 * maps typedef identifiers and enum value names to a number of such
  89	 * name occurrences
  90	 */
  91	struct hashmap *ident_names;
  92};
  93
  94static size_t str_hash_fn(const void *key, void *ctx)
  95{
  96	const char *s = key;
  97	size_t h = 0;
  98
  99	while (*s) {
 100		h = h * 31 + *s;
 101		s++;
 102	}
 103	return h;
 104}
 105
 106static bool str_equal_fn(const void *a, const void *b, void *ctx)
 107{
 108	return strcmp(a, b) == 0;
 109}
 110
 111static const char *btf_name_of(const struct btf_dump *d, __u32 name_off)
 112{
 113	return btf__name_by_offset(d->btf, name_off);
 114}
 115
 116static void btf_dump_printf(const struct btf_dump *d, const char *fmt, ...)
 117{
 118	va_list args;
 119
 120	va_start(args, fmt);
 121	d->printf_fn(d->opts.ctx, fmt, args);
 122	va_end(args);
 123}
 124
 125static int btf_dump_mark_referenced(struct btf_dump *d);
 
 126
 127struct btf_dump *btf_dump__new(const struct btf *btf,
 128			       const struct btf_ext *btf_ext,
 129			       const struct btf_dump_opts *opts,
 130			       btf_dump_printf_fn_t printf_fn)
 131{
 132	struct btf_dump *d;
 133	int err;
 134
 135	d = calloc(1, sizeof(struct btf_dump));
 136	if (!d)
 137		return ERR_PTR(-ENOMEM);
 138
 139	d->btf = btf;
 140	d->btf_ext = btf_ext;
 141	d->printf_fn = printf_fn;
 142	d->opts.ctx = opts ? opts->ctx : NULL;
 143	d->ptr_sz = btf__pointer_size(btf) ? : sizeof(void *);
 144
 145	d->type_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
 146	if (IS_ERR(d->type_names)) {
 147		err = PTR_ERR(d->type_names);
 148		d->type_names = NULL;
 149		goto err;
 150	}
 151	d->ident_names = hashmap__new(str_hash_fn, str_equal_fn, NULL);
 152	if (IS_ERR(d->ident_names)) {
 153		err = PTR_ERR(d->ident_names);
 154		d->ident_names = NULL;
 155		goto err;
 156	}
 157	d->type_states = calloc(1 + btf__get_nr_types(d->btf),
 158				sizeof(d->type_states[0]));
 159	if (!d->type_states) {
 160		err = -ENOMEM;
 161		goto err;
 162	}
 163	d->cached_names = calloc(1 + btf__get_nr_types(d->btf),
 164				 sizeof(d->cached_names[0]));
 165	if (!d->cached_names) {
 166		err = -ENOMEM;
 167		goto err;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 168	}
 169
 170	/* VOID is special */
 171	d->type_states[0].order_state = ORDERED;
 172	d->type_states[0].emit_state = EMITTED;
 173
 174	/* eagerly determine referenced types for anon enums */
 175	err = btf_dump_mark_referenced(d);
 176	if (err)
 177		goto err;
 178
 179	return d;
 180err:
 181	btf_dump__free(d);
 182	return ERR_PTR(err);
 183}
 184
 185void btf_dump__free(struct btf_dump *d)
 186{
 187	int i, cnt;
 188
 189	if (IS_ERR_OR_NULL(d))
 190		return;
 191
 192	free(d->type_states);
 193	if (d->cached_names) {
 194		/* any set cached name is owned by us and should be freed */
 195		for (i = 0, cnt = btf__get_nr_types(d->btf); i <= cnt; i++) {
 196			if (d->cached_names[i])
 197				free((void *)d->cached_names[i]);
 198		}
 199	}
 200	free(d->cached_names);
 201	free(d->emit_queue);
 202	free(d->decl_stack);
 203	hashmap__free(d->type_names);
 204	hashmap__free(d->ident_names);
 205
 206	free(d);
 207}
 208
 209static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr);
 210static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id);
 211
 212/*
 213 * Dump BTF type in a compilable C syntax, including all the necessary
 214 * dependent types, necessary for compilation. If some of the dependent types
 215 * were already emitted as part of previous btf_dump__dump_type() invocation
 216 * for another type, they won't be emitted again. This API allows callers to
 217 * filter out BTF types according to user-defined criterias and emitted only
 218 * minimal subset of types, necessary to compile everything. Full struct/union
 219 * definitions will still be emitted, even if the only usage is through
 220 * pointer and could be satisfied with just a forward declaration.
 221 *
 222 * Dumping is done in two high-level passes:
 223 *   1. Topologically sort type definitions to satisfy C rules of compilation.
 224 *   2. Emit type definitions in C syntax.
 225 *
 226 * Returns 0 on success; <0, otherwise.
 227 */
 228int btf_dump__dump_type(struct btf_dump *d, __u32 id)
 229{
 230	int err, i;
 231
 232	if (id > btf__get_nr_types(d->btf))
 233		return -EINVAL;
 
 
 
 
 234
 235	d->emit_queue_cnt = 0;
 236	err = btf_dump_order_type(d, id, false);
 237	if (err < 0)
 238		return err;
 239
 240	for (i = 0; i < d->emit_queue_cnt; i++)
 241		btf_dump_emit_type(d, d->emit_queue[i], 0 /*top-level*/);
 242
 243	return 0;
 244}
 245
 246/*
 247 * Mark all types that are referenced from any other type. This is used to
 248 * determine top-level anonymous enums that need to be emitted as an
 249 * independent type declarations.
 250 * Anonymous enums come in two flavors: either embedded in a struct's field
 251 * definition, in which case they have to be declared inline as part of field
 252 * type declaration; or as a top-level anonymous enum, typically used for
 253 * declaring global constants. It's impossible to distinguish between two
 254 * without knowning whether given enum type was referenced from other type:
 255 * top-level anonymous enum won't be referenced by anything, while embedded
 256 * one will.
 257 */
 258static int btf_dump_mark_referenced(struct btf_dump *d)
 259{
 260	int i, j, n = btf__get_nr_types(d->btf);
 261	const struct btf_type *t;
 262	__u16 vlen;
 263
 264	for (i = 1; i <= n; i++) {
 265		t = btf__type_by_id(d->btf, i);
 266		vlen = btf_vlen(t);
 267
 268		switch (btf_kind(t)) {
 269		case BTF_KIND_INT:
 270		case BTF_KIND_ENUM:
 271		case BTF_KIND_FWD:
 
 272			break;
 273
 274		case BTF_KIND_VOLATILE:
 275		case BTF_KIND_CONST:
 276		case BTF_KIND_RESTRICT:
 277		case BTF_KIND_PTR:
 278		case BTF_KIND_TYPEDEF:
 279		case BTF_KIND_FUNC:
 280		case BTF_KIND_VAR:
 281			d->type_states[t->type].referenced = 1;
 282			break;
 283
 284		case BTF_KIND_ARRAY: {
 285			const struct btf_array *a = btf_array(t);
 286
 287			d->type_states[a->index_type].referenced = 1;
 288			d->type_states[a->type].referenced = 1;
 289			break;
 290		}
 291		case BTF_KIND_STRUCT:
 292		case BTF_KIND_UNION: {
 293			const struct btf_member *m = btf_members(t);
 294
 295			for (j = 0; j < vlen; j++, m++)
 296				d->type_states[m->type].referenced = 1;
 297			break;
 298		}
 299		case BTF_KIND_FUNC_PROTO: {
 300			const struct btf_param *p = btf_params(t);
 301
 302			for (j = 0; j < vlen; j++, p++)
 303				d->type_states[p->type].referenced = 1;
 304			break;
 305		}
 306		case BTF_KIND_DATASEC: {
 307			const struct btf_var_secinfo *v = btf_var_secinfos(t);
 308
 309			for (j = 0; j < vlen; j++, v++)
 310				d->type_states[v->type].referenced = 1;
 311			break;
 312		}
 313		default:
 314			return -EINVAL;
 315		}
 316	}
 317	return 0;
 318}
 
 319static int btf_dump_add_emit_queue_id(struct btf_dump *d, __u32 id)
 320{
 321	__u32 *new_queue;
 322	size_t new_cap;
 323
 324	if (d->emit_queue_cnt >= d->emit_queue_cap) {
 325		new_cap = max(16, d->emit_queue_cap * 3 / 2);
 326		new_queue = realloc(d->emit_queue,
 327				    new_cap * sizeof(new_queue[0]));
 328		if (!new_queue)
 329			return -ENOMEM;
 330		d->emit_queue = new_queue;
 331		d->emit_queue_cap = new_cap;
 332	}
 333
 334	d->emit_queue[d->emit_queue_cnt++] = id;
 335	return 0;
 336}
 337
 338/*
 339 * Determine order of emitting dependent types and specified type to satisfy
 340 * C compilation rules.  This is done through topological sorting with an
 341 * additional complication which comes from C rules. The main idea for C is
 342 * that if some type is "embedded" into a struct/union, it's size needs to be
 343 * known at the time of definition of containing type. E.g., for:
 344 *
 345 *	struct A {};
 346 *	struct B { struct A x; }
 347 *
 348 * struct A *HAS* to be defined before struct B, because it's "embedded",
 349 * i.e., it is part of struct B layout. But in the following case:
 350 *
 351 *	struct A;
 352 *	struct B { struct A *x; }
 353 *	struct A {};
 354 *
 355 * it's enough to just have a forward declaration of struct A at the time of
 356 * struct B definition, as struct B has a pointer to struct A, so the size of
 357 * field x is known without knowing struct A size: it's sizeof(void *).
 358 *
 359 * Unfortunately, there are some trickier cases we need to handle, e.g.:
 360 *
 361 *	struct A {}; // if this was forward-declaration: compilation error
 362 *	struct B {
 363 *		struct { // anonymous struct
 364 *			struct A y;
 365 *		} *x;
 366 *	};
 367 *
 368 * In this case, struct B's field x is a pointer, so it's size is known
 369 * regardless of the size of (anonymous) struct it points to. But because this
 370 * struct is anonymous and thus defined inline inside struct B, *and* it
 371 * embeds struct A, compiler requires full definition of struct A to be known
 372 * before struct B can be defined. This creates a transitive dependency
 373 * between struct A and struct B. If struct A was forward-declared before
 374 * struct B definition and fully defined after struct B definition, that would
 375 * trigger compilation error.
 376 *
 377 * All this means that while we are doing topological sorting on BTF type
 378 * graph, we need to determine relationships between different types (graph
 379 * nodes):
 380 *   - weak link (relationship) between X and Y, if Y *CAN* be
 381 *   forward-declared at the point of X definition;
 382 *   - strong link, if Y *HAS* to be fully-defined before X can be defined.
 383 *
 384 * The rule is as follows. Given a chain of BTF types from X to Y, if there is
 385 * BTF_KIND_PTR type in the chain and at least one non-anonymous type
 386 * Z (excluding X, including Y), then link is weak. Otherwise, it's strong.
 387 * Weak/strong relationship is determined recursively during DFS traversal and
 388 * is returned as a result from btf_dump_order_type().
 389 *
 390 * btf_dump_order_type() is trying to avoid unnecessary forward declarations,
 391 * but it is not guaranteeing that no extraneous forward declarations will be
 392 * emitted.
 393 *
 394 * To avoid extra work, algorithm marks some of BTF types as ORDERED, when
 395 * it's done with them, but not for all (e.g., VOLATILE, CONST, RESTRICT,
 396 * ARRAY, FUNC_PROTO), as weak/strong semantics for those depends on the
 397 * entire graph path, so depending where from one came to that BTF type, it
 398 * might cause weak or strong ordering. For types like STRUCT/UNION/INT/ENUM,
 399 * once they are processed, there is no need to do it again, so they are
 400 * marked as ORDERED. We can mark PTR as ORDERED as well, as it semi-forces
 401 * weak link, unless subsequent referenced STRUCT/UNION/ENUM is anonymous. But
 402 * in any case, once those are processed, no need to do it again, as the
 403 * result won't change.
 404 *
 405 * Returns:
 406 *   - 1, if type is part of strong link (so there is strong topological
 407 *   ordering requirements);
 408 *   - 0, if type is part of weak link (so can be satisfied through forward
 409 *   declaration);
 410 *   - <0, on error (e.g., unsatisfiable type loop detected).
 411 */
 412static int btf_dump_order_type(struct btf_dump *d, __u32 id, bool through_ptr)
 413{
 414	/*
 415	 * Order state is used to detect strong link cycles, but only for BTF
 416	 * kinds that are or could be an independent definition (i.e.,
 417	 * stand-alone fwd decl, enum, typedef, struct, union). Ptrs, arrays,
 418	 * func_protos, modifiers are just means to get to these definitions.
 419	 * Int/void don't need definitions, they are assumed to be always
 420	 * properly defined.  We also ignore datasec, var, and funcs for now.
 421	 * So for all non-defining kinds, we never even set ordering state,
 422	 * for defining kinds we set ORDERING and subsequently ORDERED if it
 423	 * forms a strong link.
 424	 */
 425	struct btf_dump_type_aux_state *tstate = &d->type_states[id];
 426	const struct btf_type *t;
 427	__u16 vlen;
 428	int err, i;
 429
 430	/* return true, letting typedefs know that it's ok to be emitted */
 431	if (tstate->order_state == ORDERED)
 432		return 1;
 433
 434	t = btf__type_by_id(d->btf, id);
 435
 436	if (tstate->order_state == ORDERING) {
 437		/* type loop, but resolvable through fwd declaration */
 438		if (btf_is_composite(t) && through_ptr && t->name_off != 0)
 439			return 0;
 440		pr_warn("unsatisfiable type cycle, id:[%u]\n", id);
 441		return -ELOOP;
 442	}
 443
 444	switch (btf_kind(t)) {
 445	case BTF_KIND_INT:
 
 446		tstate->order_state = ORDERED;
 447		return 0;
 448
 449	case BTF_KIND_PTR:
 450		err = btf_dump_order_type(d, t->type, true);
 451		tstate->order_state = ORDERED;
 452		return err;
 453
 454	case BTF_KIND_ARRAY:
 455		return btf_dump_order_type(d, btf_array(t)->type, through_ptr);
 456
 457	case BTF_KIND_STRUCT:
 458	case BTF_KIND_UNION: {
 459		const struct btf_member *m = btf_members(t);
 460		/*
 461		 * struct/union is part of strong link, only if it's embedded
 462		 * (so no ptr in a path) or it's anonymous (so has to be
 463		 * defined inline, even if declared through ptr)
 464		 */
 465		if (through_ptr && t->name_off != 0)
 466			return 0;
 467
 468		tstate->order_state = ORDERING;
 469
 470		vlen = btf_vlen(t);
 471		for (i = 0; i < vlen; i++, m++) {
 472			err = btf_dump_order_type(d, m->type, false);
 473			if (err < 0)
 474				return err;
 475		}
 476
 477		if (t->name_off != 0) {
 478			err = btf_dump_add_emit_queue_id(d, id);
 479			if (err < 0)
 480				return err;
 481		}
 482
 483		tstate->order_state = ORDERED;
 484		return 1;
 485	}
 486	case BTF_KIND_ENUM:
 487	case BTF_KIND_FWD:
 488		/*
 489		 * non-anonymous or non-referenced enums are top-level
 490		 * declarations and should be emitted. Same logic can be
 491		 * applied to FWDs, it won't hurt anyways.
 492		 */
 493		if (t->name_off != 0 || !tstate->referenced) {
 494			err = btf_dump_add_emit_queue_id(d, id);
 495			if (err)
 496				return err;
 497		}
 498		tstate->order_state = ORDERED;
 499		return 1;
 500
 501	case BTF_KIND_TYPEDEF: {
 502		int is_strong;
 503
 504		is_strong = btf_dump_order_type(d, t->type, through_ptr);
 505		if (is_strong < 0)
 506			return is_strong;
 507
 508		/* typedef is similar to struct/union w.r.t. fwd-decls */
 509		if (through_ptr && !is_strong)
 510			return 0;
 511
 512		/* typedef is always a named definition */
 513		err = btf_dump_add_emit_queue_id(d, id);
 514		if (err)
 515			return err;
 516
 517		d->type_states[id].order_state = ORDERED;
 518		return 1;
 519	}
 520	case BTF_KIND_VOLATILE:
 521	case BTF_KIND_CONST:
 522	case BTF_KIND_RESTRICT:
 523		return btf_dump_order_type(d, t->type, through_ptr);
 524
 525	case BTF_KIND_FUNC_PROTO: {
 526		const struct btf_param *p = btf_params(t);
 527		bool is_strong;
 528
 529		err = btf_dump_order_type(d, t->type, through_ptr);
 530		if (err < 0)
 531			return err;
 532		is_strong = err > 0;
 533
 534		vlen = btf_vlen(t);
 535		for (i = 0; i < vlen; i++, p++) {
 536			err = btf_dump_order_type(d, p->type, through_ptr);
 537			if (err < 0)
 538				return err;
 539			if (err > 0)
 540				is_strong = true;
 541		}
 542		return is_strong;
 543	}
 544	case BTF_KIND_FUNC:
 545	case BTF_KIND_VAR:
 546	case BTF_KIND_DATASEC:
 547		d->type_states[id].order_state = ORDERED;
 548		return 0;
 549
 550	default:
 551		return -EINVAL;
 552	}
 553}
 554
 555static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
 556					  const struct btf_type *t);
 557
 558static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
 559				     const struct btf_type *t);
 560static void btf_dump_emit_struct_def(struct btf_dump *d, __u32 id,
 561				     const struct btf_type *t, int lvl);
 562
 563static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
 564				   const struct btf_type *t);
 565static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
 566				   const struct btf_type *t, int lvl);
 567
 568static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
 569				  const struct btf_type *t);
 570
 571static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
 572				      const struct btf_type *t, int lvl);
 573
 574/* a local view into a shared stack */
 575struct id_stack {
 576	const __u32 *ids;
 577	int cnt;
 578};
 579
 580static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
 581				    const char *fname, int lvl);
 582static void btf_dump_emit_type_chain(struct btf_dump *d,
 583				     struct id_stack *decl_stack,
 584				     const char *fname, int lvl);
 585
 586static const char *btf_dump_type_name(struct btf_dump *d, __u32 id);
 587static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id);
 588static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
 589				 const char *orig_name);
 590
 591static bool btf_dump_is_blacklisted(struct btf_dump *d, __u32 id)
 592{
 593	const struct btf_type *t = btf__type_by_id(d->btf, id);
 594
 595	/* __builtin_va_list is a compiler built-in, which causes compilation
 596	 * errors, when compiling w/ different compiler, then used to compile
 597	 * original code (e.g., GCC to compile kernel, Clang to use generated
 598	 * C header from BTF). As it is built-in, it should be already defined
 599	 * properly internally in compiler.
 600	 */
 601	if (t->name_off == 0)
 602		return false;
 603	return strcmp(btf_name_of(d, t->name_off), "__builtin_va_list") == 0;
 604}
 605
 606/*
 607 * Emit C-syntax definitions of types from chains of BTF types.
 608 *
 609 * High-level handling of determining necessary forward declarations are handled
 610 * by btf_dump_emit_type() itself, but all nitty-gritty details of emitting type
 611 * declarations/definitions in C syntax  are handled by a combo of
 612 * btf_dump_emit_type_decl()/btf_dump_emit_type_chain() w/ delegation to
 613 * corresponding btf_dump_emit_*_{def,fwd}() functions.
 614 *
 615 * We also keep track of "containing struct/union type ID" to determine when
 616 * we reference it from inside and thus can avoid emitting unnecessary forward
 617 * declaration.
 618 *
 619 * This algorithm is designed in such a way, that even if some error occurs
 620 * (either technical, e.g., out of memory, or logical, i.e., malformed BTF
 621 * that doesn't comply to C rules completely), algorithm will try to proceed
 622 * and produce as much meaningful output as possible.
 623 */
 624static void btf_dump_emit_type(struct btf_dump *d, __u32 id, __u32 cont_id)
 625{
 626	struct btf_dump_type_aux_state *tstate = &d->type_states[id];
 627	bool top_level_def = cont_id == 0;
 628	const struct btf_type *t;
 629	__u16 kind;
 630
 631	if (tstate->emit_state == EMITTED)
 632		return;
 633
 634	t = btf__type_by_id(d->btf, id);
 635	kind = btf_kind(t);
 636
 637	if (tstate->emit_state == EMITTING) {
 638		if (tstate->fwd_emitted)
 639			return;
 640
 641		switch (kind) {
 642		case BTF_KIND_STRUCT:
 643		case BTF_KIND_UNION:
 644			/*
 645			 * if we are referencing a struct/union that we are
 646			 * part of - then no need for fwd declaration
 647			 */
 648			if (id == cont_id)
 649				return;
 650			if (t->name_off == 0) {
 651				pr_warn("anonymous struct/union loop, id:[%u]\n",
 652					id);
 653				return;
 654			}
 655			btf_dump_emit_struct_fwd(d, id, t);
 656			btf_dump_printf(d, ";\n\n");
 657			tstate->fwd_emitted = 1;
 658			break;
 659		case BTF_KIND_TYPEDEF:
 660			/*
 661			 * for typedef fwd_emitted means typedef definition
 662			 * was emitted, but it can be used only for "weak"
 663			 * references through pointer only, not for embedding
 664			 */
 665			if (!btf_dump_is_blacklisted(d, id)) {
 666				btf_dump_emit_typedef_def(d, id, t, 0);
 667				btf_dump_printf(d, ";\n\n");
 668			}
 669			tstate->fwd_emitted = 1;
 670			break;
 671		default:
 672			break;
 673		}
 674
 675		return;
 676	}
 677
 678	switch (kind) {
 679	case BTF_KIND_INT:
 680		/* Emit type alias definitions if necessary */
 681		btf_dump_emit_missing_aliases(d, id, t);
 682
 683		tstate->emit_state = EMITTED;
 684		break;
 685	case BTF_KIND_ENUM:
 686		if (top_level_def) {
 687			btf_dump_emit_enum_def(d, id, t, 0);
 688			btf_dump_printf(d, ";\n\n");
 689		}
 690		tstate->emit_state = EMITTED;
 691		break;
 692	case BTF_KIND_PTR:
 693	case BTF_KIND_VOLATILE:
 694	case BTF_KIND_CONST:
 695	case BTF_KIND_RESTRICT:
 696		btf_dump_emit_type(d, t->type, cont_id);
 697		break;
 698	case BTF_KIND_ARRAY:
 699		btf_dump_emit_type(d, btf_array(t)->type, cont_id);
 700		break;
 701	case BTF_KIND_FWD:
 702		btf_dump_emit_fwd_def(d, id, t);
 703		btf_dump_printf(d, ";\n\n");
 704		tstate->emit_state = EMITTED;
 705		break;
 706	case BTF_KIND_TYPEDEF:
 707		tstate->emit_state = EMITTING;
 708		btf_dump_emit_type(d, t->type, id);
 709		/*
 710		 * typedef can server as both definition and forward
 711		 * declaration; at this stage someone depends on
 712		 * typedef as a forward declaration (refers to it
 713		 * through pointer), so unless we already did it,
 714		 * emit typedef as a forward declaration
 715		 */
 716		if (!tstate->fwd_emitted && !btf_dump_is_blacklisted(d, id)) {
 717			btf_dump_emit_typedef_def(d, id, t, 0);
 718			btf_dump_printf(d, ";\n\n");
 719		}
 720		tstate->emit_state = EMITTED;
 721		break;
 722	case BTF_KIND_STRUCT:
 723	case BTF_KIND_UNION:
 724		tstate->emit_state = EMITTING;
 725		/* if it's a top-level struct/union definition or struct/union
 726		 * is anonymous, then in C we'll be emitting all fields and
 727		 * their types (as opposed to just `struct X`), so we need to
 728		 * make sure that all types, referenced from struct/union
 729		 * members have necessary forward-declarations, where
 730		 * applicable
 731		 */
 732		if (top_level_def || t->name_off == 0) {
 733			const struct btf_member *m = btf_members(t);
 734			__u16 vlen = btf_vlen(t);
 735			int i, new_cont_id;
 736
 737			new_cont_id = t->name_off == 0 ? cont_id : id;
 738			for (i = 0; i < vlen; i++, m++)
 739				btf_dump_emit_type(d, m->type, new_cont_id);
 740		} else if (!tstate->fwd_emitted && id != cont_id) {
 741			btf_dump_emit_struct_fwd(d, id, t);
 742			btf_dump_printf(d, ";\n\n");
 743			tstate->fwd_emitted = 1;
 744		}
 745
 746		if (top_level_def) {
 747			btf_dump_emit_struct_def(d, id, t, 0);
 748			btf_dump_printf(d, ";\n\n");
 749			tstate->emit_state = EMITTED;
 750		} else {
 751			tstate->emit_state = NOT_EMITTED;
 752		}
 753		break;
 754	case BTF_KIND_FUNC_PROTO: {
 755		const struct btf_param *p = btf_params(t);
 756		__u16 vlen = btf_vlen(t);
 757		int i;
 758
 759		btf_dump_emit_type(d, t->type, cont_id);
 760		for (i = 0; i < vlen; i++, p++)
 761			btf_dump_emit_type(d, p->type, cont_id);
 762
 763		break;
 764	}
 765	default:
 766		break;
 767	}
 768}
 769
 770static bool btf_is_struct_packed(const struct btf *btf, __u32 id,
 771				 const struct btf_type *t)
 772{
 773	const struct btf_member *m;
 774	int align, i, bit_sz;
 775	__u16 vlen;
 776
 777	align = btf__align_of(btf, id);
 778	/* size of a non-packed struct has to be a multiple of its alignment*/
 779	if (align && t->size % align)
 780		return true;
 781
 782	m = btf_members(t);
 783	vlen = btf_vlen(t);
 784	/* all non-bitfield fields have to be naturally aligned */
 785	for (i = 0; i < vlen; i++, m++) {
 786		align = btf__align_of(btf, m->type);
 787		bit_sz = btf_member_bitfield_size(t, i);
 788		if (align && bit_sz == 0 && m->offset % (8 * align) != 0)
 789			return true;
 790	}
 791
 792	/*
 793	 * if original struct was marked as packed, but its layout is
 794	 * naturally aligned, we'll detect that it's not packed
 795	 */
 796	return false;
 797}
 798
 799static int chip_away_bits(int total, int at_most)
 800{
 801	return total % at_most ? : at_most;
 802}
 803
 804static void btf_dump_emit_bit_padding(const struct btf_dump *d,
 805				      int cur_off, int m_off, int m_bit_sz,
 806				      int align, int lvl)
 807{
 808	int off_diff = m_off - cur_off;
 809	int ptr_bits = d->ptr_sz * 8;
 810
 811	if (off_diff <= 0)
 812		/* no gap */
 813		return;
 814	if (m_bit_sz == 0 && off_diff < align * 8)
 815		/* natural padding will take care of a gap */
 816		return;
 817
 818	while (off_diff > 0) {
 819		const char *pad_type;
 820		int pad_bits;
 821
 822		if (ptr_bits > 32 && off_diff > 32) {
 823			pad_type = "long";
 824			pad_bits = chip_away_bits(off_diff, ptr_bits);
 825		} else if (off_diff > 16) {
 826			pad_type = "int";
 827			pad_bits = chip_away_bits(off_diff, 32);
 828		} else if (off_diff > 8) {
 829			pad_type = "short";
 830			pad_bits = chip_away_bits(off_diff, 16);
 831		} else {
 832			pad_type = "char";
 833			pad_bits = chip_away_bits(off_diff, 8);
 834		}
 835		btf_dump_printf(d, "\n%s%s: %d;", pfx(lvl), pad_type, pad_bits);
 836		off_diff -= pad_bits;
 837	}
 838}
 839
 840static void btf_dump_emit_struct_fwd(struct btf_dump *d, __u32 id,
 841				     const struct btf_type *t)
 842{
 843	btf_dump_printf(d, "%s %s",
 844			btf_is_struct(t) ? "struct" : "union",
 845			btf_dump_type_name(d, id));
 846}
 847
 848static void btf_dump_emit_struct_def(struct btf_dump *d,
 849				     __u32 id,
 850				     const struct btf_type *t,
 851				     int lvl)
 852{
 853	const struct btf_member *m = btf_members(t);
 854	bool is_struct = btf_is_struct(t);
 855	int align, i, packed, off = 0;
 856	__u16 vlen = btf_vlen(t);
 857
 858	packed = is_struct ? btf_is_struct_packed(d->btf, id, t) : 0;
 859
 860	btf_dump_printf(d, "%s%s%s {",
 861			is_struct ? "struct" : "union",
 862			t->name_off ? " " : "",
 863			btf_dump_type_name(d, id));
 864
 865	for (i = 0; i < vlen; i++, m++) {
 866		const char *fname;
 867		int m_off, m_sz;
 868
 869		fname = btf_name_of(d, m->name_off);
 870		m_sz = btf_member_bitfield_size(t, i);
 871		m_off = btf_member_bit_offset(t, i);
 872		align = packed ? 1 : btf__align_of(d->btf, m->type);
 873
 874		btf_dump_emit_bit_padding(d, off, m_off, m_sz, align, lvl + 1);
 875		btf_dump_printf(d, "\n%s", pfx(lvl + 1));
 876		btf_dump_emit_type_decl(d, m->type, fname, lvl + 1);
 877
 878		if (m_sz) {
 879			btf_dump_printf(d, ": %d", m_sz);
 880			off = m_off + m_sz;
 881		} else {
 882			m_sz = max((__s64)0, btf__resolve_size(d->btf, m->type));
 883			off = m_off + m_sz * 8;
 884		}
 885		btf_dump_printf(d, ";");
 886	}
 887
 888	/* pad at the end, if necessary */
 889	if (is_struct) {
 890		align = packed ? 1 : btf__align_of(d->btf, id);
 891		btf_dump_emit_bit_padding(d, off, t->size * 8, 0, align,
 892					  lvl + 1);
 893	}
 894
 895	if (vlen)
 896		btf_dump_printf(d, "\n");
 897	btf_dump_printf(d, "%s}", pfx(lvl));
 898	if (packed)
 899		btf_dump_printf(d, " __attribute__((packed))");
 900}
 901
 902static const char *missing_base_types[][2] = {
 903	/*
 904	 * GCC emits typedefs to its internal __PolyX_t types when compiling Arm
 905	 * SIMD intrinsics. Alias them to standard base types.
 906	 */
 907	{ "__Poly8_t",		"unsigned char" },
 908	{ "__Poly16_t",		"unsigned short" },
 909	{ "__Poly64_t",		"unsigned long long" },
 910	{ "__Poly128_t",	"unsigned __int128" },
 911};
 912
 913static void btf_dump_emit_missing_aliases(struct btf_dump *d, __u32 id,
 914					  const struct btf_type *t)
 915{
 916	const char *name = btf_dump_type_name(d, id);
 917	int i;
 918
 919	for (i = 0; i < ARRAY_SIZE(missing_base_types); i++) {
 920		if (strcmp(name, missing_base_types[i][0]) == 0) {
 921			btf_dump_printf(d, "typedef %s %s;\n\n",
 922					missing_base_types[i][1], name);
 923			break;
 924		}
 925	}
 926}
 927
 928static void btf_dump_emit_enum_fwd(struct btf_dump *d, __u32 id,
 929				   const struct btf_type *t)
 930{
 931	btf_dump_printf(d, "enum %s", btf_dump_type_name(d, id));
 932}
 933
 934static void btf_dump_emit_enum_def(struct btf_dump *d, __u32 id,
 935				   const struct btf_type *t,
 936				   int lvl)
 937{
 938	const struct btf_enum *v = btf_enum(t);
 939	__u16 vlen = btf_vlen(t);
 940	const char *name;
 941	size_t dup_cnt;
 942	int i;
 943
 944	btf_dump_printf(d, "enum%s%s",
 945			t->name_off ? " " : "",
 946			btf_dump_type_name(d, id));
 947
 948	if (vlen) {
 949		btf_dump_printf(d, " {");
 950		for (i = 0; i < vlen; i++, v++) {
 951			name = btf_name_of(d, v->name_off);
 952			/* enumerators share namespace with typedef idents */
 953			dup_cnt = btf_dump_name_dups(d, d->ident_names, name);
 954			if (dup_cnt > 1) {
 955				btf_dump_printf(d, "\n%s%s___%zu = %u,",
 956						pfx(lvl + 1), name, dup_cnt,
 957						(__u32)v->val);
 958			} else {
 959				btf_dump_printf(d, "\n%s%s = %u,",
 960						pfx(lvl + 1), name,
 961						(__u32)v->val);
 962			}
 963		}
 964		btf_dump_printf(d, "\n%s}", pfx(lvl));
 965	}
 966}
 967
 968static void btf_dump_emit_fwd_def(struct btf_dump *d, __u32 id,
 969				  const struct btf_type *t)
 970{
 971	const char *name = btf_dump_type_name(d, id);
 972
 973	if (btf_kflag(t))
 974		btf_dump_printf(d, "union %s", name);
 975	else
 976		btf_dump_printf(d, "struct %s", name);
 977}
 978
 979static void btf_dump_emit_typedef_def(struct btf_dump *d, __u32 id,
 980				     const struct btf_type *t, int lvl)
 981{
 982	const char *name = btf_dump_ident_name(d, id);
 983
 984	/*
 985	 * Old GCC versions are emitting invalid typedef for __gnuc_va_list
 986	 * pointing to VOID. This generates warnings from btf_dump() and
 987	 * results in uncompilable header file, so we are fixing it up here
 988	 * with valid typedef into __builtin_va_list.
 989	 */
 990	if (t->type == 0 && strcmp(name, "__gnuc_va_list") == 0) {
 991		btf_dump_printf(d, "typedef __builtin_va_list __gnuc_va_list");
 992		return;
 993	}
 994
 995	btf_dump_printf(d, "typedef ");
 996	btf_dump_emit_type_decl(d, t->type, name, lvl);
 997}
 998
 999static int btf_dump_push_decl_stack_id(struct btf_dump *d, __u32 id)
1000{
1001	__u32 *new_stack;
1002	size_t new_cap;
1003
1004	if (d->decl_stack_cnt >= d->decl_stack_cap) {
1005		new_cap = max(16, d->decl_stack_cap * 3 / 2);
1006		new_stack = realloc(d->decl_stack,
1007				    new_cap * sizeof(new_stack[0]));
1008		if (!new_stack)
1009			return -ENOMEM;
1010		d->decl_stack = new_stack;
1011		d->decl_stack_cap = new_cap;
1012	}
1013
1014	d->decl_stack[d->decl_stack_cnt++] = id;
1015
1016	return 0;
1017}
1018
1019/*
1020 * Emit type declaration (e.g., field type declaration in a struct or argument
1021 * declaration in function prototype) in correct C syntax.
1022 *
1023 * For most types it's trivial, but there are few quirky type declaration
1024 * cases worth mentioning:
1025 *   - function prototypes (especially nesting of function prototypes);
1026 *   - arrays;
1027 *   - const/volatile/restrict for pointers vs other types.
1028 *
1029 * For a good discussion of *PARSING* C syntax (as a human), see
1030 * Peter van der Linden's "Expert C Programming: Deep C Secrets",
1031 * Ch.3 "Unscrambling Declarations in C".
1032 *
1033 * It won't help with BTF to C conversion much, though, as it's an opposite
1034 * problem. So we came up with this algorithm in reverse to van der Linden's
1035 * parsing algorithm. It goes from structured BTF representation of type
1036 * declaration to a valid compilable C syntax.
1037 *
1038 * For instance, consider this C typedef:
1039 *	typedef const int * const * arr[10] arr_t;
1040 * It will be represented in BTF with this chain of BTF types:
1041 *	[typedef] -> [array] -> [ptr] -> [const] -> [ptr] -> [const] -> [int]
1042 *
1043 * Notice how [const] modifier always goes before type it modifies in BTF type
1044 * graph, but in C syntax, const/volatile/restrict modifiers are written to
1045 * the right of pointers, but to the left of other types. There are also other
1046 * quirks, like function pointers, arrays of them, functions returning other
1047 * functions, etc.
1048 *
1049 * We handle that by pushing all the types to a stack, until we hit "terminal"
1050 * type (int/enum/struct/union/fwd). Then depending on the kind of a type on
1051 * top of a stack, modifiers are handled differently. Array/function pointers
1052 * have also wildly different syntax and how nesting of them are done. See
1053 * code for authoritative definition.
1054 *
1055 * To avoid allocating new stack for each independent chain of BTF types, we
1056 * share one bigger stack, with each chain working only on its own local view
1057 * of a stack frame. Some care is required to "pop" stack frames after
1058 * processing type declaration chain.
1059 */
1060int btf_dump__emit_type_decl(struct btf_dump *d, __u32 id,
1061			     const struct btf_dump_emit_type_decl_opts *opts)
1062{
1063	const char *fname;
1064	int lvl;
1065
1066	if (!OPTS_VALID(opts, btf_dump_emit_type_decl_opts))
1067		return -EINVAL;
 
 
 
 
1068
1069	fname = OPTS_GET(opts, field_name, "");
1070	lvl = OPTS_GET(opts, indent_level, 0);
1071	d->strip_mods = OPTS_GET(opts, strip_mods, false);
1072	btf_dump_emit_type_decl(d, id, fname, lvl);
1073	d->strip_mods = false;
1074	return 0;
1075}
1076
1077static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,
1078				    const char *fname, int lvl)
1079{
1080	struct id_stack decl_stack;
1081	const struct btf_type *t;
1082	int err, stack_start;
1083
1084	stack_start = d->decl_stack_cnt;
1085	for (;;) {
1086		t = btf__type_by_id(d->btf, id);
1087		if (d->strip_mods && btf_is_mod(t))
1088			goto skip_mod;
1089
1090		err = btf_dump_push_decl_stack_id(d, id);
1091		if (err < 0) {
1092			/*
1093			 * if we don't have enough memory for entire type decl
1094			 * chain, restore stack, emit warning, and try to
1095			 * proceed nevertheless
1096			 */
1097			pr_warn("not enough memory for decl stack:%d", err);
1098			d->decl_stack_cnt = stack_start;
1099			return;
1100		}
1101skip_mod:
1102		/* VOID */
1103		if (id == 0)
1104			break;
1105
1106		switch (btf_kind(t)) {
1107		case BTF_KIND_PTR:
1108		case BTF_KIND_VOLATILE:
1109		case BTF_KIND_CONST:
1110		case BTF_KIND_RESTRICT:
1111		case BTF_KIND_FUNC_PROTO:
1112			id = t->type;
1113			break;
1114		case BTF_KIND_ARRAY:
1115			id = btf_array(t)->type;
1116			break;
1117		case BTF_KIND_INT:
1118		case BTF_KIND_ENUM:
1119		case BTF_KIND_FWD:
1120		case BTF_KIND_STRUCT:
1121		case BTF_KIND_UNION:
1122		case BTF_KIND_TYPEDEF:
 
1123			goto done;
1124		default:
1125			pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1126				btf_kind(t), id);
1127			goto done;
1128		}
1129	}
1130done:
1131	/*
1132	 * We might be inside a chain of declarations (e.g., array of function
1133	 * pointers returning anonymous (so inlined) structs, having another
1134	 * array field). Each of those needs its own "stack frame" to handle
1135	 * emitting of declarations. Those stack frames are non-overlapping
1136	 * portions of shared btf_dump->decl_stack. To make it a bit nicer to
1137	 * handle this set of nested stacks, we create a view corresponding to
1138	 * our own "stack frame" and work with it as an independent stack.
1139	 * We'll need to clean up after emit_type_chain() returns, though.
1140	 */
1141	decl_stack.ids = d->decl_stack + stack_start;
1142	decl_stack.cnt = d->decl_stack_cnt - stack_start;
1143	btf_dump_emit_type_chain(d, &decl_stack, fname, lvl);
1144	/*
1145	 * emit_type_chain() guarantees that it will pop its entire decl_stack
1146	 * frame before returning. But it works with a read-only view into
1147	 * decl_stack, so it doesn't actually pop anything from the
1148	 * perspective of shared btf_dump->decl_stack, per se. We need to
1149	 * reset decl_stack state to how it was before us to avoid it growing
1150	 * all the time.
1151	 */
1152	d->decl_stack_cnt = stack_start;
1153}
1154
1155static void btf_dump_emit_mods(struct btf_dump *d, struct id_stack *decl_stack)
1156{
1157	const struct btf_type *t;
1158	__u32 id;
1159
1160	while (decl_stack->cnt) {
1161		id = decl_stack->ids[decl_stack->cnt - 1];
1162		t = btf__type_by_id(d->btf, id);
1163
1164		switch (btf_kind(t)) {
1165		case BTF_KIND_VOLATILE:
1166			btf_dump_printf(d, "volatile ");
1167			break;
1168		case BTF_KIND_CONST:
1169			btf_dump_printf(d, "const ");
1170			break;
1171		case BTF_KIND_RESTRICT:
1172			btf_dump_printf(d, "restrict ");
1173			break;
1174		default:
1175			return;
1176		}
1177		decl_stack->cnt--;
1178	}
1179}
1180
1181static void btf_dump_drop_mods(struct btf_dump *d, struct id_stack *decl_stack)
1182{
1183	const struct btf_type *t;
1184	__u32 id;
1185
1186	while (decl_stack->cnt) {
1187		id = decl_stack->ids[decl_stack->cnt - 1];
1188		t = btf__type_by_id(d->btf, id);
1189		if (!btf_is_mod(t))
1190			return;
1191		decl_stack->cnt--;
1192	}
1193}
1194
1195static void btf_dump_emit_name(const struct btf_dump *d,
1196			       const char *name, bool last_was_ptr)
1197{
1198	bool separate = name[0] && !last_was_ptr;
1199
1200	btf_dump_printf(d, "%s%s", separate ? " " : "", name);
1201}
1202
1203static void btf_dump_emit_type_chain(struct btf_dump *d,
1204				     struct id_stack *decls,
1205				     const char *fname, int lvl)
1206{
1207	/*
1208	 * last_was_ptr is used to determine if we need to separate pointer
1209	 * asterisk (*) from previous part of type signature with space, so
1210	 * that we get `int ***`, instead of `int * * *`. We default to true
1211	 * for cases where we have single pointer in a chain. E.g., in ptr ->
1212	 * func_proto case. func_proto will start a new emit_type_chain call
1213	 * with just ptr, which should be emitted as (*) or (*<fname>), so we
1214	 * don't want to prepend space for that last pointer.
1215	 */
1216	bool last_was_ptr = true;
1217	const struct btf_type *t;
1218	const char *name;
1219	__u16 kind;
1220	__u32 id;
1221
1222	while (decls->cnt) {
1223		id = decls->ids[--decls->cnt];
1224		if (id == 0) {
1225			/* VOID is a special snowflake */
1226			btf_dump_emit_mods(d, decls);
1227			btf_dump_printf(d, "void");
1228			last_was_ptr = false;
1229			continue;
1230		}
1231
1232		t = btf__type_by_id(d->btf, id);
1233		kind = btf_kind(t);
1234
1235		switch (kind) {
1236		case BTF_KIND_INT:
 
1237			btf_dump_emit_mods(d, decls);
1238			name = btf_name_of(d, t->name_off);
1239			btf_dump_printf(d, "%s", name);
1240			break;
1241		case BTF_KIND_STRUCT:
1242		case BTF_KIND_UNION:
1243			btf_dump_emit_mods(d, decls);
1244			/* inline anonymous struct/union */
1245			if (t->name_off == 0)
1246				btf_dump_emit_struct_def(d, id, t, lvl);
1247			else
1248				btf_dump_emit_struct_fwd(d, id, t);
1249			break;
1250		case BTF_KIND_ENUM:
1251			btf_dump_emit_mods(d, decls);
1252			/* inline anonymous enum */
1253			if (t->name_off == 0)
1254				btf_dump_emit_enum_def(d, id, t, lvl);
1255			else
1256				btf_dump_emit_enum_fwd(d, id, t);
1257			break;
1258		case BTF_KIND_FWD:
1259			btf_dump_emit_mods(d, decls);
1260			btf_dump_emit_fwd_def(d, id, t);
1261			break;
1262		case BTF_KIND_TYPEDEF:
1263			btf_dump_emit_mods(d, decls);
1264			btf_dump_printf(d, "%s", btf_dump_ident_name(d, id));
1265			break;
1266		case BTF_KIND_PTR:
1267			btf_dump_printf(d, "%s", last_was_ptr ? "*" : " *");
1268			break;
1269		case BTF_KIND_VOLATILE:
1270			btf_dump_printf(d, " volatile");
1271			break;
1272		case BTF_KIND_CONST:
1273			btf_dump_printf(d, " const");
1274			break;
1275		case BTF_KIND_RESTRICT:
1276			btf_dump_printf(d, " restrict");
1277			break;
1278		case BTF_KIND_ARRAY: {
1279			const struct btf_array *a = btf_array(t);
1280			const struct btf_type *next_t;
1281			__u32 next_id;
1282			bool multidim;
1283			/*
1284			 * GCC has a bug
1285			 * (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=8354)
1286			 * which causes it to emit extra const/volatile
1287			 * modifiers for an array, if array's element type has
1288			 * const/volatile modifiers. Clang doesn't do that.
1289			 * In general, it doesn't seem very meaningful to have
1290			 * a const/volatile modifier for array, so we are
1291			 * going to silently skip them here.
1292			 */
1293			btf_dump_drop_mods(d, decls);
1294
1295			if (decls->cnt == 0) {
1296				btf_dump_emit_name(d, fname, last_was_ptr);
1297				btf_dump_printf(d, "[%u]", a->nelems);
1298				return;
1299			}
1300
1301			next_id = decls->ids[decls->cnt - 1];
1302			next_t = btf__type_by_id(d->btf, next_id);
1303			multidim = btf_is_array(next_t);
1304			/* we need space if we have named non-pointer */
1305			if (fname[0] && !last_was_ptr)
1306				btf_dump_printf(d, " ");
1307			/* no parentheses for multi-dimensional array */
1308			if (!multidim)
1309				btf_dump_printf(d, "(");
1310			btf_dump_emit_type_chain(d, decls, fname, lvl);
1311			if (!multidim)
1312				btf_dump_printf(d, ")");
1313			btf_dump_printf(d, "[%u]", a->nelems);
1314			return;
1315		}
1316		case BTF_KIND_FUNC_PROTO: {
1317			const struct btf_param *p = btf_params(t);
1318			__u16 vlen = btf_vlen(t);
1319			int i;
1320
1321			/*
1322			 * GCC emits extra volatile qualifier for
1323			 * __attribute__((noreturn)) function pointers. Clang
1324			 * doesn't do it. It's a GCC quirk for backwards
1325			 * compatibility with code written for GCC <2.5. So,
1326			 * similarly to extra qualifiers for array, just drop
1327			 * them, instead of handling them.
1328			 */
1329			btf_dump_drop_mods(d, decls);
1330			if (decls->cnt) {
1331				btf_dump_printf(d, " (");
1332				btf_dump_emit_type_chain(d, decls, fname, lvl);
1333				btf_dump_printf(d, ")");
1334			} else {
1335				btf_dump_emit_name(d, fname, last_was_ptr);
1336			}
1337			btf_dump_printf(d, "(");
1338			/*
1339			 * Clang for BPF target generates func_proto with no
1340			 * args as a func_proto with a single void arg (e.g.,
1341			 * `int (*f)(void)` vs just `int (*f)()`). We are
1342			 * going to pretend there are no args for such case.
1343			 */
1344			if (vlen == 1 && p->type == 0) {
1345				btf_dump_printf(d, ")");
1346				return;
1347			}
1348
1349			for (i = 0; i < vlen; i++, p++) {
1350				if (i > 0)
1351					btf_dump_printf(d, ", ");
1352
1353				/* last arg of type void is vararg */
1354				if (i == vlen - 1 && p->type == 0) {
1355					btf_dump_printf(d, "...");
1356					break;
1357				}
1358
1359				name = btf_name_of(d, p->name_off);
1360				btf_dump_emit_type_decl(d, p->type, name, lvl);
1361			}
1362
1363			btf_dump_printf(d, ")");
1364			return;
1365		}
1366		default:
1367			pr_warn("unexpected type in decl chain, kind:%u, id:[%u]\n",
1368				kind, id);
1369			return;
1370		}
1371
1372		last_was_ptr = kind == BTF_KIND_PTR;
1373	}
1374
1375	btf_dump_emit_name(d, fname, last_was_ptr);
1376}
1377
1378/* return number of duplicates (occurrences) of a given name */
1379static size_t btf_dump_name_dups(struct btf_dump *d, struct hashmap *name_map,
1380				 const char *orig_name)
1381{
1382	size_t dup_cnt = 0;
1383
1384	hashmap__find(name_map, orig_name, (void **)&dup_cnt);
1385	dup_cnt++;
1386	hashmap__set(name_map, orig_name, (void *)dup_cnt, NULL, NULL);
1387
1388	return dup_cnt;
1389}
1390
1391static const char *btf_dump_resolve_name(struct btf_dump *d, __u32 id,
1392					 struct hashmap *name_map)
1393{
1394	struct btf_dump_type_aux_state *s = &d->type_states[id];
1395	const struct btf_type *t = btf__type_by_id(d->btf, id);
1396	const char *orig_name = btf_name_of(d, t->name_off);
1397	const char **cached_name = &d->cached_names[id];
1398	size_t dup_cnt;
1399
1400	if (t->name_off == 0)
1401		return "";
1402
1403	if (s->name_resolved)
1404		return *cached_name ? *cached_name : orig_name;
1405
1406	dup_cnt = btf_dump_name_dups(d, name_map, orig_name);
1407	if (dup_cnt > 1) {
1408		const size_t max_len = 256;
1409		char new_name[max_len];
1410
1411		snprintf(new_name, max_len, "%s___%zu", orig_name, dup_cnt);
1412		*cached_name = strdup(new_name);
1413	}
1414
1415	s->name_resolved = 1;
1416	return *cached_name ? *cached_name : orig_name;
1417}
1418
1419static const char *btf_dump_type_name(struct btf_dump *d, __u32 id)
1420{
1421	return btf_dump_resolve_name(d, id, d->type_names);
1422}
1423
1424static const char *btf_dump_ident_name(struct btf_dump *d, __u32 id)
1425{
1426	return btf_dump_resolve_name(d, id, d->ident_names);
1427}