kbuild: code refactoring in modpost
[sfrench/cifs-2.6.git] / scripts / mod / modpost.c
1 /* Postprocess module symbol versions
2  *
3  * Copyright 2003       Kai Germaschewski
4  * Copyright 2002-2004  Rusty Russell, IBM Corporation
5  * Copyright 2006-2008  Sam Ravnborg
6  * Based in part on module-init-tools/depmod.c,file2alias
7  *
8  * This software may be used and distributed according to the terms
9  * of the GNU General Public License, incorporated herein by reference.
10  *
11  * Usage: modpost vmlinux module1.o module2.o ...
12  */
13
14 #include <ctype.h>
15 #include "modpost.h"
16 #include "../../include/linux/license.h"
17
18 /* Are we using CONFIG_MODVERSIONS? */
19 int modversions = 0;
20 /* Warn about undefined symbols? (do so if we have vmlinux) */
21 int have_vmlinux = 0;
22 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
23 static int all_versions = 0;
24 /* If we are modposting external module set to 1 */
25 static int external_module = 0;
26 /* Warn about section mismatch in vmlinux if set to 1 */
27 static int vmlinux_section_warnings = 1;
28 /* Only warn about unresolved symbols */
29 static int warn_unresolved = 0;
30 /* How a symbol is exported */
31 enum export {
32         export_plain,      export_unused,     export_gpl,
33         export_unused_gpl, export_gpl_future, export_unknown
34 };
35
36 #define PRINTF __attribute__ ((format (printf, 1, 2)))
37
38 PRINTF void fatal(const char *fmt, ...)
39 {
40         va_list arglist;
41
42         fprintf(stderr, "FATAL: ");
43
44         va_start(arglist, fmt);
45         vfprintf(stderr, fmt, arglist);
46         va_end(arglist);
47
48         exit(1);
49 }
50
51 PRINTF void warn(const char *fmt, ...)
52 {
53         va_list arglist;
54
55         fprintf(stderr, "WARNING: ");
56
57         va_start(arglist, fmt);
58         vfprintf(stderr, fmt, arglist);
59         va_end(arglist);
60 }
61
62 PRINTF void merror(const char *fmt, ...)
63 {
64         va_list arglist;
65
66         fprintf(stderr, "ERROR: ");
67
68         va_start(arglist, fmt);
69         vfprintf(stderr, fmt, arglist);
70         va_end(arglist);
71 }
72
73 static int is_vmlinux(const char *modname)
74 {
75         const char *myname;
76
77         myname = strrchr(modname, '/');
78         if (myname)
79                 myname++;
80         else
81                 myname = modname;
82
83         return (strcmp(myname, "vmlinux") == 0) ||
84                (strcmp(myname, "vmlinux.o") == 0);
85 }
86
87 void *do_nofail(void *ptr, const char *expr)
88 {
89         if (!ptr)
90                 fatal("modpost: Memory allocation failure: %s.\n", expr);
91
92         return ptr;
93 }
94
95 /* A list of all modules we processed */
96 static struct module *modules;
97
98 static struct module *find_module(char *modname)
99 {
100         struct module *mod;
101
102         for (mod = modules; mod; mod = mod->next)
103                 if (strcmp(mod->name, modname) == 0)
104                         break;
105         return mod;
106 }
107
108 static struct module *new_module(char *modname)
109 {
110         struct module *mod;
111         char *p, *s;
112
113         mod = NOFAIL(malloc(sizeof(*mod)));
114         memset(mod, 0, sizeof(*mod));
115         p = NOFAIL(strdup(modname));
116
117         /* strip trailing .o */
118         s = strrchr(p, '.');
119         if (s != NULL)
120                 if (strcmp(s, ".o") == 0)
121                         *s = '\0';
122
123         /* add to list */
124         mod->name = p;
125         mod->gpl_compatible = -1;
126         mod->next = modules;
127         modules = mod;
128
129         return mod;
130 }
131
132 /* A hash of all exported symbols,
133  * struct symbol is also used for lists of unresolved symbols */
134
135 #define SYMBOL_HASH_SIZE 1024
136
137 struct symbol {
138         struct symbol *next;
139         struct module *module;
140         unsigned int crc;
141         int crc_valid;
142         unsigned int weak:1;
143         unsigned int vmlinux:1;    /* 1 if symbol is defined in vmlinux */
144         unsigned int kernel:1;     /* 1 if symbol is from kernel
145                                     *  (only for external modules) **/
146         unsigned int preloaded:1;  /* 1 if symbol from Module.symvers */
147         enum export  export;       /* Type of export */
148         char name[0];
149 };
150
151 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
152
153 /* This is based on the hash agorithm from gdbm, via tdb */
154 static inline unsigned int tdb_hash(const char *name)
155 {
156         unsigned value; /* Used to compute the hash value.  */
157         unsigned   i;   /* Used to cycle through random values. */
158
159         /* Set the initial value from the key size. */
160         for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
161                 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
162
163         return (1103515243 * value + 12345);
164 }
165
166 /**
167  * Allocate a new symbols for use in the hash of exported symbols or
168  * the list of unresolved symbols per module
169  **/
170 static struct symbol *alloc_symbol(const char *name, unsigned int weak,
171                                    struct symbol *next)
172 {
173         struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
174
175         memset(s, 0, sizeof(*s));
176         strcpy(s->name, name);
177         s->weak = weak;
178         s->next = next;
179         return s;
180 }
181
182 /* For the hash of exported symbols */
183 static struct symbol *new_symbol(const char *name, struct module *module,
184                                  enum export export)
185 {
186         unsigned int hash;
187         struct symbol *new;
188
189         hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
190         new = symbolhash[hash] = alloc_symbol(name, 0, symbolhash[hash]);
191         new->module = module;
192         new->export = export;
193         return new;
194 }
195
196 static struct symbol *find_symbol(const char *name)
197 {
198         struct symbol *s;
199
200         /* For our purposes, .foo matches foo.  PPC64 needs this. */
201         if (name[0] == '.')
202                 name++;
203
204         for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) {
205                 if (strcmp(s->name, name) == 0)
206                         return s;
207         }
208         return NULL;
209 }
210
211 static struct {
212         const char *str;
213         enum export export;
214 } export_list[] = {
215         { .str = "EXPORT_SYMBOL",            .export = export_plain },
216         { .str = "EXPORT_UNUSED_SYMBOL",     .export = export_unused },
217         { .str = "EXPORT_SYMBOL_GPL",        .export = export_gpl },
218         { .str = "EXPORT_UNUSED_SYMBOL_GPL", .export = export_unused_gpl },
219         { .str = "EXPORT_SYMBOL_GPL_FUTURE", .export = export_gpl_future },
220         { .str = "(unknown)",                .export = export_unknown },
221 };
222
223
224 static const char *export_str(enum export ex)
225 {
226         return export_list[ex].str;
227 }
228
229 static enum export export_no(const char *s)
230 {
231         int i;
232
233         if (!s)
234                 return export_unknown;
235         for (i = 0; export_list[i].export != export_unknown; i++) {
236                 if (strcmp(export_list[i].str, s) == 0)
237                         return export_list[i].export;
238         }
239         return export_unknown;
240 }
241
242 static enum export export_from_sec(struct elf_info *elf, Elf_Section sec)
243 {
244         if (sec == elf->export_sec)
245                 return export_plain;
246         else if (sec == elf->export_unused_sec)
247                 return export_unused;
248         else if (sec == elf->export_gpl_sec)
249                 return export_gpl;
250         else if (sec == elf->export_unused_gpl_sec)
251                 return export_unused_gpl;
252         else if (sec == elf->export_gpl_future_sec)
253                 return export_gpl_future;
254         else
255                 return export_unknown;
256 }
257
258 /**
259  * Add an exported symbol - it may have already been added without a
260  * CRC, in this case just update the CRC
261  **/
262 static struct symbol *sym_add_exported(const char *name, struct module *mod,
263                                        enum export export)
264 {
265         struct symbol *s = find_symbol(name);
266
267         if (!s) {
268                 s = new_symbol(name, mod, export);
269         } else {
270                 if (!s->preloaded) {
271                         warn("%s: '%s' exported twice. Previous export "
272                              "was in %s%s\n", mod->name, name,
273                              s->module->name,
274                              is_vmlinux(s->module->name) ?"":".ko");
275                 } else {
276                         /* In case Modules.symvers was out of date */
277                         s->module = mod;
278                 }
279         }
280         s->preloaded = 0;
281         s->vmlinux   = is_vmlinux(mod->name);
282         s->kernel    = 0;
283         s->export    = export;
284         return s;
285 }
286
287 static void sym_update_crc(const char *name, struct module *mod,
288                            unsigned int crc, enum export export)
289 {
290         struct symbol *s = find_symbol(name);
291
292         if (!s)
293                 s = new_symbol(name, mod, export);
294         s->crc = crc;
295         s->crc_valid = 1;
296 }
297
298 void *grab_file(const char *filename, unsigned long *size)
299 {
300         struct stat st;
301         void *map;
302         int fd;
303
304         fd = open(filename, O_RDONLY);
305         if (fd < 0 || fstat(fd, &st) != 0)
306                 return NULL;
307
308         *size = st.st_size;
309         map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
310         close(fd);
311
312         if (map == MAP_FAILED)
313                 return NULL;
314         return map;
315 }
316
317 /**
318   * Return a copy of the next line in a mmap'ed file.
319   * spaces in the beginning of the line is trimmed away.
320   * Return a pointer to a static buffer.
321   **/
322 char *get_next_line(unsigned long *pos, void *file, unsigned long size)
323 {
324         static char line[4096];
325         int skip = 1;
326         size_t len = 0;
327         signed char *p = (signed char *)file + *pos;
328         char *s = line;
329
330         for (; *pos < size ; (*pos)++) {
331                 if (skip && isspace(*p)) {
332                         p++;
333                         continue;
334                 }
335                 skip = 0;
336                 if (*p != '\n' && (*pos < size)) {
337                         len++;
338                         *s++ = *p++;
339                         if (len > 4095)
340                                 break; /* Too long, stop */
341                 } else {
342                         /* End of string */
343                         *s = '\0';
344                         return line;
345                 }
346         }
347         /* End of buffer */
348         return NULL;
349 }
350
351 void release_file(void *file, unsigned long size)
352 {
353         munmap(file, size);
354 }
355
356 static int parse_elf(struct elf_info *info, const char *filename)
357 {
358         unsigned int i;
359         Elf_Ehdr *hdr;
360         Elf_Shdr *sechdrs;
361         Elf_Sym  *sym;
362
363         hdr = grab_file(filename, &info->size);
364         if (!hdr) {
365                 perror(filename);
366                 exit(1);
367         }
368         info->hdr = hdr;
369         if (info->size < sizeof(*hdr)) {
370                 /* file too small, assume this is an empty .o file */
371                 return 0;
372         }
373         /* Is this a valid ELF file? */
374         if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
375             (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
376             (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
377             (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
378                 /* Not an ELF file - silently ignore it */
379                 return 0;
380         }
381         /* Fix endianness in ELF header */
382         hdr->e_shoff    = TO_NATIVE(hdr->e_shoff);
383         hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
384         hdr->e_shnum    = TO_NATIVE(hdr->e_shnum);
385         hdr->e_machine  = TO_NATIVE(hdr->e_machine);
386         hdr->e_type     = TO_NATIVE(hdr->e_type);
387         sechdrs = (void *)hdr + hdr->e_shoff;
388         info->sechdrs = sechdrs;
389
390         /* Check if file offset is correct */
391         if (hdr->e_shoff > info->size) {
392                 fatal("section header offset=%lu in file '%s' is bigger than "
393                       "filesize=%lu\n", (unsigned long)hdr->e_shoff,
394                       filename, info->size);
395                 return 0;
396         }
397
398         /* Fix endianness in section headers */
399         for (i = 0; i < hdr->e_shnum; i++) {
400                 sechdrs[i].sh_type   = TO_NATIVE(sechdrs[i].sh_type);
401                 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
402                 sechdrs[i].sh_size   = TO_NATIVE(sechdrs[i].sh_size);
403                 sechdrs[i].sh_link   = TO_NATIVE(sechdrs[i].sh_link);
404                 sechdrs[i].sh_name   = TO_NATIVE(sechdrs[i].sh_name);
405                 sechdrs[i].sh_info   = TO_NATIVE(sechdrs[i].sh_info);
406                 sechdrs[i].sh_addr   = TO_NATIVE(sechdrs[i].sh_addr);
407         }
408         /* Find symbol table. */
409         for (i = 1; i < hdr->e_shnum; i++) {
410                 const char *secstrings
411                         = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
412                 const char *secname;
413
414                 if (sechdrs[i].sh_offset > info->size) {
415                         fatal("%s is truncated. sechdrs[i].sh_offset=%lu > "
416                               "sizeof(*hrd)=%zu\n", filename,
417                               (unsigned long)sechdrs[i].sh_offset,
418                               sizeof(*hdr));
419                         return 0;
420                 }
421                 secname = secstrings + sechdrs[i].sh_name;
422                 if (strcmp(secname, ".modinfo") == 0) {
423                         info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
424                         info->modinfo_len = sechdrs[i].sh_size;
425                 } else if (strcmp(secname, "__ksymtab") == 0)
426                         info->export_sec = i;
427                 else if (strcmp(secname, "__ksymtab_unused") == 0)
428                         info->export_unused_sec = i;
429                 else if (strcmp(secname, "__ksymtab_gpl") == 0)
430                         info->export_gpl_sec = i;
431                 else if (strcmp(secname, "__ksymtab_unused_gpl") == 0)
432                         info->export_unused_gpl_sec = i;
433                 else if (strcmp(secname, "__ksymtab_gpl_future") == 0)
434                         info->export_gpl_future_sec = i;
435
436                 if (sechdrs[i].sh_type != SHT_SYMTAB)
437                         continue;
438
439                 info->symtab_start = (void *)hdr + sechdrs[i].sh_offset;
440                 info->symtab_stop  = (void *)hdr + sechdrs[i].sh_offset
441                                                  + sechdrs[i].sh_size;
442                 info->strtab       = (void *)hdr +
443                                      sechdrs[sechdrs[i].sh_link].sh_offset;
444         }
445         if (!info->symtab_start)
446                 fatal("%s has no symtab?\n", filename);
447
448         /* Fix endianness in symbols */
449         for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
450                 sym->st_shndx = TO_NATIVE(sym->st_shndx);
451                 sym->st_name  = TO_NATIVE(sym->st_name);
452                 sym->st_value = TO_NATIVE(sym->st_value);
453                 sym->st_size  = TO_NATIVE(sym->st_size);
454         }
455         return 1;
456 }
457
458 static void parse_elf_finish(struct elf_info *info)
459 {
460         release_file(info->hdr, info->size);
461 }
462
463 #define CRC_PFX     MODULE_SYMBOL_PREFIX "__crc_"
464 #define KSYMTAB_PFX MODULE_SYMBOL_PREFIX "__ksymtab_"
465
466 static void handle_modversions(struct module *mod, struct elf_info *info,
467                                Elf_Sym *sym, const char *symname)
468 {
469         unsigned int crc;
470         enum export export = export_from_sec(info, sym->st_shndx);
471
472         switch (sym->st_shndx) {
473         case SHN_COMMON:
474                 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
475                 break;
476         case SHN_ABS:
477                 /* CRC'd symbol */
478                 if (memcmp(symname, CRC_PFX, strlen(CRC_PFX)) == 0) {
479                         crc = (unsigned int) sym->st_value;
480                         sym_update_crc(symname + strlen(CRC_PFX), mod, crc,
481                                         export);
482                 }
483                 break;
484         case SHN_UNDEF:
485                 /* undefined symbol */
486                 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
487                     ELF_ST_BIND(sym->st_info) != STB_WEAK)
488                         break;
489                 /* ignore global offset table */
490                 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
491                         break;
492                 /* ignore __this_module, it will be resolved shortly */
493                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "__this_module") == 0)
494                         break;
495 /* cope with newer glibc (2.3.4 or higher) STT_ definition in elf.h */
496 #if defined(STT_REGISTER) || defined(STT_SPARC_REGISTER)
497 /* add compatibility with older glibc */
498 #ifndef STT_SPARC_REGISTER
499 #define STT_SPARC_REGISTER STT_REGISTER
500 #endif
501                 if (info->hdr->e_machine == EM_SPARC ||
502                     info->hdr->e_machine == EM_SPARCV9) {
503                         /* Ignore register directives. */
504                         if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
505                                 break;
506                         if (symname[0] == '.') {
507                                 char *munged = strdup(symname);
508                                 munged[0] = '_';
509                                 munged[1] = toupper(munged[1]);
510                                 symname = munged;
511                         }
512                 }
513 #endif
514
515                 if (memcmp(symname, MODULE_SYMBOL_PREFIX,
516                            strlen(MODULE_SYMBOL_PREFIX)) == 0) {
517                         mod->unres =
518                           alloc_symbol(symname +
519                                        strlen(MODULE_SYMBOL_PREFIX),
520                                        ELF_ST_BIND(sym->st_info) == STB_WEAK,
521                                        mod->unres);
522                 }
523                 break;
524         default:
525                 /* All exported symbols */
526                 if (memcmp(symname, KSYMTAB_PFX, strlen(KSYMTAB_PFX)) == 0) {
527                         sym_add_exported(symname + strlen(KSYMTAB_PFX), mod,
528                                         export);
529                 }
530                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "init_module") == 0)
531                         mod->has_init = 1;
532                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "cleanup_module") == 0)
533                         mod->has_cleanup = 1;
534                 break;
535         }
536 }
537
538 /**
539  * Parse tag=value strings from .modinfo section
540  **/
541 static char *next_string(char *string, unsigned long *secsize)
542 {
543         /* Skip non-zero chars */
544         while (string[0]) {
545                 string++;
546                 if ((*secsize)-- <= 1)
547                         return NULL;
548         }
549
550         /* Skip any zero padding. */
551         while (!string[0]) {
552                 string++;
553                 if ((*secsize)-- <= 1)
554                         return NULL;
555         }
556         return string;
557 }
558
559 static char *get_next_modinfo(void *modinfo, unsigned long modinfo_len,
560                               const char *tag, char *info)
561 {
562         char *p;
563         unsigned int taglen = strlen(tag);
564         unsigned long size = modinfo_len;
565
566         if (info) {
567                 size -= info - (char *)modinfo;
568                 modinfo = next_string(info, &size);
569         }
570
571         for (p = modinfo; p; p = next_string(p, &size)) {
572                 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
573                         return p + taglen + 1;
574         }
575         return NULL;
576 }
577
578 static char *get_modinfo(void *modinfo, unsigned long modinfo_len,
579                          const char *tag)
580
581 {
582         return get_next_modinfo(modinfo, modinfo_len, tag, NULL);
583 }
584
585 /**
586  * Test if string s ends in string sub
587  * return 0 if match
588  **/
589 static int strrcmp(const char *s, const char *sub)
590 {
591         int slen, sublen;
592
593         if (!s || !sub)
594                 return 1;
595
596         slen = strlen(s);
597         sublen = strlen(sub);
598
599         if ((slen == 0) || (sublen == 0))
600                 return 1;
601
602         if (sublen > slen)
603                 return 1;
604
605         return memcmp(s + slen - sublen, sub, sublen);
606 }
607
608 /*
609  * Functions used only during module init is marked __init and is stored in
610  * a .init.text section. Likewise data is marked __initdata and stored in
611  * a .init.data section.
612  * If this section is one of these sections return 1
613  * See include/linux/init.h for the details
614  */
615 static int init_section(const char *name)
616 {
617         if (strcmp(name, ".init") == 0)
618                 return 1;
619         if (strncmp(name, ".init.", strlen(".init.")) == 0)
620                 return 1;
621         return 0;
622 }
623
624 /*
625  * Functions used only during module exit is marked __exit and is stored in
626  * a .exit.text section. Likewise data is marked __exitdata and stored in
627  * a .exit.data section.
628  * If this section is one of these sections return 1
629  * See include/linux/init.h for the details
630  **/
631 static int exit_section(const char *name)
632 {
633         if (strcmp(name, ".exit.text") == 0)
634                 return 1;
635         if (strcmp(name, ".exit.data") == 0)
636                 return 1;
637         return 0;
638
639 }
640
641 /*
642  * Data sections are named like this:
643  * .data | .data.rel | .data.rel.*
644  * Return 1 if the specified section is a data section
645  */
646 static int data_section(const char *name)
647 {
648         if ((strcmp(name, ".data") == 0) ||
649             (strcmp(name, ".data.rel") == 0) ||
650             (strncmp(name, ".data.rel.", strlen(".data.rel.")) == 0))
651                 return 1;
652         else
653                 return 0;
654 }
655
656 /**
657  * Whitelist to allow certain references to pass with no warning.
658  *
659  * Pattern 0:
660  *   Do not warn if funtion/data are marked with __init_refok/__initdata_refok.
661  *   The pattern is identified by:
662  *   fromsec = .text.init.refok* | .data.init.refok*
663  *
664  * Pattern 1:
665  *   If a module parameter is declared __initdata and permissions=0
666  *   then this is legal despite the warning generated.
667  *   We cannot see value of permissions here, so just ignore
668  *   this pattern.
669  *   The pattern is identified by:
670  *   tosec   = .init.data
671  *   fromsec = .data*
672  *   atsym   =__param*
673  *
674  * Pattern 2:
675  *   Many drivers utilise a *driver container with references to
676  *   add, remove, probe functions etc.
677  *   These functions may often be marked __init and we do not want to
678  *   warn here.
679  *   the pattern is identified by:
680  *   tosec   = init or exit section
681  *   fromsec = data section
682  *   atsym = *driver, *_template, *_sht, *_ops, *_probe,
683  *           *probe_one, *_console, *_timer
684  *
685  * Pattern 3:
686  *   Whitelist all refereces from .text.head to .init.data
687  *   Whitelist all refereces from .text.head to .init.text
688  *
689  * Pattern 4:
690  *   Some symbols belong to init section but still it is ok to reference
691  *   these from non-init sections as these symbols don't have any memory
692  *   allocated for them and symbol address and value are same. So even
693  *   if init section is freed, its ok to reference those symbols.
694  *   For ex. symbols marking the init section boundaries.
695  *   This pattern is identified by
696  *   refsymname = __init_begin, _sinittext, _einittext
697  *
698  * Pattern 5:
699  *   Xtensa uses literal sections for constants that are accessed PC-relative.
700  *   Literal sections may safely reference their text sections.
701  *   (Note that the name for the literal section omits any trailing '.text')
702  *   tosec = <section>[.text]
703  *   fromsec = <section>.literal
704  **/
705 static int secref_whitelist(const char *modname, const char *tosec,
706                             const char *fromsec, const char *atsym,
707                             const char *refsymname)
708 {
709         int len;
710         const char **s;
711         const char *pat2sym[] = {
712                 "driver",
713                 "_template", /* scsi uses *_template a lot */
714                 "_timer",    /* arm uses ops structures named _timer a lot */
715                 "_sht",      /* scsi also used *_sht to some extent */
716                 "_ops",
717                 "_probe",
718                 "_probe_one",
719                 "_console",
720                 NULL
721         };
722
723         const char *pat3refsym[] = {
724                 "__init_begin",
725                 "_sinittext",
726                 "_einittext",
727                 NULL
728         };
729
730         /* Check for pattern 0 */
731         if ((strncmp(fromsec, ".text.init.refok", strlen(".text.init.refok")) == 0) ||
732             (strncmp(fromsec, ".exit.text.refok", strlen(".exit.text.refok")) == 0) ||
733             (strncmp(fromsec, ".data.init.refok", strlen(".data.init.refok")) == 0))
734                 return 1;
735
736         /* Check for pattern 1 */
737         if ((strcmp(tosec, ".init.data") == 0) &&
738             (strncmp(fromsec, ".data", strlen(".data")) == 0) &&
739             (strncmp(atsym, "__param", strlen("__param")) == 0))
740                 return 1;
741
742         /* Check for pattern 2 */
743         if ((init_section(tosec) || exit_section(tosec))
744             && data_section(fromsec))
745                 for (s = pat2sym; *s; s++)
746                         if (strrcmp(atsym, *s) == 0)
747                                 return 1;
748
749         /* Check for pattern 3 */
750         if ((strcmp(fromsec, ".text.head") == 0) &&
751             ((strcmp(tosec, ".init.data") == 0) ||
752             (strcmp(tosec, ".init.text") == 0)))
753         return 1;
754
755         /* Check for pattern 4 */
756         for (s = pat3refsym; *s; s++)
757                 if (strcmp(refsymname, *s) == 0)
758                         return 1;
759
760         /* Check for pattern 5 */
761         if (strrcmp(tosec, ".text") == 0)
762                 len = strlen(tosec) - strlen(".text");
763         else
764                 len = strlen(tosec);
765         if ((strncmp(tosec, fromsec, len) == 0) && (strlen(fromsec) > len) &&
766             (strcmp(fromsec + len, ".literal") == 0))
767                 return 1;
768
769         return 0;
770 }
771
772 /**
773  * Find symbol based on relocation record info.
774  * In some cases the symbol supplied is a valid symbol so
775  * return refsym. If st_name != 0 we assume this is a valid symbol.
776  * In other cases the symbol needs to be looked up in the symbol table
777  * based on section and address.
778  *  **/
779 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
780                                 Elf_Sym *relsym)
781 {
782         Elf_Sym *sym;
783         Elf_Sym *near = NULL;
784         Elf64_Sword distance = 20;
785         Elf64_Sword d;
786
787         if (relsym->st_name != 0)
788                 return relsym;
789         for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
790                 if (sym->st_shndx != relsym->st_shndx)
791                         continue;
792                 if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
793                         continue;
794                 if (sym->st_value == addr)
795                         return sym;
796                 /* Find a symbol nearby - addr are maybe negative */
797                 d = sym->st_value - addr;
798                 if (d < 0)
799                         d = addr - sym->st_value;
800                 if (d < distance) {
801                         distance = d;
802                         near = sym;
803                 }
804         }
805         /* We need a close match */
806         if (distance < 20)
807                 return near;
808         else
809                 return NULL;
810 }
811
812 static inline int is_arm_mapping_symbol(const char *str)
813 {
814         return str[0] == '$' && strchr("atd", str[1])
815                && (str[2] == '\0' || str[2] == '.');
816 }
817
818 /*
819  * If there's no name there, ignore it; likewise, ignore it if it's
820  * one of the magic symbols emitted used by current ARM tools.
821  *
822  * Otherwise if find_symbols_between() returns those symbols, they'll
823  * fail the whitelist tests and cause lots of false alarms ... fixable
824  * only by merging __exit and __init sections into __text, bloating
825  * the kernel (which is especially evil on embedded platforms).
826  */
827 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
828 {
829         const char *name = elf->strtab + sym->st_name;
830
831         if (!name || !strlen(name))
832                 return 0;
833         return !is_arm_mapping_symbol(name);
834 }
835
836 /*
837  * Find symbols before or equal addr and after addr - in the section sec.
838  * If we find two symbols with equal offset prefer one with a valid name.
839  * The ELF format may have a better way to detect what type of symbol
840  * it is, but this works for now.
841  **/
842 static void find_symbols_between(struct elf_info *elf, Elf_Addr addr,
843                                  const char *sec,
844                                  Elf_Sym **before, Elf_Sym **after)
845 {
846         Elf_Sym *sym;
847         Elf_Ehdr *hdr = elf->hdr;
848         Elf_Addr beforediff = ~0;
849         Elf_Addr afterdiff = ~0;
850         const char *secstrings = (void *)hdr +
851                                  elf->sechdrs[hdr->e_shstrndx].sh_offset;
852
853         *before = NULL;
854         *after = NULL;
855
856         for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
857                 const char *symsec;
858
859                 if (sym->st_shndx >= SHN_LORESERVE)
860                         continue;
861                 symsec = secstrings + elf->sechdrs[sym->st_shndx].sh_name;
862                 if (strcmp(symsec, sec) != 0)
863                         continue;
864                 if (!is_valid_name(elf, sym))
865                         continue;
866                 if (sym->st_value <= addr) {
867                         if ((addr - sym->st_value) < beforediff) {
868                                 beforediff = addr - sym->st_value;
869                                 *before = sym;
870                         } else if ((addr - sym->st_value) == beforediff) {
871                                 *before = sym;
872                         }
873                 } else {
874                         if ((sym->st_value - addr) < afterdiff) {
875                                 afterdiff = sym->st_value - addr;
876                                 *after = sym;
877                         } else if ((sym->st_value - addr) == afterdiff)
878                                 *after = sym;
879                 }
880         }
881 }
882
883 /**
884  * Print a warning about a section mismatch.
885  * Try to find symbols near it so user can find it.
886  * Check whitelist before warning - it may be a false positive.
887  **/
888 static void warn_sec_mismatch(const char *modname, const char *fromsec,
889                               struct elf_info *elf, Elf_Sym *sym, Elf_Rela r)
890 {
891         const char *refsymname = "";
892         Elf_Sym *before, *after;
893         Elf_Sym *refsym;
894         Elf_Ehdr *hdr = elf->hdr;
895         Elf_Shdr *sechdrs = elf->sechdrs;
896         const char *secstrings = (void *)hdr +
897                                  sechdrs[hdr->e_shstrndx].sh_offset;
898         const char *secname = secstrings + sechdrs[sym->st_shndx].sh_name;
899
900         find_symbols_between(elf, r.r_offset, fromsec, &before, &after);
901
902         refsym = find_elf_symbol(elf, r.r_addend, sym);
903         if (refsym && strlen(elf->strtab + refsym->st_name))
904                 refsymname = elf->strtab + refsym->st_name;
905
906         /* check whitelist - we may ignore it */
907         if (secref_whitelist(modname, secname, fromsec,
908                              before ? elf->strtab + before->st_name : "",
909                              refsymname))
910                 return;
911
912         if (before && after) {
913                 warn("%s(%s+0x%llx): Section mismatch: reference to %s:%s "
914                      "(between '%s' and '%s')\n",
915                      modname, fromsec, (unsigned long long)r.r_offset,
916                      secname, refsymname,
917                      elf->strtab + before->st_name,
918                      elf->strtab + after->st_name);
919         } else if (before) {
920                 warn("%s(%s+0x%llx): Section mismatch: reference to %s:%s "
921                      "(after '%s')\n",
922                      modname, fromsec, (unsigned long long)r.r_offset,
923                      secname, refsymname,
924                      elf->strtab + before->st_name);
925         } else if (after) {
926                 warn("%s(%s+0x%llx): Section mismatch: reference to %s:%s "
927                      "before '%s' (at offset -0x%llx)\n",
928                      modname, fromsec, (unsigned long long)r.r_offset,
929                      secname, refsymname,
930                      elf->strtab + after->st_name,
931                      (unsigned long long)r.r_offset);
932         } else {
933                 warn("%s(%s+0x%llx): Section mismatch: reference to %s:%s\n",
934                      modname, fromsec, (unsigned long long)r.r_offset,
935                      secname, refsymname);
936         }
937 }
938
939 static unsigned int *reloc_location(struct elf_info *elf,
940                                     Elf_Shdr *sechdr, Elf_Rela *r)
941 {
942         Elf_Shdr *sechdrs = elf->sechdrs;
943         int section = sechdr->sh_info;
944
945         return (void *)elf->hdr + sechdrs[section].sh_offset +
946                 (r->r_offset - sechdrs[section].sh_addr);
947 }
948
949 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
950 {
951         unsigned int r_typ = ELF_R_TYPE(r->r_info);
952         unsigned int *location = reloc_location(elf, sechdr, r);
953
954         switch (r_typ) {
955         case R_386_32:
956                 r->r_addend = TO_NATIVE(*location);
957                 break;
958         case R_386_PC32:
959                 r->r_addend = TO_NATIVE(*location) + 4;
960                 /* For CONFIG_RELOCATABLE=y */
961                 if (elf->hdr->e_type == ET_EXEC)
962                         r->r_addend += r->r_offset;
963                 break;
964         }
965         return 0;
966 }
967
968 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
969 {
970         unsigned int r_typ = ELF_R_TYPE(r->r_info);
971
972         switch (r_typ) {
973         case R_ARM_ABS32:
974                 /* From ARM ABI: (S + A) | T */
975                 r->r_addend = (int)(long)
976                               (elf->symtab_start + ELF_R_SYM(r->r_info));
977                 break;
978         case R_ARM_PC24:
979                 /* From ARM ABI: ((S + A) | T) - P */
980                 r->r_addend = (int)(long)(elf->hdr +
981                               sechdr->sh_offset +
982                               (r->r_offset - sechdr->sh_addr));
983                 break;
984         default:
985                 return 1;
986         }
987         return 0;
988 }
989
990 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
991 {
992         unsigned int r_typ = ELF_R_TYPE(r->r_info);
993         unsigned int *location = reloc_location(elf, sechdr, r);
994         unsigned int inst;
995
996         if (r_typ == R_MIPS_HI16)
997                 return 1;       /* skip this */
998         inst = TO_NATIVE(*location);
999         switch (r_typ) {
1000         case R_MIPS_LO16:
1001                 r->r_addend = inst & 0xffff;
1002                 break;
1003         case R_MIPS_26:
1004                 r->r_addend = (inst & 0x03ffffff) << 2;
1005                 break;
1006         case R_MIPS_32:
1007                 r->r_addend = inst;
1008                 break;
1009         }
1010         return 0;
1011 }
1012
1013 static void section_rela(const char *modname, struct elf_info *elf,
1014                          Elf_Shdr *sechdr, int section(const char *),
1015                          int section_ref_ok(const char *))
1016 {
1017         Elf_Sym  *sym;
1018         Elf_Rela *rela;
1019         Elf_Rela r;
1020         unsigned int r_sym;
1021         const char *fromsec;
1022         const char * tosec;
1023
1024         Elf_Ehdr *hdr = elf->hdr;
1025         Elf_Rela *start = (void *)hdr + sechdr->sh_offset;
1026         Elf_Rela *stop  = (void *)start + sechdr->sh_size;
1027
1028         const char *secstrings = (void *)hdr +
1029                                  elf->sechdrs[hdr->e_shstrndx].sh_offset;
1030
1031         fromsec = secstrings + sechdr->sh_name;
1032         fromsec += strlen(".rela");
1033         /* if from section (name) is know good then skip it */
1034         if (section_ref_ok(fromsec))
1035                 return;
1036
1037         for (rela = start; rela < stop; rela++) {
1038                 r.r_offset = TO_NATIVE(rela->r_offset);
1039 #if KERNEL_ELFCLASS == ELFCLASS64
1040                 if (hdr->e_machine == EM_MIPS) {
1041                         unsigned int r_typ;
1042                         r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1043                         r_sym = TO_NATIVE(r_sym);
1044                         r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1045                         r.r_info = ELF64_R_INFO(r_sym, r_typ);
1046                 } else {
1047                         r.r_info = TO_NATIVE(rela->r_info);
1048                         r_sym = ELF_R_SYM(r.r_info);
1049                 }
1050 #else
1051                 r.r_info = TO_NATIVE(rela->r_info);
1052                 r_sym = ELF_R_SYM(r.r_info);
1053 #endif
1054                 r.r_addend = TO_NATIVE(rela->r_addend);
1055                 sym = elf->symtab_start + r_sym;
1056                 /* Skip special sections */
1057                 if (sym->st_shndx >= SHN_LORESERVE)
1058                         continue;
1059
1060                 tosec = secstrings +
1061                         elf->sechdrs[sym->st_shndx].sh_name;
1062                 if (section(tosec))
1063                         warn_sec_mismatch(modname, fromsec, elf, sym, r);
1064         }
1065 }
1066
1067 static void section_rel(const char *modname, struct elf_info *elf,
1068                         Elf_Shdr *sechdr, int section(const char *),
1069                         int section_ref_ok(const char *))
1070 {
1071         Elf_Sym *sym;
1072         Elf_Rel *rel;
1073         Elf_Rela r;
1074         unsigned int r_sym;
1075         const char *fromsec;
1076         const char * tosec;
1077
1078         Elf_Ehdr *hdr = elf->hdr;
1079         Elf_Rel *start = (void *)hdr + sechdr->sh_offset;
1080         Elf_Rel *stop  = (void *)start + sechdr->sh_size;
1081
1082         const char *secstrings = (void *)hdr +
1083                                  elf->sechdrs[hdr->e_shstrndx].sh_offset;
1084
1085         fromsec = secstrings + sechdr->sh_name;
1086         fromsec += strlen(".rel");
1087         /* if from section (name) is know good then skip it */
1088         if (section_ref_ok(fromsec))
1089                 return;
1090
1091         for (rel = start; rel < stop; rel++) {
1092                 r.r_offset = TO_NATIVE(rel->r_offset);
1093 #if KERNEL_ELFCLASS == ELFCLASS64
1094                 if (hdr->e_machine == EM_MIPS) {
1095                         unsigned int r_typ;
1096                         r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1097                         r_sym = TO_NATIVE(r_sym);
1098                         r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1099                         r.r_info = ELF64_R_INFO(r_sym, r_typ);
1100                 } else {
1101                         r.r_info = TO_NATIVE(rel->r_info);
1102                         r_sym = ELF_R_SYM(r.r_info);
1103                 }
1104 #else
1105                 r.r_info = TO_NATIVE(rel->r_info);
1106                 r_sym = ELF_R_SYM(r.r_info);
1107 #endif
1108                 r.r_addend = 0;
1109                 switch (hdr->e_machine) {
1110                 case EM_386:
1111                         if (addend_386_rel(elf, sechdr, &r))
1112                                 continue;
1113                         break;
1114                 case EM_ARM:
1115                         if (addend_arm_rel(elf, sechdr, &r))
1116                                 continue;
1117                         break;
1118                 case EM_MIPS:
1119                         if (addend_mips_rel(elf, sechdr, &r))
1120                                 continue;
1121                         break;
1122                 }
1123                 sym = elf->symtab_start + r_sym;
1124                 /* Skip special sections */
1125                 if (sym->st_shndx >= SHN_LORESERVE)
1126                         continue;
1127
1128                 tosec = secstrings +
1129                         elf->sechdrs[sym->st_shndx].sh_name;
1130                 if (section(tosec))
1131                         warn_sec_mismatch(modname, fromsec, elf, sym, r);
1132         }
1133 }
1134
1135 /**
1136  * A module includes a number of sections that are discarded
1137  * either when loaded or when used as built-in.
1138  * For loaded modules all functions marked __init and all data
1139  * marked __initdata will be discarded when the module has been intialized.
1140  * Likewise for modules used built-in the sections marked __exit
1141  * are discarded because __exit marked function are supposed to be called
1142  * only when a moduel is unloaded which never happes for built-in modules.
1143  * The check_sec_ref() function traverses all relocation records
1144  * to find all references to a section that reference a section that will
1145  * be discarded and warns about it.
1146  **/
1147 static void check_sec_ref(struct module *mod, const char *modname,
1148                           struct elf_info *elf,
1149                           int section(const char *),
1150                           int section_ref_ok(const char *))
1151 {
1152         int i;
1153         Elf_Ehdr *hdr = elf->hdr;
1154         Elf_Shdr *sechdrs = elf->sechdrs;
1155
1156         /* Walk through all sections */
1157         for (i = 0; i < hdr->e_shnum; i++) {
1158                 /* We want to process only relocation sections and not .init */
1159                 if (sechdrs[i].sh_type == SHT_RELA)
1160                         section_rela(modname, elf, &elf->sechdrs[i],
1161                                      section, section_ref_ok);
1162                 else if (sechdrs[i].sh_type == SHT_REL)
1163                         section_rel(modname, elf, &elf->sechdrs[i],
1164                                     section, section_ref_ok);
1165         }
1166 }
1167
1168 /*
1169  * Identify sections from which references to either a
1170  * .init or a .exit section is OK.
1171  *
1172  * [OPD] Keith Ownes <kaos@sgi.com> commented:
1173  * For our future {in}sanity, add a comment that this is the ppc .opd
1174  * section, not the ia64 .opd section.
1175  * ia64 .opd should not point to discarded sections.
1176  * [.rodata] like for .init.text we ignore .rodata references -same reason
1177  */
1178 static int initexit_section_ref_ok(const char *name)
1179 {
1180         const char **s;
1181         /* Absolute section names */
1182         const char *namelist1[] = {
1183                 "__bug_table",  /* used by powerpc for BUG() */
1184                 "__ex_table",
1185                 ".altinstructions",
1186                 ".cranges",     /* used by sh64 */
1187                 ".fixup",
1188                 ".machvec",     /* ia64 + powerpc uses these */
1189                 ".machine.desc",
1190                 ".opd",         /* See comment [OPD] */
1191                 "__dbe_table",
1192                 ".parainstructions",
1193                 ".pdr",
1194                 ".plt",         /* seen on ARCH=um build on x86_64. Harmless */
1195                 ".smp_locks",
1196                 ".stab",
1197                 ".m68k_fixup",
1198                 ".xt.prop",     /* xtensa informational section */
1199                 ".xt.lit",      /* xtensa informational section */
1200                 NULL
1201         };
1202         /* Start of section names */
1203         const char *namelist2[] = {
1204                 ".debug",
1205                 ".eh_frame",
1206                 ".note",        /* ignore ELF notes - may contain anything */
1207                 ".got",         /* powerpc - global offset table */
1208                 ".toc",         /* powerpc - table of contents */
1209                 NULL
1210         };
1211         /* part of section name */
1212         const char *namelist3 [] = {
1213                 ".unwind",  /* Sample: IA_64.unwind.exit.text */
1214                 NULL
1215         };
1216
1217         for (s = namelist1; *s; s++)
1218                 if (strcmp(*s, name) == 0)
1219                         return 1;
1220         for (s = namelist2; *s; s++)
1221                 if (strncmp(*s, name, strlen(*s)) == 0)
1222                         return 1;
1223         for (s = namelist3; *s; s++)
1224                 if (strstr(name, *s) != NULL)
1225                         return 1;
1226         return 0;
1227 }
1228
1229
1230 /*
1231  * Identify sections from which references to a .init section is OK.
1232  *
1233  * Unfortunately references to read only data that referenced .init
1234  * sections had to be excluded. Almost all of these are false
1235  * positives, they are created by gcc. The downside of excluding rodata
1236  * is that there really are some user references from rodata to
1237  * init code, e.g. drivers/video/vgacon.c:
1238  *
1239  * const struct consw vga_con = {
1240  *        con_startup:            vgacon_startup,
1241  *
1242  * where vgacon_startup is __init.  If you want to wade through the false
1243  * positives, take out the check for rodata.
1244  */
1245 static int init_section_ref_ok(const char *name)
1246 {
1247         const char **s;
1248         /* Absolute section names */
1249         const char *namelist1[] = {
1250                 "__dbe_table",          /* MIPS generate these */
1251                 "__ftr_fixup",          /* powerpc cpu feature fixup */
1252                 "__fw_ftr_fixup",       /* powerpc firmware feature fixup */
1253                 "__param",
1254                 ".data.rel.ro",         /* used by parisc64 */
1255                 ".init",
1256                 ".text.lock",
1257                 NULL
1258         };
1259         /* Start of section names */
1260         const char *namelist2[] = {
1261                 ".init.",
1262                 ".pci_fixup",
1263                 ".rodata",
1264                 NULL
1265         };
1266
1267         if (initexit_section_ref_ok(name))
1268                 return 1;
1269
1270         for (s = namelist1; *s; s++)
1271                 if (strcmp(*s, name) == 0)
1272                         return 1;
1273         for (s = namelist2; *s; s++)
1274                 if (strncmp(*s, name, strlen(*s)) == 0)
1275                         return 1;
1276
1277         /* If section name ends with ".init" we allow references
1278          * as is the case with .initcallN.init, .early_param.init,
1279          * .taglist.init etc
1280          */
1281         if (strrcmp(name, ".init") == 0)
1282                 return 1;
1283         return 0;
1284 }
1285
1286 /*
1287  * Identify sections from which references to a .exit section is OK.
1288  */
1289 static int exit_section_ref_ok(const char *name)
1290 {
1291         const char **s;
1292         /* Absolute section names */
1293         const char *namelist1[] = {
1294                 ".exit.data",
1295                 ".exit.text",
1296                 ".exitcall.exit",
1297                 ".rodata",
1298                 NULL
1299         };
1300
1301         if (initexit_section_ref_ok(name))
1302                 return 1;
1303
1304         for (s = namelist1; *s; s++)
1305                 if (strcmp(*s, name) == 0)
1306                         return 1;
1307         return 0;
1308 }
1309
1310 static void read_symbols(char *modname)
1311 {
1312         const char *symname;
1313         char *version;
1314         char *license;
1315         struct module *mod;
1316         struct elf_info info = { };
1317         Elf_Sym *sym;
1318
1319         if (!parse_elf(&info, modname))
1320                 return;
1321
1322         mod = new_module(modname);
1323
1324         /* When there's no vmlinux, don't print warnings about
1325          * unresolved symbols (since there'll be too many ;) */
1326         if (is_vmlinux(modname)) {
1327                 have_vmlinux = 1;
1328                 mod->skip = 1;
1329         }
1330
1331         license = get_modinfo(info.modinfo, info.modinfo_len, "license");
1332         while (license) {
1333                 if (license_is_gpl_compatible(license))
1334                         mod->gpl_compatible = 1;
1335                 else {
1336                         mod->gpl_compatible = 0;
1337                         break;
1338                 }
1339                 license = get_next_modinfo(info.modinfo, info.modinfo_len,
1340                                            "license", license);
1341         }
1342
1343         for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1344                 symname = info.strtab + sym->st_name;
1345
1346                 handle_modversions(mod, &info, sym, symname);
1347                 handle_moddevtable(mod, &info, sym, symname);
1348         }
1349         if (!is_vmlinux(modname) ||
1350              (is_vmlinux(modname) && vmlinux_section_warnings)) {
1351                 check_sec_ref(mod, modname, &info, init_section, init_section_ref_ok);
1352                 check_sec_ref(mod, modname, &info, exit_section, exit_section_ref_ok);
1353         }
1354
1355         version = get_modinfo(info.modinfo, info.modinfo_len, "version");
1356         if (version)
1357                 maybe_frob_rcs_version(modname, version, info.modinfo,
1358                                        version - (char *)info.hdr);
1359         if (version || (all_versions && !is_vmlinux(modname)))
1360                 get_src_version(modname, mod->srcversion,
1361                                 sizeof(mod->srcversion)-1);
1362
1363         parse_elf_finish(&info);
1364
1365         /* Our trick to get versioning for struct_module - it's
1366          * never passed as an argument to an exported function, so
1367          * the automatic versioning doesn't pick it up, but it's really
1368          * important anyhow */
1369         if (modversions)
1370                 mod->unres = alloc_symbol("struct_module", 0, mod->unres);
1371 }
1372
1373 #define SZ 500
1374
1375 /* We first write the generated file into memory using the
1376  * following helper, then compare to the file on disk and
1377  * only update the later if anything changed */
1378
1379 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1380                                                       const char *fmt, ...)
1381 {
1382         char tmp[SZ];
1383         int len;
1384         va_list ap;
1385
1386         va_start(ap, fmt);
1387         len = vsnprintf(tmp, SZ, fmt, ap);
1388         buf_write(buf, tmp, len);
1389         va_end(ap);
1390 }
1391
1392 void buf_write(struct buffer *buf, const char *s, int len)
1393 {
1394         if (buf->size - buf->pos < len) {
1395                 buf->size += len + SZ;
1396                 buf->p = realloc(buf->p, buf->size);
1397         }
1398         strncpy(buf->p + buf->pos, s, len);
1399         buf->pos += len;
1400 }
1401
1402 static void check_for_gpl_usage(enum export exp, const char *m, const char *s)
1403 {
1404         const char *e = is_vmlinux(m) ?"":".ko";
1405
1406         switch (exp) {
1407         case export_gpl:
1408                 fatal("modpost: GPL-incompatible module %s%s "
1409                       "uses GPL-only symbol '%s'\n", m, e, s);
1410                 break;
1411         case export_unused_gpl:
1412                 fatal("modpost: GPL-incompatible module %s%s "
1413                       "uses GPL-only symbol marked UNUSED '%s'\n", m, e, s);
1414                 break;
1415         case export_gpl_future:
1416                 warn("modpost: GPL-incompatible module %s%s "
1417                       "uses future GPL-only symbol '%s'\n", m, e, s);
1418                 break;
1419         case export_plain:
1420         case export_unused:
1421         case export_unknown:
1422                 /* ignore */
1423                 break;
1424         }
1425 }
1426
1427 static void check_for_unused(enum export exp, const char *m, const char *s)
1428 {
1429         const char *e = is_vmlinux(m) ?"":".ko";
1430
1431         switch (exp) {
1432         case export_unused:
1433         case export_unused_gpl:
1434                 warn("modpost: module %s%s "
1435                       "uses symbol '%s' marked UNUSED\n", m, e, s);
1436                 break;
1437         default:
1438                 /* ignore */
1439                 break;
1440         }
1441 }
1442
1443 static void check_exports(struct module *mod)
1444 {
1445         struct symbol *s, *exp;
1446
1447         for (s = mod->unres; s; s = s->next) {
1448                 const char *basename;
1449                 exp = find_symbol(s->name);
1450                 if (!exp || exp->module == mod)
1451                         continue;
1452                 basename = strrchr(mod->name, '/');
1453                 if (basename)
1454                         basename++;
1455                 else
1456                         basename = mod->name;
1457                 if (!mod->gpl_compatible)
1458                         check_for_gpl_usage(exp->export, basename, exp->name);
1459                 check_for_unused(exp->export, basename, exp->name);
1460         }
1461 }
1462
1463 /**
1464  * Header for the generated file
1465  **/
1466 static void add_header(struct buffer *b, struct module *mod)
1467 {
1468         buf_printf(b, "#include <linux/module.h>\n");
1469         buf_printf(b, "#include <linux/vermagic.h>\n");
1470         buf_printf(b, "#include <linux/compiler.h>\n");
1471         buf_printf(b, "\n");
1472         buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
1473         buf_printf(b, "\n");
1474         buf_printf(b, "struct module __this_module\n");
1475         buf_printf(b, "__attribute__((section(\".gnu.linkonce.this_module\"))) = {\n");
1476         buf_printf(b, " .name = KBUILD_MODNAME,\n");
1477         if (mod->has_init)
1478                 buf_printf(b, " .init = init_module,\n");
1479         if (mod->has_cleanup)
1480                 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1481                               " .exit = cleanup_module,\n"
1482                               "#endif\n");
1483         buf_printf(b, " .arch = MODULE_ARCH_INIT,\n");
1484         buf_printf(b, "};\n");
1485 }
1486
1487 /**
1488  * Record CRCs for unresolved symbols
1489  **/
1490 static int add_versions(struct buffer *b, struct module *mod)
1491 {
1492         struct symbol *s, *exp;
1493         int err = 0;
1494
1495         for (s = mod->unres; s; s = s->next) {
1496                 exp = find_symbol(s->name);
1497                 if (!exp || exp->module == mod) {
1498                         if (have_vmlinux && !s->weak) {
1499                                 if (warn_unresolved) {
1500                                         warn("\"%s\" [%s.ko] undefined!\n",
1501                                              s->name, mod->name);
1502                                 } else {
1503                                         merror("\"%s\" [%s.ko] undefined!\n",
1504                                                   s->name, mod->name);
1505                                         err = 1;
1506                                 }
1507                         }
1508                         continue;
1509                 }
1510                 s->module = exp->module;
1511                 s->crc_valid = exp->crc_valid;
1512                 s->crc = exp->crc;
1513         }
1514
1515         if (!modversions)
1516                 return err;
1517
1518         buf_printf(b, "\n");
1519         buf_printf(b, "static const struct modversion_info ____versions[]\n");
1520         buf_printf(b, "__attribute_used__\n");
1521         buf_printf(b, "__attribute__((section(\"__versions\"))) = {\n");
1522
1523         for (s = mod->unres; s; s = s->next) {
1524                 if (!s->module)
1525                         continue;
1526                 if (!s->crc_valid) {
1527                         warn("\"%s\" [%s.ko] has no CRC!\n",
1528                                 s->name, mod->name);
1529                         continue;
1530                 }
1531                 buf_printf(b, "\t{ %#8x, \"%s\" },\n", s->crc, s->name);
1532         }
1533
1534         buf_printf(b, "};\n");
1535
1536         return err;
1537 }
1538
1539 static void add_depends(struct buffer *b, struct module *mod,
1540                         struct module *modules)
1541 {
1542         struct symbol *s;
1543         struct module *m;
1544         int first = 1;
1545
1546         for (m = modules; m; m = m->next)
1547                 m->seen = is_vmlinux(m->name);
1548
1549         buf_printf(b, "\n");
1550         buf_printf(b, "static const char __module_depends[]\n");
1551         buf_printf(b, "__attribute_used__\n");
1552         buf_printf(b, "__attribute__((section(\".modinfo\"))) =\n");
1553         buf_printf(b, "\"depends=");
1554         for (s = mod->unres; s; s = s->next) {
1555                 const char *p;
1556                 if (!s->module)
1557                         continue;
1558
1559                 if (s->module->seen)
1560                         continue;
1561
1562                 s->module->seen = 1;
1563                 p = strrchr(s->module->name, '/');
1564                 if (p)
1565                         p++;
1566                 else
1567                         p = s->module->name;
1568                 buf_printf(b, "%s%s", first ? "" : ",", p);
1569                 first = 0;
1570         }
1571         buf_printf(b, "\";\n");
1572 }
1573
1574 static void add_srcversion(struct buffer *b, struct module *mod)
1575 {
1576         if (mod->srcversion[0]) {
1577                 buf_printf(b, "\n");
1578                 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
1579                            mod->srcversion);
1580         }
1581 }
1582
1583 static void write_if_changed(struct buffer *b, const char *fname)
1584 {
1585         char *tmp;
1586         FILE *file;
1587         struct stat st;
1588
1589         file = fopen(fname, "r");
1590         if (!file)
1591                 goto write;
1592
1593         if (fstat(fileno(file), &st) < 0)
1594                 goto close_write;
1595
1596         if (st.st_size != b->pos)
1597                 goto close_write;
1598
1599         tmp = NOFAIL(malloc(b->pos));
1600         if (fread(tmp, 1, b->pos, file) != b->pos)
1601                 goto free_write;
1602
1603         if (memcmp(tmp, b->p, b->pos) != 0)
1604                 goto free_write;
1605
1606         free(tmp);
1607         fclose(file);
1608         return;
1609
1610  free_write:
1611         free(tmp);
1612  close_write:
1613         fclose(file);
1614  write:
1615         file = fopen(fname, "w");
1616         if (!file) {
1617                 perror(fname);
1618                 exit(1);
1619         }
1620         if (fwrite(b->p, 1, b->pos, file) != b->pos) {
1621                 perror(fname);
1622                 exit(1);
1623         }
1624         fclose(file);
1625 }
1626
1627 /* parse Module.symvers file. line format:
1628  * 0x12345678<tab>symbol<tab>module[[<tab>export]<tab>something]
1629  **/
1630 static void read_dump(const char *fname, unsigned int kernel)
1631 {
1632         unsigned long size, pos = 0;
1633         void *file = grab_file(fname, &size);
1634         char *line;
1635
1636         if (!file)
1637                 /* No symbol versions, silently ignore */
1638                 return;
1639
1640         while ((line = get_next_line(&pos, file, size))) {
1641                 char *symname, *modname, *d, *export, *end;
1642                 unsigned int crc;
1643                 struct module *mod;
1644                 struct symbol *s;
1645
1646                 if (!(symname = strchr(line, '\t')))
1647                         goto fail;
1648                 *symname++ = '\0';
1649                 if (!(modname = strchr(symname, '\t')))
1650                         goto fail;
1651                 *modname++ = '\0';
1652                 if ((export = strchr(modname, '\t')) != NULL)
1653                         *export++ = '\0';
1654                 if (export && ((end = strchr(export, '\t')) != NULL))
1655                         *end = '\0';
1656                 crc = strtoul(line, &d, 16);
1657                 if (*symname == '\0' || *modname == '\0' || *d != '\0')
1658                         goto fail;
1659                 mod = find_module(modname);
1660                 if (!mod) {
1661                         if (is_vmlinux(modname))
1662                                 have_vmlinux = 1;
1663                         mod = new_module(NOFAIL(strdup(modname)));
1664                         mod->skip = 1;
1665                 }
1666                 s = sym_add_exported(symname, mod, export_no(export));
1667                 s->kernel    = kernel;
1668                 s->preloaded = 1;
1669                 sym_update_crc(symname, mod, crc, export_no(export));
1670         }
1671         return;
1672 fail:
1673         fatal("parse error in symbol dump file\n");
1674 }
1675
1676 /* For normal builds always dump all symbols.
1677  * For external modules only dump symbols
1678  * that are not read from kernel Module.symvers.
1679  **/
1680 static int dump_sym(struct symbol *sym)
1681 {
1682         if (!external_module)
1683                 return 1;
1684         if (sym->vmlinux || sym->kernel)
1685                 return 0;
1686         return 1;
1687 }
1688
1689 static void write_dump(const char *fname)
1690 {
1691         struct buffer buf = { };
1692         struct symbol *symbol;
1693         int n;
1694
1695         for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
1696                 symbol = symbolhash[n];
1697                 while (symbol) {
1698                         if (dump_sym(symbol))
1699                                 buf_printf(&buf, "0x%08x\t%s\t%s\t%s\n",
1700                                         symbol->crc, symbol->name,
1701                                         symbol->module->name,
1702                                         export_str(symbol->export));
1703                         symbol = symbol->next;
1704                 }
1705         }
1706         write_if_changed(&buf, fname);
1707 }
1708
1709 int main(int argc, char **argv)
1710 {
1711         struct module *mod;
1712         struct buffer buf = { };
1713         char *kernel_read = NULL, *module_read = NULL;
1714         char *dump_write = NULL;
1715         int opt;
1716         int err;
1717
1718         while ((opt = getopt(argc, argv, "i:I:mso:aw")) != -1) {
1719                 switch (opt) {
1720                 case 'i':
1721                         kernel_read = optarg;
1722                         break;
1723                 case 'I':
1724                         module_read = optarg;
1725                         external_module = 1;
1726                         break;
1727                 case 'm':
1728                         modversions = 1;
1729                         break;
1730                 case 'o':
1731                         dump_write = optarg;
1732                         break;
1733                 case 'a':
1734                         all_versions = 1;
1735                         break;
1736                 case 's':
1737                         vmlinux_section_warnings = 0;
1738                         break;
1739                 case 'w':
1740                         warn_unresolved = 1;
1741                         break;
1742                 default:
1743                         exit(1);
1744                 }
1745         }
1746
1747         if (kernel_read)
1748                 read_dump(kernel_read, 1);
1749         if (module_read)
1750                 read_dump(module_read, 0);
1751
1752         while (optind < argc)
1753                 read_symbols(argv[optind++]);
1754
1755         for (mod = modules; mod; mod = mod->next) {
1756                 if (mod->skip)
1757                         continue;
1758                 check_exports(mod);
1759         }
1760
1761         err = 0;
1762
1763         for (mod = modules; mod; mod = mod->next) {
1764                 char fname[strlen(mod->name) + 10];
1765
1766                 if (mod->skip)
1767                         continue;
1768
1769                 buf.pos = 0;
1770
1771                 add_header(&buf, mod);
1772                 err |= add_versions(&buf, mod);
1773                 add_depends(&buf, mod, modules);
1774                 add_moddevtable(&buf, mod);
1775                 add_srcversion(&buf, mod);
1776
1777                 sprintf(fname, "%s.mod.c", mod->name);
1778                 write_if_changed(&buf, fname);
1779         }
1780
1781         if (dump_write)
1782                 write_dump(dump_write);
1783
1784         return err;
1785 }