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