1 /* Generate assembler source containing symbol information
3 * Copyright 2002 by Kai Germaschewski
5 * This software may be used and distributed according to the terms
6 * of the GNU General Public License, incorporated herein by reference.
8 * Usage: nm -n vmlinux | scripts/kallsyms [--all-symbols] > symbols.S
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
28 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
30 #define KSYM_NAME_LEN 128
33 unsigned long long addr;
35 unsigned int start_pos;
36 unsigned int percpu_absolute;
41 const char *start_sym, *end_sym;
42 unsigned long long start, end;
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" },
51 #define text_range_text (&text_ranges[0])
52 #define text_range_inittext (&text_ranges[1])
54 static struct addr_range percpu_range = {
55 "__per_cpu_start", "__per_cpu_end", -1ULL, 0
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;
64 static int token_profit[0x10000];
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];
71 static void usage(void)
73 fprintf(stderr, "Usage: kallsyms [--all-symbols] "
74 "[--base-relative] < in.map > out.S\n");
78 static char *sym_name(const struct sym_entry *s)
80 return (char *)s->sym + 1;
83 static bool is_ignored_symbol(const char *name, char type)
85 /* Symbol names that exactly match to the following are ignored.*/
86 static const char * const ignored_symbols[] = {
88 * Symbols which vary between passes. Passes 1 and 2 must have
89 * identical symbol lists. The kallsyms_* symbols below are
90 * only added after pass 1, they would be included in pass 2
91 * when --all-symbols is specified so exclude them to get a
96 "kallsyms_relative_base",
100 "kallsyms_token_table",
101 "kallsyms_token_index",
102 /* Exclude linker generated symbols which vary between passes */
103 "_SDA_BASE_", /* ppc */
104 "_SDA2_BASE_", /* ppc */
108 /* Symbol names that begin with the following are ignored.*/
109 static const char * const ignored_prefixes[] = {
110 "$", /* local symbols for ARM, MIPS, etc. */
111 ".LASANPC", /* s390 kasan local symbols */
112 "__crc_", /* modversions */
113 "__efistub_", /* arm64 EFI stub namespace */
114 "__kvm_nvhe_", /* arm64 non-VHE KVM namespace */
115 "__AArch64ADRPThunk_", /* arm64 lld */
116 "__ARMV5PILongThunk_", /* arm lld */
117 "__ARMV7PILongThunk_",
118 "__ThumbV7PILongThunk_",
119 "__LA25Thunk_", /* mips lld */
124 /* Symbol names that end with the following are ignored.*/
125 static const char * const ignored_suffixes[] = {
126 "_from_arm", /* arm */
127 "_from_thumb", /* arm */
132 /* Symbol names that contain the following are ignored.*/
133 static const char * const ignored_matches[] = {
134 ".long_branch.", /* ppc stub */
135 ".plt_branch.", /* ppc stub */
139 const char * const *p;
141 for (p = ignored_symbols; *p; p++)
142 if (!strcmp(name, *p))
145 for (p = ignored_prefixes; *p; p++)
146 if (!strncmp(name, *p, strlen(*p)))
149 for (p = ignored_suffixes; *p; p++) {
150 int l = strlen(name) - strlen(*p);
152 if (l >= 0 && !strcmp(name + l, *p))
156 for (p = ignored_matches; *p; p++) {
157 if (strstr(name, *p))
161 if (type == 'U' || type == 'u')
163 /* exclude debugging symbols */
164 if (type == 'N' || type == 'n')
167 if (toupper(type) == 'A') {
168 /* Keep these useful absolute symbols */
169 if (strcmp(name, "__kernel_syscall_via_break") &&
170 strcmp(name, "__kernel_syscall_via_epc") &&
171 strcmp(name, "__kernel_sigtramp") &&
172 strcmp(name, "__gp"))
179 static void check_symbol_range(const char *sym, unsigned long long addr,
180 struct addr_range *ranges, int entries)
183 struct addr_range *ar;
185 for (i = 0; i < entries; ++i) {
188 if (strcmp(sym, ar->start_sym) == 0) {
191 } else if (strcmp(sym, ar->end_sym) == 0) {
198 static struct sym_entry *read_symbol(FILE *in)
200 char name[500], type;
201 unsigned long long addr;
203 struct sym_entry *sym;
206 rc = fscanf(in, "%llx %c %499s\n", &addr, &type, name);
208 if (rc != EOF && fgets(name, 500, in) == NULL)
209 fprintf(stderr, "Read error or end of file.\n");
212 if (strlen(name) >= KSYM_NAME_LEN) {
213 fprintf(stderr, "Symbol %s too long for kallsyms (%zu >= %d).\n"
214 "Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n",
215 name, strlen(name), KSYM_NAME_LEN);
219 if (strcmp(name, "_text") == 0)
222 /* Ignore most absolute/undefined (?) symbols. */
223 if (is_ignored_symbol(name, type))
226 check_symbol_range(name, addr, text_ranges, ARRAY_SIZE(text_ranges));
227 check_symbol_range(name, addr, &percpu_range, 1);
229 /* include the type field in the symbol name, so that it gets
230 * compressed together */
232 len = strlen(name) + 1;
234 sym = malloc(sizeof(*sym) + len + 1);
236 fprintf(stderr, "kallsyms failure: "
237 "unable to allocate required amount of memory\n");
243 strcpy(sym_name(sym), name);
244 sym->percpu_absolute = 0;
249 static int symbol_in_range(const struct sym_entry *s,
250 const struct addr_range *ranges, int entries)
253 const struct addr_range *ar;
255 for (i = 0; i < entries; ++i) {
258 if (s->addr >= ar->start && s->addr <= ar->end)
265 static int symbol_valid(const struct sym_entry *s)
267 const char *name = sym_name(s);
269 /* if --all-symbols is not specified, then symbols outside the text
270 * and inittext sections are discarded */
272 if (symbol_in_range(s, text_ranges,
273 ARRAY_SIZE(text_ranges)) == 0)
275 /* Corner case. Discard any symbols with the same value as
276 * _etext _einittext; they can move between pass 1 and 2 when
277 * the kallsyms data are added. If these symbols move then
278 * they may get dropped in pass 2, which breaks the kallsyms
281 if ((s->addr == text_range_text->end &&
282 strcmp(name, text_range_text->end_sym)) ||
283 (s->addr == text_range_inittext->end &&
284 strcmp(name, text_range_inittext->end_sym)))
291 /* remove all the invalid symbols from the table */
292 static void shrink_table(void)
297 for (i = 0; i < table_cnt; i++) {
298 if (symbol_valid(table[i])) {
300 table[pos] = table[i];
308 /* When valid symbol is not registered, exit to error */
310 fprintf(stderr, "No valid symbol.\n");
315 static void read_map(FILE *in)
317 struct sym_entry *sym;
320 sym = read_symbol(in);
324 sym->start_pos = table_cnt;
326 if (table_cnt >= table_size) {
328 table = realloc(table, sizeof(*table) * table_size);
330 fprintf(stderr, "out of memory\n");
335 table[table_cnt++] = sym;
339 static void output_label(const char *label)
341 printf(".globl %s\n", label);
343 printf("%s:\n", label);
346 /* Provide proper symbols relocatability by their '_text' relativeness. */
347 static void output_address(unsigned long long addr)
350 printf("\tPTR\t_text + %#llx\n", addr - _text);
352 printf("\tPTR\t_text - %#llx\n", _text - addr);
355 /* uncompress a compressed symbol. When this function is called, the best table
356 * might still be compressed itself, so the function needs to be recursive */
357 static int expand_symbol(const unsigned char *data, int len, char *result)
359 int c, rlen, total=0;
363 /* if the table holds a single char that is the same as the one
364 * we are looking for, then end the search */
365 if (best_table[c][0]==c && best_table_len[c]==1) {
369 /* if not, recurse and expand */
370 rlen = expand_symbol(best_table[c], best_table_len[c], result);
382 static int symbol_absolute(const struct sym_entry *s)
384 return s->percpu_absolute;
387 static void write_src(void)
389 unsigned int i, k, off;
390 unsigned int best_idx[256];
391 unsigned int *markers;
392 char buf[KSYM_NAME_LEN];
394 printf("#include <asm/bitsperlong.h>\n");
395 printf("#if BITS_PER_LONG == 64\n");
396 printf("#define PTR .quad\n");
397 printf("#define ALGN .balign 8\n");
399 printf("#define PTR .long\n");
400 printf("#define ALGN .balign 4\n");
403 printf("\t.section .rodata, \"a\"\n");
406 output_label("kallsyms_addresses");
408 output_label("kallsyms_offsets");
410 for (i = 0; i < table_cnt; i++) {
413 * Use the offset relative to the lowest value
414 * encountered of all relative symbols, and emit
415 * non-relocatable fixed offsets that will be fixed
422 if (!absolute_percpu) {
423 offset = table[i]->addr - relative_base;
424 overflow = (offset < 0 || offset > UINT_MAX);
425 } else if (symbol_absolute(table[i])) {
426 offset = table[i]->addr;
427 overflow = (offset < 0 || offset > INT_MAX);
429 offset = relative_base - table[i]->addr - 1;
430 overflow = (offset < INT_MIN || offset >= 0);
433 fprintf(stderr, "kallsyms failure: "
434 "%s symbol value %#llx out of range in relative mode\n",
435 symbol_absolute(table[i]) ? "absolute" : "relative",
439 printf("\t.long\t%#x\n", (int)offset);
440 } else if (!symbol_absolute(table[i])) {
441 output_address(table[i]->addr);
443 printf("\tPTR\t%#llx\n", table[i]->addr);
449 output_label("kallsyms_relative_base");
450 output_address(relative_base);
454 output_label("kallsyms_num_syms");
455 printf("\t.long\t%u\n", table_cnt);
458 /* table of offset markers, that give the offset in the compressed stream
459 * every 256 symbols */
460 markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
462 fprintf(stderr, "kallsyms failure: "
463 "unable to allocate required memory\n");
467 output_label("kallsyms_names");
469 for (i = 0; i < table_cnt; i++) {
471 markers[i >> 8] = off;
473 printf("\t.byte 0x%02x", table[i]->len);
474 for (k = 0; k < table[i]->len; k++)
475 printf(", 0x%02x", table[i]->sym[k]);
478 off += table[i]->len + 1;
482 output_label("kallsyms_markers");
483 for (i = 0; i < ((table_cnt + 255) >> 8); i++)
484 printf("\t.long\t%u\n", markers[i]);
489 output_label("kallsyms_token_table");
491 for (i = 0; i < 256; i++) {
493 expand_symbol(best_table[i], best_table_len[i], buf);
494 printf("\t.asciz\t\"%s\"\n", buf);
495 off += strlen(buf) + 1;
499 output_label("kallsyms_token_index");
500 for (i = 0; i < 256; i++)
501 printf("\t.short\t%d\n", best_idx[i]);
506 /* table lookup compression functions */
508 /* count all the possible tokens in a symbol */
509 static void learn_symbol(const unsigned char *symbol, int len)
513 for (i = 0; i < len - 1; i++)
514 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
517 /* decrease the count for all the possible tokens in a symbol */
518 static void forget_symbol(const unsigned char *symbol, int len)
522 for (i = 0; i < len - 1; i++)
523 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
526 /* do the initial token count */
527 static void build_initial_tok_table(void)
531 for (i = 0; i < table_cnt; i++)
532 learn_symbol(table[i]->sym, table[i]->len);
535 static unsigned char *find_token(unsigned char *str, int len,
536 const unsigned char *token)
540 for (i = 0; i < len - 1; i++) {
541 if (str[i] == token[0] && str[i+1] == token[1])
547 /* replace a given token in all the valid symbols. Use the sampled symbols
548 * to update the counts */
549 static void compress_symbols(const unsigned char *str, int idx)
551 unsigned int i, len, size;
552 unsigned char *p1, *p2;
554 for (i = 0; i < table_cnt; i++) {
559 /* find the token on the symbol */
560 p2 = find_token(p1, len, str);
563 /* decrease the counts for this symbol's tokens */
564 forget_symbol(table[i]->sym, len);
572 memmove(p2, p2 + 1, size);
578 /* find the token on the symbol */
579 p2 = find_token(p1, size, str);
585 /* increase the counts for this symbol's new tokens */
586 learn_symbol(table[i]->sym, len);
590 /* search the token with the maximum profit */
591 static int find_best_token(void)
593 int i, best, bestprofit;
598 for (i = 0; i < 0x10000; i++) {
599 if (token_profit[i] > bestprofit) {
601 bestprofit = token_profit[i];
607 /* this is the core of the algorithm: calculate the "best" table */
608 static void optimize_result(void)
612 /* using the '\0' symbol last allows compress_symbols to use standard
613 * fast string functions */
614 for (i = 255; i >= 0; i--) {
616 /* if this table slot is empty (it is not used by an actual
617 * original char code */
618 if (!best_table_len[i]) {
620 /* find the token with the best profit value */
621 best = find_best_token();
622 if (token_profit[best] == 0)
625 /* place it in the "best" table */
626 best_table_len[i] = 2;
627 best_table[i][0] = best & 0xFF;
628 best_table[i][1] = (best >> 8) & 0xFF;
630 /* replace this token in all the valid symbols */
631 compress_symbols(best_table[i], i);
636 /* start by placing the symbols that are actually used on the table */
637 static void insert_real_symbols_in_table(void)
639 unsigned int i, j, c;
641 for (i = 0; i < table_cnt; i++) {
642 for (j = 0; j < table[i]->len; j++) {
643 c = table[i]->sym[j];
650 static void optimize_token_table(void)
652 build_initial_tok_table();
654 insert_real_symbols_in_table();
659 /* guess for "linker script provide" symbol */
660 static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
662 const char *symbol = sym_name(se);
663 int len = se->len - 1;
668 if (symbol[0] != '_' || symbol[1] != '_')
672 if (!memcmp(symbol + 2, "start_", 6))
676 if (!memcmp(symbol + 2, "stop_", 5))
680 if (!memcmp(symbol + 2, "end_", 4))
684 if (!memcmp(symbol + len - 6, "_start", 6))
688 if (!memcmp(symbol + len - 4, "_end", 4))
694 static int compare_symbols(const void *a, const void *b)
696 const struct sym_entry *sa = *(const struct sym_entry **)a;
697 const struct sym_entry *sb = *(const struct sym_entry **)b;
700 /* sort by address first */
701 if (sa->addr > sb->addr)
703 if (sa->addr < sb->addr)
706 /* sort by "weakness" type */
707 wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
708 wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
712 /* sort by "linker script provide" type */
713 wa = may_be_linker_script_provide_symbol(sa);
714 wb = may_be_linker_script_provide_symbol(sb);
718 /* sort by the number of prefix underscores */
719 wa = strspn(sym_name(sa), "_");
720 wb = strspn(sym_name(sb), "_");
724 /* sort by initial order, so that other symbols are left undisturbed */
725 return sa->start_pos - sb->start_pos;
728 static void sort_symbols(void)
730 qsort(table, table_cnt, sizeof(table[0]), compare_symbols);
733 static void make_percpus_absolute(void)
737 for (i = 0; i < table_cnt; i++)
738 if (symbol_in_range(table[i], &percpu_range, 1)) {
740 * Keep the 'A' override for percpu symbols to
741 * ensure consistent behavior compared to older
742 * versions of this tool.
744 table[i]->sym[0] = 'A';
745 table[i]->percpu_absolute = 1;
749 /* find the minimum non-absolute symbol address */
750 static void record_relative_base(void)
754 for (i = 0; i < table_cnt; i++)
755 if (!symbol_absolute(table[i])) {
757 * The table is sorted by address.
758 * Take the first non-absolute symbol value.
760 relative_base = table[i]->addr;
765 int main(int argc, char **argv)
769 for (i = 1; i < argc; i++) {
770 if(strcmp(argv[i], "--all-symbols") == 0)
772 else if (strcmp(argv[i], "--absolute-percpu") == 0)
774 else if (strcmp(argv[i], "--base-relative") == 0)
779 } else if (argc != 1)
785 make_percpus_absolute();
788 record_relative_base();
789 optimize_token_table();