xref: /linux/scripts/gendwarfksyms/dwarf.c (revision ba6ec09911b805778a2fed6d626bfe77b011a717)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2024 Google LLC
4  */
5 
6 #include <assert.h>
7 #include <inttypes.h>
8 #include <stdarg.h>
9 #include "gendwarfksyms.h"
10 
11 /* See get_union_kabi_status */
12 #define KABI_PREFIX "__kabi_"
13 #define KABI_PREFIX_LEN (sizeof(KABI_PREFIX) - 1)
14 #define KABI_RESERVED_PREFIX "reserved"
15 #define KABI_RESERVED_PREFIX_LEN (sizeof(KABI_RESERVED_PREFIX) - 1)
16 #define KABI_RENAMED_PREFIX "renamed"
17 #define KABI_RENAMED_PREFIX_LEN (sizeof(KABI_RENAMED_PREFIX) - 1)
18 #define KABI_IGNORED_PREFIX "ignored"
19 #define KABI_IGNORED_PREFIX_LEN (sizeof(KABI_IGNORED_PREFIX) - 1)
20 
is_kabi_prefix(const char * name)21 static inline bool is_kabi_prefix(const char *name)
22 {
23 	return name && !strncmp(name, KABI_PREFIX, KABI_PREFIX_LEN);
24 }
25 
26 enum kabi_status {
27 	/* >0 to stop DIE processing */
28 	KABI_NORMAL = 1,
29 	KABI_RESERVED,
30 	KABI_IGNORED,
31 };
32 
33 static bool do_linebreak;
34 static int indentation_level;
35 
36 /* Line breaks and indentation for pretty-printing */
process_linebreak(struct die * cache,int n)37 static void process_linebreak(struct die *cache, int n)
38 {
39 	indentation_level += n;
40 	do_linebreak = true;
41 	die_map_add_linebreak(cache, n);
42 }
43 
44 #define DEFINE_GET_ATTR(attr, type)                                    \
45 	static bool get_##attr##_attr(Dwarf_Die *die, unsigned int id, \
46 				      type *value)                     \
47 	{                                                              \
48 		Dwarf_Attribute da;                                    \
49 		return dwarf_attr(die, id, &da) &&                     \
50 		       !dwarf_form##attr(&da, value);                  \
51 	}
52 
DEFINE_GET_ATTR(flag,bool)53 DEFINE_GET_ATTR(flag, bool)
54 DEFINE_GET_ATTR(udata, Dwarf_Word)
55 
56 static bool get_ref_die_attr(Dwarf_Die *die, unsigned int id, Dwarf_Die *value)
57 {
58 	Dwarf_Attribute da;
59 
60 	/* dwarf_formref_die returns a pointer instead of an error value. */
61 	return dwarf_attr(die, id, &da) && dwarf_formref_die(&da, value);
62 }
63 
64 #define DEFINE_GET_STRING_ATTR(attr)                         \
65 	static const char *get_##attr##_attr(Dwarf_Die *die) \
66 	{                                                    \
67 		Dwarf_Attribute da;                          \
68 		if (dwarf_attr(die, DW_AT_##attr, &da))      \
69 			return dwarf_formstring(&da);        \
70 		return NULL;                                 \
71 	}
72 
73 DEFINE_GET_STRING_ATTR(name)
DEFINE_GET_STRING_ATTR(linkage_name)74 DEFINE_GET_STRING_ATTR(linkage_name)
75 
76 static const char *get_symbol_name(Dwarf_Die *die)
77 {
78 	const char *name;
79 
80 	/* rustc uses DW_AT_linkage_name for exported symbols */
81 	name = get_linkage_name_attr(die);
82 	if (!name)
83 		name = get_name_attr(die);
84 
85 	return name;
86 }
87 
match_export_symbol(struct state * state,Dwarf_Die * die)88 static bool match_export_symbol(struct state *state, Dwarf_Die *die)
89 {
90 	Dwarf_Die *source = die;
91 	Dwarf_Die origin;
92 
93 	/* If the DIE has an abstract origin, use it for type information. */
94 	if (get_ref_die_attr(die, DW_AT_abstract_origin, &origin))
95 		source = &origin;
96 
97 	state->sym = symbol_get(get_symbol_name(die));
98 
99 	/* Look up using the origin name if there are no matches. */
100 	if (!state->sym && source != die)
101 		state->sym = symbol_get(get_symbol_name(source));
102 
103 	state->die = *source;
104 	return !!state->sym;
105 }
106 
107 /* DW_AT_decl_file -> struct srcfile */
108 static struct cache srcfile_cache;
109 
is_definition_private(Dwarf_Die * die)110 static bool is_definition_private(Dwarf_Die *die)
111 {
112 	Dwarf_Word filenum;
113 	Dwarf_Files *files;
114 	Dwarf_Die cudie;
115 	const char *s;
116 	int res;
117 
118 	/*
119 	 * Definitions in .c files cannot change the public ABI,
120 	 * so consider them private.
121 	 */
122 	if (!get_udata_attr(die, DW_AT_decl_file, &filenum))
123 		return false;
124 
125 	res = cache_get(&srcfile_cache, filenum);
126 	if (res >= 0)
127 		return !!res;
128 
129 	if (!dwarf_cu_die(die->cu, &cudie, NULL, NULL, NULL, NULL, NULL, NULL))
130 		error("dwarf_cu_die failed: '%s'", dwarf_errmsg(-1));
131 
132 	if (dwarf_getsrcfiles(&cudie, &files, NULL))
133 		error("dwarf_getsrcfiles failed: '%s'", dwarf_errmsg(-1));
134 
135 	s = dwarf_filesrc(files, filenum, NULL, NULL);
136 	if (!s)
137 		error("dwarf_filesrc failed: '%s'", dwarf_errmsg(-1));
138 
139 	s = strrchr(s, '.');
140 	res = s && !strcmp(s, ".c");
141 	cache_set(&srcfile_cache, filenum, res);
142 
143 	return !!res;
144 }
145 
is_kabi_definition(struct die * cache,Dwarf_Die * die)146 static bool is_kabi_definition(struct die *cache, Dwarf_Die *die)
147 {
148 	bool value;
149 
150 	if (get_flag_attr(die, DW_AT_declaration, &value) && value)
151 		return false;
152 
153 	if (kabi_is_declonly(cache->fqn))
154 		return false;
155 
156 	return !is_definition_private(die);
157 }
158 
159 /*
160  * Type string processing
161  */
process(struct die * cache,const char * s)162 static void process(struct die *cache, const char *s)
163 {
164 	s = s ?: "<null>";
165 
166 	if (dump_dies && do_linebreak) {
167 		fputs("\n", stderr);
168 		for (int i = 0; i < indentation_level; i++)
169 			fputs("  ", stderr);
170 		do_linebreak = false;
171 	}
172 	if (dump_dies)
173 		fputs(s, stderr);
174 
175 	if (cache)
176 		die_debug_r("cache %p string '%s'", cache, s);
177 	die_map_add_string(cache, s);
178 }
179 
180 #define MAX_FMT_BUFFER_SIZE 128
181 
process_fmt(struct die * cache,const char * fmt,...)182 static void process_fmt(struct die *cache, const char *fmt, ...)
183 {
184 	char buf[MAX_FMT_BUFFER_SIZE];
185 	va_list args;
186 
187 	va_start(args, fmt);
188 
189 	if (checkp(vsnprintf(buf, sizeof(buf), fmt, args)) >= sizeof(buf))
190 		error("vsnprintf overflow: increase MAX_FMT_BUFFER_SIZE");
191 
192 	process(cache, buf);
193 	va_end(args);
194 }
195 
196 #define MAX_FQN_SIZE 64
197 
198 /* Get a fully qualified name from DWARF scopes */
get_fqn(Dwarf_Die * die)199 static char *get_fqn(Dwarf_Die *die)
200 {
201 	const char *list[MAX_FQN_SIZE];
202 	Dwarf_Die *scopes = NULL;
203 	bool has_name = false;
204 	char *fqn = NULL;
205 	char *p;
206 	int count = 0;
207 	int len = 0;
208 	int res;
209 	int i;
210 
211 	res = checkp(dwarf_getscopes_die(die, &scopes));
212 	if (!res) {
213 		list[count] = get_name_attr(die);
214 
215 		if (!list[count])
216 			return NULL;
217 
218 		len += strlen(list[count]);
219 		count++;
220 
221 		goto done;
222 	}
223 
224 	for (i = res - 1; i >= 0 && count < MAX_FQN_SIZE; i--) {
225 		if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
226 			continue;
227 
228 		list[count] = get_name_attr(&scopes[i]);
229 
230 		if (list[count]) {
231 			has_name = true;
232 		} else {
233 			list[count] = "<anonymous>";
234 			has_name = false;
235 		}
236 
237 		len += strlen(list[count]);
238 		count++;
239 
240 		if (i > 0) {
241 			list[count++] = "::";
242 			len += 2;
243 		}
244 	}
245 
246 	free(scopes);
247 
248 	if (count == MAX_FQN_SIZE)
249 		warn("increase MAX_FQN_SIZE: reached the maximum");
250 
251 	/* Consider the DIE unnamed if the last scope doesn't have a name */
252 	if (!has_name)
253 		return NULL;
254 done:
255 	fqn = xmalloc(len + 1);
256 	*fqn = '\0';
257 
258 	p = fqn;
259 	for (i = 0; i < count; i++)
260 		p = stpcpy(p, list[i]);
261 
262 	return fqn;
263 }
264 
update_fqn(struct die * cache,Dwarf_Die * die)265 static void update_fqn(struct die *cache, Dwarf_Die *die)
266 {
267 	if (!cache->fqn)
268 		cache->fqn = get_fqn(die) ?: "";
269 }
270 
process_fqn(struct die * cache,Dwarf_Die * die)271 static void process_fqn(struct die *cache, Dwarf_Die *die)
272 {
273 	update_fqn(cache, die);
274 	if (*cache->fqn)
275 		process(cache, " ");
276 	process(cache, cache->fqn);
277 }
278 
279 #define DEFINE_PROCESS_UDATA_ATTRIBUTE(attribute)                          \
280 	static void process_##attribute##_attr(struct die *cache,          \
281 					       Dwarf_Die *die)             \
282 	{                                                                  \
283 		Dwarf_Word value;                                          \
284 		if (get_udata_attr(die, DW_AT_##attribute, &value))        \
285 			process_fmt(cache, " " #attribute "(%" PRIu64 ")", \
286 				    value);                                \
287 	}
288 
289 DEFINE_PROCESS_UDATA_ATTRIBUTE(accessibility)
DEFINE_PROCESS_UDATA_ATTRIBUTE(alignment)290 DEFINE_PROCESS_UDATA_ATTRIBUTE(alignment)
291 DEFINE_PROCESS_UDATA_ATTRIBUTE(bit_size)
292 DEFINE_PROCESS_UDATA_ATTRIBUTE(byte_size)
293 DEFINE_PROCESS_UDATA_ATTRIBUTE(encoding)
294 DEFINE_PROCESS_UDATA_ATTRIBUTE(data_bit_offset)
295 DEFINE_PROCESS_UDATA_ATTRIBUTE(data_member_location)
296 DEFINE_PROCESS_UDATA_ATTRIBUTE(discr_value)
297 
298 /* Match functions -- die_match_callback_t */
299 #define DEFINE_MATCH(type)                                     \
300 	static bool match_##type##_type(Dwarf_Die *die)        \
301 	{                                                      \
302 		return dwarf_tag(die) == DW_TAG_##type##_type; \
303 	}
304 
305 DEFINE_MATCH(enumerator)
306 DEFINE_MATCH(formal_parameter)
307 DEFINE_MATCH(member)
308 DEFINE_MATCH(subrange)
309 
310 bool match_all(Dwarf_Die *die)
311 {
312 	return true;
313 }
314 
process_die_container(struct state * state,struct die * cache,Dwarf_Die * die,die_callback_t func,die_match_callback_t match)315 int process_die_container(struct state *state, struct die *cache,
316 			  Dwarf_Die *die, die_callback_t func,
317 			  die_match_callback_t match)
318 {
319 	Dwarf_Die current;
320 	int res;
321 
322 	/* Track the first item in lists. */
323 	if (state)
324 		state->first_list_item = true;
325 
326 	res = checkp(dwarf_child(die, &current));
327 	while (!res) {
328 		if (match(&current)) {
329 			/* <0 = error, 0 = continue, >0 = stop */
330 			res = checkp(func(state, cache, &current));
331 			if (res)
332 				goto out;
333 		}
334 
335 		res = checkp(dwarf_siblingof(&current, &current));
336 	}
337 
338 	res = 0;
339 out:
340 	if (state)
341 		state->first_list_item = false;
342 
343 	return res;
344 }
345 
346 static int process_type(struct state *state, struct die *parent,
347 			Dwarf_Die *die);
348 
process_type_attr(struct state * state,struct die * cache,Dwarf_Die * die)349 static void process_type_attr(struct state *state, struct die *cache,
350 			      Dwarf_Die *die)
351 {
352 	Dwarf_Die type;
353 
354 	if (get_ref_die_attr(die, DW_AT_type, &type)) {
355 		check(process_type(state, cache, &type));
356 		return;
357 	}
358 
359 	/* Compilers can omit DW_AT_type -- print out 'void' to clarify */
360 	process(cache, "base_type void");
361 }
362 
process_list_comma(struct state * state,struct die * cache)363 static void process_list_comma(struct state *state, struct die *cache)
364 {
365 	if (state->first_list_item) {
366 		state->first_list_item = false;
367 	} else {
368 		process(cache, " ,");
369 		process_linebreak(cache, 0);
370 	}
371 }
372 
373 /* Comma-separated with DW_AT_type */
__process_list_type(struct state * state,struct die * cache,Dwarf_Die * die,const char * type)374 static void __process_list_type(struct state *state, struct die *cache,
375 				Dwarf_Die *die, const char *type)
376 {
377 	const char *name = get_name_attr(die);
378 
379 	if (stable) {
380 		if (is_kabi_prefix(name))
381 			name = NULL;
382 		state->kabi.orig_name = NULL;
383 	}
384 
385 	process_list_comma(state, cache);
386 	process(cache, type);
387 	process_type_attr(state, cache, die);
388 
389 	if (stable && state->kabi.orig_name)
390 		name = state->kabi.orig_name;
391 	if (name) {
392 		process(cache, " ");
393 		process(cache, name);
394 	}
395 
396 	process_accessibility_attr(cache, die);
397 	process_bit_size_attr(cache, die);
398 	process_data_bit_offset_attr(cache, die);
399 	process_data_member_location_attr(cache, die);
400 }
401 
402 #define DEFINE_PROCESS_LIST_TYPE(type)                                       \
403 	static void process_##type##_type(struct state *state,               \
404 					  struct die *cache, Dwarf_Die *die) \
405 	{                                                                    \
406 		__process_list_type(state, cache, die, #type " ");           \
407 	}
408 
409 DEFINE_PROCESS_LIST_TYPE(formal_parameter)
DEFINE_PROCESS_LIST_TYPE(member)410 DEFINE_PROCESS_LIST_TYPE(member)
411 
412 /* Container types with DW_AT_type */
413 static void __process_type(struct state *state, struct die *cache,
414 			   Dwarf_Die *die, const char *type)
415 {
416 	process(cache, type);
417 	process_fqn(cache, die);
418 	process(cache, " {");
419 	process_linebreak(cache, 1);
420 	process_type_attr(state, cache, die);
421 	process_linebreak(cache, -1);
422 	process(cache, "}");
423 	process_byte_size_attr(cache, die);
424 	process_alignment_attr(cache, die);
425 }
426 
427 #define DEFINE_PROCESS_TYPE(type)                                            \
428 	static void process_##type##_type(struct state *state,               \
429 					  struct die *cache, Dwarf_Die *die) \
430 	{                                                                    \
431 		__process_type(state, cache, die, #type "_type");            \
432 	}
433 
434 DEFINE_PROCESS_TYPE(atomic)
DEFINE_PROCESS_TYPE(const)435 DEFINE_PROCESS_TYPE(const)
436 DEFINE_PROCESS_TYPE(immutable)
437 DEFINE_PROCESS_TYPE(packed)
438 DEFINE_PROCESS_TYPE(pointer)
439 DEFINE_PROCESS_TYPE(reference)
440 DEFINE_PROCESS_TYPE(restrict)
441 DEFINE_PROCESS_TYPE(rvalue_reference)
442 DEFINE_PROCESS_TYPE(shared)
443 DEFINE_PROCESS_TYPE(template_type_parameter)
444 DEFINE_PROCESS_TYPE(volatile)
445 DEFINE_PROCESS_TYPE(typedef)
446 
447 static void process_subrange_type(struct state *state, struct die *cache,
448 				  Dwarf_Die *die)
449 {
450 	Dwarf_Word count = 0;
451 
452 	if (get_udata_attr(die, DW_AT_count, &count))
453 		process_fmt(cache, "[%" PRIu64 "]", count);
454 	else if (get_udata_attr(die, DW_AT_upper_bound, &count))
455 		process_fmt(cache, "[%" PRIu64 "]", count + 1);
456 	else
457 		process(cache, "[]");
458 }
459 
process_array_type(struct state * state,struct die * cache,Dwarf_Die * die)460 static void process_array_type(struct state *state, struct die *cache,
461 			       Dwarf_Die *die)
462 {
463 	process(cache, "array_type");
464 	/* Array size */
465 	check(process_die_container(state, cache, die, process_type,
466 				    match_subrange_type));
467 	process(cache, " {");
468 	process_linebreak(cache, 1);
469 	process_type_attr(state, cache, die);
470 	process_linebreak(cache, -1);
471 	process(cache, "}");
472 }
473 
__process_subroutine_type(struct state * state,struct die * cache,Dwarf_Die * die,const char * type)474 static void __process_subroutine_type(struct state *state, struct die *cache,
475 				      Dwarf_Die *die, const char *type)
476 {
477 	process(cache, type);
478 	process(cache, " (");
479 	process_linebreak(cache, 1);
480 	/* Parameters */
481 	check(process_die_container(state, cache, die, process_type,
482 				    match_formal_parameter_type));
483 	process_linebreak(cache, -1);
484 	process(cache, ")");
485 	process_linebreak(cache, 0);
486 	/* Return type */
487 	process(cache, "-> ");
488 	process_type_attr(state, cache, die);
489 }
490 
process_subroutine_type(struct state * state,struct die * cache,Dwarf_Die * die)491 static void process_subroutine_type(struct state *state, struct die *cache,
492 				    Dwarf_Die *die)
493 {
494 	__process_subroutine_type(state, cache, die, "subroutine_type");
495 }
496 
process_variant_type(struct state * state,struct die * cache,Dwarf_Die * die)497 static void process_variant_type(struct state *state, struct die *cache,
498 				 Dwarf_Die *die)
499 {
500 	process_list_comma(state, cache);
501 	process(cache, "variant {");
502 	process_linebreak(cache, 1);
503 	check(process_die_container(state, cache, die, process_type,
504 				    match_member_type));
505 	process_linebreak(cache, -1);
506 	process(cache, "}");
507 	process_discr_value_attr(cache, die);
508 }
509 
process_variant_part_type(struct state * state,struct die * cache,Dwarf_Die * die)510 static void process_variant_part_type(struct state *state, struct die *cache,
511 				      Dwarf_Die *die)
512 {
513 	process_list_comma(state, cache);
514 	process(cache, "variant_part {");
515 	process_linebreak(cache, 1);
516 	check(process_die_container(state, cache, die, process_type,
517 				    match_all));
518 	process_linebreak(cache, -1);
519 	process(cache, "}");
520 }
521 
get_kabi_status(Dwarf_Die * die,const char ** suffix)522 static int get_kabi_status(Dwarf_Die *die, const char **suffix)
523 {
524 	const char *name = get_name_attr(die);
525 
526 	if (suffix)
527 		*suffix = NULL;
528 
529 	if (is_kabi_prefix(name)) {
530 		name += KABI_PREFIX_LEN;
531 
532 		if (!strncmp(name, KABI_RESERVED_PREFIX,
533 			     KABI_RESERVED_PREFIX_LEN))
534 			return KABI_RESERVED;
535 		if (!strncmp(name, KABI_IGNORED_PREFIX,
536 			     KABI_IGNORED_PREFIX_LEN))
537 			return KABI_IGNORED;
538 
539 		if (!strncmp(name, KABI_RENAMED_PREFIX,
540 			     KABI_RENAMED_PREFIX_LEN)) {
541 			if (suffix) {
542 				name += KABI_RENAMED_PREFIX_LEN;
543 				*suffix = name;
544 			}
545 			return KABI_RESERVED;
546 		}
547 	}
548 
549 	return KABI_NORMAL;
550 }
551 
check_struct_member_kabi_status(struct state * state,struct die * __unused,Dwarf_Die * die)552 static int check_struct_member_kabi_status(struct state *state,
553 					   struct die *__unused, Dwarf_Die *die)
554 {
555 	int res;
556 
557 	assert(dwarf_tag(die) == DW_TAG_member_type);
558 
559 	/*
560 	 * If the union member is a struct, expect the __kabi field to
561 	 * be the first member of the structure, i.e..:
562 	 *
563 	 * union {
564 	 * 	type new_member;
565 	 * 	struct {
566 	 * 		type __kabi_field;
567 	 * 	}
568 	 * };
569 	 */
570 	res = get_kabi_status(die, &state->kabi.orig_name);
571 
572 	if (res == KABI_RESERVED &&
573 	    !get_ref_die_attr(die, DW_AT_type, &state->kabi.placeholder))
574 		error("structure member missing a type?");
575 
576 	return res;
577 }
578 
check_union_member_kabi_status(struct state * state,struct die * __unused,Dwarf_Die * die)579 static int check_union_member_kabi_status(struct state *state,
580 					  struct die *__unused, Dwarf_Die *die)
581 {
582 	Dwarf_Die type;
583 	int res;
584 
585 	assert(dwarf_tag(die) == DW_TAG_member_type);
586 
587 	if (!get_ref_die_attr(die, DW_AT_type, &type))
588 		error("union member missing a type?");
589 
590 	/*
591 	 * We expect a union with two members. Check if either of them
592 	 * has a __kabi name prefix, i.e.:
593 	 *
594 	 * union {
595 	 * 	...
596 	 * 	type memberN; // <- type, N = {0,1}
597 	 *	...
598 	 * };
599 	 *
600 	 * The member can also be a structure type, in which case we'll
601 	 * check the first structure member.
602 	 *
603 	 * In any case, stop processing after we've seen two members.
604 	 */
605 	res = get_kabi_status(die, &state->kabi.orig_name);
606 
607 	if (res == KABI_RESERVED)
608 		state->kabi.placeholder = type;
609 	if (res != KABI_NORMAL)
610 		return res;
611 
612 	if (dwarf_tag(&type) == DW_TAG_structure_type)
613 		res = checkp(process_die_container(
614 			state, NULL, &type, check_struct_member_kabi_status,
615 			match_member_type));
616 
617 	if (res <= KABI_NORMAL && ++state->kabi.members < 2)
618 		return 0; /* Continue */
619 
620 	return res;
621 }
622 
get_union_kabi_status(Dwarf_Die * die,Dwarf_Die * placeholder,const char ** orig_name)623 static int get_union_kabi_status(Dwarf_Die *die, Dwarf_Die *placeholder,
624 				 const char **orig_name)
625 {
626 	struct state state;
627 	int res;
628 
629 	if (!stable)
630 		return KABI_NORMAL;
631 
632 	/*
633 	 * To maintain a stable kABI, distributions may choose to reserve
634 	 * space in structs for later use by adding placeholder members,
635 	 * for example:
636 	 *
637 	 * struct s {
638 	 * 	u32 a;
639 	 *	// an 8-byte placeholder for future use
640 	 * 	u64 __kabi_reserved_0;
641 	 * };
642 	 *
643 	 * When the reserved member is taken into use, the type change
644 	 * would normally cause the symbol version to change as well, but
645 	 * if the replacement uses the following convention, gendwarfksyms
646 	 * continues to use the placeholder type for versioning instead,
647 	 * thus maintaining the same symbol version:
648 	 *
649 	 * struct s {
650 	 * 	u32 a;
651 	 *	union {
652 	 * 		// placeholder replaced with a new member `b`
653 	 * 		struct t b;
654 	 * 		struct {
655 	 * 			// the placeholder type that is still
656 	 *			// used for versioning
657 	 * 			u64 __kabi_reserved_0;
658 	 * 		};
659 	 * 	};
660 	 * };
661 	 *
662 	 * I.e., as long as the replaced member is in a union, and the
663 	 * placeholder has a __kabi_reserved name prefix, we'll continue
664 	 * to use the placeholder type (here u64) for version calculation
665 	 * instead of the union type.
666 	 *
667 	 * It's also possible to ignore new members from versioning if
668 	 * they've been added to alignment holes, for example, by
669 	 * including them in a union with another member that uses the
670 	 * __kabi_ignored name prefix:
671 	 *
672 	 * struct s {
673 	 * 	u32 a;
674 	 *	// an alignment hole is used to add `n`
675 	 * 	union {
676 	 * 		u32 n;
677 	 *		// hide the entire union member from versioning
678 	 * 		u8 __kabi_ignored_0;
679 	 * 	};
680 	 * 	u64 b;
681 	 * };
682 	 *
683 	 * Note that the user of this feature is responsible for ensuring
684 	 * that the structure actually remains ABI compatible.
685 	 */
686 	memset(&state.kabi, 0, sizeof(struct kabi_state));
687 
688 	res = checkp(process_die_container(&state, NULL, die,
689 					   check_union_member_kabi_status,
690 					   match_member_type));
691 
692 	if (res == KABI_RESERVED) {
693 		if (placeholder)
694 			*placeholder = state.kabi.placeholder;
695 		if (orig_name)
696 			*orig_name = state.kabi.orig_name;
697 	}
698 
699 	return res;
700 }
701 
is_kabi_ignored(Dwarf_Die * die)702 static bool is_kabi_ignored(Dwarf_Die *die)
703 {
704 	Dwarf_Die type;
705 
706 	if (!stable)
707 		return false;
708 
709 	if (!get_ref_die_attr(die, DW_AT_type, &type))
710 		error("member missing a type?");
711 
712 	return dwarf_tag(&type) == DW_TAG_union_type &&
713 	       checkp(get_union_kabi_status(&type, NULL, NULL)) == KABI_IGNORED;
714 }
715 
___process_structure_type(struct state * state,struct die * cache,Dwarf_Die * die)716 static int ___process_structure_type(struct state *state, struct die *cache,
717 				     Dwarf_Die *die)
718 {
719 	switch (dwarf_tag(die)) {
720 	case DW_TAG_member:
721 		if (is_kabi_ignored(die))
722 			return 0;
723 		return check(process_type(state, cache, die));
724 	case DW_TAG_variant_part:
725 		return check(process_type(state, cache, die));
726 	case DW_TAG_class_type:
727 	case DW_TAG_enumeration_type:
728 	case DW_TAG_structure_type:
729 	case DW_TAG_template_type_parameter:
730 	case DW_TAG_union_type:
731 	case DW_TAG_subprogram:
732 		/* Skip non-member types, including member functions */
733 		return 0;
734 	default:
735 		error("unexpected structure_type child: %x", dwarf_tag(die));
736 	}
737 }
738 
__process_structure_type(struct state * state,struct die * cache,Dwarf_Die * die,const char * type,die_callback_t process_func,die_match_callback_t match_func)739 static void __process_structure_type(struct state *state, struct die *cache,
740 				     Dwarf_Die *die, const char *type,
741 				     die_callback_t process_func,
742 				     die_match_callback_t match_func)
743 {
744 	bool expand;
745 
746 	process(cache, type);
747 	process_fqn(cache, die);
748 	process(cache, " {");
749 	process_linebreak(cache, 1);
750 
751 	expand = state->expand.expand && is_kabi_definition(cache, die);
752 
753 	if (expand) {
754 		state->expand.current_fqn = cache->fqn;
755 		check(process_die_container(state, cache, die, process_func,
756 					    match_func));
757 	}
758 
759 	process_linebreak(cache, -1);
760 	process(cache, "}");
761 
762 	if (expand) {
763 		process_byte_size_attr(cache, die);
764 		process_alignment_attr(cache, die);
765 	}
766 }
767 
768 #define DEFINE_PROCESS_STRUCTURE_TYPE(structure)                        \
769 	static void process_##structure##_type(                         \
770 		struct state *state, struct die *cache, Dwarf_Die *die) \
771 	{                                                               \
772 		__process_structure_type(state, cache, die,             \
773 					 #structure "_type",            \
774 					 ___process_structure_type,     \
775 					 match_all);                    \
776 	}
777 
778 DEFINE_PROCESS_STRUCTURE_TYPE(class)
DEFINE_PROCESS_STRUCTURE_TYPE(structure)779 DEFINE_PROCESS_STRUCTURE_TYPE(structure)
780 
781 static void process_union_type(struct state *state, struct die *cache,
782 			       Dwarf_Die *die)
783 {
784 	Dwarf_Die placeholder;
785 
786 	int res = checkp(get_union_kabi_status(die, &placeholder,
787 					       &state->kabi.orig_name));
788 
789 	if (res == KABI_RESERVED)
790 		check(process_type(state, cache, &placeholder));
791 	if (res > KABI_NORMAL)
792 		return;
793 
794 	__process_structure_type(state, cache, die, "union_type",
795 				 ___process_structure_type, match_all);
796 }
797 
process_enumerator_type(struct state * state,struct die * cache,Dwarf_Die * die)798 static void process_enumerator_type(struct state *state, struct die *cache,
799 				    Dwarf_Die *die)
800 {
801 	bool overridden = false;
802 	Dwarf_Word value;
803 
804 	if (stable) {
805 		/* Get the fqn before we process anything */
806 		update_fqn(cache, die);
807 
808 		if (kabi_is_enumerator_ignored(state->expand.current_fqn,
809 					       cache->fqn))
810 			return;
811 
812 		overridden = kabi_get_enumerator_value(
813 			state->expand.current_fqn, cache->fqn, &value);
814 	}
815 
816 	process_list_comma(state, cache);
817 	process(cache, "enumerator");
818 	process_fqn(cache, die);
819 
820 	if (overridden || get_udata_attr(die, DW_AT_const_value, &value)) {
821 		process(cache, " = ");
822 		process_fmt(cache, "%" PRIu64, value);
823 	}
824 }
825 
process_enumeration_type(struct state * state,struct die * cache,Dwarf_Die * die)826 static void process_enumeration_type(struct state *state, struct die *cache,
827 				     Dwarf_Die *die)
828 {
829 	__process_structure_type(state, cache, die, "enumeration_type",
830 				 process_type, match_enumerator_type);
831 }
832 
process_base_type(struct state * state,struct die * cache,Dwarf_Die * die)833 static void process_base_type(struct state *state, struct die *cache,
834 			      Dwarf_Die *die)
835 {
836 	process(cache, "base_type");
837 	process_fqn(cache, die);
838 	process_byte_size_attr(cache, die);
839 	process_encoding_attr(cache, die);
840 	process_alignment_attr(cache, die);
841 }
842 
process_unspecified_type(struct state * state,struct die * cache,Dwarf_Die * die)843 static void process_unspecified_type(struct state *state, struct die *cache,
844 				     Dwarf_Die *die)
845 {
846 	/*
847 	 * These can be emitted for stand-alone assembly code, which means we
848 	 * might run into them in vmlinux.o.
849 	 */
850 	process(cache, "unspecified_type");
851 }
852 
process_cached(struct state * state,struct die * cache,Dwarf_Die * die)853 static void process_cached(struct state *state, struct die *cache,
854 			   Dwarf_Die *die)
855 {
856 	struct die_fragment *df;
857 	Dwarf_Die child;
858 
859 	list_for_each_entry(df, &cache->fragments, list) {
860 		switch (df->type) {
861 		case FRAGMENT_STRING:
862 			die_debug_b("cache %p STRING '%s'", cache,
863 				    df->data.str);
864 			process(NULL, df->data.str);
865 			break;
866 		case FRAGMENT_LINEBREAK:
867 			process_linebreak(NULL, df->data.linebreak);
868 			break;
869 		case FRAGMENT_DIE:
870 			if (!dwarf_die_addr_die(dwarf_cu_getdwarf(die->cu),
871 						(void *)df->data.addr, &child))
872 				error("dwarf_die_addr_die failed");
873 			die_debug_b("cache %p DIE addr %" PRIxPTR " tag %x",
874 				    cache, df->data.addr, dwarf_tag(&child));
875 			check(process_type(state, NULL, &child));
876 			break;
877 		default:
878 			error("empty die_fragment");
879 		}
880 	}
881 }
882 
state_init(struct state * state)883 static void state_init(struct state *state)
884 {
885 	state->expand.expand = true;
886 	state->expand.current_fqn = NULL;
887 	cache_init(&state->expansion_cache);
888 }
889 
expansion_state_restore(struct expansion_state * state,struct expansion_state * saved)890 static void expansion_state_restore(struct expansion_state *state,
891 				    struct expansion_state *saved)
892 {
893 	state->expand = saved->expand;
894 	state->current_fqn = saved->current_fqn;
895 }
896 
expansion_state_save(struct expansion_state * state,struct expansion_state * saved)897 static void expansion_state_save(struct expansion_state *state,
898 				 struct expansion_state *saved)
899 {
900 	expansion_state_restore(saved, state);
901 }
902 
is_expanded_type(int tag)903 static bool is_expanded_type(int tag)
904 {
905 	return tag == DW_TAG_class_type || tag == DW_TAG_structure_type ||
906 	       tag == DW_TAG_union_type || tag == DW_TAG_enumeration_type;
907 }
908 
909 #define PROCESS_TYPE(type)                                \
910 	case DW_TAG_##type##_type:                        \
911 		process_##type##_type(state, cache, die); \
912 		break;
913 
process_type(struct state * state,struct die * parent,Dwarf_Die * die)914 static int process_type(struct state *state, struct die *parent, Dwarf_Die *die)
915 {
916 	enum die_state want_state = DIE_COMPLETE;
917 	struct die *cache;
918 	struct expansion_state saved;
919 	int tag = dwarf_tag(die);
920 
921 	expansion_state_save(&state->expand, &saved);
922 
923 	/*
924 	 * Structures and enumeration types are expanded only once per
925 	 * exported symbol. This is sufficient for detecting ABI changes
926 	 * within the structure.
927 	 */
928 	if (is_expanded_type(tag)) {
929 		if (cache_was_expanded(&state->expansion_cache, die->addr))
930 			state->expand.expand = false;
931 
932 		if (state->expand.expand)
933 			cache_mark_expanded(&state->expansion_cache, die->addr);
934 		else
935 			want_state = DIE_UNEXPANDED;
936 	}
937 
938 	/*
939 	 * If we have want_state already cached, use it instead of walking
940 	 * through DWARF.
941 	 */
942 	cache = die_map_get(die, want_state);
943 
944 	if (cache->state == want_state) {
945 		die_debug_g("cached addr %p tag %x -- %s", die->addr, tag,
946 			    die_state_name(cache->state));
947 
948 		process_cached(state, cache, die);
949 		die_map_add_die(parent, cache);
950 
951 		expansion_state_restore(&state->expand, &saved);
952 		return 0;
953 	}
954 
955 	die_debug_g("addr %p tag %x -- %s -> %s", die->addr, tag,
956 		    die_state_name(cache->state), die_state_name(want_state));
957 
958 	switch (tag) {
959 	/* Type modifiers */
960 	PROCESS_TYPE(atomic)
961 	PROCESS_TYPE(const)
962 	PROCESS_TYPE(immutable)
963 	PROCESS_TYPE(packed)
964 	PROCESS_TYPE(pointer)
965 	PROCESS_TYPE(reference)
966 	PROCESS_TYPE(restrict)
967 	PROCESS_TYPE(rvalue_reference)
968 	PROCESS_TYPE(shared)
969 	PROCESS_TYPE(volatile)
970 	/* Container types */
971 	PROCESS_TYPE(class)
972 	PROCESS_TYPE(structure)
973 	PROCESS_TYPE(union)
974 	PROCESS_TYPE(enumeration)
975 	/* Subtypes */
976 	PROCESS_TYPE(enumerator)
977 	PROCESS_TYPE(formal_parameter)
978 	PROCESS_TYPE(member)
979 	PROCESS_TYPE(subrange)
980 	PROCESS_TYPE(template_type_parameter)
981 	PROCESS_TYPE(variant)
982 	PROCESS_TYPE(variant_part)
983 	/* Other types */
984 	PROCESS_TYPE(array)
985 	PROCESS_TYPE(base)
986 	PROCESS_TYPE(subroutine)
987 	PROCESS_TYPE(typedef)
988 	PROCESS_TYPE(unspecified)
989 	default:
990 		error("unexpected type: %x", tag);
991 	}
992 
993 	die_debug_r("parent %p cache %p die addr %p tag %x", parent, cache,
994 		    die->addr, tag);
995 
996 	/* Update cache state and append to the parent (if any) */
997 	cache->tag = tag;
998 	cache->state = want_state;
999 	die_map_add_die(parent, cache);
1000 
1001 	expansion_state_restore(&state->expand, &saved);
1002 	return 0;
1003 }
1004 
1005 /*
1006  * Exported symbol processing
1007  */
get_symbol_cache(struct state * state,Dwarf_Die * die)1008 static struct die *get_symbol_cache(struct state *state, Dwarf_Die *die)
1009 {
1010 	struct die *cache;
1011 
1012 	cache = die_map_get(die, DIE_SYMBOL);
1013 
1014 	if (cache->state != DIE_INCOMPLETE)
1015 		return NULL; /* We already processed a symbol for this DIE */
1016 
1017 	cache->tag = dwarf_tag(die);
1018 	return cache;
1019 }
1020 
process_symbol(struct state * state,Dwarf_Die * die,die_callback_t process_func)1021 static void process_symbol(struct state *state, Dwarf_Die *die,
1022 			   die_callback_t process_func)
1023 {
1024 	struct die *cache;
1025 
1026 	symbol_set_die(state->sym, die);
1027 
1028 	cache = get_symbol_cache(state, die);
1029 	if (!cache)
1030 		return;
1031 
1032 	debug("%s", state->sym->name);
1033 	check(process_func(state, cache, die));
1034 	cache->state = DIE_SYMBOL;
1035 	if (dump_dies)
1036 		fputs("\n", stderr);
1037 }
1038 
__process_subprogram(struct state * state,struct die * cache,Dwarf_Die * die)1039 static int __process_subprogram(struct state *state, struct die *cache,
1040 				Dwarf_Die *die)
1041 {
1042 	__process_subroutine_type(state, cache, die, "subprogram");
1043 	return 0;
1044 }
1045 
process_subprogram(struct state * state,Dwarf_Die * die)1046 static void process_subprogram(struct state *state, Dwarf_Die *die)
1047 {
1048 	process_symbol(state, die, __process_subprogram);
1049 }
1050 
__process_variable(struct state * state,struct die * cache,Dwarf_Die * die)1051 static int __process_variable(struct state *state, struct die *cache,
1052 			      Dwarf_Die *die)
1053 {
1054 	process(cache, "variable ");
1055 	process_type_attr(state, cache, die);
1056 	return 0;
1057 }
1058 
process_variable(struct state * state,Dwarf_Die * die)1059 static void process_variable(struct state *state, Dwarf_Die *die)
1060 {
1061 	process_symbol(state, die, __process_variable);
1062 }
1063 
save_symbol_ptr(struct state * state)1064 static void save_symbol_ptr(struct state *state)
1065 {
1066 	Dwarf_Die ptr_type;
1067 	Dwarf_Die type;
1068 
1069 	if (!get_ref_die_attr(&state->die, DW_AT_type, &ptr_type) ||
1070 	    dwarf_tag(&ptr_type) != DW_TAG_pointer_type)
1071 		error("%s must be a pointer type!",
1072 		      get_symbol_name(&state->die));
1073 
1074 	if (!get_ref_die_attr(&ptr_type, DW_AT_type, &type))
1075 		error("%s pointer missing a type attribute?",
1076 		      get_symbol_name(&state->die));
1077 
1078 	/*
1079 	 * Save the symbol pointer DIE in case the actual symbol is
1080 	 * missing from the DWARF. Clang, for example, intentionally
1081 	 * omits external symbols from the debugging information.
1082 	 */
1083 	if (dwarf_tag(&type) == DW_TAG_subroutine_type)
1084 		symbol_set_ptr(state->sym, &type);
1085 	else
1086 		symbol_set_ptr(state->sym, &ptr_type);
1087 }
1088 
process_exported_symbols(struct state * unused,struct die * cache,Dwarf_Die * die)1089 static int process_exported_symbols(struct state *unused, struct die *cache,
1090 				    Dwarf_Die *die)
1091 {
1092 	int tag = dwarf_tag(die);
1093 
1094 	switch (tag) {
1095 	/* Possible containers of exported symbols */
1096 	case DW_TAG_namespace:
1097 	case DW_TAG_class_type:
1098 	case DW_TAG_structure_type:
1099 		return check(process_die_container(
1100 			NULL, cache, die, process_exported_symbols, match_all));
1101 
1102 	/* Possible exported symbols */
1103 	case DW_TAG_subprogram:
1104 	case DW_TAG_variable: {
1105 		struct state state;
1106 
1107 		if (!match_export_symbol(&state, die))
1108 			return 0;
1109 
1110 		state_init(&state);
1111 
1112 		if (is_symbol_ptr(get_symbol_name(&state.die)))
1113 			save_symbol_ptr(&state);
1114 		else if (tag == DW_TAG_subprogram)
1115 			process_subprogram(&state, &state.die);
1116 		else
1117 			process_variable(&state, &state.die);
1118 
1119 		cache_free(&state.expansion_cache);
1120 		return 0;
1121 	}
1122 	default:
1123 		return 0;
1124 	}
1125 }
1126 
process_symbol_ptr(struct symbol * sym,void * arg)1127 static void process_symbol_ptr(struct symbol *sym, void *arg)
1128 {
1129 	struct state state;
1130 	Dwarf *dwarf = arg;
1131 
1132 	if (sym->state != SYMBOL_UNPROCESSED || !sym->ptr_die_addr)
1133 		return;
1134 
1135 	debug("%s", sym->name);
1136 	state_init(&state);
1137 	state.sym = sym;
1138 
1139 	if (!dwarf_die_addr_die(dwarf, (void *)sym->ptr_die_addr, &state.die))
1140 		error("dwarf_die_addr_die failed for symbol ptr: '%s'",
1141 		      sym->name);
1142 
1143 	if (dwarf_tag(&state.die) == DW_TAG_subroutine_type)
1144 		process_subprogram(&state, &state.die);
1145 	else
1146 		process_variable(&state, &state.die);
1147 
1148 	cache_free(&state.expansion_cache);
1149 }
1150 
process_cu(Dwarf_Die * cudie)1151 void process_cu(Dwarf_Die *cudie)
1152 {
1153 	check(process_die_container(NULL, NULL, cudie, process_exported_symbols,
1154 				    match_all));
1155 
1156 	symbol_for_each(process_symbol_ptr, dwarf_cu_getdwarf(cudie->cu));
1157 
1158 	cache_free(&srcfile_cache);
1159 }
1160