kallsyms: support kernel symbols in Blackfin on-chip memory
[safe/jmp/linux-2.6] / scripts / kallsyms.c
1 /* Generate assembler source containing symbol information
2  *
3  * Copyright 2002       by Kai Germaschewski
4  *
5  * This software may be used and distributed according to the terms
6  * of the GNU General Public License, incorporated herein by reference.
7  *
8  * Usage: nm -n vmlinux | scripts/kallsyms [--all-symbols] > symbols.S
9  *
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
17  *  of about 50%.
18  *
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <ctype.h>
25
26 #define KSYM_NAME_LEN           128
27
28 struct sym_entry {
29         unsigned long long addr;
30         unsigned int len;
31         unsigned int start_pos;
32         unsigned char *sym;
33 };
34
35 static struct sym_entry *table;
36 static unsigned int table_size, table_cnt;
37 static unsigned long long _text, _stext, _etext, _sinittext, _einittext;
38 static unsigned long long _stext_l1, _etext_l1, _stext_l2, _etext_l2;
39 static int all_symbols = 0;
40 static char symbol_prefix_char = '\0';
41
42 int token_profit[0x10000];
43
44 /* the table that holds the result of the compression */
45 unsigned char best_table[256][2];
46 unsigned char best_table_len[256];
47
48
49 static void usage(void)
50 {
51         fprintf(stderr, "Usage: kallsyms [--all-symbols] [--symbol-prefix=<prefix char>] < in.map > out.S\n");
52         exit(1);
53 }
54
55 /*
56  * This ignores the intensely annoying "mapping symbols" found
57  * in ARM ELF files: $a, $t and $d.
58  */
59 static inline int is_arm_mapping_symbol(const char *str)
60 {
61         return str[0] == '$' && strchr("atd", str[1])
62                && (str[2] == '\0' || str[2] == '.');
63 }
64
65 static int read_symbol(FILE *in, struct sym_entry *s)
66 {
67         char str[500];
68         char *sym, stype;
69         int rc;
70
71         rc = fscanf(in, "%llx %c %499s\n", &s->addr, &stype, str);
72         if (rc != 3) {
73                 if (rc != EOF) {
74                         /* skip line */
75                         fgets(str, 500, in);
76                 }
77                 return -1;
78         }
79
80         sym = str;
81         /* skip prefix char */
82         if (symbol_prefix_char && str[0] == symbol_prefix_char)
83                 sym++;
84
85         /* Ignore most absolute/undefined (?) symbols. */
86         if (strcmp(sym, "_text") == 0)
87                 _text = s->addr;
88         else if (strcmp(sym, "_stext") == 0)
89                 _stext = s->addr;
90         else if (strcmp(sym, "_etext") == 0)
91                 _etext = s->addr;
92         else if (strcmp(sym, "_sinittext") == 0)
93                 _sinittext = s->addr;
94         else if (strcmp(sym, "_einittext") == 0)
95                 _einittext = s->addr;
96         else if (strcmp(sym, "_stext_l1") == 0)
97                 _stext_l1 = s->addr;
98         else if (strcmp(sym, "_etext_l1") == 0)
99                 _etext_l1 = s->addr;
100         else if (strcmp(sym, "_stext_l2") == 0)
101                 _stext_l2 = s->addr;
102         else if (strcmp(sym, "_etext_l2") == 0)
103                 _etext_l2 = s->addr;
104         else if (toupper(stype) == 'A')
105         {
106                 /* Keep these useful absolute symbols */
107                 if (strcmp(sym, "__kernel_syscall_via_break") &&
108                     strcmp(sym, "__kernel_syscall_via_epc") &&
109                     strcmp(sym, "__kernel_sigtramp") &&
110                     strcmp(sym, "__gp"))
111                         return -1;
112
113         }
114         else if (toupper(stype) == 'U' ||
115                  is_arm_mapping_symbol(sym))
116                 return -1;
117         /* exclude also MIPS ELF local symbols ($L123 instead of .L123) */
118         else if (str[0] == '$')
119                 return -1;
120         /* exclude debugging symbols */
121         else if (stype == 'N')
122                 return -1;
123
124         /* include the type field in the symbol name, so that it gets
125          * compressed together */
126         s->len = strlen(str) + 1;
127         s->sym = malloc(s->len + 1);
128         if (!s->sym) {
129                 fprintf(stderr, "kallsyms failure: "
130                         "unable to allocate required amount of memory\n");
131                 exit(EXIT_FAILURE);
132         }
133         strcpy((char *)s->sym + 1, str);
134         s->sym[0] = stype;
135
136         return 0;
137 }
138
139 static int symbol_valid(struct sym_entry *s)
140 {
141         /* Symbols which vary between passes.  Passes 1 and 2 must have
142          * identical symbol lists.  The kallsyms_* symbols below are only added
143          * after pass 1, they would be included in pass 2 when --all-symbols is
144          * specified so exclude them to get a stable symbol list.
145          */
146         static char *special_symbols[] = {
147                 "kallsyms_addresses",
148                 "kallsyms_num_syms",
149                 "kallsyms_names",
150                 "kallsyms_markers",
151                 "kallsyms_token_table",
152                 "kallsyms_token_index",
153
154         /* Exclude linker generated symbols which vary between passes */
155                 "_SDA_BASE_",           /* ppc */
156                 "_SDA2_BASE_",          /* ppc */
157                 NULL };
158         int i;
159         int offset = 1;
160
161         /* skip prefix char */
162         if (symbol_prefix_char && *(s->sym + 1) == symbol_prefix_char)
163                 offset++;
164
165         /* if --all-symbols is not specified, then symbols outside the text
166          * and inittext sections are discarded */
167         if (!all_symbols) {
168                 if ((s->addr < _stext || s->addr > _etext)
169                     && (s->addr < _sinittext || s->addr > _einittext)
170                     && (s->addr < _stext_l1 || s->addr > _etext_l1)
171                     && (s->addr < _stext_l2 || s->addr > _etext_l2))
172                         return 0;
173                 /* Corner case.  Discard any symbols with the same value as
174                  * _etext _einittext; they can move between pass 1 and 2 when
175                  * the kallsyms data are added.  If these symbols move then
176                  * they may get dropped in pass 2, which breaks the kallsyms
177                  * rules.
178                  */
179                 if ((s->addr == _etext &&
180                                 strcmp((char *)s->sym + offset, "_etext")) ||
181                     (s->addr == _einittext &&
182                                 strcmp((char *)s->sym + offset, "_einittext")))
183                         return 0;
184         }
185
186         /* Exclude symbols which vary between passes. */
187         if (strstr((char *)s->sym + offset, "_compiled."))
188                 return 0;
189
190         for (i = 0; special_symbols[i]; i++)
191                 if( strcmp((char *)s->sym + offset, special_symbols[i]) == 0 )
192                         return 0;
193
194         return 1;
195 }
196
197 static void read_map(FILE *in)
198 {
199         while (!feof(in)) {
200                 if (table_cnt >= table_size) {
201                         table_size += 10000;
202                         table = realloc(table, sizeof(*table) * table_size);
203                         if (!table) {
204                                 fprintf(stderr, "out of memory\n");
205                                 exit (1);
206                         }
207                 }
208                 if (read_symbol(in, &table[table_cnt]) == 0) {
209                         table[table_cnt].start_pos = table_cnt;
210                         table_cnt++;
211                 }
212         }
213 }
214
215 static void output_label(char *label)
216 {
217         if (symbol_prefix_char)
218                 printf(".globl %c%s\n", symbol_prefix_char, label);
219         else
220                 printf(".globl %s\n", label);
221         printf("\tALGN\n");
222         if (symbol_prefix_char)
223                 printf("%c%s:\n", symbol_prefix_char, label);
224         else
225                 printf("%s:\n", label);
226 }
227
228 /* uncompress a compressed symbol. When this function is called, the best table
229  * might still be compressed itself, so the function needs to be recursive */
230 static int expand_symbol(unsigned char *data, int len, char *result)
231 {
232         int c, rlen, total=0;
233
234         while (len) {
235                 c = *data;
236                 /* if the table holds a single char that is the same as the one
237                  * we are looking for, then end the search */
238                 if (best_table[c][0]==c && best_table_len[c]==1) {
239                         *result++ = c;
240                         total++;
241                 } else {
242                         /* if not, recurse and expand */
243                         rlen = expand_symbol(best_table[c], best_table_len[c], result);
244                         total += rlen;
245                         result += rlen;
246                 }
247                 data++;
248                 len--;
249         }
250         *result=0;
251
252         return total;
253 }
254
255 static void write_src(void)
256 {
257         unsigned int i, k, off;
258         unsigned int best_idx[256];
259         unsigned int *markers;
260         char buf[KSYM_NAME_LEN];
261
262         printf("#include <asm/types.h>\n");
263         printf("#if BITS_PER_LONG == 64\n");
264         printf("#define PTR .quad\n");
265         printf("#define ALGN .align 8\n");
266         printf("#else\n");
267         printf("#define PTR .long\n");
268         printf("#define ALGN .align 4\n");
269         printf("#endif\n");
270
271         printf("\t.section .rodata, \"a\"\n");
272
273         /* Provide proper symbols relocatability by their '_text'
274          * relativeness.  The symbol names cannot be used to construct
275          * normal symbol references as the list of symbols contains
276          * symbols that are declared static and are private to their
277          * .o files.  This prevents .tmp_kallsyms.o or any other
278          * object from referencing them.
279          */
280         output_label("kallsyms_addresses");
281         for (i = 0; i < table_cnt; i++) {
282                 if (toupper(table[i].sym[0]) != 'A') {
283                         if (_text <= table[i].addr)
284                                 printf("\tPTR\t_text + %#llx\n",
285                                         table[i].addr - _text);
286                         else
287                                 printf("\tPTR\t_text - %#llx\n",
288                                         _text - table[i].addr);
289                 } else {
290                         printf("\tPTR\t%#llx\n", table[i].addr);
291                 }
292         }
293         printf("\n");
294
295         output_label("kallsyms_num_syms");
296         printf("\tPTR\t%d\n", table_cnt);
297         printf("\n");
298
299         /* table of offset markers, that give the offset in the compressed stream
300          * every 256 symbols */
301         markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256));
302         if (!markers) {
303                 fprintf(stderr, "kallsyms failure: "
304                         "unable to allocate required memory\n");
305                 exit(EXIT_FAILURE);
306         }
307
308         output_label("kallsyms_names");
309         off = 0;
310         for (i = 0; i < table_cnt; i++) {
311                 if ((i & 0xFF) == 0)
312                         markers[i >> 8] = off;
313
314                 printf("\t.byte 0x%02x", table[i].len);
315                 for (k = 0; k < table[i].len; k++)
316                         printf(", 0x%02x", table[i].sym[k]);
317                 printf("\n");
318
319                 off += table[i].len + 1;
320         }
321         printf("\n");
322
323         output_label("kallsyms_markers");
324         for (i = 0; i < ((table_cnt + 255) >> 8); i++)
325                 printf("\tPTR\t%d\n", markers[i]);
326         printf("\n");
327
328         free(markers);
329
330         output_label("kallsyms_token_table");
331         off = 0;
332         for (i = 0; i < 256; i++) {
333                 best_idx[i] = off;
334                 expand_symbol(best_table[i], best_table_len[i], buf);
335                 printf("\t.asciz\t\"%s\"\n", buf);
336                 off += strlen(buf) + 1;
337         }
338         printf("\n");
339
340         output_label("kallsyms_token_index");
341         for (i = 0; i < 256; i++)
342                 printf("\t.short\t%d\n", best_idx[i]);
343         printf("\n");
344 }
345
346
347 /* table lookup compression functions */
348
349 /* count all the possible tokens in a symbol */
350 static void learn_symbol(unsigned char *symbol, int len)
351 {
352         int i;
353
354         for (i = 0; i < len - 1; i++)
355                 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++;
356 }
357
358 /* decrease the count for all the possible tokens in a symbol */
359 static void forget_symbol(unsigned char *symbol, int len)
360 {
361         int i;
362
363         for (i = 0; i < len - 1; i++)
364                 token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--;
365 }
366
367 /* remove all the invalid symbols from the table and do the initial token count */
368 static void build_initial_tok_table(void)
369 {
370         unsigned int i, pos;
371
372         pos = 0;
373         for (i = 0; i < table_cnt; i++) {
374                 if ( symbol_valid(&table[i]) ) {
375                         if (pos != i)
376                                 table[pos] = table[i];
377                         learn_symbol(table[pos].sym, table[pos].len);
378                         pos++;
379                 }
380         }
381         table_cnt = pos;
382 }
383
384 static void *find_token(unsigned char *str, int len, unsigned char *token)
385 {
386         int i;
387
388         for (i = 0; i < len - 1; i++) {
389                 if (str[i] == token[0] && str[i+1] == token[1])
390                         return &str[i];
391         }
392         return NULL;
393 }
394
395 /* replace a given token in all the valid symbols. Use the sampled symbols
396  * to update the counts */
397 static void compress_symbols(unsigned char *str, int idx)
398 {
399         unsigned int i, len, size;
400         unsigned char *p1, *p2;
401
402         for (i = 0; i < table_cnt; i++) {
403
404                 len = table[i].len;
405                 p1 = table[i].sym;
406
407                 /* find the token on the symbol */
408                 p2 = find_token(p1, len, str);
409                 if (!p2) continue;
410
411                 /* decrease the counts for this symbol's tokens */
412                 forget_symbol(table[i].sym, len);
413
414                 size = len;
415
416                 do {
417                         *p2 = idx;
418                         p2++;
419                         size -= (p2 - p1);
420                         memmove(p2, p2 + 1, size);
421                         p1 = p2;
422                         len--;
423
424                         if (size < 2) break;
425
426                         /* find the token on the symbol */
427                         p2 = find_token(p1, size, str);
428
429                 } while (p2);
430
431                 table[i].len = len;
432
433                 /* increase the counts for this symbol's new tokens */
434                 learn_symbol(table[i].sym, len);
435         }
436 }
437
438 /* search the token with the maximum profit */
439 static int find_best_token(void)
440 {
441         int i, best, bestprofit;
442
443         bestprofit=-10000;
444         best = 0;
445
446         for (i = 0; i < 0x10000; i++) {
447                 if (token_profit[i] > bestprofit) {
448                         best = i;
449                         bestprofit = token_profit[i];
450                 }
451         }
452         return best;
453 }
454
455 /* this is the core of the algorithm: calculate the "best" table */
456 static void optimize_result(void)
457 {
458         int i, best;
459
460         /* using the '\0' symbol last allows compress_symbols to use standard
461          * fast string functions */
462         for (i = 255; i >= 0; i--) {
463
464                 /* if this table slot is empty (it is not used by an actual
465                  * original char code */
466                 if (!best_table_len[i]) {
467
468                         /* find the token with the breates profit value */
469                         best = find_best_token();
470
471                         /* place it in the "best" table */
472                         best_table_len[i] = 2;
473                         best_table[i][0] = best & 0xFF;
474                         best_table[i][1] = (best >> 8) & 0xFF;
475
476                         /* replace this token in all the valid symbols */
477                         compress_symbols(best_table[i], i);
478                 }
479         }
480 }
481
482 /* start by placing the symbols that are actually used on the table */
483 static void insert_real_symbols_in_table(void)
484 {
485         unsigned int i, j, c;
486
487         memset(best_table, 0, sizeof(best_table));
488         memset(best_table_len, 0, sizeof(best_table_len));
489
490         for (i = 0; i < table_cnt; i++) {
491                 for (j = 0; j < table[i].len; j++) {
492                         c = table[i].sym[j];
493                         best_table[c][0]=c;
494                         best_table_len[c]=1;
495                 }
496         }
497 }
498
499 static void optimize_token_table(void)
500 {
501         build_initial_tok_table();
502
503         insert_real_symbols_in_table();
504
505         /* When valid symbol is not registered, exit to error */
506         if (!table_cnt) {
507                 fprintf(stderr, "No valid symbol.\n");
508                 exit(1);
509         }
510
511         optimize_result();
512 }
513
514 /* guess for "linker script provide" symbol */
515 static int may_be_linker_script_provide_symbol(const struct sym_entry *se)
516 {
517         const char *symbol = (char *)se->sym + 1;
518         int len = se->len - 1;
519
520         if (len < 8)
521                 return 0;
522
523         if (symbol[0] != '_' || symbol[1] != '_')
524                 return 0;
525
526         /* __start_XXXXX */
527         if (!memcmp(symbol + 2, "start_", 6))
528                 return 1;
529
530         /* __stop_XXXXX */
531         if (!memcmp(symbol + 2, "stop_", 5))
532                 return 1;
533
534         /* __end_XXXXX */
535         if (!memcmp(symbol + 2, "end_", 4))
536                 return 1;
537
538         /* __XXXXX_start */
539         if (!memcmp(symbol + len - 6, "_start", 6))
540                 return 1;
541
542         /* __XXXXX_end */
543         if (!memcmp(symbol + len - 4, "_end", 4))
544                 return 1;
545
546         return 0;
547 }
548
549 static int prefix_underscores_count(const char *str)
550 {
551         const char *tail = str;
552
553         while (*tail != '_')
554                 tail++;
555
556         return tail - str;
557 }
558
559 static int compare_symbols(const void *a, const void *b)
560 {
561         const struct sym_entry *sa;
562         const struct sym_entry *sb;
563         int wa, wb;
564
565         sa = a;
566         sb = b;
567
568         /* sort by address first */
569         if (sa->addr > sb->addr)
570                 return 1;
571         if (sa->addr < sb->addr)
572                 return -1;
573
574         /* sort by "weakness" type */
575         wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W');
576         wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W');
577         if (wa != wb)
578                 return wa - wb;
579
580         /* sort by "linker script provide" type */
581         wa = may_be_linker_script_provide_symbol(sa);
582         wb = may_be_linker_script_provide_symbol(sb);
583         if (wa != wb)
584                 return wa - wb;
585
586         /* sort by the number of prefix underscores */
587         wa = prefix_underscores_count((const char *)sa->sym + 1);
588         wb = prefix_underscores_count((const char *)sb->sym + 1);
589         if (wa != wb)
590                 return wa - wb;
591
592         /* sort by initial order, so that other symbols are left undisturbed */
593         return sa->start_pos - sb->start_pos;
594 }
595
596 static void sort_symbols(void)
597 {
598         qsort(table, table_cnt, sizeof(struct sym_entry), compare_symbols);
599 }
600
601 int main(int argc, char **argv)
602 {
603         if (argc >= 2) {
604                 int i;
605                 for (i = 1; i < argc; i++) {
606                         if(strcmp(argv[i], "--all-symbols") == 0)
607                                 all_symbols = 1;
608                         else if (strncmp(argv[i], "--symbol-prefix=", 16) == 0) {
609                                 char *p = &argv[i][16];
610                                 /* skip quote */
611                                 if ((*p == '"' && *(p+2) == '"') || (*p == '\'' && *(p+2) == '\''))
612                                         p++;
613                                 symbol_prefix_char = *p;
614                         } else
615                                 usage();
616                 }
617         } else if (argc != 1)
618                 usage();
619
620         read_map(stdin);
621         sort_symbols();
622         optimize_token_table();
623         write_src();
624
625         return 0;
626 }