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