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