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