xref: /openbmc/linux/scripts/kallsyms.c (revision 3a83e4e6)
1 /* Generate assembler source containing symbol information
2  *
3  * Copyright 2002       by Kai Germaschewski
4  *
5  * This software may be used and distributed according to the terms
6  * of the GNU General Public License, incorporated herein by reference.
7  *
8  * Usage: nm -n vmlinux | scripts/kallsyms [--all-symbols] > symbols.S
9  *
10  *      Table compression uses all the unused char codes on the symbols and
11  *  maps these to the most used substrings (tokens). For instance, it might
12  *  map char code 0xF7 to represent "write_" and then in every symbol where
13  *  "write_" appears it can be replaced by 0xF7, saving 5 bytes.
14  *      The used codes themselves are also placed in the table so that the
15  *  decompresion can work without "special cases".
16  *      Applied to kernel symbols, this usually produces a compression ratio
17  *  of about 50%.
18  *
19  */
20 
21 #include <stdbool.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <limits.h>
27 
28 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
29 
30 #define KSYM_NAME_LEN		128
31 
32 struct sym_entry {
33 	unsigned long long addr;
34 	unsigned int len;
35 	unsigned int start_pos;
36 	unsigned int percpu_absolute;
37 	unsigned char sym[];
38 };
39 
40 struct addr_range {
41 	const char *start_sym, *end_sym;
42 	unsigned long long start, end;
43 };
44 
45 static unsigned long long _text;
46 static unsigned long long relative_base;
47 static struct addr_range text_ranges[] = {
48 	{ "_stext",     "_etext"     },
49 	{ "_sinittext", "_einittext" },
50 };
51 #define text_range_text     (&text_ranges[0])
52 #define text_range_inittext (&text_ranges[1])
53 
54 static struct addr_range percpu_range = {
55 	"__per_cpu_start", "__per_cpu_end", -1ULL, 0
56 };
57 
58 static struct sym_entry **table;
59 static unsigned int table_size, table_cnt;
60 static int all_symbols;
61 static int absolute_percpu;
62 static int base_relative;
63 
64 static int token_profit[0x10000];
65 
66 /* the table that holds the result of the compression */
67 static unsigned char best_table[256][2];
68 static unsigned char best_table_len[256];
69 
70 
71 static void usage(void)
72 {
73 	fprintf(stderr, "Usage: kallsyms [--all-symbols] "
74 			"[--base-relative] < in.map > out.S\n");
75 	exit(1);
76 }
77 
78 static char *sym_name(const struct sym_entry *s)
79 {
80 	return (char *)s->sym + 1;
81 }
82 
83 static bool is_ignored_symbol(const char *name, char type)
84 {
85 	static const char * const ignored_symbols[] = {
86 		/*
87 		 * Symbols which vary between passes. Passes 1 and 2 must have
88 		 * identical symbol lists. The kallsyms_* symbols below are
89 		 * only added after pass 1, they would be included in pass 2
90 		 * when --all-symbols is specified so exclude them to get a
91 		 * stable symbol list.
92 		 */
93 		"kallsyms_addresses",
94 		"kallsyms_offsets",
95 		"kallsyms_relative_base",
96 		"kallsyms_num_syms",
97 		"kallsyms_names",
98 		"kallsyms_markers",
99 		"kallsyms_token_table",
100 		"kallsyms_token_index",
101 		/* Exclude linker generated symbols which vary between passes */
102 		"_SDA_BASE_",		/* ppc */
103 		"_SDA2_BASE_",		/* ppc */
104 		NULL
105 	};
106 
107 	static const char * const ignored_prefixes[] = {
108 		"$",			/* local symbols for ARM, MIPS, etc. */
109 		".LASANPC",		/* s390 kasan local symbols */
110 		"__crc_",		/* modversions */
111 		"__efistub_",		/* arm64 EFI stub namespace */
112 		"__kvm_nvhe_",		/* arm64 non-VHE KVM namespace */
113 		NULL
114 	};
115 
116 	static const char * const ignored_suffixes[] = {
117 		"_from_arm",		/* arm */
118 		"_from_thumb",		/* arm */
119 		"_veneer",		/* arm */
120 		NULL
121 	};
122 
123 	const char * const *p;
124 
125 	/* Exclude symbols which vary between passes. */
126 	for (p = ignored_symbols; *p; p++)
127 		if (!strcmp(name, *p))
128 			return true;
129 
130 	for (p = ignored_prefixes; *p; p++)
131 		if (!strncmp(name, *p, strlen(*p)))
132 			return true;
133 
134 	for (p = ignored_suffixes; *p; p++) {
135 		int l = strlen(name) - strlen(*p);
136 
137 		if (l >= 0 && !strcmp(name + l, *p))
138 			return true;
139 	}
140 
141 	if (type == 'U' || type == 'u')
142 		return true;
143 	/* exclude debugging symbols */
144 	if (type == 'N' || type == 'n')
145 		return true;
146 
147 	if (toupper(type) == 'A') {
148 		/* Keep these useful absolute symbols */
149 		if (strcmp(name, "__kernel_syscall_via_break") &&
150 		    strcmp(name, "__kernel_syscall_via_epc") &&
151 		    strcmp(name, "__kernel_sigtramp") &&
152 		    strcmp(name, "__gp"))
153 			return true;
154 	}
155 
156 	return false;
157 }
158 
159 static void check_symbol_range(const char *sym, unsigned long long addr,
160 			       struct addr_range *ranges, int entries)
161 {
162 	size_t i;
163 	struct addr_range *ar;
164 
165 	for (i = 0; i < entries; ++i) {
166 		ar = &ranges[i];
167 
168 		if (strcmp(sym, ar->start_sym) == 0) {
169 			ar->start = addr;
170 			return;
171 		} else if (strcmp(sym, ar->end_sym) == 0) {
172 			ar->end = addr;
173 			return;
174 		}
175 	}
176 }
177 
178 static struct sym_entry *read_symbol(FILE *in)
179 {
180 	char name[500], type;
181 	unsigned long long addr;
182 	unsigned int len;
183 	struct sym_entry *sym;
184 	int rc;
185 
186 	rc = fscanf(in, "%llx %c %499s\n", &addr, &type, name);
187 	if (rc != 3) {
188 		if (rc != EOF && fgets(name, 500, in) == NULL)
189 			fprintf(stderr, "Read error or end of file.\n");
190 		return NULL;
191 	}
192 	if (strlen(name) >= KSYM_NAME_LEN) {
193 		fprintf(stderr, "Symbol %s too long for kallsyms (%zu >= %d).\n"
194 				"Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n",
195 			name, strlen(name), KSYM_NAME_LEN);
196 		return NULL;
197 	}
198 
199 	if (strcmp(name, "_text") == 0)
200 		_text = addr;
201 
202 	/* Ignore most absolute/undefined (?) symbols. */
203 	if (is_ignored_symbol(name, type))
204 		return NULL;
205 
206 	check_symbol_range(name, addr, text_ranges, ARRAY_SIZE(text_ranges));
207 	check_symbol_range(name, addr, &percpu_range, 1);
208 
209 	/* include the type field in the symbol name, so that it gets
210 	 * compressed together */
211 
212 	len = strlen(name) + 1;
213 
214 	sym = malloc(sizeof(*sym) + len + 1);
215 	if (!sym) {
216 		fprintf(stderr, "kallsyms failure: "
217 			"unable to allocate required amount of memory\n");
218 		exit(EXIT_FAILURE);
219 	}
220 	sym->addr = addr;
221 	sym->len = len;
222 	sym->sym[0] = type;
223 	strcpy(sym_name(sym), name);
224 	sym->percpu_absolute = 0;
225 
226 	return sym;
227 }
228 
229 static int symbol_in_range(const struct sym_entry *s,
230 			   const struct addr_range *ranges, int entries)
231 {
232 	size_t i;
233 	const struct addr_range *ar;
234 
235 	for (i = 0; i < entries; ++i) {
236 		ar = &ranges[i];
237 
238 		if (s->addr >= ar->start && s->addr <= ar->end)
239 			return 1;
240 	}
241 
242 	return 0;
243 }
244 
245 static int symbol_valid(const struct sym_entry *s)
246 {
247 	const char *name = sym_name(s);
248 
249 	/* if --all-symbols is not specified, then symbols outside the text
250 	 * and inittext sections are discarded */
251 	if (!all_symbols) {
252 		if (symbol_in_range(s, text_ranges,
253 				    ARRAY_SIZE(text_ranges)) == 0)
254 			return 0;
255 		/* Corner case.  Discard any symbols with the same value as
256 		 * _etext _einittext; they can move between pass 1 and 2 when
257 		 * the kallsyms data are added.  If these symbols move then
258 		 * they may get dropped in pass 2, which breaks the kallsyms
259 		 * rules.
260 		 */
261 		if ((s->addr == text_range_text->end &&
262 		     strcmp(name, text_range_text->end_sym)) ||
263 		    (s->addr == text_range_inittext->end &&
264 		     strcmp(name, text_range_inittext->end_sym)))
265 			return 0;
266 	}
267 
268 	return 1;
269 }
270 
271 /* remove all the invalid symbols from the table */
272 static void shrink_table(void)
273 {
274 	unsigned int i, pos;
275 
276 	pos = 0;
277 	for (i = 0; i < table_cnt; i++) {
278 		if (symbol_valid(table[i])) {
279 			if (pos != i)
280 				table[pos] = table[i];
281 			pos++;
282 		} else {
283 			free(table[i]);
284 		}
285 	}
286 	table_cnt = pos;
287 
288 	/* When valid symbol is not registered, exit to error */
289 	if (!table_cnt) {
290 		fprintf(stderr, "No valid symbol.\n");
291 		exit(1);
292 	}
293 }
294 
295 static void read_map(FILE *in)
296 {
297 	struct sym_entry *sym;
298 
299 	while (!feof(in)) {
300 		sym = read_symbol(in);
301 		if (!sym)
302 			continue;
303 
304 		sym->start_pos = table_cnt;
305 
306 		if (table_cnt >= table_size) {
307 			table_size += 10000;
308 			table = realloc(table, sizeof(*table) * table_size);
309 			if (!table) {
310 				fprintf(stderr, "out of memory\n");
311 				exit (1);
312 			}
313 		}
314 
315 		table[table_cnt++] = sym;
316 	}
317 }
318 
319 static void output_label(const char *label)
320 {
321 	printf(".globl %s\n", label);
322 	printf("\tALGN\n");
323 	printf("%s:\n", label);
324 }
325 
326 /* Provide proper symbols relocatability by their '_text' relativeness. */
327 static void output_address(unsigned long long addr)
328 {
329 	if (_text <= addr)
330 		printf("\tPTR\t_text + %#llx\n", addr - _text);
331 	else
332 		printf("\tPTR\t_text - %#llx\n", _text - addr);
333 }
334 
335 /* uncompress a compressed symbol. When this function is called, the best table
336  * might still be compressed itself, so the function needs to be recursive */
337 static int expand_symbol(const unsigned char *data, int len, char *result)
338 {
339 	int c, rlen, total=0;
340 
341 	while (len) {
342 		c = *data;
343 		/* if the table holds a single char that is the same as the one
344 		 * we are looking for, then end the search */
345 		if (best_table[c][0]==c && best_table_len[c]==1) {
346 			*result++ = c;
347 			total++;
348 		} else {
349 			/* if not, recurse and expand */
350 			rlen = expand_symbol(best_table[c], best_table_len[c], result);
351 			total += rlen;
352 			result += rlen;
353 		}
354 		data++;
355 		len--;
356 	}
357 	*result=0;
358 
359 	return total;
360 }
361 
362 static int symbol_absolute(const struct sym_entry *s)
363 {
364 	return s->percpu_absolute;
365 }
366 
367 static void write_src(void)
368 {
369 	unsigned int i, k, off;
370 	unsigned int best_idx[256];
371 	unsigned int *markers;
372 	char buf[KSYM_NAME_LEN];
373 
374 	printf("#include <asm/bitsperlong.h>\n");
375 	printf("#if BITS_PER_LONG == 64\n");
376 	printf("#define PTR .quad\n");
377 	printf("#define ALGN .balign 8\n");
378 	printf("#else\n");
379 	printf("#define PTR .long\n");
380 	printf("#define ALGN .balign 4\n");
381 	printf("#endif\n");
382 
383 	printf("\t.section .rodata, \"a\"\n");
384 
385 	if (!base_relative)
386 		output_label("kallsyms_addresses");
387 	else
388 		output_label("kallsyms_offsets");
389 
390 	for (i = 0; i < table_cnt; i++) {
391 		if (base_relative) {
392 			/*
393 			 * Use the offset relative to the lowest value
394 			 * encountered of all relative symbols, and emit
395 			 * non-relocatable fixed offsets that will be fixed
396 			 * up at runtime.
397 			 */
398 
399 			long long offset;
400 			int overflow;
401 
402 			if (!absolute_percpu) {
403 				offset = table[i]->addr - relative_base;
404 				overflow = (offset < 0 || offset > UINT_MAX);
405 			} else if (symbol_absolute(table[i])) {
406 				offset = table[i]->addr;
407 				overflow = (offset < 0 || offset > INT_MAX);
408 			} else {
409 				offset = relative_base - table[i]->addr - 1;
410 				overflow = (offset < INT_MIN || offset >= 0);
411 			}
412 			if (overflow) {
413 				fprintf(stderr, "kallsyms failure: "
414 					"%s symbol value %#llx out of range in relative mode\n",
415 					symbol_absolute(table[i]) ? "absolute" : "relative",
416 					table[i]->addr);
417 				exit(EXIT_FAILURE);
418 			}
419 			printf("\t.long\t%#x\n", (int)offset);
420 		} else if (!symbol_absolute(table[i])) {
421 			output_address(table[i]->addr);
422 		} else {
423 			printf("\tPTR\t%#llx\n", table[i]->addr);
424 		}
425 	}
426 	printf("\n");
427 
428 	if (base_relative) {
429 		output_label("kallsyms_relative_base");
430 		output_address(relative_base);
431 		printf("\n");
432 	}
433 
434 	output_label("kallsyms_num_syms");
435 	printf("\t.long\t%u\n", table_cnt);
436 	printf("\n");
437 
438 	/* table of offset markers, that give the offset in the compressed stream
439 	 * every 256 symbols */
440 	markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
441 	if (!markers) {
442 		fprintf(stderr, "kallsyms failure: "
443 			"unable to allocate required memory\n");
444 		exit(EXIT_FAILURE);
445 	}
446 
447 	output_label("kallsyms_names");
448 	off = 0;
449 	for (i = 0; i < table_cnt; i++) {
450 		if ((i & 0xFF) == 0)
451 			markers[i >> 8] = off;
452 
453 		printf("\t.byte 0x%02x", table[i]->len);
454 		for (k = 0; k < table[i]->len; k++)
455 			printf(", 0x%02x", table[i]->sym[k]);
456 		printf("\n");
457 
458 		off += table[i]->len + 1;
459 	}
460 	printf("\n");
461 
462 	output_label("kallsyms_markers");
463 	for (i = 0; i < ((table_cnt + 255) >> 8); i++)
464 		printf("\t.long\t%u\n", markers[i]);
465 	printf("\n");
466 
467 	free(markers);
468 
469 	output_label("kallsyms_token_table");
470 	off = 0;
471 	for (i = 0; i < 256; i++) {
472 		best_idx[i] = off;
473 		expand_symbol(best_table[i], best_table_len[i], buf);
474 		printf("\t.asciz\t\"%s\"\n", buf);
475 		off += strlen(buf) + 1;
476 	}
477 	printf("\n");
478 
479 	output_label("kallsyms_token_index");
480 	for (i = 0; i < 256; i++)
481 		printf("\t.short\t%d\n", best_idx[i]);
482 	printf("\n");
483 }
484 
485 
486 /* table lookup compression functions */
487 
488 /* count all the possible tokens in a symbol */
489 static void learn_symbol(const unsigned char *symbol, int len)
490 {
491 	int i;
492 
493 	for (i = 0; i < len - 1; i++)
494 		token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
495 }
496 
497 /* decrease the count for all the possible tokens in a symbol */
498 static void forget_symbol(const unsigned char *symbol, int len)
499 {
500 	int i;
501 
502 	for (i = 0; i < len - 1; i++)
503 		token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
504 }
505 
506 /* do the initial token count */
507 static void build_initial_tok_table(void)
508 {
509 	unsigned int i;
510 
511 	for (i = 0; i < table_cnt; i++)
512 		learn_symbol(table[i]->sym, table[i]->len);
513 }
514 
515 static unsigned char *find_token(unsigned char *str, int len,
516 				 const unsigned char *token)
517 {
518 	int i;
519 
520 	for (i = 0; i < len - 1; i++) {
521 		if (str[i] == token[0] && str[i+1] == token[1])
522 			return &str[i];
523 	}
524 	return NULL;
525 }
526 
527 /* replace a given token in all the valid symbols. Use the sampled symbols
528  * to update the counts */
529 static void compress_symbols(const unsigned char *str, int idx)
530 {
531 	unsigned int i, len, size;
532 	unsigned char *p1, *p2;
533 
534 	for (i = 0; i < table_cnt; i++) {
535 
536 		len = table[i]->len;
537 		p1 = table[i]->sym;
538 
539 		/* find the token on the symbol */
540 		p2 = find_token(p1, len, str);
541 		if (!p2) continue;
542 
543 		/* decrease the counts for this symbol's tokens */
544 		forget_symbol(table[i]->sym, len);
545 
546 		size = len;
547 
548 		do {
549 			*p2 = idx;
550 			p2++;
551 			size -= (p2 - p1);
552 			memmove(p2, p2 + 1, size);
553 			p1 = p2;
554 			len--;
555 
556 			if (size < 2) break;
557 
558 			/* find the token on the symbol */
559 			p2 = find_token(p1, size, str);
560 
561 		} while (p2);
562 
563 		table[i]->len = len;
564 
565 		/* increase the counts for this symbol's new tokens */
566 		learn_symbol(table[i]->sym, len);
567 	}
568 }
569 
570 /* search the token with the maximum profit */
571 static int find_best_token(void)
572 {
573 	int i, best, bestprofit;
574 
575 	bestprofit=-10000;
576 	best = 0;
577 
578 	for (i = 0; i < 0x10000; i++) {
579 		if (token_profit[i] > bestprofit) {
580 			best = i;
581 			bestprofit = token_profit[i];
582 		}
583 	}
584 	return best;
585 }
586 
587 /* this is the core of the algorithm: calculate the "best" table */
588 static void optimize_result(void)
589 {
590 	int i, best;
591 
592 	/* using the '\0' symbol last allows compress_symbols to use standard
593 	 * fast string functions */
594 	for (i = 255; i >= 0; i--) {
595 
596 		/* if this table slot is empty (it is not used by an actual
597 		 * original char code */
598 		if (!best_table_len[i]) {
599 
600 			/* find the token with the best profit value */
601 			best = find_best_token();
602 			if (token_profit[best] == 0)
603 				break;
604 
605 			/* place it in the "best" table */
606 			best_table_len[i] = 2;
607 			best_table[i][0] = best & 0xFF;
608 			best_table[i][1] = (best >> 8) & 0xFF;
609 
610 			/* replace this token in all the valid symbols */
611 			compress_symbols(best_table[i], i);
612 		}
613 	}
614 }
615 
616 /* start by placing the symbols that are actually used on the table */
617 static void insert_real_symbols_in_table(void)
618 {
619 	unsigned int i, j, c;
620 
621 	for (i = 0; i < table_cnt; i++) {
622 		for (j = 0; j < table[i]->len; j++) {
623 			c = table[i]->sym[j];
624 			best_table[c][0]=c;
625 			best_table_len[c]=1;
626 		}
627 	}
628 }
629 
630 static void optimize_token_table(void)
631 {
632 	build_initial_tok_table();
633 
634 	insert_real_symbols_in_table();
635 
636 	optimize_result();
637 }
638 
639 /* guess for "linker script provide" symbol */
640 static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
641 {
642 	const char *symbol = sym_name(se);
643 	int len = se->len - 1;
644 
645 	if (len < 8)
646 		return 0;
647 
648 	if (symbol[0] != '_' || symbol[1] != '_')
649 		return 0;
650 
651 	/* __start_XXXXX */
652 	if (!memcmp(symbol + 2, "start_", 6))
653 		return 1;
654 
655 	/* __stop_XXXXX */
656 	if (!memcmp(symbol + 2, "stop_", 5))
657 		return 1;
658 
659 	/* __end_XXXXX */
660 	if (!memcmp(symbol + 2, "end_", 4))
661 		return 1;
662 
663 	/* __XXXXX_start */
664 	if (!memcmp(symbol + len - 6, "_start", 6))
665 		return 1;
666 
667 	/* __XXXXX_end */
668 	if (!memcmp(symbol + len - 4, "_end", 4))
669 		return 1;
670 
671 	return 0;
672 }
673 
674 static int compare_symbols(const void *a, const void *b)
675 {
676 	const struct sym_entry *sa = *(const struct sym_entry **)a;
677 	const struct sym_entry *sb = *(const struct sym_entry **)b;
678 	int wa, wb;
679 
680 	/* sort by address first */
681 	if (sa->addr > sb->addr)
682 		return 1;
683 	if (sa->addr < sb->addr)
684 		return -1;
685 
686 	/* sort by "weakness" type */
687 	wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
688 	wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
689 	if (wa != wb)
690 		return wa - wb;
691 
692 	/* sort by "linker script provide" type */
693 	wa = may_be_linker_script_provide_symbol(sa);
694 	wb = may_be_linker_script_provide_symbol(sb);
695 	if (wa != wb)
696 		return wa - wb;
697 
698 	/* sort by the number of prefix underscores */
699 	wa = strspn(sym_name(sa), "_");
700 	wb = strspn(sym_name(sb), "_");
701 	if (wa != wb)
702 		return wa - wb;
703 
704 	/* sort by initial order, so that other symbols are left undisturbed */
705 	return sa->start_pos - sb->start_pos;
706 }
707 
708 static void sort_symbols(void)
709 {
710 	qsort(table, table_cnt, sizeof(table[0]), compare_symbols);
711 }
712 
713 static void make_percpus_absolute(void)
714 {
715 	unsigned int i;
716 
717 	for (i = 0; i < table_cnt; i++)
718 		if (symbol_in_range(table[i], &percpu_range, 1)) {
719 			/*
720 			 * Keep the 'A' override for percpu symbols to
721 			 * ensure consistent behavior compared to older
722 			 * versions of this tool.
723 			 */
724 			table[i]->sym[0] = 'A';
725 			table[i]->percpu_absolute = 1;
726 		}
727 }
728 
729 /* find the minimum non-absolute symbol address */
730 static void record_relative_base(void)
731 {
732 	unsigned int i;
733 
734 	for (i = 0; i < table_cnt; i++)
735 		if (!symbol_absolute(table[i])) {
736 			/*
737 			 * The table is sorted by address.
738 			 * Take the first non-absolute symbol value.
739 			 */
740 			relative_base = table[i]->addr;
741 			return;
742 		}
743 }
744 
745 int main(int argc, char **argv)
746 {
747 	if (argc >= 2) {
748 		int i;
749 		for (i = 1; i < argc; i++) {
750 			if(strcmp(argv[i], "--all-symbols") == 0)
751 				all_symbols = 1;
752 			else if (strcmp(argv[i], "--absolute-percpu") == 0)
753 				absolute_percpu = 1;
754 			else if (strcmp(argv[i], "--base-relative") == 0)
755 				base_relative = 1;
756 			else
757 				usage();
758 		}
759 	} else if (argc != 1)
760 		usage();
761 
762 	read_map(stdin);
763 	shrink_table();
764 	if (absolute_percpu)
765 		make_percpus_absolute();
766 	sort_symbols();
767 	if (base_relative)
768 		record_relative_base();
769 	optimize_token_table();
770 	write_src();
771 
772 	return 0;
773 }
774