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: kallsyms [--all-symbols] [--absolute-percpu]
9 * [--lto-clang] in.map > out.S
11 * Table compression uses all the unused char codes on the symbols and
12 * maps these to the most used substrings (tokens). For instance, it might
13 * map char code 0xF7 to represent "write_" and then in every symbol where
14 * "write_" appears it can be replaced by 0xF7, saving 5 bytes.
15 * The used codes themselves are also placed in the table so that the
16 * decompresion can work without "special cases".
17 * Applied to kernel symbols, this usually produces a compression ratio
31 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
33 #define KSYM_NAME_LEN 512
36 unsigned long long addr;
39 unsigned int start_pos;
40 unsigned int percpu_absolute;
45 const char *start_sym, *end_sym;
46 unsigned long long start, end;
49 static unsigned long long _text;
50 static unsigned long long relative_base;
51 static struct addr_range text_ranges[] = {
52 { "_stext", "_etext" },
53 { "_sinittext", "_einittext" },
55 #define text_range_text (&text_ranges[0])
56 #define text_range_inittext (&text_ranges[1])
58 static struct addr_range percpu_range = {
59 "__per_cpu_start", "__per_cpu_end", -1ULL, 0
62 static struct sym_entry **table;
63 static unsigned int table_size, table_cnt;
64 static int all_symbols;
65 static int absolute_percpu;
68 static int token_profit[0x10000];
70 /* the table that holds the result of the compression */
71 static unsigned char best_table[256][2];
72 static unsigned char best_table_len[256];
75 static void usage(void)
77 fprintf(stderr, "Usage: kallsyms [--all-symbols] [--absolute-percpu] "
78 "[--lto-clang] in.map > out.S\n");
82 static char *sym_name(const struct sym_entry *s)
84 return (char *)s->sym + 1;
87 static bool is_ignored_symbol(const char *name, char type)
89 if (type == 'u' || type == 'n')
92 if (toupper(type) == 'A') {
93 /* Keep these useful absolute symbols */
94 if (strcmp(name, "__kernel_syscall_via_break") &&
95 strcmp(name, "__kernel_syscall_via_epc") &&
96 strcmp(name, "__kernel_sigtramp") &&
104 static void check_symbol_range(const char *sym, unsigned long long addr,
105 struct addr_range *ranges, int entries)
108 struct addr_range *ar;
110 for (i = 0; i < entries; ++i) {
113 if (strcmp(sym, ar->start_sym) == 0) {
116 } else if (strcmp(sym, ar->end_sym) == 0) {
123 static struct sym_entry *read_symbol(FILE *in, char **buf, size_t *buf_len)
125 char *name, type, *p;
126 unsigned long long addr;
129 struct sym_entry *sym;
132 readlen = getline(buf, buf_len, in);
135 perror("read_symbol");
141 if ((*buf)[readlen - 1] == '\n')
142 (*buf)[readlen - 1] = 0;
144 addr = strtoull(*buf, &p, 16);
146 if (*buf == p || *p++ != ' ' || !isascii((type = *p++)) || *p++ != ' ') {
147 fprintf(stderr, "line format error\n");
154 if (len >= KSYM_NAME_LEN) {
155 fprintf(stderr, "Symbol %s too long for kallsyms (%zu >= %d).\n"
156 "Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n",
157 name, len, KSYM_NAME_LEN);
161 if (strcmp(name, "_text") == 0)
164 /* Ignore most absolute/undefined (?) symbols. */
165 if (is_ignored_symbol(name, type))
168 check_symbol_range(name, addr, text_ranges, ARRAY_SIZE(text_ranges));
169 check_symbol_range(name, addr, &percpu_range, 1);
171 /* include the type field in the symbol name, so that it gets
172 * compressed together */
175 sym = malloc(sizeof(*sym) + len + 1);
177 fprintf(stderr, "kallsyms failure: "
178 "unable to allocate required amount of memory\n");
184 strcpy(sym_name(sym), name);
185 sym->percpu_absolute = 0;
190 static int symbol_in_range(const struct sym_entry *s,
191 const struct addr_range *ranges, int entries)
194 const struct addr_range *ar;
196 for (i = 0; i < entries; ++i) {
199 if (s->addr >= ar->start && s->addr <= ar->end)
206 static bool string_starts_with(const char *s, const char *prefix)
208 return strncmp(s, prefix, strlen(prefix)) == 0;
211 static int symbol_valid(const struct sym_entry *s)
213 const char *name = sym_name(s);
215 /* if --all-symbols is not specified, then symbols outside the text
216 * and inittext sections are discarded */
219 * Symbols starting with __start and __stop are used to denote
220 * section boundaries, and should always be included:
222 if (string_starts_with(name, "__start_") ||
223 string_starts_with(name, "__stop_"))
226 if (symbol_in_range(s, text_ranges,
227 ARRAY_SIZE(text_ranges)) == 0)
229 /* Corner case. Discard any symbols with the same value as
230 * _etext _einittext; they can move between pass 1 and 2 when
231 * the kallsyms data are added. If these symbols move then
232 * they may get dropped in pass 2, which breaks the kallsyms
235 if ((s->addr == text_range_text->end &&
236 strcmp(name, text_range_text->end_sym)) ||
237 (s->addr == text_range_inittext->end &&
238 strcmp(name, text_range_inittext->end_sym)))
245 /* remove all the invalid symbols from the table */
246 static void shrink_table(void)
251 for (i = 0; i < table_cnt; i++) {
252 if (symbol_valid(table[i])) {
254 table[pos] = table[i];
263 static void read_map(const char *in)
266 struct sym_entry *sym;
277 sym = read_symbol(fp, &buf, &buflen);
281 sym->start_pos = table_cnt;
283 if (table_cnt >= table_size) {
285 table = realloc(table, sizeof(*table) * table_size);
287 fprintf(stderr, "out of memory\n");
293 table[table_cnt++] = sym;
300 static void output_label(const char *label)
302 printf(".globl %s\n", label);
304 printf("%s:\n", label);
307 /* Provide proper symbols relocatability by their '_text' relativeness. */
308 static void output_address(unsigned long long addr)
311 printf("\tPTR\t_text + %#llx\n", addr - _text);
313 printf("\tPTR\t_text - %#llx\n", _text - addr);
316 /* uncompress a compressed symbol. When this function is called, the best table
317 * might still be compressed itself, so the function needs to be recursive */
318 static int expand_symbol(const unsigned char *data, int len, char *result)
320 int c, rlen, total=0;
324 /* if the table holds a single char that is the same as the one
325 * we are looking for, then end the search */
326 if (best_table[c][0]==c && best_table_len[c]==1) {
330 /* if not, recurse and expand */
331 rlen = expand_symbol(best_table[c], best_table_len[c], result);
343 static int symbol_absolute(const struct sym_entry *s)
345 return s->percpu_absolute;
348 static void cleanup_symbol_name(char *s)
359 * As above, replacing the first '.' in ".llvm." with '\0' does not
360 * affect the main sorting, but it helps us with subsorting.
362 p = strstr(s, ".llvm.");
367 static int compare_names(const void *a, const void *b)
370 const struct sym_entry *sa = *(const struct sym_entry **)a;
371 const struct sym_entry *sb = *(const struct sym_entry **)b;
373 ret = strcmp(sym_name(sa), sym_name(sb));
375 if (sa->addr > sb->addr)
377 else if (sa->addr < sb->addr)
381 return (int)(sa->seq - sb->seq);
387 static void sort_symbols_by_name(void)
389 qsort(table, table_cnt, sizeof(table[0]), compare_names);
392 static void write_src(void)
394 unsigned int i, k, off;
395 unsigned int best_idx[256];
396 unsigned int *markers;
397 char buf[KSYM_NAME_LEN];
399 printf("#include <asm/bitsperlong.h>\n");
400 printf("#if BITS_PER_LONG == 64\n");
401 printf("#define PTR .quad\n");
402 printf("#define ALGN .balign 8\n");
404 printf("#define PTR .long\n");
405 printf("#define ALGN .balign 4\n");
408 printf("\t.section .rodata, \"a\"\n");
410 output_label("kallsyms_num_syms");
411 printf("\t.long\t%u\n", table_cnt);
414 /* table of offset markers, that give the offset in the compressed stream
415 * every 256 symbols */
416 markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
418 fprintf(stderr, "kallsyms failure: "
419 "unable to allocate required memory\n");
423 output_label("kallsyms_names");
425 for (i = 0; i < table_cnt; i++) {
427 markers[i >> 8] = off;
430 /* There cannot be any symbol of length zero. */
431 if (table[i]->len == 0) {
432 fprintf(stderr, "kallsyms failure: "
433 "unexpected zero symbol length\n");
437 /* Only lengths that fit in up-to-two-byte ULEB128 are supported. */
438 if (table[i]->len > 0x3FFF) {
439 fprintf(stderr, "kallsyms failure: "
440 "unexpected huge symbol length\n");
444 /* Encode length with ULEB128. */
445 if (table[i]->len <= 0x7F) {
446 /* Most symbols use a single byte for the length. */
447 printf("\t.byte 0x%02x", table[i]->len);
448 off += table[i]->len + 1;
450 /* "Big" symbols use two bytes. */
451 printf("\t.byte 0x%02x, 0x%02x",
452 (table[i]->len & 0x7F) | 0x80,
453 (table[i]->len >> 7) & 0x7F);
454 off += table[i]->len + 2;
456 for (k = 0; k < table[i]->len; k++)
457 printf(", 0x%02x", table[i]->sym[k]);
463 * Now that we wrote out the compressed symbol names, restore the
464 * original names, which are needed in some of the later steps.
466 for (i = 0; i < table_cnt; i++) {
467 expand_symbol(table[i]->sym, table[i]->len, buf);
468 strcpy((char *)table[i]->sym, buf);
471 output_label("kallsyms_markers");
472 for (i = 0; i < ((table_cnt + 255) >> 8); i++)
473 printf("\t.long\t%u\n", markers[i]);
478 output_label("kallsyms_token_table");
480 for (i = 0; i < 256; i++) {
482 expand_symbol(best_table[i], best_table_len[i], buf);
483 printf("\t.asciz\t\"%s\"\n", buf);
484 off += strlen(buf) + 1;
488 output_label("kallsyms_token_index");
489 for (i = 0; i < 256; i++)
490 printf("\t.short\t%d\n", best_idx[i]);
493 output_label("kallsyms_offsets");
495 for (i = 0; i < table_cnt; i++) {
497 * Use the offset relative to the lowest value
498 * encountered of all relative symbols, and emit
499 * non-relocatable fixed offsets that will be fixed
506 if (!absolute_percpu) {
507 offset = table[i]->addr - relative_base;
508 overflow = (offset < 0 || offset > UINT_MAX);
509 } else if (symbol_absolute(table[i])) {
510 offset = table[i]->addr;
511 overflow = (offset < 0 || offset > INT_MAX);
513 offset = relative_base - table[i]->addr - 1;
514 overflow = (offset < INT_MIN || offset >= 0);
517 fprintf(stderr, "kallsyms failure: "
518 "%s symbol value %#llx out of range in relative mode\n",
519 symbol_absolute(table[i]) ? "absolute" : "relative",
523 printf("\t.long\t%#x /* %s */\n", (int)offset, table[i]->sym);
527 output_label("kallsyms_relative_base");
528 output_address(relative_base);
532 for (i = 0; i < table_cnt; i++)
533 cleanup_symbol_name((char *)table[i]->sym);
535 sort_symbols_by_name();
536 output_label("kallsyms_seqs_of_names");
537 for (i = 0; i < table_cnt; i++)
538 printf("\t.byte 0x%02x, 0x%02x, 0x%02x\n",
539 (unsigned char)(table[i]->seq >> 16),
540 (unsigned char)(table[i]->seq >> 8),
541 (unsigned char)(table[i]->seq >> 0));
546 /* table lookup compression functions */
548 /* count all the possible tokens in a symbol */
549 static void learn_symbol(const unsigned char *symbol, int len)
553 for (i = 0; i < len - 1; i++)
554 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
557 /* decrease the count for all the possible tokens in a symbol */
558 static void forget_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 /* do the initial token count */
567 static void build_initial_token_table(void)
571 for (i = 0; i < table_cnt; i++)
572 learn_symbol(table[i]->sym, table[i]->len);
575 static unsigned char *find_token(unsigned char *str, int len,
576 const unsigned char *token)
580 for (i = 0; i < len - 1; i++) {
581 if (str[i] == token[0] && str[i+1] == token[1])
587 /* replace a given token in all the valid symbols. Use the sampled symbols
588 * to update the counts */
589 static void compress_symbols(const unsigned char *str, int idx)
591 unsigned int i, len, size;
592 unsigned char *p1, *p2;
594 for (i = 0; i < table_cnt; i++) {
599 /* find the token on the symbol */
600 p2 = find_token(p1, len, str);
603 /* decrease the counts for this symbol's tokens */
604 forget_symbol(table[i]->sym, len);
612 memmove(p2, p2 + 1, size);
618 /* find the token on the symbol */
619 p2 = find_token(p1, size, str);
625 /* increase the counts for this symbol's new tokens */
626 learn_symbol(table[i]->sym, len);
630 /* search the token with the maximum profit */
631 static int find_best_token(void)
633 int i, best, bestprofit;
638 for (i = 0; i < 0x10000; i++) {
639 if (token_profit[i] > bestprofit) {
641 bestprofit = token_profit[i];
647 /* this is the core of the algorithm: calculate the "best" table */
648 static void optimize_result(void)
652 /* using the '\0' symbol last allows compress_symbols to use standard
653 * fast string functions */
654 for (i = 255; i >= 0; i--) {
656 /* if this table slot is empty (it is not used by an actual
657 * original char code */
658 if (!best_table_len[i]) {
660 /* find the token with the best profit value */
661 best = find_best_token();
662 if (token_profit[best] == 0)
665 /* place it in the "best" table */
666 best_table_len[i] = 2;
667 best_table[i][0] = best & 0xFF;
668 best_table[i][1] = (best >> 8) & 0xFF;
670 /* replace this token in all the valid symbols */
671 compress_symbols(best_table[i], i);
676 /* start by placing the symbols that are actually used on the table */
677 static void insert_real_symbols_in_table(void)
679 unsigned int i, j, c;
681 for (i = 0; i < table_cnt; i++) {
682 for (j = 0; j < table[i]->len; j++) {
683 c = table[i]->sym[j];
690 static void optimize_token_table(void)
692 build_initial_token_table();
694 insert_real_symbols_in_table();
699 /* guess for "linker script provide" symbol */
700 static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
702 const char *symbol = sym_name(se);
703 int len = se->len - 1;
708 if (symbol[0] != '_' || symbol[1] != '_')
712 if (!memcmp(symbol + 2, "start_", 6))
716 if (!memcmp(symbol + 2, "stop_", 5))
720 if (!memcmp(symbol + 2, "end_", 4))
724 if (!memcmp(symbol + len - 6, "_start", 6))
728 if (!memcmp(symbol + len - 4, "_end", 4))
734 static int compare_symbols(const void *a, const void *b)
736 const struct sym_entry *sa = *(const struct sym_entry **)a;
737 const struct sym_entry *sb = *(const struct sym_entry **)b;
740 /* sort by address first */
741 if (sa->addr > sb->addr)
743 if (sa->addr < sb->addr)
746 /* sort by "weakness" type */
747 wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
748 wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
752 /* sort by "linker script provide" type */
753 wa = may_be_linker_script_provide_symbol(sa);
754 wb = may_be_linker_script_provide_symbol(sb);
758 /* sort by the number of prefix underscores */
759 wa = strspn(sym_name(sa), "_");
760 wb = strspn(sym_name(sb), "_");
764 /* sort by initial order, so that other symbols are left undisturbed */
765 return sa->start_pos - sb->start_pos;
768 static void sort_symbols(void)
770 qsort(table, table_cnt, sizeof(table[0]), compare_symbols);
773 static void make_percpus_absolute(void)
777 for (i = 0; i < table_cnt; i++)
778 if (symbol_in_range(table[i], &percpu_range, 1)) {
780 * Keep the 'A' override for percpu symbols to
781 * ensure consistent behavior compared to older
782 * versions of this tool.
784 table[i]->sym[0] = 'A';
785 table[i]->percpu_absolute = 1;
789 /* find the minimum non-absolute symbol address */
790 static void record_relative_base(void)
794 for (i = 0; i < table_cnt; i++)
795 if (!symbol_absolute(table[i])) {
797 * The table is sorted by address.
798 * Take the first non-absolute symbol value.
800 relative_base = table[i]->addr;
805 int main(int argc, char **argv)
808 static const struct option long_options[] = {
809 {"all-symbols", no_argument, &all_symbols, 1},
810 {"absolute-percpu", no_argument, &absolute_percpu, 1},
811 {"lto-clang", no_argument, <o_clang, 1},
815 int c = getopt_long(argc, argv, "", long_options, NULL);
826 read_map(argv[optind]);
829 make_percpus_absolute();
831 record_relative_base();
832 optimize_token_table();