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
12 * (25/Aug/2004) Paulo Marques <pmarques@grupopie.com>
13 * Changed the compression method from stem compression to "table lookup"
16 * Table compression uses all the unused char codes on the symbols and
17 * maps these to the most used substrings (tokens). For instance, it might
18 * map char code 0xF7 to represent "write_" and then in every symbol where
19 * "write_" appears it can be replaced by 0xF7, saving 5 bytes.
20 * The used codes themselves are also placed in the table so that the
21 * decompresion can work without "special cases".
22 * Applied to kernel symbols, this usually produces a compression ratio
32 /* maximum token length used. It doesn't pay to increase it a lot, because
33 * very long substrings probably don't repeat themselves too often. */
34 #define MAX_TOK_SIZE 11
35 #define KSYM_NAME_LEN 127
37 /* we use only a subset of the complete symbol table to gather the token count,
38 * to speed up compression, at the expense of a little compression ratio */
39 #define WORKING_SET 1024
41 /* first find the best token only on the list of tokens that would profit more
42 * than GOOD_BAD_THRESHOLD. Only if this list is empty go to the "bad" list.
43 * Increasing this value will put less tokens on the "good" list, so the search
44 * is faster. However, if the good list runs out of tokens, we must painfully
45 * search the bad list. */
46 #define GOOD_BAD_THRESHOLD 10
48 /* token hash parameters */
50 #define HASH_TABLE_SIZE (1 << HASH_BITS)
51 #define HASH_MASK (HASH_TABLE_SIZE - 1)
52 #define HASH_BASE_OFFSET 2166136261U
53 #define HASH_FOLD(a) ((a)&(HASH_MASK))
55 /* flags to mark symbols */
56 #define SYM_FLAG_VALID 1
57 #define SYM_FLAG_SAMPLED 2
60 unsigned long long addr;
68 static struct sym_entry *table;
70 static unsigned long long _stext, _etext, _sinittext, _einittext;
71 static int all_symbols = 0;
74 unsigned char data[MAX_TOK_SIZE];
76 /* profit: the number of bytes that could be saved by inserting this
77 * token into the table */
79 struct token *next; /* next token on the hash list */
80 struct token *right; /* next token on the good/bad list */
81 struct token *left; /* previous token on the good/bad list */
82 struct token *smaller; /* token that is less one letter than this one */
85 struct token bad_head, good_head;
86 struct token *hash_table[HASH_TABLE_SIZE];
88 /* the table that holds the result of the compression */
89 unsigned char best_table[256][MAX_TOK_SIZE+1];
90 unsigned char best_table_len[256];
96 fprintf(stderr, "Usage: kallsyms [--all-symbols] < in.map > out.S\n");
101 * This ignores the intensely annoying "mapping symbols" found
102 * in ARM ELF files: $a, $t and $d.
105 is_arm_mapping_symbol(const char *str)
107 return str[0] == '$' && strchr("atd", str[1])
108 && (str[2] == '\0' || str[2] == '.');
112 read_symbol(FILE *in, struct sym_entry *s)
117 rc = fscanf(in, "%llx %c %499s\n", &s->addr, &s->type, str);
126 /* Ignore most absolute/undefined (?) symbols. */
127 if (strcmp(str, "_stext") == 0)
129 else if (strcmp(str, "_etext") == 0)
131 else if (strcmp(str, "_sinittext") == 0)
132 _sinittext = s->addr;
133 else if (strcmp(str, "_einittext") == 0)
134 _einittext = s->addr;
135 else if (toupper(s->type) == 'A')
137 /* Keep these useful absolute symbols */
138 if (strcmp(str, "__kernel_syscall_via_break") &&
139 strcmp(str, "__kernel_syscall_via_epc") &&
140 strcmp(str, "__kernel_sigtramp") &&
145 else if (toupper(s->type) == 'U' ||
146 is_arm_mapping_symbol(str))
149 /* include the type field in the symbol name, so that it gets
150 * compressed together */
151 s->len = strlen(str) + 1;
152 s->sym = (char *) malloc(s->len + 1);
153 strcpy(s->sym + 1, str);
160 symbol_valid(struct sym_entry *s)
162 /* Symbols which vary between passes. Passes 1 and 2 must have
163 * identical symbol lists. The kallsyms_* symbols below are only added
164 * after pass 1, they would be included in pass 2 when --all-symbols is
165 * specified so exclude them to get a stable symbol list.
167 static char *special_symbols[] = {
168 "kallsyms_addresses",
172 "kallsyms_token_table",
173 "kallsyms_token_index",
175 /* Exclude linker generated symbols which vary between passes */
176 "_SDA_BASE_", /* ppc */
177 "_SDA2_BASE_", /* ppc */
181 /* if --all-symbols is not specified, then symbols outside the text
182 * and inittext sections are discarded */
184 if ((s->addr < _stext || s->addr > _etext)
185 && (s->addr < _sinittext || s->addr > _einittext))
189 /* Exclude symbols which vary between passes. */
190 if (strstr(s->sym + 1, "_compiled."))
193 for (i = 0; special_symbols[i]; i++)
194 if( strcmp(s->sym + 1, special_symbols[i]) == 0 )
206 table = realloc(table, sizeof(*table) * size);
208 fprintf(stderr, "out of memory\n");
212 if (read_symbol(in, &table[cnt]) == 0)
217 static void output_label(char *label)
219 printf(".globl %s\n",label);
221 printf("%s:\n",label);
224 /* uncompress a compressed symbol. When this function is called, the best table
225 * might still be compressed itself, so the function needs to be recursive */
226 static int expand_symbol(unsigned char *data, int len, char *result)
228 int c, rlen, total=0;
232 /* if the table holds a single char that is the same as the one
233 * we are looking for, then end the search */
234 if (best_table[c][0]==c && best_table_len[c]==1) {
238 /* if not, recurse and expand */
239 rlen = expand_symbol(best_table[c], best_table_len[c], result);
254 int i, k, off, valid;
255 unsigned int best_idx[256];
256 unsigned int *markers;
257 char buf[KSYM_NAME_LEN+1];
259 printf("#include <asm/types.h>\n");
260 printf("#if BITS_PER_LONG == 64\n");
261 printf("#define PTR .quad\n");
262 printf("#define ALGN .align 8\n");
264 printf("#define PTR .long\n");
265 printf("#define ALGN .align 4\n");
270 output_label("kallsyms_addresses");
272 for (i = 0; i < cnt; i++) {
273 if (table[i].flags & SYM_FLAG_VALID) {
274 printf("\tPTR\t%#llx\n", table[i].addr);
280 output_label("kallsyms_num_syms");
281 printf("\tPTR\t%d\n", valid);
284 /* table of offset markers, that give the offset in the compressed stream
285 * every 256 symbols */
286 markers = (unsigned int *) malloc(sizeof(unsigned int)*((valid + 255) / 256));
288 output_label("kallsyms_names");
291 for (i = 0; i < cnt; i++) {
293 if (!table[i].flags & SYM_FLAG_VALID)
296 if ((valid & 0xFF) == 0)
297 markers[valid >> 8] = off;
299 printf("\t.byte 0x%02x", table[i].len);
300 for (k = 0; k < table[i].len; k++)
301 printf(", 0x%02x", table[i].sym[k]);
304 off += table[i].len + 1;
309 output_label("kallsyms_markers");
310 for (i = 0; i < ((valid + 255) >> 8); i++)
311 printf("\tPTR\t%d\n", markers[i]);
316 output_label("kallsyms_token_table");
318 for (i = 0; i < 256; i++) {
320 expand_symbol(best_table[i],best_table_len[i],buf);
321 printf("\t.asciz\t\"%s\"\n", buf);
322 off += strlen(buf) + 1;
326 output_label("kallsyms_token_index");
327 for (i = 0; i < 256; i++)
328 printf("\t.short\t%d\n", best_idx[i]);
333 /* table lookup compression functions */
335 static inline unsigned int rehash_token(unsigned int hash, unsigned char data)
337 return ((hash * 16777619) ^ data);
340 static unsigned int hash_token(unsigned char *data, int len)
342 unsigned int hash=HASH_BASE_OFFSET;
345 for (i = 0; i < len; i++)
346 hash = rehash_token(hash, data[i]);
348 return HASH_FOLD(hash);
351 /* find a token given its data and hash value */
352 static struct token *find_token_hash(unsigned char *data, int len, unsigned int hash)
356 ptr = hash_table[hash];
359 if ((ptr->len == len) && (memcmp(ptr->data, data, len) == 0))
367 static inline void insert_token_in_group(struct token *head, struct token *ptr)
369 ptr->right = head->right;
370 ptr->right->left = ptr;
375 static inline void remove_token_from_group(struct token *ptr)
377 ptr->left->right = ptr->right;
378 ptr->right->left = ptr->left;
382 /* build the counts for all the tokens that start with "data", and have lenghts
384 static void learn_token(unsigned char *data, int len)
386 struct token *ptr,*last_ptr;
388 unsigned int hash = HASH_BASE_OFFSET;
389 unsigned int hashes[MAX_TOK_SIZE + 1];
391 if (len > MAX_TOK_SIZE)
394 /* calculate and store the hash values for all the sub-tokens */
395 hash = rehash_token(hash, data[0]);
396 for (i = 2; i <= len; i++) {
397 hash = rehash_token(hash, data[i-1]);
398 hashes[i] = HASH_FOLD(hash);
404 for (i = len; i >= 2; i--) {
407 if (!ptr) ptr = find_token_hash(data, i, hash);
410 /* create a new token entry */
411 ptr = (struct token *) malloc(sizeof(*ptr));
413 memcpy(ptr->data, data, i);
416 /* when we create an entry, it's profit is 0 because
417 * we also take into account the size of the token on
418 * the compressed table. We then subtract GOOD_BAD_THRESHOLD
419 * so that the test to see if this token belongs to
420 * the good or bad list, is a comparison to zero */
421 ptr->profit = -GOOD_BAD_THRESHOLD;
423 ptr->next = hash_table[hash];
424 hash_table[hash] = ptr;
426 insert_token_in_group(&bad_head, ptr);
430 newprofit = ptr->profit + (ptr->len - 1);
431 /* check to see if this token needs to be moved to a
433 if((ptr->profit < 0) && (newprofit >= 0)) {
434 remove_token_from_group(ptr);
435 insert_token_in_group(&good_head,ptr);
437 ptr->profit = newprofit;
440 if (last_ptr) last_ptr->smaller = ptr;
447 /* decrease the counts for all the tokens that start with "data", and have lenghts
448 * from 2 to "len". This function is much simpler than learn_token because we have
449 * more guarantees (tho tokens exist, the ->smaller pointer is set, etc.)
450 * The two separate functions exist only because of compression performance */
451 static void forget_token(unsigned char *data, int len)
457 if (len > MAX_TOK_SIZE) len = MAX_TOK_SIZE;
459 hash = hash_token(data, len);
460 ptr = find_token_hash(data, len, hash);
462 for (i = len; i >= 2; i--) {
464 newprofit = ptr->profit - (ptr->len - 1);
465 if ((ptr->profit >= 0) && (newprofit < 0)) {
466 remove_token_from_group(ptr);
467 insert_token_in_group(&bad_head, ptr);
469 ptr->profit=newprofit;
475 /* count all the possible tokens in a symbol */
476 static void learn_symbol(unsigned char *symbol, int len)
480 for (i = 0; i < len - 1; i++)
481 learn_token(symbol + i, len - i);
484 /* decrease the count for all the possible tokens in a symbol */
485 static void forget_symbol(unsigned char *symbol, int len)
489 for (i = 0; i < len - 1; i++)
490 forget_token(symbol + i, len - i);
493 /* set all the symbol flags and do the initial token count */
494 static void build_initial_tok_table(void)
496 int i, use_it, valid;
499 for (i = 0; i < cnt; i++) {
501 if ( symbol_valid(&table[i]) ) {
502 table[i].flags |= SYM_FLAG_VALID;
508 for (i = 0; i < cnt; i++) {
510 /* subsample the available symbols. This method is almost like
511 * a Bresenham's algorithm to get uniformly distributed samples
512 * across the symbol table */
513 if (table[i].flags & SYM_FLAG_VALID) {
515 use_it += WORKING_SET;
517 if (use_it >= valid) {
518 table[i].flags |= SYM_FLAG_SAMPLED;
522 if (table[i].flags & SYM_FLAG_SAMPLED)
523 learn_symbol(table[i].sym, table[i].len);
527 /* replace a given token in all the valid symbols. Use the sampled symbols
528 * to update the counts */
529 static void compress_symbols(unsigned char *str, int tlen, int idx)
531 int i, len, learn, size;
534 for (i = 0; i < cnt; i++) {
536 if (!(table[i].flags & SYM_FLAG_VALID)) continue;
543 /* find the token on the symbol */
544 p = (unsigned char *) strstr((char *) p, (char *) str);
548 /* if this symbol was used to count, decrease it */
549 if (table[i].flags & SYM_FLAG_SAMPLED)
550 forget_symbol(table[i].sym, len);
555 size = (len - (p - table[i].sym)) - tlen + 1;
556 memmove(p + 1, p + tlen, size);
560 } while (size >= tlen);
564 /* if this symbol was used to count, learn it again */
565 if(table[i].flags & SYM_FLAG_SAMPLED)
566 learn_symbol(table[i].sym, len);
571 /* search the token with the maximum profit */
572 static struct token *find_best_token(void)
574 struct token *ptr,*best,*head;
579 /* failsafe: if the "good" list is empty search from the "bad" list */
580 if(good_head.right == &good_head) head = &bad_head;
581 else head = &good_head;
585 while (ptr != head) {
586 if (ptr->profit > bestprofit) {
587 bestprofit = ptr->profit;
596 /* this is the core of the algorithm: calculate the "best" table */
597 static void optimize_result(void)
602 /* using the '\0' symbol last allows compress_symbols to use standard
603 * fast string functions */
604 for (i = 255; i >= 0; i--) {
606 /* if this table slot is empty (it is not used by an actual
607 * original char code */
608 if (!best_table_len[i]) {
610 /* find the token with the breates profit value */
611 best = find_best_token();
613 /* place it in the "best" table */
614 best_table_len[i] = best->len;
615 memcpy(best_table[i], best->data, best_table_len[i]);
616 /* zero terminate the token so that we can use strstr
617 in compress_symbols */
618 best_table[i][best_table_len[i]]='\0';
620 /* replace this token in all the valid symbols */
621 compress_symbols(best_table[i], best_table_len[i], i);
626 /* start by placing the symbols that are actually used on the table */
627 static void insert_real_symbols_in_table(void)
631 memset(best_table, 0, sizeof(best_table));
632 memset(best_table_len, 0, sizeof(best_table_len));
634 for (i = 0; i < cnt; i++) {
635 if (table[i].flags & SYM_FLAG_VALID) {
636 for (j = 0; j < table[i].len; j++) {
645 static void optimize_token_table(void)
647 memset(hash_table, 0, sizeof(hash_table));
649 good_head.left = &good_head;
650 good_head.right = &good_head;
652 bad_head.left = &bad_head;
653 bad_head.right = &bad_head;
655 build_initial_tok_table();
657 insert_real_symbols_in_table();
664 main(int argc, char **argv)
666 if (argc == 2 && strcmp(argv[1], "--all-symbols") == 0)
672 optimize_token_table();