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 * [--base-relative] [--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;
66 static int base_relative;
69 static int token_profit[0x10000];
71 /* the table that holds the result of the compression */
72 static unsigned char best_table[256][2];
73 static unsigned char best_table_len[256];
76 static void usage(void)
78 fprintf(stderr, "Usage: kallsyms [--all-symbols] [--absolute-percpu] "
79 "[--base-relative] [--lto-clang] in.map > out.S\n");
83 static char *sym_name(const struct sym_entry *s)
85 return (char *)s->sym + 1;
88 static bool is_ignored_symbol(const char *name, char type)
90 if (type == 'u' || type == 'n')
93 if (toupper(type) == 'A') {
94 /* Keep these useful absolute symbols */
95 if (strcmp(name, "__kernel_syscall_via_break") &&
96 strcmp(name, "__kernel_syscall_via_epc") &&
97 strcmp(name, "__kernel_sigtramp") &&
105 static void check_symbol_range(const char *sym, unsigned long long addr,
106 struct addr_range *ranges, int entries)
109 struct addr_range *ar;
111 for (i = 0; i < entries; ++i) {
114 if (strcmp(sym, ar->start_sym) == 0) {
117 } else if (strcmp(sym, ar->end_sym) == 0) {
124 static struct sym_entry *read_symbol(FILE *in, char **buf, size_t *buf_len)
126 char *name, type, *p;
127 unsigned long long addr;
130 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 int symbol_valid(const struct sym_entry *s)
208 const char *name = sym_name(s);
210 /* if --all-symbols is not specified, then symbols outside the text
211 * and inittext sections are discarded */
213 if (symbol_in_range(s, text_ranges,
214 ARRAY_SIZE(text_ranges)) == 0)
216 /* Corner case. Discard any symbols with the same value as
217 * _etext _einittext; they can move between pass 1 and 2 when
218 * the kallsyms data are added. If these symbols move then
219 * they may get dropped in pass 2, which breaks the kallsyms
222 if ((s->addr == text_range_text->end &&
223 strcmp(name, text_range_text->end_sym)) ||
224 (s->addr == text_range_inittext->end &&
225 strcmp(name, text_range_inittext->end_sym)))
232 /* remove all the invalid symbols from the table */
233 static void shrink_table(void)
238 for (i = 0; i < table_cnt; i++) {
239 if (symbol_valid(table[i])) {
241 table[pos] = table[i];
249 /* When valid symbol is not registered, exit to error */
251 fprintf(stderr, "No valid symbol.\n");
256 static void read_map(const char *in)
259 struct sym_entry *sym;
270 sym = read_symbol(fp, &buf, &buflen);
274 sym->start_pos = table_cnt;
276 if (table_cnt >= table_size) {
278 table = realloc(table, sizeof(*table) * table_size);
280 fprintf(stderr, "out of memory\n");
286 table[table_cnt++] = sym;
293 static void output_label(const char *label)
295 printf(".globl %s\n", label);
297 printf("%s:\n", label);
300 /* Provide proper symbols relocatability by their '_text' relativeness. */
301 static void output_address(unsigned long long addr)
304 printf("\tPTR\t_text + %#llx\n", addr - _text);
306 printf("\tPTR\t_text - %#llx\n", _text - addr);
309 /* uncompress a compressed symbol. When this function is called, the best table
310 * might still be compressed itself, so the function needs to be recursive */
311 static int expand_symbol(const unsigned char *data, int len, char *result)
313 int c, rlen, total=0;
317 /* if the table holds a single char that is the same as the one
318 * we are looking for, then end the search */
319 if (best_table[c][0]==c && best_table_len[c]==1) {
323 /* if not, recurse and expand */
324 rlen = expand_symbol(best_table[c], best_table_len[c], result);
336 static int symbol_absolute(const struct sym_entry *s)
338 return s->percpu_absolute;
341 static void cleanup_symbol_name(char *s)
352 * As above, replacing the first '.' in ".llvm." with '\0' does not
353 * affect the main sorting, but it helps us with subsorting.
355 p = strstr(s, ".llvm.");
360 static int compare_names(const void *a, const void *b)
363 const struct sym_entry *sa = *(const struct sym_entry **)a;
364 const struct sym_entry *sb = *(const struct sym_entry **)b;
366 ret = strcmp(sym_name(sa), sym_name(sb));
368 if (sa->addr > sb->addr)
370 else if (sa->addr < sb->addr)
374 return (int)(sa->seq - sb->seq);
380 static void sort_symbols_by_name(void)
382 qsort(table, table_cnt, sizeof(table[0]), compare_names);
385 static void write_src(void)
387 unsigned int i, k, off;
388 unsigned int best_idx[256];
389 unsigned int *markers;
390 char buf[KSYM_NAME_LEN];
392 printf("#include <asm/bitsperlong.h>\n");
393 printf("#if BITS_PER_LONG == 64\n");
394 printf("#define PTR .quad\n");
395 printf("#define ALGN .balign 8\n");
397 printf("#define PTR .long\n");
398 printf("#define ALGN .balign 4\n");
401 printf("\t.section .rodata, \"a\"\n");
403 output_label("kallsyms_num_syms");
404 printf("\t.long\t%u\n", table_cnt);
407 /* table of offset markers, that give the offset in the compressed stream
408 * every 256 symbols */
409 markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
411 fprintf(stderr, "kallsyms failure: "
412 "unable to allocate required memory\n");
416 output_label("kallsyms_names");
418 for (i = 0; i < table_cnt; i++) {
420 markers[i >> 8] = off;
423 /* There cannot be any symbol of length zero. */
424 if (table[i]->len == 0) {
425 fprintf(stderr, "kallsyms failure: "
426 "unexpected zero symbol length\n");
430 /* Only lengths that fit in up-to-two-byte ULEB128 are supported. */
431 if (table[i]->len > 0x3FFF) {
432 fprintf(stderr, "kallsyms failure: "
433 "unexpected huge symbol length\n");
437 /* Encode length with ULEB128. */
438 if (table[i]->len <= 0x7F) {
439 /* Most symbols use a single byte for the length. */
440 printf("\t.byte 0x%02x", table[i]->len);
441 off += table[i]->len + 1;
443 /* "Big" symbols use two bytes. */
444 printf("\t.byte 0x%02x, 0x%02x",
445 (table[i]->len & 0x7F) | 0x80,
446 (table[i]->len >> 7) & 0x7F);
447 off += table[i]->len + 2;
449 for (k = 0; k < table[i]->len; k++)
450 printf(", 0x%02x", table[i]->sym[k]);
456 * Now that we wrote out the compressed symbol names, restore the
457 * original names, which are needed in some of the later steps.
459 for (i = 0; i < table_cnt; i++) {
460 expand_symbol(table[i]->sym, table[i]->len, buf);
461 strcpy((char *)table[i]->sym, buf);
464 output_label("kallsyms_markers");
465 for (i = 0; i < ((table_cnt + 255) >> 8); i++)
466 printf("\t.long\t%u\n", markers[i]);
471 output_label("kallsyms_token_table");
473 for (i = 0; i < 256; i++) {
475 expand_symbol(best_table[i], best_table_len[i], buf);
476 printf("\t.asciz\t\"%s\"\n", buf);
477 off += strlen(buf) + 1;
481 output_label("kallsyms_token_index");
482 for (i = 0; i < 256; i++)
483 printf("\t.short\t%d\n", best_idx[i]);
487 output_label("kallsyms_addresses");
489 output_label("kallsyms_offsets");
491 for (i = 0; i < table_cnt; i++) {
494 * Use the offset relative to the lowest value
495 * encountered of all relative symbols, and emit
496 * non-relocatable fixed offsets that will be fixed
503 if (!absolute_percpu) {
504 offset = table[i]->addr - relative_base;
505 overflow = (offset < 0 || offset > UINT_MAX);
506 } else if (symbol_absolute(table[i])) {
507 offset = table[i]->addr;
508 overflow = (offset < 0 || offset > INT_MAX);
510 offset = relative_base - table[i]->addr - 1;
511 overflow = (offset < INT_MIN || offset >= 0);
514 fprintf(stderr, "kallsyms failure: "
515 "%s symbol value %#llx out of range in relative mode\n",
516 symbol_absolute(table[i]) ? "absolute" : "relative",
520 printf("\t.long\t%#x /* %s */\n", (int)offset, table[i]->sym);
521 } else if (!symbol_absolute(table[i])) {
522 output_address(table[i]->addr);
524 printf("\tPTR\t%#llx\n", table[i]->addr);
530 output_label("kallsyms_relative_base");
531 output_address(relative_base);
536 for (i = 0; i < table_cnt; i++)
537 cleanup_symbol_name((char *)table[i]->sym);
539 sort_symbols_by_name();
540 output_label("kallsyms_seqs_of_names");
541 for (i = 0; i < table_cnt; i++)
542 printf("\t.byte 0x%02x, 0x%02x, 0x%02x\n",
543 (unsigned char)(table[i]->seq >> 16),
544 (unsigned char)(table[i]->seq >> 8),
545 (unsigned char)(table[i]->seq >> 0));
550 /* table lookup compression functions */
552 /* count all the possible tokens in a symbol */
553 static void learn_symbol(const unsigned char *symbol, int len)
557 for (i = 0; i < len - 1; i++)
558 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
561 /* decrease the count for all the possible tokens in a symbol */
562 static void forget_symbol(const unsigned char *symbol, int len)
566 for (i = 0; i < len - 1; i++)
567 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
570 /* do the initial token count */
571 static void build_initial_token_table(void)
575 for (i = 0; i < table_cnt; i++)
576 learn_symbol(table[i]->sym, table[i]->len);
579 static unsigned char *find_token(unsigned char *str, int len,
580 const unsigned char *token)
584 for (i = 0; i < len - 1; i++) {
585 if (str[i] == token[0] && str[i+1] == token[1])
591 /* replace a given token in all the valid symbols. Use the sampled symbols
592 * to update the counts */
593 static void compress_symbols(const unsigned char *str, int idx)
595 unsigned int i, len, size;
596 unsigned char *p1, *p2;
598 for (i = 0; i < table_cnt; i++) {
603 /* find the token on the symbol */
604 p2 = find_token(p1, len, str);
607 /* decrease the counts for this symbol's tokens */
608 forget_symbol(table[i]->sym, len);
616 memmove(p2, p2 + 1, size);
622 /* find the token on the symbol */
623 p2 = find_token(p1, size, str);
629 /* increase the counts for this symbol's new tokens */
630 learn_symbol(table[i]->sym, len);
634 /* search the token with the maximum profit */
635 static int find_best_token(void)
637 int i, best, bestprofit;
642 for (i = 0; i < 0x10000; i++) {
643 if (token_profit[i] > bestprofit) {
645 bestprofit = token_profit[i];
651 /* this is the core of the algorithm: calculate the "best" table */
652 static void optimize_result(void)
656 /* using the '\0' symbol last allows compress_symbols to use standard
657 * fast string functions */
658 for (i = 255; i >= 0; i--) {
660 /* if this table slot is empty (it is not used by an actual
661 * original char code */
662 if (!best_table_len[i]) {
664 /* find the token with the best profit value */
665 best = find_best_token();
666 if (token_profit[best] == 0)
669 /* place it in the "best" table */
670 best_table_len[i] = 2;
671 best_table[i][0] = best & 0xFF;
672 best_table[i][1] = (best >> 8) & 0xFF;
674 /* replace this token in all the valid symbols */
675 compress_symbols(best_table[i], i);
680 /* start by placing the symbols that are actually used on the table */
681 static void insert_real_symbols_in_table(void)
683 unsigned int i, j, c;
685 for (i = 0; i < table_cnt; i++) {
686 for (j = 0; j < table[i]->len; j++) {
687 c = table[i]->sym[j];
694 static void optimize_token_table(void)
696 build_initial_token_table();
698 insert_real_symbols_in_table();
703 /* guess for "linker script provide" symbol */
704 static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
706 const char *symbol = sym_name(se);
707 int len = se->len - 1;
712 if (symbol[0] != '_' || symbol[1] != '_')
716 if (!memcmp(symbol + 2, "start_", 6))
720 if (!memcmp(symbol + 2, "stop_", 5))
724 if (!memcmp(symbol + 2, "end_", 4))
728 if (!memcmp(symbol + len - 6, "_start", 6))
732 if (!memcmp(symbol + len - 4, "_end", 4))
738 static int compare_symbols(const void *a, const void *b)
740 const struct sym_entry *sa = *(const struct sym_entry **)a;
741 const struct sym_entry *sb = *(const struct sym_entry **)b;
744 /* sort by address first */
745 if (sa->addr > sb->addr)
747 if (sa->addr < sb->addr)
750 /* sort by "weakness" type */
751 wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
752 wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
756 /* sort by "linker script provide" type */
757 wa = may_be_linker_script_provide_symbol(sa);
758 wb = may_be_linker_script_provide_symbol(sb);
762 /* sort by the number of prefix underscores */
763 wa = strspn(sym_name(sa), "_");
764 wb = strspn(sym_name(sb), "_");
768 /* sort by initial order, so that other symbols are left undisturbed */
769 return sa->start_pos - sb->start_pos;
772 static void sort_symbols(void)
774 qsort(table, table_cnt, sizeof(table[0]), compare_symbols);
777 static void make_percpus_absolute(void)
781 for (i = 0; i < table_cnt; i++)
782 if (symbol_in_range(table[i], &percpu_range, 1)) {
784 * Keep the 'A' override for percpu symbols to
785 * ensure consistent behavior compared to older
786 * versions of this tool.
788 table[i]->sym[0] = 'A';
789 table[i]->percpu_absolute = 1;
793 /* find the minimum non-absolute symbol address */
794 static void record_relative_base(void)
798 for (i = 0; i < table_cnt; i++)
799 if (!symbol_absolute(table[i])) {
801 * The table is sorted by address.
802 * Take the first non-absolute symbol value.
804 relative_base = table[i]->addr;
809 int main(int argc, char **argv)
812 static const struct option long_options[] = {
813 {"all-symbols", no_argument, &all_symbols, 1},
814 {"absolute-percpu", no_argument, &absolute_percpu, 1},
815 {"base-relative", no_argument, &base_relative, 1},
816 {"lto-clang", no_argument, <o_clang, 1},
820 int c = getopt_long(argc, argv, "", long_options, NULL);
831 read_map(argv[optind]);
834 make_percpus_absolute();
837 record_relative_base();
838 optimize_token_table();