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] in.map > out.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
30 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
32 #define KSYM_NAME_LEN 512
35 unsigned long long addr;
43 const char *start_sym, *end_sym;
44 unsigned long long start, end;
47 static unsigned long long _text;
48 static unsigned long long relative_base;
49 static struct addr_range text_ranges[] = {
50 { "_stext", "_etext" },
51 { "_sinittext", "_einittext" },
53 #define text_range_text (&text_ranges[0])
54 #define text_range_inittext (&text_ranges[1])
56 static struct addr_range percpu_range = {
57 "__per_cpu_start", "__per_cpu_end", -1ULL, 0
60 static struct sym_entry **table;
61 static unsigned int table_size, table_cnt;
62 static int all_symbols;
63 static int absolute_percpu;
65 static int token_profit[0x10000];
67 /* the table that holds the result of the compression */
68 static unsigned char best_table[256][2];
69 static unsigned char best_table_len[256];
72 static void usage(void)
74 fprintf(stderr, "Usage: kallsyms [--all-symbols] [--absolute-percpu] 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 if (type == 'u' || type == 'n')
88 if (toupper(type) == 'A') {
89 /* Keep these useful absolute symbols */
90 if (strcmp(name, "__kernel_syscall_via_break") &&
91 strcmp(name, "__kernel_syscall_via_epc") &&
92 strcmp(name, "__kernel_sigtramp") &&
100 static void check_symbol_range(const char *sym, unsigned long long addr,
101 struct addr_range *ranges, int entries)
104 struct addr_range *ar;
106 for (i = 0; i < entries; ++i) {
109 if (strcmp(sym, ar->start_sym) == 0) {
112 } else if (strcmp(sym, ar->end_sym) == 0) {
119 static struct sym_entry *read_symbol(FILE *in, char **buf, size_t *buf_len)
121 char *name, type, *p;
122 unsigned long long addr;
125 struct sym_entry *sym;
128 readlen = getline(buf, buf_len, in);
131 perror("read_symbol");
137 if ((*buf)[readlen - 1] == '\n')
138 (*buf)[readlen - 1] = 0;
140 addr = strtoull(*buf, &p, 16);
142 if (*buf == p || *p++ != ' ' || !isascii((type = *p++)) || *p++ != ' ') {
143 fprintf(stderr, "line format error\n");
150 if (len >= KSYM_NAME_LEN) {
151 fprintf(stderr, "Symbol %s too long for kallsyms (%zu >= %d).\n"
152 "Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n",
153 name, len, KSYM_NAME_LEN);
157 if (strcmp(name, "_text") == 0)
160 /* Ignore most absolute/undefined (?) symbols. */
161 if (is_ignored_symbol(name, type))
164 check_symbol_range(name, addr, text_ranges, ARRAY_SIZE(text_ranges));
165 check_symbol_range(name, addr, &percpu_range, 1);
167 /* include the type field in the symbol name, so that it gets
168 * compressed together */
171 sym = malloc(sizeof(*sym) + len + 1);
173 fprintf(stderr, "kallsyms failure: "
174 "unable to allocate required amount of memory\n");
180 strcpy(sym_name(sym), name);
181 sym->percpu_absolute = false;
186 static int symbol_in_range(const struct sym_entry *s,
187 const struct addr_range *ranges, int entries)
190 const struct addr_range *ar;
192 for (i = 0; i < entries; ++i) {
195 if (s->addr >= ar->start && s->addr <= ar->end)
202 static bool string_starts_with(const char *s, const char *prefix)
204 return strncmp(s, prefix, strlen(prefix)) == 0;
207 static int symbol_valid(const struct sym_entry *s)
209 const char *name = sym_name(s);
211 /* if --all-symbols is not specified, then symbols outside the text
212 * and inittext sections are discarded */
215 * Symbols starting with __start and __stop are used to denote
216 * section boundaries, and should always be included:
218 if (string_starts_with(name, "__start_") ||
219 string_starts_with(name, "__stop_"))
222 if (symbol_in_range(s, text_ranges,
223 ARRAY_SIZE(text_ranges)) == 0)
225 /* Corner case. Discard any symbols with the same value as
226 * _etext _einittext; they can move between pass 1 and 2 when
227 * the kallsyms data are added. If these symbols move then
228 * they may get dropped in pass 2, which breaks the kallsyms
231 if ((s->addr == text_range_text->end &&
232 strcmp(name, text_range_text->end_sym)) ||
233 (s->addr == text_range_inittext->end &&
234 strcmp(name, text_range_inittext->end_sym)))
241 /* remove all the invalid symbols from the table */
242 static void shrink_table(void)
247 for (i = 0; i < table_cnt; i++) {
248 if (symbol_valid(table[i])) {
250 table[pos] = table[i];
259 static void read_map(const char *in)
262 struct sym_entry *sym;
273 sym = read_symbol(fp, &buf, &buflen);
277 sym->seq = table_cnt;
279 if (table_cnt >= table_size) {
281 table = realloc(table, sizeof(*table) * table_size);
283 fprintf(stderr, "out of memory\n");
289 table[table_cnt++] = sym;
296 static void output_label(const char *label)
298 printf(".globl %s\n", label);
300 printf("%s:\n", label);
303 /* Provide proper symbols relocatability by their '_text' relativeness. */
304 static void output_address(unsigned long long addr)
307 printf("\tPTR\t_text + %#llx\n", addr - _text);
309 printf("\tPTR\t_text - %#llx\n", _text - addr);
312 /* uncompress a compressed symbol. When this function is called, the best table
313 * might still be compressed itself, so the function needs to be recursive */
314 static int expand_symbol(const unsigned char *data, int len, char *result)
316 int c, rlen, total=0;
320 /* if the table holds a single char that is the same as the one
321 * we are looking for, then end the search */
322 if (best_table[c][0]==c && best_table_len[c]==1) {
326 /* if not, recurse and expand */
327 rlen = expand_symbol(best_table[c], best_table_len[c], result);
339 static bool symbol_absolute(const struct sym_entry *s)
341 return s->percpu_absolute;
344 static int compare_names(const void *a, const void *b)
347 const struct sym_entry *sa = *(const struct sym_entry **)a;
348 const struct sym_entry *sb = *(const struct sym_entry **)b;
350 ret = strcmp(sym_name(sa), sym_name(sb));
352 if (sa->addr > sb->addr)
354 else if (sa->addr < sb->addr)
358 return (int)(sa->seq - sb->seq);
364 static void sort_symbols_by_name(void)
366 qsort(table, table_cnt, sizeof(table[0]), compare_names);
369 static void write_src(void)
371 unsigned int i, k, off;
372 unsigned int best_idx[256];
373 unsigned int *markers, markers_cnt;
374 char buf[KSYM_NAME_LEN];
376 printf("#include <asm/bitsperlong.h>\n");
377 printf("#if BITS_PER_LONG == 64\n");
378 printf("#define PTR .quad\n");
379 printf("#define ALGN .balign 8\n");
381 printf("#define PTR .long\n");
382 printf("#define ALGN .balign 4\n");
385 printf("\t.section .rodata, \"a\"\n");
387 output_label("kallsyms_num_syms");
388 printf("\t.long\t%u\n", table_cnt);
391 /* table of offset markers, that give the offset in the compressed stream
392 * every 256 symbols */
393 markers_cnt = (table_cnt + 255) / 256;
394 markers = malloc(sizeof(*markers) * markers_cnt);
396 fprintf(stderr, "kallsyms failure: "
397 "unable to allocate required memory\n");
401 output_label("kallsyms_names");
403 for (i = 0; i < table_cnt; i++) {
405 markers[i >> 8] = off;
408 /* There cannot be any symbol of length zero. */
409 if (table[i]->len == 0) {
410 fprintf(stderr, "kallsyms failure: "
411 "unexpected zero symbol length\n");
415 /* Only lengths that fit in up-to-two-byte ULEB128 are supported. */
416 if (table[i]->len > 0x3FFF) {
417 fprintf(stderr, "kallsyms failure: "
418 "unexpected huge symbol length\n");
422 /* Encode length with ULEB128. */
423 if (table[i]->len <= 0x7F) {
424 /* Most symbols use a single byte for the length. */
425 printf("\t.byte 0x%02x", table[i]->len);
426 off += table[i]->len + 1;
428 /* "Big" symbols use two bytes. */
429 printf("\t.byte 0x%02x, 0x%02x",
430 (table[i]->len & 0x7F) | 0x80,
431 (table[i]->len >> 7) & 0x7F);
432 off += table[i]->len + 2;
434 for (k = 0; k < table[i]->len; k++)
435 printf(", 0x%02x", table[i]->sym[k]);
438 * Now that we wrote out the compressed symbol name, restore the
439 * original name and print it in the comment.
441 expand_symbol(table[i]->sym, table[i]->len, buf);
442 strcpy((char *)table[i]->sym, buf);
443 printf("\t/* %s */\n", table[i]->sym);
447 output_label("kallsyms_markers");
448 for (i = 0; i < markers_cnt; i++)
449 printf("\t.long\t%u\n", markers[i]);
454 output_label("kallsyms_token_table");
456 for (i = 0; i < 256; i++) {
458 expand_symbol(best_table[i], best_table_len[i], buf);
459 printf("\t.asciz\t\"%s\"\n", buf);
460 off += strlen(buf) + 1;
464 output_label("kallsyms_token_index");
465 for (i = 0; i < 256; i++)
466 printf("\t.short\t%d\n", best_idx[i]);
469 output_label("kallsyms_offsets");
471 for (i = 0; i < table_cnt; i++) {
473 * Use the offset relative to the lowest value
474 * encountered of all relative symbols, and emit
475 * non-relocatable fixed offsets that will be fixed
482 if (!absolute_percpu) {
483 offset = table[i]->addr - relative_base;
484 overflow = (offset < 0 || offset > UINT_MAX);
485 } else if (symbol_absolute(table[i])) {
486 offset = table[i]->addr;
487 overflow = (offset < 0 || offset > INT_MAX);
489 offset = relative_base - table[i]->addr - 1;
490 overflow = (offset < INT_MIN || offset >= 0);
493 fprintf(stderr, "kallsyms failure: "
494 "%s symbol value %#llx out of range in relative mode\n",
495 symbol_absolute(table[i]) ? "absolute" : "relative",
499 printf("\t.long\t%#x\t/* %s */\n", (int)offset, table[i]->sym);
503 output_label("kallsyms_relative_base");
504 output_address(relative_base);
507 sort_symbols_by_name();
508 output_label("kallsyms_seqs_of_names");
509 for (i = 0; i < table_cnt; i++)
510 printf("\t.byte 0x%02x, 0x%02x, 0x%02x\t/* %s */\n",
511 (unsigned char)(table[i]->seq >> 16),
512 (unsigned char)(table[i]->seq >> 8),
513 (unsigned char)(table[i]->seq >> 0),
519 /* table lookup compression functions */
521 /* count all the possible tokens in a symbol */
522 static void learn_symbol(const unsigned char *symbol, int len)
526 for (i = 0; i < len - 1; i++)
527 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
530 /* decrease the count for all the possible tokens in a symbol */
531 static void forget_symbol(const unsigned char *symbol, int len)
535 for (i = 0; i < len - 1; i++)
536 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
539 /* do the initial token count */
540 static void build_initial_token_table(void)
544 for (i = 0; i < table_cnt; i++)
545 learn_symbol(table[i]->sym, table[i]->len);
548 static unsigned char *find_token(unsigned char *str, int len,
549 const unsigned char *token)
553 for (i = 0; i < len - 1; i++) {
554 if (str[i] == token[0] && str[i+1] == token[1])
560 /* replace a given token in all the valid symbols. Use the sampled symbols
561 * to update the counts */
562 static void compress_symbols(const unsigned char *str, int idx)
564 unsigned int i, len, size;
565 unsigned char *p1, *p2;
567 for (i = 0; i < table_cnt; i++) {
572 /* find the token on the symbol */
573 p2 = find_token(p1, len, str);
576 /* decrease the counts for this symbol's tokens */
577 forget_symbol(table[i]->sym, len);
585 memmove(p2, p2 + 1, size);
591 /* find the token on the symbol */
592 p2 = find_token(p1, size, str);
598 /* increase the counts for this symbol's new tokens */
599 learn_symbol(table[i]->sym, len);
603 /* search the token with the maximum profit */
604 static int find_best_token(void)
606 int i, best, bestprofit;
611 for (i = 0; i < 0x10000; i++) {
612 if (token_profit[i] > bestprofit) {
614 bestprofit = token_profit[i];
620 /* this is the core of the algorithm: calculate the "best" table */
621 static void optimize_result(void)
625 /* using the '\0' symbol last allows compress_symbols to use standard
626 * fast string functions */
627 for (i = 255; i >= 0; i--) {
629 /* if this table slot is empty (it is not used by an actual
630 * original char code */
631 if (!best_table_len[i]) {
633 /* find the token with the best profit value */
634 best = find_best_token();
635 if (token_profit[best] == 0)
638 /* place it in the "best" table */
639 best_table_len[i] = 2;
640 best_table[i][0] = best & 0xFF;
641 best_table[i][1] = (best >> 8) & 0xFF;
643 /* replace this token in all the valid symbols */
644 compress_symbols(best_table[i], i);
649 /* start by placing the symbols that are actually used on the table */
650 static void insert_real_symbols_in_table(void)
652 unsigned int i, j, c;
654 for (i = 0; i < table_cnt; i++) {
655 for (j = 0; j < table[i]->len; j++) {
656 c = table[i]->sym[j];
663 static void optimize_token_table(void)
665 build_initial_token_table();
667 insert_real_symbols_in_table();
672 /* guess for "linker script provide" symbol */
673 static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
675 const char *symbol = sym_name(se);
676 int len = se->len - 1;
681 if (symbol[0] != '_' || symbol[1] != '_')
685 if (!memcmp(symbol + 2, "start_", 6))
689 if (!memcmp(symbol + 2, "stop_", 5))
693 if (!memcmp(symbol + 2, "end_", 4))
697 if (!memcmp(symbol + len - 6, "_start", 6))
701 if (!memcmp(symbol + len - 4, "_end", 4))
707 static int compare_symbols(const void *a, const void *b)
709 const struct sym_entry *sa = *(const struct sym_entry **)a;
710 const struct sym_entry *sb = *(const struct sym_entry **)b;
713 /* sort by address first */
714 if (sa->addr > sb->addr)
716 if (sa->addr < sb->addr)
719 /* sort by "weakness" type */
720 wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
721 wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
725 /* sort by "linker script provide" type */
726 wa = may_be_linker_script_provide_symbol(sa);
727 wb = may_be_linker_script_provide_symbol(sb);
731 /* sort by the number of prefix underscores */
732 wa = strspn(sym_name(sa), "_");
733 wb = strspn(sym_name(sb), "_");
737 /* sort by initial order, so that other symbols are left undisturbed */
738 return sa->seq - sb->seq;
741 static void sort_symbols(void)
743 qsort(table, table_cnt, sizeof(table[0]), compare_symbols);
746 static void make_percpus_absolute(void)
750 for (i = 0; i < table_cnt; i++)
751 if (symbol_in_range(table[i], &percpu_range, 1)) {
753 * Keep the 'A' override for percpu symbols to
754 * ensure consistent behavior compared to older
755 * versions of this tool.
757 table[i]->sym[0] = 'A';
758 table[i]->percpu_absolute = true;
762 /* find the minimum non-absolute symbol address */
763 static void record_relative_base(void)
767 for (i = 0; i < table_cnt; i++)
768 if (!symbol_absolute(table[i])) {
770 * The table is sorted by address.
771 * Take the first non-absolute symbol value.
773 relative_base = table[i]->addr;
778 int main(int argc, char **argv)
781 static const struct option long_options[] = {
782 {"all-symbols", no_argument, &all_symbols, 1},
783 {"absolute-percpu", no_argument, &absolute_percpu, 1},
787 int c = getopt_long(argc, argv, "", long_options, NULL);
798 read_map(argv[optind]);
801 make_percpus_absolute();
803 record_relative_base();
804 optimize_token_table();