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