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
29 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
31 #define _stringify_1(x) #x
32 #define _stringify(x) _stringify_1(x)
34 #define KSYM_NAME_LEN 512
37 * A substantially bigger size than the current maximum.
39 * It cannot be defined as an expression because it gets stringified
40 * for the fscanf() format string. Therefore, a _Static_assert() is
41 * used instead to maintain the relationship with KSYM_NAME_LEN.
43 #define KSYM_NAME_LEN_BUFFER 2048
45 KSYM_NAME_LEN_BUFFER == KSYM_NAME_LEN * 4,
46 "Please keep KSYM_NAME_LEN_BUFFER in sync with KSYM_NAME_LEN"
50 unsigned long long addr;
52 unsigned int start_pos;
53 unsigned int percpu_absolute;
58 const char *start_sym, *end_sym;
59 unsigned long long start, end;
62 static unsigned long long _text;
63 static unsigned long long relative_base;
64 static struct addr_range text_ranges[] = {
65 { "_stext", "_etext" },
66 { "_sinittext", "_einittext" },
68 #define text_range_text (&text_ranges[0])
69 #define text_range_inittext (&text_ranges[1])
71 static struct addr_range percpu_range = {
72 "__per_cpu_start", "__per_cpu_end", -1ULL, 0
75 static struct sym_entry **table;
76 static unsigned int table_size, table_cnt;
77 static int all_symbols;
78 static int absolute_percpu;
79 static int base_relative;
81 static int token_profit[0x10000];
83 /* the table that holds the result of the compression */
84 static unsigned char best_table[256][2];
85 static unsigned char best_table_len[256];
88 static void usage(void)
90 fprintf(stderr, "Usage: kallsyms [--all-symbols] [--absolute-percpu] "
91 "[--base-relative] in.map > out.S\n");
95 static char *sym_name(const struct sym_entry *s)
97 return (char *)s->sym + 1;
100 static bool is_ignored_symbol(const char *name, char type)
102 /* Symbol names that exactly match to the following are ignored.*/
103 static const char * const ignored_symbols[] = {
105 * Symbols which vary between passes. Passes 1 and 2 must have
106 * identical symbol lists. The kallsyms_* symbols below are
107 * only added after pass 1, they would be included in pass 2
108 * when --all-symbols is specified so exclude them to get a
109 * stable symbol list.
111 "kallsyms_addresses",
113 "kallsyms_relative_base",
117 "kallsyms_token_table",
118 "kallsyms_token_index",
119 /* Exclude linker generated symbols which vary between passes */
120 "_SDA_BASE_", /* ppc */
121 "_SDA2_BASE_", /* ppc */
125 /* Symbol names that begin with the following are ignored.*/
126 static const char * const ignored_prefixes[] = {
127 "__efistub_", /* arm64 EFI stub namespace */
128 "__kvm_nvhe_$", /* arm64 local symbols in non-VHE KVM namespace */
129 "__kvm_nvhe_.L", /* arm64 local symbols in non-VHE KVM namespace */
130 "__AArch64ADRPThunk_", /* arm64 lld */
131 "__ARMV5PILongThunk_", /* arm lld */
132 "__ARMV7PILongThunk_",
133 "__ThumbV7PILongThunk_",
134 "__LA25Thunk_", /* mips lld */
136 "__kcfi_typeid_", /* CFI type identifiers */
140 /* Symbol names that end with the following are ignored.*/
141 static const char * const ignored_suffixes[] = {
142 "_from_arm", /* arm */
143 "_from_thumb", /* arm */
148 /* Symbol names that contain the following are ignored.*/
149 static const char * const ignored_matches[] = {
150 ".long_branch.", /* ppc stub */
151 ".plt_branch.", /* ppc stub */
155 const char * const *p;
157 for (p = ignored_symbols; *p; p++)
158 if (!strcmp(name, *p))
161 for (p = ignored_prefixes; *p; p++)
162 if (!strncmp(name, *p, strlen(*p)))
165 for (p = ignored_suffixes; *p; p++) {
166 int l = strlen(name) - strlen(*p);
168 if (l >= 0 && !strcmp(name + l, *p))
172 for (p = ignored_matches; *p; p++) {
173 if (strstr(name, *p))
177 if (type == 'U' || type == 'u')
179 /* exclude debugging symbols */
180 if (type == 'N' || type == 'n')
183 if (toupper(type) == 'A') {
184 /* Keep these useful absolute symbols */
185 if (strcmp(name, "__kernel_syscall_via_break") &&
186 strcmp(name, "__kernel_syscall_via_epc") &&
187 strcmp(name, "__kernel_sigtramp") &&
188 strcmp(name, "__gp"))
195 static void check_symbol_range(const char *sym, unsigned long long addr,
196 struct addr_range *ranges, int entries)
199 struct addr_range *ar;
201 for (i = 0; i < entries; ++i) {
204 if (strcmp(sym, ar->start_sym) == 0) {
207 } else if (strcmp(sym, ar->end_sym) == 0) {
214 static struct sym_entry *read_symbol(FILE *in)
216 char name[KSYM_NAME_LEN_BUFFER+1], type;
217 unsigned long long addr;
219 struct sym_entry *sym;
222 rc = fscanf(in, "%llx %c %" _stringify(KSYM_NAME_LEN_BUFFER) "s\n", &addr, &type, name);
224 if (rc != EOF && fgets(name, ARRAY_SIZE(name), in) == NULL)
225 fprintf(stderr, "Read error or end of file.\n");
228 if (strlen(name) >= KSYM_NAME_LEN) {
229 fprintf(stderr, "Symbol %s too long for kallsyms (%zu >= %d).\n"
230 "Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n",
231 name, strlen(name), KSYM_NAME_LEN);
235 if (strcmp(name, "_text") == 0)
238 /* Ignore most absolute/undefined (?) symbols. */
239 if (is_ignored_symbol(name, type))
242 check_symbol_range(name, addr, text_ranges, ARRAY_SIZE(text_ranges));
243 check_symbol_range(name, addr, &percpu_range, 1);
245 /* include the type field in the symbol name, so that it gets
246 * compressed together */
248 len = strlen(name) + 1;
250 sym = malloc(sizeof(*sym) + len + 1);
252 fprintf(stderr, "kallsyms failure: "
253 "unable to allocate required amount of memory\n");
259 strcpy(sym_name(sym), name);
260 sym->percpu_absolute = 0;
265 static int symbol_in_range(const struct sym_entry *s,
266 const struct addr_range *ranges, int entries)
269 const struct addr_range *ar;
271 for (i = 0; i < entries; ++i) {
274 if (s->addr >= ar->start && s->addr <= ar->end)
281 static int symbol_valid(const struct sym_entry *s)
283 const char *name = sym_name(s);
285 /* if --all-symbols is not specified, then symbols outside the text
286 * and inittext sections are discarded */
288 if (symbol_in_range(s, text_ranges,
289 ARRAY_SIZE(text_ranges)) == 0)
291 /* Corner case. Discard any symbols with the same value as
292 * _etext _einittext; they can move between pass 1 and 2 when
293 * the kallsyms data are added. If these symbols move then
294 * they may get dropped in pass 2, which breaks the kallsyms
297 if ((s->addr == text_range_text->end &&
298 strcmp(name, text_range_text->end_sym)) ||
299 (s->addr == text_range_inittext->end &&
300 strcmp(name, text_range_inittext->end_sym)))
307 /* remove all the invalid symbols from the table */
308 static void shrink_table(void)
313 for (i = 0; i < table_cnt; i++) {
314 if (symbol_valid(table[i])) {
316 table[pos] = table[i];
324 /* When valid symbol is not registered, exit to error */
326 fprintf(stderr, "No valid symbol.\n");
331 static void read_map(const char *in)
334 struct sym_entry *sym;
343 sym = read_symbol(fp);
347 sym->start_pos = table_cnt;
349 if (table_cnt >= table_size) {
351 table = realloc(table, sizeof(*table) * table_size);
353 fprintf(stderr, "out of memory\n");
359 table[table_cnt++] = sym;
365 static void output_label(const char *label)
367 printf(".globl %s\n", label);
369 printf("%s:\n", label);
372 /* Provide proper symbols relocatability by their '_text' relativeness. */
373 static void output_address(unsigned long long addr)
376 printf("\tPTR\t_text + %#llx\n", addr - _text);
378 printf("\tPTR\t_text - %#llx\n", _text - addr);
381 /* uncompress a compressed symbol. When this function is called, the best table
382 * might still be compressed itself, so the function needs to be recursive */
383 static int expand_symbol(const unsigned char *data, int len, char *result)
385 int c, rlen, total=0;
389 /* if the table holds a single char that is the same as the one
390 * we are looking for, then end the search */
391 if (best_table[c][0]==c && best_table_len[c]==1) {
395 /* if not, recurse and expand */
396 rlen = expand_symbol(best_table[c], best_table_len[c], result);
408 static int symbol_absolute(const struct sym_entry *s)
410 return s->percpu_absolute;
413 static void write_src(void)
415 unsigned int i, k, off;
416 unsigned int best_idx[256];
417 unsigned int *markers;
418 char buf[KSYM_NAME_LEN];
420 printf("#include <asm/bitsperlong.h>\n");
421 printf("#if BITS_PER_LONG == 64\n");
422 printf("#define PTR .quad\n");
423 printf("#define ALGN .balign 8\n");
425 printf("#define PTR .long\n");
426 printf("#define ALGN .balign 4\n");
429 printf("\t.section .rodata, \"a\"\n");
432 output_label("kallsyms_addresses");
434 output_label("kallsyms_offsets");
436 for (i = 0; i < table_cnt; i++) {
439 * Use the offset relative to the lowest value
440 * encountered of all relative symbols, and emit
441 * non-relocatable fixed offsets that will be fixed
448 if (!absolute_percpu) {
449 offset = table[i]->addr - relative_base;
450 overflow = (offset < 0 || offset > UINT_MAX);
451 } else if (symbol_absolute(table[i])) {
452 offset = table[i]->addr;
453 overflow = (offset < 0 || offset > INT_MAX);
455 offset = relative_base - table[i]->addr - 1;
456 overflow = (offset < INT_MIN || offset >= 0);
459 fprintf(stderr, "kallsyms failure: "
460 "%s symbol value %#llx out of range in relative mode\n",
461 symbol_absolute(table[i]) ? "absolute" : "relative",
465 printf("\t.long\t%#x\n", (int)offset);
466 } else if (!symbol_absolute(table[i])) {
467 output_address(table[i]->addr);
469 printf("\tPTR\t%#llx\n", table[i]->addr);
475 output_label("kallsyms_relative_base");
476 output_address(relative_base);
480 output_label("kallsyms_num_syms");
481 printf("\t.long\t%u\n", table_cnt);
484 /* table of offset markers, that give the offset in the compressed stream
485 * every 256 symbols */
486 markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
488 fprintf(stderr, "kallsyms failure: "
489 "unable to allocate required memory\n");
493 output_label("kallsyms_names");
495 for (i = 0; i < table_cnt; i++) {
497 markers[i >> 8] = off;
499 /* There cannot be any symbol of length zero. */
500 if (table[i]->len == 0) {
501 fprintf(stderr, "kallsyms failure: "
502 "unexpected zero symbol length\n");
506 /* Only lengths that fit in up-to-two-byte ULEB128 are supported. */
507 if (table[i]->len > 0x3FFF) {
508 fprintf(stderr, "kallsyms failure: "
509 "unexpected huge symbol length\n");
513 /* Encode length with ULEB128. */
514 if (table[i]->len <= 0x7F) {
515 /* Most symbols use a single byte for the length. */
516 printf("\t.byte 0x%02x", table[i]->len);
517 off += table[i]->len + 1;
519 /* "Big" symbols use two bytes. */
520 printf("\t.byte 0x%02x, 0x%02x",
521 (table[i]->len & 0x7F) | 0x80,
522 (table[i]->len >> 7) & 0x7F);
523 off += table[i]->len + 2;
525 for (k = 0; k < table[i]->len; k++)
526 printf(", 0x%02x", table[i]->sym[k]);
531 output_label("kallsyms_markers");
532 for (i = 0; i < ((table_cnt + 255) >> 8); i++)
533 printf("\t.long\t%u\n", markers[i]);
538 output_label("kallsyms_token_table");
540 for (i = 0; i < 256; i++) {
542 expand_symbol(best_table[i], best_table_len[i], buf);
543 printf("\t.asciz\t\"%s\"\n", buf);
544 off += strlen(buf) + 1;
548 output_label("kallsyms_token_index");
549 for (i = 0; i < 256; i++)
550 printf("\t.short\t%d\n", best_idx[i]);
555 /* table lookup compression functions */
557 /* count all the possible tokens in a symbol */
558 static void learn_symbol(const unsigned char *symbol, int len)
562 for (i = 0; i < len - 1; i++)
563 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
566 /* decrease the count for all the possible tokens in a symbol */
567 static void forget_symbol(const unsigned char *symbol, int len)
571 for (i = 0; i < len - 1; i++)
572 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
575 /* do the initial token count */
576 static void build_initial_tok_table(void)
580 for (i = 0; i < table_cnt; i++)
581 learn_symbol(table[i]->sym, table[i]->len);
584 static unsigned char *find_token(unsigned char *str, int len,
585 const unsigned char *token)
589 for (i = 0; i < len - 1; i++) {
590 if (str[i] == token[0] && str[i+1] == token[1])
596 /* replace a given token in all the valid symbols. Use the sampled symbols
597 * to update the counts */
598 static void compress_symbols(const unsigned char *str, int idx)
600 unsigned int i, len, size;
601 unsigned char *p1, *p2;
603 for (i = 0; i < table_cnt; i++) {
608 /* find the token on the symbol */
609 p2 = find_token(p1, len, str);
612 /* decrease the counts for this symbol's tokens */
613 forget_symbol(table[i]->sym, len);
621 memmove(p2, p2 + 1, size);
627 /* find the token on the symbol */
628 p2 = find_token(p1, size, str);
634 /* increase the counts for this symbol's new tokens */
635 learn_symbol(table[i]->sym, len);
639 /* search the token with the maximum profit */
640 static int find_best_token(void)
642 int i, best, bestprofit;
647 for (i = 0; i < 0x10000; i++) {
648 if (token_profit[i] > bestprofit) {
650 bestprofit = token_profit[i];
656 /* this is the core of the algorithm: calculate the "best" table */
657 static void optimize_result(void)
661 /* using the '\0' symbol last allows compress_symbols to use standard
662 * fast string functions */
663 for (i = 255; i >= 0; i--) {
665 /* if this table slot is empty (it is not used by an actual
666 * original char code */
667 if (!best_table_len[i]) {
669 /* find the token with the best profit value */
670 best = find_best_token();
671 if (token_profit[best] == 0)
674 /* place it in the "best" table */
675 best_table_len[i] = 2;
676 best_table[i][0] = best & 0xFF;
677 best_table[i][1] = (best >> 8) & 0xFF;
679 /* replace this token in all the valid symbols */
680 compress_symbols(best_table[i], i);
685 /* start by placing the symbols that are actually used on the table */
686 static void insert_real_symbols_in_table(void)
688 unsigned int i, j, c;
690 for (i = 0; i < table_cnt; i++) {
691 for (j = 0; j < table[i]->len; j++) {
692 c = table[i]->sym[j];
699 static void optimize_token_table(void)
701 build_initial_tok_table();
703 insert_real_symbols_in_table();
708 /* guess for "linker script provide" symbol */
709 static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
711 const char *symbol = sym_name(se);
712 int len = se->len - 1;
717 if (symbol[0] != '_' || symbol[1] != '_')
721 if (!memcmp(symbol + 2, "start_", 6))
725 if (!memcmp(symbol + 2, "stop_", 5))
729 if (!memcmp(symbol + 2, "end_", 4))
733 if (!memcmp(symbol + len - 6, "_start", 6))
737 if (!memcmp(symbol + len - 4, "_end", 4))
743 static int compare_symbols(const void *a, const void *b)
745 const struct sym_entry *sa = *(const struct sym_entry **)a;
746 const struct sym_entry *sb = *(const struct sym_entry **)b;
749 /* sort by address first */
750 if (sa->addr > sb->addr)
752 if (sa->addr < sb->addr)
755 /* sort by "weakness" type */
756 wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
757 wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
761 /* sort by "linker script provide" type */
762 wa = may_be_linker_script_provide_symbol(sa);
763 wb = may_be_linker_script_provide_symbol(sb);
767 /* sort by the number of prefix underscores */
768 wa = strspn(sym_name(sa), "_");
769 wb = strspn(sym_name(sb), "_");
773 /* sort by initial order, so that other symbols are left undisturbed */
774 return sa->start_pos - sb->start_pos;
777 static void sort_symbols(void)
779 qsort(table, table_cnt, sizeof(table[0]), compare_symbols);
782 static void make_percpus_absolute(void)
786 for (i = 0; i < table_cnt; i++)
787 if (symbol_in_range(table[i], &percpu_range, 1)) {
789 * Keep the 'A' override for percpu symbols to
790 * ensure consistent behavior compared to older
791 * versions of this tool.
793 table[i]->sym[0] = 'A';
794 table[i]->percpu_absolute = 1;
798 /* find the minimum non-absolute symbol address */
799 static void record_relative_base(void)
803 for (i = 0; i < table_cnt; i++)
804 if (!symbol_absolute(table[i])) {
806 * The table is sorted by address.
807 * Take the first non-absolute symbol value.
809 relative_base = table[i]->addr;
814 int main(int argc, char **argv)
817 static struct option long_options[] = {
818 {"all-symbols", no_argument, &all_symbols, 1},
819 {"absolute-percpu", no_argument, &absolute_percpu, 1},
820 {"base-relative", no_argument, &base_relative, 1},
824 int c = getopt_long(argc, argv, "", long_options, NULL);
835 read_map(argv[optind]);
838 make_percpus_absolute();
841 record_relative_base();
842 optimize_token_table();