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