kbuild: fix comment in modpost.c
[safe/jmp/linux-2.6] / 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 #define _GNU_SOURCE
15 #include <stdio.h>
16 #include <ctype.h>
17 #include "modpost.h"
18 #include "../../include/linux/license.h"
19
20 /* Are we using CONFIG_MODVERSIONS? */
21 int modversions = 0;
22 /* Warn about undefined symbols? (do so if we have vmlinux) */
23 int have_vmlinux = 0;
24 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
25 static int all_versions = 0;
26 /* If we are modposting external module set to 1 */
27 static int external_module = 0;
28 /* Warn about section mismatch in vmlinux if set to 1 */
29 static int vmlinux_section_warnings = 1;
30 /* Only warn about unresolved symbols */
31 static int warn_unresolved = 0;
32 /* How a symbol is exported */
33 static int sec_mismatch_count = 0;
34 static int sec_mismatch_verbose = 1;
35
36 enum export {
37         export_plain,      export_unused,     export_gpl,
38         export_unused_gpl, export_gpl_future, export_unknown
39 };
40
41 #define PRINTF __attribute__ ((format (printf, 1, 2)))
42
43 PRINTF void fatal(const char *fmt, ...)
44 {
45         va_list arglist;
46
47         fprintf(stderr, "FATAL: ");
48
49         va_start(arglist, fmt);
50         vfprintf(stderr, fmt, arglist);
51         va_end(arglist);
52
53         exit(1);
54 }
55
56 PRINTF void warn(const char *fmt, ...)
57 {
58         va_list arglist;
59
60         fprintf(stderr, "WARNING: ");
61
62         va_start(arglist, fmt);
63         vfprintf(stderr, fmt, arglist);
64         va_end(arglist);
65 }
66
67 PRINTF void merror(const char *fmt, ...)
68 {
69         va_list arglist;
70
71         fprintf(stderr, "ERROR: ");
72
73         va_start(arglist, fmt);
74         vfprintf(stderr, fmt, arglist);
75         va_end(arglist);
76 }
77
78 static int is_vmlinux(const char *modname)
79 {
80         const char *myname;
81
82         myname = strrchr(modname, '/');
83         if (myname)
84                 myname++;
85         else
86                 myname = modname;
87
88         return (strcmp(myname, "vmlinux") == 0) ||
89                (strcmp(myname, "vmlinux.o") == 0);
90 }
91
92 void *do_nofail(void *ptr, const char *expr)
93 {
94         if (!ptr)
95                 fatal("modpost: Memory allocation failure: %s.\n", expr);
96
97         return ptr;
98 }
99
100 /* A list of all modules we processed */
101 static struct module *modules;
102
103 static struct module *find_module(char *modname)
104 {
105         struct module *mod;
106
107         for (mod = modules; mod; mod = mod->next)
108                 if (strcmp(mod->name, modname) == 0)
109                         break;
110         return mod;
111 }
112
113 static struct module *new_module(char *modname)
114 {
115         struct module *mod;
116         char *p, *s;
117
118         mod = NOFAIL(malloc(sizeof(*mod)));
119         memset(mod, 0, sizeof(*mod));
120         p = NOFAIL(strdup(modname));
121
122         /* strip trailing .o */
123         s = strrchr(p, '.');
124         if (s != NULL)
125                 if (strcmp(s, ".o") == 0)
126                         *s = '\0';
127
128         /* add to list */
129         mod->name = p;
130         mod->gpl_compatible = -1;
131         mod->next = modules;
132         modules = mod;
133
134         return mod;
135 }
136
137 /* A hash of all exported symbols,
138  * struct symbol is also used for lists of unresolved symbols */
139
140 #define SYMBOL_HASH_SIZE 1024
141
142 struct symbol {
143         struct symbol *next;
144         struct module *module;
145         unsigned int crc;
146         int crc_valid;
147         unsigned int weak:1;
148         unsigned int vmlinux:1;    /* 1 if symbol is defined in vmlinux */
149         unsigned int kernel:1;     /* 1 if symbol is from kernel
150                                     *  (only for external modules) **/
151         unsigned int preloaded:1;  /* 1 if symbol from Module.symvers */
152         enum export  export;       /* Type of export */
153         char name[0];
154 };
155
156 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
157
158 /* This is based on the hash agorithm from gdbm, via tdb */
159 static inline unsigned int tdb_hash(const char *name)
160 {
161         unsigned value; /* Used to compute the hash value.  */
162         unsigned   i;   /* Used to cycle through random values. */
163
164         /* Set the initial value from the key size. */
165         for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++)
166                 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
167
168         return (1103515243 * value + 12345);
169 }
170
171 /**
172  * Allocate a new symbols for use in the hash of exported symbols or
173  * the list of unresolved symbols per module
174  **/
175 static struct symbol *alloc_symbol(const char *name, unsigned int weak,
176                                    struct symbol *next)
177 {
178         struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
179
180         memset(s, 0, sizeof(*s));
181         strcpy(s->name, name);
182         s->weak = weak;
183         s->next = next;
184         return s;
185 }
186
187 /* For the hash of exported symbols */
188 static struct symbol *new_symbol(const char *name, struct module *module,
189                                  enum export export)
190 {
191         unsigned int hash;
192         struct symbol *new;
193
194         hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
195         new = symbolhash[hash] = alloc_symbol(name, 0, symbolhash[hash]);
196         new->module = module;
197         new->export = export;
198         return new;
199 }
200
201 static struct symbol *find_symbol(const char *name)
202 {
203         struct symbol *s;
204
205         /* For our purposes, .foo matches foo.  PPC64 needs this. */
206         if (name[0] == '.')
207                 name++;
208
209         for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) {
210                 if (strcmp(s->name, name) == 0)
211                         return s;
212         }
213         return NULL;
214 }
215
216 static struct {
217         const char *str;
218         enum export export;
219 } export_list[] = {
220         { .str = "EXPORT_SYMBOL",            .export = export_plain },
221         { .str = "EXPORT_UNUSED_SYMBOL",     .export = export_unused },
222         { .str = "EXPORT_SYMBOL_GPL",        .export = export_gpl },
223         { .str = "EXPORT_UNUSED_SYMBOL_GPL", .export = export_unused_gpl },
224         { .str = "EXPORT_SYMBOL_GPL_FUTURE", .export = export_gpl_future },
225         { .str = "(unknown)",                .export = export_unknown },
226 };
227
228
229 static const char *export_str(enum export ex)
230 {
231         return export_list[ex].str;
232 }
233
234 static enum export export_no(const char *s)
235 {
236         int i;
237
238         if (!s)
239                 return export_unknown;
240         for (i = 0; export_list[i].export != export_unknown; i++) {
241                 if (strcmp(export_list[i].str, s) == 0)
242                         return export_list[i].export;
243         }
244         return export_unknown;
245 }
246
247 static enum export export_from_sec(struct elf_info *elf, Elf_Section sec)
248 {
249         if (sec == elf->export_sec)
250                 return export_plain;
251         else if (sec == elf->export_unused_sec)
252                 return export_unused;
253         else if (sec == elf->export_gpl_sec)
254                 return export_gpl;
255         else if (sec == elf->export_unused_gpl_sec)
256                 return export_unused_gpl;
257         else if (sec == elf->export_gpl_future_sec)
258                 return export_gpl_future;
259         else
260                 return export_unknown;
261 }
262
263 /**
264  * Add an exported symbol - it may have already been added without a
265  * CRC, in this case just update the CRC
266  **/
267 static struct symbol *sym_add_exported(const char *name, struct module *mod,
268                                        enum export export)
269 {
270         struct symbol *s = find_symbol(name);
271
272         if (!s) {
273                 s = new_symbol(name, mod, export);
274         } else {
275                 if (!s->preloaded) {
276                         warn("%s: '%s' exported twice. Previous export "
277                              "was in %s%s\n", mod->name, name,
278                              s->module->name,
279                              is_vmlinux(s->module->name) ?"":".ko");
280                 } else {
281                         /* In case Modules.symvers was out of date */
282                         s->module = mod;
283                 }
284         }
285         s->preloaded = 0;
286         s->vmlinux   = is_vmlinux(mod->name);
287         s->kernel    = 0;
288         s->export    = export;
289         return s;
290 }
291
292 static void sym_update_crc(const char *name, struct module *mod,
293                            unsigned int crc, enum export export)
294 {
295         struct symbol *s = find_symbol(name);
296
297         if (!s)
298                 s = new_symbol(name, mod, export);
299         s->crc = crc;
300         s->crc_valid = 1;
301 }
302
303 void *grab_file(const char *filename, unsigned long *size)
304 {
305         struct stat st;
306         void *map;
307         int fd;
308
309         fd = open(filename, O_RDONLY);
310         if (fd < 0 || fstat(fd, &st) != 0)
311                 return NULL;
312
313         *size = st.st_size;
314         map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
315         close(fd);
316
317         if (map == MAP_FAILED)
318                 return NULL;
319         return map;
320 }
321
322 /**
323   * Return a copy of the next line in a mmap'ed file.
324   * spaces in the beginning of the line is trimmed away.
325   * Return a pointer to a static buffer.
326   **/
327 char *get_next_line(unsigned long *pos, void *file, unsigned long size)
328 {
329         static char line[4096];
330         int skip = 1;
331         size_t len = 0;
332         signed char *p = (signed char *)file + *pos;
333         char *s = line;
334
335         for (; *pos < size ; (*pos)++) {
336                 if (skip && isspace(*p)) {
337                         p++;
338                         continue;
339                 }
340                 skip = 0;
341                 if (*p != '\n' && (*pos < size)) {
342                         len++;
343                         *s++ = *p++;
344                         if (len > 4095)
345                                 break; /* Too long, stop */
346                 } else {
347                         /* End of string */
348                         *s = '\0';
349                         return line;
350                 }
351         }
352         /* End of buffer */
353         return NULL;
354 }
355
356 void release_file(void *file, unsigned long size)
357 {
358         munmap(file, size);
359 }
360
361 static int parse_elf(struct elf_info *info, const char *filename)
362 {
363         unsigned int i;
364         Elf_Ehdr *hdr;
365         Elf_Shdr *sechdrs;
366         Elf_Sym  *sym;
367
368         hdr = grab_file(filename, &info->size);
369         if (!hdr) {
370                 perror(filename);
371                 exit(1);
372         }
373         info->hdr = hdr;
374         if (info->size < sizeof(*hdr)) {
375                 /* file too small, assume this is an empty .o file */
376                 return 0;
377         }
378         /* Is this a valid ELF file? */
379         if ((hdr->e_ident[EI_MAG0] != ELFMAG0) ||
380             (hdr->e_ident[EI_MAG1] != ELFMAG1) ||
381             (hdr->e_ident[EI_MAG2] != ELFMAG2) ||
382             (hdr->e_ident[EI_MAG3] != ELFMAG3)) {
383                 /* Not an ELF file - silently ignore it */
384                 return 0;
385         }
386         /* Fix endianness in ELF header */
387         hdr->e_shoff    = TO_NATIVE(hdr->e_shoff);
388         hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
389         hdr->e_shnum    = TO_NATIVE(hdr->e_shnum);
390         hdr->e_machine  = TO_NATIVE(hdr->e_machine);
391         hdr->e_type     = TO_NATIVE(hdr->e_type);
392         sechdrs = (void *)hdr + hdr->e_shoff;
393         info->sechdrs = sechdrs;
394
395         /* Check if file offset is correct */
396         if (hdr->e_shoff > info->size) {
397                 fatal("section header offset=%lu in file '%s' is bigger than "
398                       "filesize=%lu\n", (unsigned long)hdr->e_shoff,
399                       filename, info->size);
400                 return 0;
401         }
402
403         /* Fix endianness in section headers */
404         for (i = 0; i < hdr->e_shnum; i++) {
405                 sechdrs[i].sh_type   = TO_NATIVE(sechdrs[i].sh_type);
406                 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
407                 sechdrs[i].sh_size   = TO_NATIVE(sechdrs[i].sh_size);
408                 sechdrs[i].sh_link   = TO_NATIVE(sechdrs[i].sh_link);
409                 sechdrs[i].sh_name   = TO_NATIVE(sechdrs[i].sh_name);
410                 sechdrs[i].sh_info   = TO_NATIVE(sechdrs[i].sh_info);
411                 sechdrs[i].sh_addr   = TO_NATIVE(sechdrs[i].sh_addr);
412         }
413         /* Find symbol table. */
414         for (i = 1; i < hdr->e_shnum; i++) {
415                 const char *secstrings
416                         = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
417                 const char *secname;
418                 int nobits = sechdrs[i].sh_type == SHT_NOBITS;
419
420                 if (!nobits && sechdrs[i].sh_offset > info->size) {
421                         fatal("%s is truncated. sechdrs[i].sh_offset=%lu > "
422                               "sizeof(*hrd)=%zu\n", filename,
423                               (unsigned long)sechdrs[i].sh_offset,
424                               sizeof(*hdr));
425                         return 0;
426                 }
427                 secname = secstrings + sechdrs[i].sh_name;
428                 if (strcmp(secname, ".modinfo") == 0) {
429                         if (nobits)
430                                 fatal("%s has NOBITS .modinfo\n", filename);
431                         info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
432                         info->modinfo_len = sechdrs[i].sh_size;
433                 } else if (strcmp(secname, "__ksymtab") == 0)
434                         info->export_sec = i;
435                 else if (strcmp(secname, "__ksymtab_unused") == 0)
436                         info->export_unused_sec = i;
437                 else if (strcmp(secname, "__ksymtab_gpl") == 0)
438                         info->export_gpl_sec = i;
439                 else if (strcmp(secname, "__ksymtab_unused_gpl") == 0)
440                         info->export_unused_gpl_sec = i;
441                 else if (strcmp(secname, "__ksymtab_gpl_future") == 0)
442                         info->export_gpl_future_sec = i;
443                 else if (strcmp(secname, "__markers_strings") == 0)
444                         info->markers_strings_sec = i;
445
446                 if (sechdrs[i].sh_type != SHT_SYMTAB)
447                         continue;
448
449                 info->symtab_start = (void *)hdr + sechdrs[i].sh_offset;
450                 info->symtab_stop  = (void *)hdr + sechdrs[i].sh_offset
451                                                  + sechdrs[i].sh_size;
452                 info->strtab       = (void *)hdr +
453                                      sechdrs[sechdrs[i].sh_link].sh_offset;
454         }
455         if (!info->symtab_start)
456                 fatal("%s has no symtab?\n", filename);
457
458         /* Fix endianness in symbols */
459         for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
460                 sym->st_shndx = TO_NATIVE(sym->st_shndx);
461                 sym->st_name  = TO_NATIVE(sym->st_name);
462                 sym->st_value = TO_NATIVE(sym->st_value);
463                 sym->st_size  = TO_NATIVE(sym->st_size);
464         }
465         return 1;
466 }
467
468 static void parse_elf_finish(struct elf_info *info)
469 {
470         release_file(info->hdr, info->size);
471 }
472
473 static int ignore_undef_symbol(struct elf_info *info, const char *symname)
474 {
475         /* ignore __this_module, it will be resolved shortly */
476         if (strcmp(symname, MODULE_SYMBOL_PREFIX "__this_module") == 0)
477                 return 1;
478         /* ignore global offset table */
479         if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
480                 return 1;
481         if (info->hdr->e_machine == EM_PPC)
482                 /* Special register function linked on all modules during final link of .ko */
483                 if (strncmp(symname, "_restgpr_", sizeof("_restgpr_") - 1) == 0 ||
484                     strncmp(symname, "_savegpr_", sizeof("_savegpr_") - 1) == 0 ||
485                     strncmp(symname, "_rest32gpr_", sizeof("_rest32gpr_") - 1) == 0 ||
486                     strncmp(symname, "_save32gpr_", sizeof("_save32gpr_") - 1) == 0)
487                         return 1;
488         /* Do not ignore this symbol */
489         return 0;
490 }
491
492 #define CRC_PFX     MODULE_SYMBOL_PREFIX "__crc_"
493 #define KSYMTAB_PFX MODULE_SYMBOL_PREFIX "__ksymtab_"
494
495 static void handle_modversions(struct module *mod, struct elf_info *info,
496                                Elf_Sym *sym, const char *symname)
497 {
498         unsigned int crc;
499         enum export export = export_from_sec(info, sym->st_shndx);
500
501         switch (sym->st_shndx) {
502         case SHN_COMMON:
503                 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
504                 break;
505         case SHN_ABS:
506                 /* CRC'd symbol */
507                 if (memcmp(symname, CRC_PFX, strlen(CRC_PFX)) == 0) {
508                         crc = (unsigned int) sym->st_value;
509                         sym_update_crc(symname + strlen(CRC_PFX), mod, crc,
510                                         export);
511                 }
512                 break;
513         case SHN_UNDEF:
514                 /* undefined symbol */
515                 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
516                     ELF_ST_BIND(sym->st_info) != STB_WEAK)
517                         break;
518                 if (ignore_undef_symbol(info, symname))
519                         break;
520 /* cope with newer glibc (2.3.4 or higher) STT_ definition in elf.h */
521 #if defined(STT_REGISTER) || defined(STT_SPARC_REGISTER)
522 /* add compatibility with older glibc */
523 #ifndef STT_SPARC_REGISTER
524 #define STT_SPARC_REGISTER STT_REGISTER
525 #endif
526                 if (info->hdr->e_machine == EM_SPARC ||
527                     info->hdr->e_machine == EM_SPARCV9) {
528                         /* Ignore register directives. */
529                         if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
530                                 break;
531                         if (symname[0] == '.') {
532                                 char *munged = strdup(symname);
533                                 munged[0] = '_';
534                                 munged[1] = toupper(munged[1]);
535                                 symname = munged;
536                         }
537                 }
538 #endif
539
540                 if (memcmp(symname, MODULE_SYMBOL_PREFIX,
541                            strlen(MODULE_SYMBOL_PREFIX)) == 0) {
542                         mod->unres =
543                           alloc_symbol(symname +
544                                        strlen(MODULE_SYMBOL_PREFIX),
545                                        ELF_ST_BIND(sym->st_info) == STB_WEAK,
546                                        mod->unres);
547                 }
548                 break;
549         default:
550                 /* All exported symbols */
551                 if (memcmp(symname, KSYMTAB_PFX, strlen(KSYMTAB_PFX)) == 0) {
552                         sym_add_exported(symname + strlen(KSYMTAB_PFX), mod,
553                                         export);
554                 }
555                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "init_module") == 0)
556                         mod->has_init = 1;
557                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "cleanup_module") == 0)
558                         mod->has_cleanup = 1;
559                 break;
560         }
561 }
562
563 /**
564  * Parse tag=value strings from .modinfo section
565  **/
566 static char *next_string(char *string, unsigned long *secsize)
567 {
568         /* Skip non-zero chars */
569         while (string[0]) {
570                 string++;
571                 if ((*secsize)-- <= 1)
572                         return NULL;
573         }
574
575         /* Skip any zero padding. */
576         while (!string[0]) {
577                 string++;
578                 if ((*secsize)-- <= 1)
579                         return NULL;
580         }
581         return string;
582 }
583
584 static char *get_next_modinfo(void *modinfo, unsigned long modinfo_len,
585                               const char *tag, char *info)
586 {
587         char *p;
588         unsigned int taglen = strlen(tag);
589         unsigned long size = modinfo_len;
590
591         if (info) {
592                 size -= info - (char *)modinfo;
593                 modinfo = next_string(info, &size);
594         }
595
596         for (p = modinfo; p; p = next_string(p, &size)) {
597                 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
598                         return p + taglen + 1;
599         }
600         return NULL;
601 }
602
603 static char *get_modinfo(void *modinfo, unsigned long modinfo_len,
604                          const char *tag)
605
606 {
607         return get_next_modinfo(modinfo, modinfo_len, tag, NULL);
608 }
609
610 /**
611  * Test if string s ends in string sub
612  * return 0 if match
613  **/
614 static int strrcmp(const char *s, const char *sub)
615 {
616         int slen, sublen;
617
618         if (!s || !sub)
619                 return 1;
620
621         slen = strlen(s);
622         sublen = strlen(sub);
623
624         if ((slen == 0) || (sublen == 0))
625                 return 1;
626
627         if (sublen > slen)
628                 return 1;
629
630         return memcmp(s + slen - sublen, sub, sublen);
631 }
632
633 static const char *sym_name(struct elf_info *elf, Elf_Sym *sym)
634 {
635         if (sym)
636                 return elf->strtab + sym->st_name;
637         else
638                 return "(unknown)";
639 }
640
641 static const char *sec_name(struct elf_info *elf, int shndx)
642 {
643         Elf_Shdr *sechdrs = elf->sechdrs;
644         return (void *)elf->hdr +
645                 elf->sechdrs[elf->hdr->e_shstrndx].sh_offset +
646                 sechdrs[shndx].sh_name;
647 }
648
649 static const char *sech_name(struct elf_info *elf, Elf_Shdr *sechdr)
650 {
651         return (void *)elf->hdr +
652                 elf->sechdrs[elf->hdr->e_shstrndx].sh_offset +
653                 sechdr->sh_name;
654 }
655
656 /* if sym is empty or point to a string
657  * like ".[0-9]+" then return 1.
658  * This is the optional prefix added by ld to some sections
659  */
660 static int number_prefix(const char *sym)
661 {
662         if (*sym++ == '\0')
663                 return 1;
664         if (*sym != '.')
665                 return 0;
666         do {
667                 char c = *sym++;
668                 if (c < '0' || c > '9')
669                         return 0;
670         } while (*sym);
671         return 1;
672 }
673
674 /* The pattern is an array of simple patterns.
675  * "foo" will match an exact string equal to "foo"
676  * "*foo" will match a string that ends with "foo"
677  * "foo*" will match a string that begins with "foo"
678  * "foo$" will match a string equal to "foo" or "foo.1"
679  *   where the '1' can be any number including several digits.
680  *   The $ syntax is for sections where ld append a dot number
681  *   to make section name unique.
682  */
683 int match(const char *sym, const char * const pat[])
684 {
685         const char *p;
686         while (*pat) {
687                 p = *pat++;
688                 const char *endp = p + strlen(p) - 1;
689
690                 /* "*foo" */
691                 if (*p == '*') {
692                         if (strrcmp(sym, p + 1) == 0)
693                                 return 1;
694                 }
695                 /* "foo*" */
696                 else if (*endp == '*') {
697                         if (strncmp(sym, p, strlen(p) - 1) == 0)
698                                 return 1;
699                 }
700                 /* "foo$" */
701                 else if (*endp == '$') {
702                         if (strncmp(sym, p, strlen(p) - 1) == 0) {
703                                 if (number_prefix(sym + strlen(p) - 1))
704                                         return 1;
705                         }
706                 }
707                 /* no wildcards */
708                 else {
709                         if (strcmp(p, sym) == 0)
710                                 return 1;
711                 }
712         }
713         /* no match */
714         return 0;
715 }
716
717 /* sections that we do not want to do full section mismatch check on */
718 static const char *section_white_list[] =
719         { ".debug*", ".stab*", ".note*", ".got*", ".toc*", NULL };
720
721 /*
722  * Is this section one we do not want to check?
723  * This is often debug sections.
724  * If we are going to check this section then
725  * test if section name ends with a dot and a number.
726  * This is used to find sections where the linker have
727  * appended a dot-number to make the name unique.
728  * The cause of this is often a section specified in assembler
729  * without "ax" / "aw" and the same section used in .c
730  * code where gcc add these.
731  */
732 static int check_section(const char *modname, const char *sec)
733 {
734         const char *e = sec + strlen(sec) - 1;
735         if (match(sec, section_white_list))
736                 return 1;
737
738         if (*e && isdigit(*e)) {
739                 /* consume all digits */
740                 while (*e && e != sec && isdigit(*e))
741                         e--;
742                 if (*e == '.' && !strstr(sec, ".linkonce")) {
743                         warn("%s (%s): unexpected section name.\n"
744                              "The (.[number]+) following section name are "
745                              "ld generated and not expected.\n"
746                              "Did you forget to use \"ax\"/\"aw\" "
747                              "in a .S file?\n"
748                              "Note that for example <linux/init.h> contains\n"
749                              "section definitions for use in .S files.\n\n",
750                              modname, sec);
751                 }
752         }
753         return 0;
754 }
755
756
757
758 #define ALL_INIT_DATA_SECTIONS \
759         ".init.data$", ".devinit.data$", ".cpuinit.data$", ".meminit.data$"
760 #define ALL_EXIT_DATA_SECTIONS \
761         ".exit.data$", ".devexit.data$", ".cpuexit.data$", ".memexit.data$"
762
763 #define ALL_INIT_TEXT_SECTIONS \
764         ".init.text$", ".devinit.text$", ".cpuinit.text$", ".meminit.text$"
765 #define ALL_EXIT_TEXT_SECTIONS \
766         ".exit.text$", ".devexit.text$", ".cpuexit.text$", ".memexit.text$"
767
768 #define ALL_INIT_SECTIONS ALL_INIT_DATA_SECTIONS, ALL_INIT_TEXT_SECTIONS
769 #define ALL_EXIT_SECTIONS ALL_EXIT_DATA_SECTIONS, ALL_EXIT_TEXT_SECTIONS
770
771 #define DATA_SECTIONS ".data$", ".data.rel$"
772 #define TEXT_SECTIONS ".text$"
773
774 #define INIT_SECTIONS      ".init.data$", ".init.text$"
775 #define DEV_INIT_SECTIONS  ".devinit.data$", ".devinit.text$"
776 #define CPU_INIT_SECTIONS  ".cpuinit.data$", ".cpuinit.text$"
777 #define MEM_INIT_SECTIONS  ".meminit.data$", ".meminit.text$"
778
779 #define EXIT_SECTIONS      ".exit.data$", ".exit.text$"
780 #define DEV_EXIT_SECTIONS  ".devexit.data$", ".devexit.text$"
781 #define CPU_EXIT_SECTIONS  ".cpuexit.data$", ".cpuexit.text$"
782 #define MEM_EXIT_SECTIONS  ".memexit.data$", ".memexit.text$"
783
784 /* init data sections */
785 static const char *init_data_sections[] = { ALL_INIT_DATA_SECTIONS, NULL };
786
787 /* all init sections */
788 static const char *init_sections[] = { ALL_INIT_SECTIONS, NULL };
789
790 /* All init and exit sections (code + data) */
791 static const char *init_exit_sections[] =
792         {ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS, NULL };
793
794 /* data section */
795 static const char *data_sections[] = { DATA_SECTIONS, NULL };
796
797
798 /* symbols in .data that may refer to init/exit sections */
799 static const char *symbol_white_list[] =
800 {
801         "*driver",
802         "*_template", /* scsi uses *_template a lot */
803         "*_timer",    /* arm uses ops structures named _timer a lot */
804         "*_sht",      /* scsi also used *_sht to some extent */
805         "*_ops",
806         "*_probe",
807         "*_probe_one",
808         "*_console",
809         NULL
810 };
811
812 static const char *head_sections[] = { ".head.text*", NULL };
813 static const char *linker_symbols[] =
814         { "__init_begin", "_sinittext", "_einittext", NULL };
815
816 enum mismatch {
817         NO_MISMATCH,
818         TEXT_TO_INIT,
819         DATA_TO_INIT,
820         TEXT_TO_EXIT,
821         DATA_TO_EXIT,
822         XXXINIT_TO_INIT,
823         XXXEXIT_TO_EXIT,
824         INIT_TO_EXIT,
825         EXIT_TO_INIT,
826         EXPORT_TO_INIT_EXIT,
827 };
828
829 struct sectioncheck {
830         const char *fromsec[20];
831         const char *tosec[20];
832         enum mismatch mismatch;
833 };
834
835 const struct sectioncheck sectioncheck[] = {
836 /* Do not reference init/exit code/data from
837  * normal code and data
838  */
839 {
840         .fromsec = { TEXT_SECTIONS, NULL },
841         .tosec   = { ALL_INIT_SECTIONS, NULL },
842         .mismatch = TEXT_TO_INIT,
843 },
844 {
845         .fromsec = { DATA_SECTIONS, NULL },
846         .tosec   = { ALL_INIT_SECTIONS, NULL },
847         .mismatch = DATA_TO_INIT,
848 },
849 {
850         .fromsec = { TEXT_SECTIONS, NULL },
851         .tosec   = { ALL_EXIT_SECTIONS, NULL },
852         .mismatch = TEXT_TO_EXIT,
853 },
854 {
855         .fromsec = { DATA_SECTIONS, NULL },
856         .tosec   = { ALL_EXIT_SECTIONS, NULL },
857         .mismatch = DATA_TO_EXIT,
858 },
859 /* Do not reference init code/data from devinit/cpuinit/meminit code/data */
860 {
861         .fromsec = { DEV_INIT_SECTIONS, CPU_INIT_SECTIONS, MEM_INIT_SECTIONS, NULL },
862         .tosec   = { INIT_SECTIONS, NULL },
863         .mismatch = XXXINIT_TO_INIT,
864 },
865 /* Do not reference exit code/data from devexit/cpuexit/memexit code/data */
866 {
867         .fromsec = { DEV_EXIT_SECTIONS, CPU_EXIT_SECTIONS, MEM_EXIT_SECTIONS, NULL },
868         .tosec   = { EXIT_SECTIONS, NULL },
869         .mismatch = XXXEXIT_TO_EXIT,
870 },
871 /* Do not use exit code/data from init code */
872 {
873         .fromsec = { ALL_INIT_SECTIONS, NULL },
874         .tosec   = { ALL_EXIT_SECTIONS, NULL },
875         .mismatch = INIT_TO_EXIT,
876 },
877 /* Do not use init code/data from exit code */
878 {
879         .fromsec = { ALL_EXIT_SECTIONS, NULL },
880         .tosec   = { ALL_INIT_SECTIONS, NULL },
881         .mismatch = EXIT_TO_INIT,
882 },
883 /* Do not export init/exit functions or data */
884 {
885         .fromsec = { "__ksymtab*", NULL },
886         .tosec   = { INIT_SECTIONS, EXIT_SECTIONS, NULL },
887         .mismatch = EXPORT_TO_INIT_EXIT
888 }
889 };
890
891 static int section_mismatch(const char *fromsec, const char *tosec)
892 {
893         int i;
894         int elems = sizeof(sectioncheck) / sizeof(struct sectioncheck);
895         const struct sectioncheck *check = &sectioncheck[0];
896
897         for (i = 0; i < elems; i++) {
898                 if (match(fromsec, check->fromsec) &&
899                     match(tosec, check->tosec))
900                         return check->mismatch;
901                 check++;
902         }
903         return NO_MISMATCH;
904 }
905
906 /**
907  * Whitelist to allow certain references to pass with no warning.
908  *
909  * Pattern 1:
910  *   If a module parameter is declared __initdata and permissions=0
911  *   then this is legal despite the warning generated.
912  *   We cannot see value of permissions here, so just ignore
913  *   this pattern.
914  *   The pattern is identified by:
915  *   tosec   = .init.data
916  *   fromsec = .data*
917  *   atsym   =__param*
918  *
919  * Pattern 2:
920  *   Many drivers utilise a *driver container with references to
921  *   add, remove, probe functions etc.
922  *   These functions may often be marked __init and we do not want to
923  *   warn here.
924  *   the pattern is identified by:
925  *   tosec   = init or exit section
926  *   fromsec = data section
927  *   atsym = *driver, *_template, *_sht, *_ops, *_probe,
928  *           *probe_one, *_console, *_timer
929  *
930  * Pattern 3:
931  *   Whitelist all references from .head.text to any init section
932  *
933  * Pattern 4:
934  *   Some symbols belong to init section but still it is ok to reference
935  *   these from non-init sections as these symbols don't have any memory
936  *   allocated for them and symbol address and value are same. So even
937  *   if init section is freed, its ok to reference those symbols.
938  *   For ex. symbols marking the init section boundaries.
939  *   This pattern is identified by
940  *   refsymname = __init_begin, _sinittext, _einittext
941  *
942  **/
943 static int secref_whitelist(const char *fromsec, const char *fromsym,
944                             const char *tosec, const char *tosym)
945 {
946         /* Check for pattern 1 */
947         if (match(tosec, init_data_sections) &&
948             match(fromsec, data_sections) &&
949             (strncmp(fromsym, "__param", strlen("__param")) == 0))
950                 return 0;
951
952         /* Check for pattern 2 */
953         if (match(tosec, init_exit_sections) &&
954             match(fromsec, data_sections) &&
955             match(fromsym, symbol_white_list))
956                 return 0;
957
958         /* Check for pattern 3 */
959         if (match(fromsec, head_sections) &&
960             match(tosec, init_sections))
961                 return 0;
962
963         /* Check for pattern 4 */
964         if (match(tosym, linker_symbols))
965                 return 0;
966
967         return 1;
968 }
969
970 /**
971  * Find symbol based on relocation record info.
972  * In some cases the symbol supplied is a valid symbol so
973  * return refsym. If st_name != 0 we assume this is a valid symbol.
974  * In other cases the symbol needs to be looked up in the symbol table
975  * based on section and address.
976  *  **/
977 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf64_Sword addr,
978                                 Elf_Sym *relsym)
979 {
980         Elf_Sym *sym;
981         Elf_Sym *near = NULL;
982         Elf64_Sword distance = 20;
983         Elf64_Sword d;
984
985         if (relsym->st_name != 0)
986                 return relsym;
987         for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
988                 if (sym->st_shndx != relsym->st_shndx)
989                         continue;
990                 if (ELF_ST_TYPE(sym->st_info) == STT_SECTION)
991                         continue;
992                 if (sym->st_value == addr)
993                         return sym;
994                 /* Find a symbol nearby - addr are maybe negative */
995                 d = sym->st_value - addr;
996                 if (d < 0)
997                         d = addr - sym->st_value;
998                 if (d < distance) {
999                         distance = d;
1000                         near = sym;
1001                 }
1002         }
1003         /* We need a close match */
1004         if (distance < 20)
1005                 return near;
1006         else
1007                 return NULL;
1008 }
1009
1010 static inline int is_arm_mapping_symbol(const char *str)
1011 {
1012         return str[0] == '$' && strchr("atd", str[1])
1013                && (str[2] == '\0' || str[2] == '.');
1014 }
1015
1016 /*
1017  * If there's no name there, ignore it; likewise, ignore it if it's
1018  * one of the magic symbols emitted used by current ARM tools.
1019  *
1020  * Otherwise if find_symbols_between() returns those symbols, they'll
1021  * fail the whitelist tests and cause lots of false alarms ... fixable
1022  * only by merging __exit and __init sections into __text, bloating
1023  * the kernel (which is especially evil on embedded platforms).
1024  */
1025 static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym)
1026 {
1027         const char *name = elf->strtab + sym->st_name;
1028
1029         if (!name || !strlen(name))
1030                 return 0;
1031         return !is_arm_mapping_symbol(name);
1032 }
1033
1034 /*
1035  * Find symbols before or equal addr and after addr - in the section sec.
1036  * If we find two symbols with equal offset prefer one with a valid name.
1037  * The ELF format may have a better way to detect what type of symbol
1038  * it is, but this works for now.
1039  **/
1040 static Elf_Sym *find_elf_symbol2(struct elf_info *elf, Elf_Addr addr,
1041                                  const char *sec)
1042 {
1043         Elf_Sym *sym;
1044         Elf_Sym *near = NULL;
1045         Elf_Addr distance = ~0;
1046
1047         for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
1048                 const char *symsec;
1049
1050                 if (sym->st_shndx >= SHN_LORESERVE)
1051                         continue;
1052                 symsec = sec_name(elf, sym->st_shndx);
1053                 if (strcmp(symsec, sec) != 0)
1054                         continue;
1055                 if (!is_valid_name(elf, sym))
1056                         continue;
1057                 if (sym->st_value <= addr) {
1058                         if ((addr - sym->st_value) < distance) {
1059                                 distance = addr - sym->st_value;
1060                                 near = sym;
1061                         } else if ((addr - sym->st_value) == distance) {
1062                                 near = sym;
1063                         }
1064                 }
1065         }
1066         return near;
1067 }
1068
1069 /*
1070  * Convert a section name to the function/data attribute
1071  * .init.text => __init
1072  * .cpuinit.data => __cpudata
1073  * .memexitconst => __memconst
1074  * etc.
1075 */
1076 static char *sec2annotation(const char *s)
1077 {
1078         if (match(s, init_exit_sections)) {
1079                 char *p = malloc(20);
1080                 char *r = p;
1081
1082                 *p++ = '_';
1083                 *p++ = '_';
1084                 if (*s == '.')
1085                         s++;
1086                 while (*s && *s != '.')
1087                         *p++ = *s++;
1088                 *p = '\0';
1089                 if (*s == '.')
1090                         s++;
1091                 if (strstr(s, "rodata") != NULL)
1092                         strcat(p, "const ");
1093                 else if (strstr(s, "data") != NULL)
1094                         strcat(p, "data ");
1095                 else
1096                         strcat(p, " ");
1097                 return r; /* we leak her but we do not care */
1098         } else {
1099                 return "";
1100         }
1101 }
1102
1103 static int is_function(Elf_Sym *sym)
1104 {
1105         if (sym)
1106                 return ELF_ST_TYPE(sym->st_info) == STT_FUNC;
1107         else
1108                 return -1;
1109 }
1110
1111 /*
1112  * Print a warning about a section mismatch.
1113  * Try to find symbols near it so user can find it.
1114  * Check whitelist before warning - it may be a false positive.
1115  */
1116 static void report_sec_mismatch(const char *modname, enum mismatch mismatch,
1117                                 const char *fromsec,
1118                                 unsigned long long fromaddr,
1119                                 const char *fromsym,
1120                                 int from_is_func,
1121                                 const char *tosec, const char *tosym,
1122                                 int to_is_func)
1123 {
1124         const char *from, *from_p;
1125         const char *to, *to_p;
1126
1127         switch (from_is_func) {
1128         case 0: from = "variable"; from_p = "";   break;
1129         case 1: from = "function"; from_p = "()"; break;
1130         default: from = "(unknown reference)"; from_p = ""; break;
1131         }
1132         switch (to_is_func) {
1133         case 0: to = "variable"; to_p = "";   break;
1134         case 1: to = "function"; to_p = "()"; break;
1135         default: to = "(unknown reference)"; to_p = ""; break;
1136         }
1137
1138         sec_mismatch_count++;
1139         if (!sec_mismatch_verbose)
1140                 return;
1141
1142         warn("%s(%s+0x%llx): Section mismatch in reference from the %s %s%s "
1143              "to the %s %s:%s%s\n",
1144              modname, fromsec, fromaddr, from, fromsym, from_p, to, tosec,
1145              tosym, to_p);
1146
1147         switch (mismatch) {
1148         case TEXT_TO_INIT:
1149                 fprintf(stderr,
1150                 "The function %s%s() references\n"
1151                 "the %s %s%s%s.\n"
1152                 "This is often because %s lacks a %s\n"
1153                 "annotation or the annotation of %s is wrong.\n",
1154                 sec2annotation(fromsec), fromsym,
1155                 to, sec2annotation(tosec), tosym, to_p,
1156                 fromsym, sec2annotation(tosec), tosym);
1157                 break;
1158         case DATA_TO_INIT: {
1159                 const char **s = symbol_white_list;
1160                 fprintf(stderr,
1161                 "The variable %s references\n"
1162                 "the %s %s%s%s\n"
1163                 "If the reference is valid then annotate the\n"
1164                 "variable with __init* (see linux/init.h) "
1165                 "or name the variable:\n",
1166                 fromsym, to, sec2annotation(tosec), tosym, to_p);
1167                 while (*s)
1168                         fprintf(stderr, "%s, ", *s++);
1169                 fprintf(stderr, "\n");
1170                 break;
1171         }
1172         case TEXT_TO_EXIT:
1173                 fprintf(stderr,
1174                 "The function %s() references a %s in an exit section.\n"
1175                 "Often the %s %s%s has valid usage outside the exit section\n"
1176                 "and the fix is to remove the %sannotation of %s.\n",
1177                 fromsym, to, to, tosym, to_p, sec2annotation(tosec), tosym);
1178                 break;
1179         case DATA_TO_EXIT: {
1180                 const char **s = symbol_white_list;
1181                 fprintf(stderr,
1182                 "The variable %s references\n"
1183                 "the %s %s%s%s\n"
1184                 "If the reference is valid then annotate the\n"
1185                 "variable with __exit* (see linux/init.h) or "
1186                 "name the variable:\n",
1187                 fromsym, to, sec2annotation(tosec), tosym, to_p);
1188                 while (*s)
1189                         fprintf(stderr, "%s, ", *s++);
1190                 fprintf(stderr, "\n");
1191                 break;
1192         }
1193         case XXXINIT_TO_INIT:
1194         case XXXEXIT_TO_EXIT:
1195                 fprintf(stderr,
1196                 "The %s %s%s%s references\n"
1197                 "a %s %s%s%s.\n"
1198                 "If %s is only used by %s then\n"
1199                 "annotate %s with a matching annotation.\n",
1200                 from, sec2annotation(fromsec), fromsym, from_p,
1201                 to, sec2annotation(tosec), tosym, to_p,
1202                 tosym, fromsym, tosym);
1203                 break;
1204         case INIT_TO_EXIT:
1205                 fprintf(stderr,
1206                 "The %s %s%s%s references\n"
1207                 "a %s %s%s%s.\n"
1208                 "This is often seen when error handling "
1209                 "in the init function\n"
1210                 "uses functionality in the exit path.\n"
1211                 "The fix is often to remove the %sannotation of\n"
1212                 "%s%s so it may be used outside an exit section.\n",
1213                 from, sec2annotation(fromsec), fromsym, from_p,
1214                 to, sec2annotation(tosec), tosym, to_p,
1215                 sec2annotation(tosec), tosym, to_p);
1216                 break;
1217         case EXIT_TO_INIT:
1218                 fprintf(stderr,
1219                 "The %s %s%s%s references\n"
1220                 "a %s %s%s%s.\n"
1221                 "This is often seen when error handling "
1222                 "in the exit function\n"
1223                 "uses functionality in the init path.\n"
1224                 "The fix is often to remove the %sannotation of\n"
1225                 "%s%s so it may be used outside an init section.\n",
1226                 from, sec2annotation(fromsec), fromsym, from_p,
1227                 to, sec2annotation(tosec), tosym, to_p,
1228                 sec2annotation(tosec), tosym, to_p);
1229                 break;
1230         case EXPORT_TO_INIT_EXIT:
1231                 fprintf(stderr,
1232                 "The symbol %s is exported and annotated %s\n"
1233                 "Fix this by removing the %sannotation of %s "
1234                 "or drop the export.\n",
1235                 tosym, sec2annotation(tosec), sec2annotation(tosec), tosym);
1236         case NO_MISMATCH:
1237                 /* To get warnings on missing members */
1238                 break;
1239         }
1240         fprintf(stderr, "\n");
1241 }
1242
1243 static void check_section_mismatch(const char *modname, struct elf_info *elf,
1244                                    Elf_Rela *r, Elf_Sym *sym, const char *fromsec)
1245 {
1246         const char *tosec;
1247         enum mismatch mismatch;
1248
1249         tosec = sec_name(elf, sym->st_shndx);
1250         mismatch = section_mismatch(fromsec, tosec);
1251         if (mismatch != NO_MISMATCH) {
1252                 Elf_Sym *to;
1253                 Elf_Sym *from;
1254                 const char *tosym;
1255                 const char *fromsym;
1256
1257                 from = find_elf_symbol2(elf, r->r_offset, fromsec);
1258                 fromsym = sym_name(elf, from);
1259                 to = find_elf_symbol(elf, r->r_addend, sym);
1260                 tosym = sym_name(elf, to);
1261
1262                 /* check whitelist - we may ignore it */
1263                 if (secref_whitelist(fromsec, fromsym, tosec, tosym)) {
1264                         report_sec_mismatch(modname, mismatch,
1265                            fromsec, r->r_offset, fromsym,
1266                            is_function(from), tosec, tosym,
1267                            is_function(to));
1268                 }
1269         }
1270 }
1271
1272 static unsigned int *reloc_location(struct elf_info *elf,
1273                                     Elf_Shdr *sechdr, Elf_Rela *r)
1274 {
1275         Elf_Shdr *sechdrs = elf->sechdrs;
1276         int section = sechdr->sh_info;
1277
1278         return (void *)elf->hdr + sechdrs[section].sh_offset +
1279                 (r->r_offset - sechdrs[section].sh_addr);
1280 }
1281
1282 static int addend_386_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1283 {
1284         unsigned int r_typ = ELF_R_TYPE(r->r_info);
1285         unsigned int *location = reloc_location(elf, sechdr, r);
1286
1287         switch (r_typ) {
1288         case R_386_32:
1289                 r->r_addend = TO_NATIVE(*location);
1290                 break;
1291         case R_386_PC32:
1292                 r->r_addend = TO_NATIVE(*location) + 4;
1293                 /* For CONFIG_RELOCATABLE=y */
1294                 if (elf->hdr->e_type == ET_EXEC)
1295                         r->r_addend += r->r_offset;
1296                 break;
1297         }
1298         return 0;
1299 }
1300
1301 static int addend_arm_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1302 {
1303         unsigned int r_typ = ELF_R_TYPE(r->r_info);
1304
1305         switch (r_typ) {
1306         case R_ARM_ABS32:
1307                 /* From ARM ABI: (S + A) | T */
1308                 r->r_addend = (int)(long)
1309                               (elf->symtab_start + ELF_R_SYM(r->r_info));
1310                 break;
1311         case R_ARM_PC24:
1312                 /* From ARM ABI: ((S + A) | T) - P */
1313                 r->r_addend = (int)(long)(elf->hdr +
1314                               sechdr->sh_offset +
1315                               (r->r_offset - sechdr->sh_addr));
1316                 break;
1317         default:
1318                 return 1;
1319         }
1320         return 0;
1321 }
1322
1323 static int addend_mips_rel(struct elf_info *elf, Elf_Shdr *sechdr, Elf_Rela *r)
1324 {
1325         unsigned int r_typ = ELF_R_TYPE(r->r_info);
1326         unsigned int *location = reloc_location(elf, sechdr, r);
1327         unsigned int inst;
1328
1329         if (r_typ == R_MIPS_HI16)
1330                 return 1;       /* skip this */
1331         inst = TO_NATIVE(*location);
1332         switch (r_typ) {
1333         case R_MIPS_LO16:
1334                 r->r_addend = inst & 0xffff;
1335                 break;
1336         case R_MIPS_26:
1337                 r->r_addend = (inst & 0x03ffffff) << 2;
1338                 break;
1339         case R_MIPS_32:
1340                 r->r_addend = inst;
1341                 break;
1342         }
1343         return 0;
1344 }
1345
1346 static void section_rela(const char *modname, struct elf_info *elf,
1347                          Elf_Shdr *sechdr)
1348 {
1349         Elf_Sym  *sym;
1350         Elf_Rela *rela;
1351         Elf_Rela r;
1352         unsigned int r_sym;
1353         const char *fromsec;
1354
1355         Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset;
1356         Elf_Rela *stop  = (void *)start + sechdr->sh_size;
1357
1358         fromsec = sech_name(elf, sechdr);
1359         fromsec += strlen(".rela");
1360         /* if from section (name) is know good then skip it */
1361         if (check_section(modname, fromsec))
1362                 return;
1363
1364         for (rela = start; rela < stop; rela++) {
1365                 r.r_offset = TO_NATIVE(rela->r_offset);
1366 #if KERNEL_ELFCLASS == ELFCLASS64
1367                 if (elf->hdr->e_machine == EM_MIPS) {
1368                         unsigned int r_typ;
1369                         r_sym = ELF64_MIPS_R_SYM(rela->r_info);
1370                         r_sym = TO_NATIVE(r_sym);
1371                         r_typ = ELF64_MIPS_R_TYPE(rela->r_info);
1372                         r.r_info = ELF64_R_INFO(r_sym, r_typ);
1373                 } else {
1374                         r.r_info = TO_NATIVE(rela->r_info);
1375                         r_sym = ELF_R_SYM(r.r_info);
1376                 }
1377 #else
1378                 r.r_info = TO_NATIVE(rela->r_info);
1379                 r_sym = ELF_R_SYM(r.r_info);
1380 #endif
1381                 r.r_addend = TO_NATIVE(rela->r_addend);
1382                 sym = elf->symtab_start + r_sym;
1383                 /* Skip special sections */
1384                 if (sym->st_shndx >= SHN_LORESERVE)
1385                         continue;
1386                 check_section_mismatch(modname, elf, &r, sym, fromsec);
1387         }
1388 }
1389
1390 static void section_rel(const char *modname, struct elf_info *elf,
1391                         Elf_Shdr *sechdr)
1392 {
1393         Elf_Sym *sym;
1394         Elf_Rel *rel;
1395         Elf_Rela r;
1396         unsigned int r_sym;
1397         const char *fromsec;
1398
1399         Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset;
1400         Elf_Rel *stop  = (void *)start + sechdr->sh_size;
1401
1402         fromsec = sech_name(elf, sechdr);
1403         fromsec += strlen(".rel");
1404         /* if from section (name) is know good then skip it */
1405         if (check_section(modname, fromsec))
1406                 return;
1407
1408         for (rel = start; rel < stop; rel++) {
1409                 r.r_offset = TO_NATIVE(rel->r_offset);
1410 #if KERNEL_ELFCLASS == ELFCLASS64
1411                 if (elf->hdr->e_machine == EM_MIPS) {
1412                         unsigned int r_typ;
1413                         r_sym = ELF64_MIPS_R_SYM(rel->r_info);
1414                         r_sym = TO_NATIVE(r_sym);
1415                         r_typ = ELF64_MIPS_R_TYPE(rel->r_info);
1416                         r.r_info = ELF64_R_INFO(r_sym, r_typ);
1417                 } else {
1418                         r.r_info = TO_NATIVE(rel->r_info);
1419                         r_sym = ELF_R_SYM(r.r_info);
1420                 }
1421 #else
1422                 r.r_info = TO_NATIVE(rel->r_info);
1423                 r_sym = ELF_R_SYM(r.r_info);
1424 #endif
1425                 r.r_addend = 0;
1426                 switch (elf->hdr->e_machine) {
1427                 case EM_386:
1428                         if (addend_386_rel(elf, sechdr, &r))
1429                                 continue;
1430                         break;
1431                 case EM_ARM:
1432                         if (addend_arm_rel(elf, sechdr, &r))
1433                                 continue;
1434                         break;
1435                 case EM_MIPS:
1436                         if (addend_mips_rel(elf, sechdr, &r))
1437                                 continue;
1438                         break;
1439                 }
1440                 sym = elf->symtab_start + r_sym;
1441                 /* Skip special sections */
1442                 if (sym->st_shndx >= SHN_LORESERVE)
1443                         continue;
1444                 check_section_mismatch(modname, elf, &r, sym, fromsec);
1445         }
1446 }
1447
1448 /**
1449  * A module includes a number of sections that are discarded
1450  * either when loaded or when used as built-in.
1451  * For loaded modules all functions marked __init and all data
1452  * marked __initdata will be discarded when the module has been intialized.
1453  * Likewise for modules used built-in the sections marked __exit
1454  * are discarded because __exit marked function are supposed to be called
1455  * only when a module is unloaded which never happens for built-in modules.
1456  * The check_sec_ref() function traverses all relocation records
1457  * to find all references to a section that reference a section that will
1458  * be discarded and warns about it.
1459  **/
1460 static void check_sec_ref(struct module *mod, const char *modname,
1461                           struct elf_info *elf)
1462 {
1463         int i;
1464         Elf_Shdr *sechdrs = elf->sechdrs;
1465
1466         /* Walk through all sections */
1467         for (i = 0; i < elf->hdr->e_shnum; i++) {
1468                 /* We want to process only relocation sections and not .init */
1469                 if (sechdrs[i].sh_type == SHT_RELA)
1470                         section_rela(modname, elf, &elf->sechdrs[i]);
1471                 else if (sechdrs[i].sh_type == SHT_REL)
1472                         section_rel(modname, elf, &elf->sechdrs[i]);
1473         }
1474 }
1475
1476 static void get_markers(struct elf_info *info, struct module *mod)
1477 {
1478         const Elf_Shdr *sh = &info->sechdrs[info->markers_strings_sec];
1479         const char *strings = (const char *) info->hdr + sh->sh_offset;
1480         const Elf_Sym *sym, *first_sym, *last_sym;
1481         size_t n;
1482
1483         if (!info->markers_strings_sec)
1484                 return;
1485
1486         /*
1487          * First count the strings.  We look for all the symbols defined
1488          * in the __markers_strings section named __mstrtab_*.  For
1489          * these local names, the compiler puts a random .NNN suffix on,
1490          * so the names don't correspond exactly.
1491          */
1492         first_sym = last_sym = NULL;
1493         n = 0;
1494         for (sym = info->symtab_start; sym < info->symtab_stop; sym++)
1495                 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT &&
1496                     sym->st_shndx == info->markers_strings_sec &&
1497                     !strncmp(info->strtab + sym->st_name,
1498                              "__mstrtab_", sizeof "__mstrtab_" - 1)) {
1499                         if (first_sym == NULL)
1500                                 first_sym = sym;
1501                         last_sym = sym;
1502                         ++n;
1503                 }
1504
1505         if (n == 0)
1506                 return;
1507
1508         /*
1509          * Now collect each name and format into a line for the output.
1510          * Lines look like:
1511          *      marker_name     vmlinux marker %s format %d
1512          * The format string after the second \t can use whitespace.
1513          */
1514         mod->markers = NOFAIL(malloc(sizeof mod->markers[0] * n));
1515         mod->nmarkers = n;
1516
1517         n = 0;
1518         for (sym = first_sym; sym <= last_sym; sym++)
1519                 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT &&
1520                     sym->st_shndx == info->markers_strings_sec &&
1521                     !strncmp(info->strtab + sym->st_name,
1522                              "__mstrtab_", sizeof "__mstrtab_" - 1)) {
1523                         const char *name = strings + sym->st_value;
1524                         const char *fmt = strchr(name, '\0') + 1;
1525                         char *line = NULL;
1526                         asprintf(&line, "%s\t%s\t%s\n", name, mod->name, fmt);
1527                         NOFAIL(line);
1528                         mod->markers[n++] = line;
1529                 }
1530 }
1531
1532 static void read_symbols(char *modname)
1533 {
1534         const char *symname;
1535         char *version;
1536         char *license;
1537         struct module *mod;
1538         struct elf_info info = { };
1539         Elf_Sym *sym;
1540
1541         if (!parse_elf(&info, modname))
1542                 return;
1543
1544         mod = new_module(modname);
1545
1546         /* When there's no vmlinux, don't print warnings about
1547          * unresolved symbols (since there'll be too many ;) */
1548         if (is_vmlinux(modname)) {
1549                 have_vmlinux = 1;
1550                 mod->skip = 1;
1551         }
1552
1553         license = get_modinfo(info.modinfo, info.modinfo_len, "license");
1554         if (info.modinfo && !license && !is_vmlinux(modname))
1555                 warn("modpost: missing MODULE_LICENSE() in %s\n"
1556                      "see include/linux/module.h for "
1557                      "more information\n", modname);
1558         while (license) {
1559                 if (license_is_gpl_compatible(license))
1560                         mod->gpl_compatible = 1;
1561                 else {
1562                         mod->gpl_compatible = 0;
1563                         break;
1564                 }
1565                 license = get_next_modinfo(info.modinfo, info.modinfo_len,
1566                                            "license", license);
1567         }
1568
1569         for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1570                 symname = info.strtab + sym->st_name;
1571
1572                 handle_modversions(mod, &info, sym, symname);
1573                 handle_moddevtable(mod, &info, sym, symname);
1574         }
1575         if (!is_vmlinux(modname) ||
1576              (is_vmlinux(modname) && vmlinux_section_warnings))
1577                 check_sec_ref(mod, modname, &info);
1578
1579         version = get_modinfo(info.modinfo, info.modinfo_len, "version");
1580         if (version)
1581                 maybe_frob_rcs_version(modname, version, info.modinfo,
1582                                        version - (char *)info.hdr);
1583         if (version || (all_versions && !is_vmlinux(modname)))
1584                 get_src_version(modname, mod->srcversion,
1585                                 sizeof(mod->srcversion)-1);
1586
1587         get_markers(&info, mod);
1588
1589         parse_elf_finish(&info);
1590
1591         /* Our trick to get versioning for module struct etc. - it's
1592          * never passed as an argument to an exported function, so
1593          * the automatic versioning doesn't pick it up, but it's really
1594          * important anyhow */
1595         if (modversions)
1596                 mod->unres = alloc_symbol("module_layout", 0, mod->unres);
1597 }
1598
1599 #define SZ 500
1600
1601 /* We first write the generated file into memory using the
1602  * following helper, then compare to the file on disk and
1603  * only update the later if anything changed */
1604
1605 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1606                                                       const char *fmt, ...)
1607 {
1608         char tmp[SZ];
1609         int len;
1610         va_list ap;
1611
1612         va_start(ap, fmt);
1613         len = vsnprintf(tmp, SZ, fmt, ap);
1614         buf_write(buf, tmp, len);
1615         va_end(ap);
1616 }
1617
1618 void buf_write(struct buffer *buf, const char *s, int len)
1619 {
1620         if (buf->size - buf->pos < len) {
1621                 buf->size += len + SZ;
1622                 buf->p = realloc(buf->p, buf->size);
1623         }
1624         strncpy(buf->p + buf->pos, s, len);
1625         buf->pos += len;
1626 }
1627
1628 static void check_for_gpl_usage(enum export exp, const char *m, const char *s)
1629 {
1630         const char *e = is_vmlinux(m) ?"":".ko";
1631
1632         switch (exp) {
1633         case export_gpl:
1634                 fatal("modpost: GPL-incompatible module %s%s "
1635                       "uses GPL-only symbol '%s'\n", m, e, s);
1636                 break;
1637         case export_unused_gpl:
1638                 fatal("modpost: GPL-incompatible module %s%s "
1639                       "uses GPL-only symbol marked UNUSED '%s'\n", m, e, s);
1640                 break;
1641         case export_gpl_future:
1642                 warn("modpost: GPL-incompatible module %s%s "
1643                       "uses future GPL-only symbol '%s'\n", m, e, s);
1644                 break;
1645         case export_plain:
1646         case export_unused:
1647         case export_unknown:
1648                 /* ignore */
1649                 break;
1650         }
1651 }
1652
1653 static void check_for_unused(enum export exp, const char *m, const char *s)
1654 {
1655         const char *e = is_vmlinux(m) ?"":".ko";
1656
1657         switch (exp) {
1658         case export_unused:
1659         case export_unused_gpl:
1660                 warn("modpost: module %s%s "
1661                       "uses symbol '%s' marked UNUSED\n", m, e, s);
1662                 break;
1663         default:
1664                 /* ignore */
1665                 break;
1666         }
1667 }
1668
1669 static void check_exports(struct module *mod)
1670 {
1671         struct symbol *s, *exp;
1672
1673         for (s = mod->unres; s; s = s->next) {
1674                 const char *basename;
1675                 exp = find_symbol(s->name);
1676                 if (!exp || exp->module == mod)
1677                         continue;
1678                 basename = strrchr(mod->name, '/');
1679                 if (basename)
1680                         basename++;
1681                 else
1682                         basename = mod->name;
1683                 if (!mod->gpl_compatible)
1684                         check_for_gpl_usage(exp->export, basename, exp->name);
1685                 check_for_unused(exp->export, basename, exp->name);
1686         }
1687 }
1688
1689 /**
1690  * Header for the generated file
1691  **/
1692 static void add_header(struct buffer *b, struct module *mod)
1693 {
1694         buf_printf(b, "#include <linux/module.h>\n");
1695         buf_printf(b, "#include <linux/vermagic.h>\n");
1696         buf_printf(b, "#include <linux/compiler.h>\n");
1697         buf_printf(b, "\n");
1698         buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
1699         buf_printf(b, "\n");
1700         buf_printf(b, "struct module __this_module\n");
1701         buf_printf(b, "__attribute__((section(\".gnu.linkonce.this_module\"))) = {\n");
1702         buf_printf(b, " .name = KBUILD_MODNAME,\n");
1703         if (mod->has_init)
1704                 buf_printf(b, " .init = init_module,\n");
1705         if (mod->has_cleanup)
1706                 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1707                               " .exit = cleanup_module,\n"
1708                               "#endif\n");
1709         buf_printf(b, " .arch = MODULE_ARCH_INIT,\n");
1710         buf_printf(b, "};\n");
1711 }
1712
1713 void add_staging_flag(struct buffer *b, const char *name)
1714 {
1715         static const char *staging_dir = "drivers/staging";
1716
1717         if (strncmp(staging_dir, name, strlen(staging_dir)) == 0)
1718                 buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n");
1719 }
1720
1721 /**
1722  * Record CRCs for unresolved symbols
1723  **/
1724 static int add_versions(struct buffer *b, struct module *mod)
1725 {
1726         struct symbol *s, *exp;
1727         int err = 0;
1728
1729         for (s = mod->unres; s; s = s->next) {
1730                 exp = find_symbol(s->name);
1731                 if (!exp || exp->module == mod) {
1732                         if (have_vmlinux && !s->weak) {
1733                                 if (warn_unresolved) {
1734                                         warn("\"%s\" [%s.ko] undefined!\n",
1735                                              s->name, mod->name);
1736                                 } else {
1737                                         merror("\"%s\" [%s.ko] undefined!\n",
1738                                                   s->name, mod->name);
1739                                         err = 1;
1740                                 }
1741                         }
1742                         continue;
1743                 }
1744                 s->module = exp->module;
1745                 s->crc_valid = exp->crc_valid;
1746                 s->crc = exp->crc;
1747         }
1748
1749         if (!modversions)
1750                 return err;
1751
1752         buf_printf(b, "\n");
1753         buf_printf(b, "static const struct modversion_info ____versions[]\n");
1754         buf_printf(b, "__used\n");
1755         buf_printf(b, "__attribute__((section(\"__versions\"))) = {\n");
1756
1757         for (s = mod->unres; s; s = s->next) {
1758                 if (!s->module)
1759                         continue;
1760                 if (!s->crc_valid) {
1761                         warn("\"%s\" [%s.ko] has no CRC!\n",
1762                                 s->name, mod->name);
1763                         continue;
1764                 }
1765                 buf_printf(b, "\t{ %#8x, \"%s\" },\n", s->crc, s->name);
1766         }
1767
1768         buf_printf(b, "};\n");
1769
1770         return err;
1771 }
1772
1773 static void add_depends(struct buffer *b, struct module *mod,
1774                         struct module *modules)
1775 {
1776         struct symbol *s;
1777         struct module *m;
1778         int first = 1;
1779
1780         for (m = modules; m; m = m->next)
1781                 m->seen = is_vmlinux(m->name);
1782
1783         buf_printf(b, "\n");
1784         buf_printf(b, "static const char __module_depends[]\n");
1785         buf_printf(b, "__used\n");
1786         buf_printf(b, "__attribute__((section(\".modinfo\"))) =\n");
1787         buf_printf(b, "\"depends=");
1788         for (s = mod->unres; s; s = s->next) {
1789                 const char *p;
1790                 if (!s->module)
1791                         continue;
1792
1793                 if (s->module->seen)
1794                         continue;
1795
1796                 s->module->seen = 1;
1797                 p = strrchr(s->module->name, '/');
1798                 if (p)
1799                         p++;
1800                 else
1801                         p = s->module->name;
1802                 buf_printf(b, "%s%s", first ? "" : ",", p);
1803                 first = 0;
1804         }
1805         buf_printf(b, "\";\n");
1806 }
1807
1808 static void add_srcversion(struct buffer *b, struct module *mod)
1809 {
1810         if (mod->srcversion[0]) {
1811                 buf_printf(b, "\n");
1812                 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
1813                            mod->srcversion);
1814         }
1815 }
1816
1817 static void write_if_changed(struct buffer *b, const char *fname)
1818 {
1819         char *tmp;
1820         FILE *file;
1821         struct stat st;
1822
1823         file = fopen(fname, "r");
1824         if (!file)
1825                 goto write;
1826
1827         if (fstat(fileno(file), &st) < 0)
1828                 goto close_write;
1829
1830         if (st.st_size != b->pos)
1831                 goto close_write;
1832
1833         tmp = NOFAIL(malloc(b->pos));
1834         if (fread(tmp, 1, b->pos, file) != b->pos)
1835                 goto free_write;
1836
1837         if (memcmp(tmp, b->p, b->pos) != 0)
1838                 goto free_write;
1839
1840         free(tmp);
1841         fclose(file);
1842         return;
1843
1844  free_write:
1845         free(tmp);
1846  close_write:
1847         fclose(file);
1848  write:
1849         file = fopen(fname, "w");
1850         if (!file) {
1851                 perror(fname);
1852                 exit(1);
1853         }
1854         if (fwrite(b->p, 1, b->pos, file) != b->pos) {
1855                 perror(fname);
1856                 exit(1);
1857         }
1858         fclose(file);
1859 }
1860
1861 /* parse Module.symvers file. line format:
1862  * 0x12345678<tab>symbol<tab>module[[<tab>export]<tab>something]
1863  **/
1864 static void read_dump(const char *fname, unsigned int kernel)
1865 {
1866         unsigned long size, pos = 0;
1867         void *file = grab_file(fname, &size);
1868         char *line;
1869
1870         if (!file)
1871                 /* No symbol versions, silently ignore */
1872                 return;
1873
1874         while ((line = get_next_line(&pos, file, size))) {
1875                 char *symname, *modname, *d, *export, *end;
1876                 unsigned int crc;
1877                 struct module *mod;
1878                 struct symbol *s;
1879
1880                 if (!(symname = strchr(line, '\t')))
1881                         goto fail;
1882                 *symname++ = '\0';
1883                 if (!(modname = strchr(symname, '\t')))
1884                         goto fail;
1885                 *modname++ = '\0';
1886                 if ((export = strchr(modname, '\t')) != NULL)
1887                         *export++ = '\0';
1888                 if (export && ((end = strchr(export, '\t')) != NULL))
1889                         *end = '\0';
1890                 crc = strtoul(line, &d, 16);
1891                 if (*symname == '\0' || *modname == '\0' || *d != '\0')
1892                         goto fail;
1893                 mod = find_module(modname);
1894                 if (!mod) {
1895                         if (is_vmlinux(modname))
1896                                 have_vmlinux = 1;
1897                         mod = new_module(modname);
1898                         mod->skip = 1;
1899                 }
1900                 s = sym_add_exported(symname, mod, export_no(export));
1901                 s->kernel    = kernel;
1902                 s->preloaded = 1;
1903                 sym_update_crc(symname, mod, crc, export_no(export));
1904         }
1905         return;
1906 fail:
1907         fatal("parse error in symbol dump file\n");
1908 }
1909
1910 /* For normal builds always dump all symbols.
1911  * For external modules only dump symbols
1912  * that are not read from kernel Module.symvers.
1913  **/
1914 static int dump_sym(struct symbol *sym)
1915 {
1916         if (!external_module)
1917                 return 1;
1918         if (sym->vmlinux || sym->kernel)
1919                 return 0;
1920         return 1;
1921 }
1922
1923 static void write_dump(const char *fname)
1924 {
1925         struct buffer buf = { };
1926         struct symbol *symbol;
1927         int n;
1928
1929         for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
1930                 symbol = symbolhash[n];
1931                 while (symbol) {
1932                         if (dump_sym(symbol))
1933                                 buf_printf(&buf, "0x%08x\t%s\t%s\t%s\n",
1934                                         symbol->crc, symbol->name,
1935                                         symbol->module->name,
1936                                         export_str(symbol->export));
1937                         symbol = symbol->next;
1938                 }
1939         }
1940         write_if_changed(&buf, fname);
1941 }
1942
1943 static void add_marker(struct module *mod, const char *name, const char *fmt)
1944 {
1945         char *line = NULL;
1946         asprintf(&line, "%s\t%s\t%s\n", name, mod->name, fmt);
1947         NOFAIL(line);
1948
1949         mod->markers = NOFAIL(realloc(mod->markers, ((mod->nmarkers + 1) *
1950                                                      sizeof mod->markers[0])));
1951         mod->markers[mod->nmarkers++] = line;
1952 }
1953
1954 static void read_markers(const char *fname)
1955 {
1956         unsigned long size, pos = 0;
1957         void *file = grab_file(fname, &size);
1958         char *line;
1959
1960         if (!file)              /* No old markers, silently ignore */
1961                 return;
1962
1963         while ((line = get_next_line(&pos, file, size))) {
1964                 char *marker, *modname, *fmt;
1965                 struct module *mod;
1966
1967                 marker = line;
1968                 modname = strchr(marker, '\t');
1969                 if (!modname)
1970                         goto fail;
1971                 *modname++ = '\0';
1972                 fmt = strchr(modname, '\t');
1973                 if (!fmt)
1974                         goto fail;
1975                 *fmt++ = '\0';
1976                 if (*marker == '\0' || *modname == '\0')
1977                         goto fail;
1978
1979                 mod = find_module(modname);
1980                 if (!mod) {
1981                         mod = new_module(modname);
1982                         mod->skip = 1;
1983                 }
1984                 if (is_vmlinux(modname)) {
1985                         have_vmlinux = 1;
1986                         mod->skip = 0;
1987                 }
1988
1989                 if (!mod->skip)
1990                         add_marker(mod, marker, fmt);
1991         }
1992         release_file(file, size);
1993         return;
1994 fail:
1995         fatal("parse error in markers list file\n");
1996 }
1997
1998 static int compare_strings(const void *a, const void *b)
1999 {
2000         return strcmp(*(const char **) a, *(const char **) b);
2001 }
2002
2003 static void write_markers(const char *fname)
2004 {
2005         struct buffer buf = { };
2006         struct module *mod;
2007         size_t i;
2008
2009         for (mod = modules; mod; mod = mod->next)
2010                 if ((!external_module || !mod->skip) && mod->markers != NULL) {
2011                         /*
2012                          * Sort the strings so we can skip duplicates when
2013                          * we write them out.
2014                          */
2015                         qsort(mod->markers, mod->nmarkers,
2016                               sizeof mod->markers[0], &compare_strings);
2017                         for (i = 0; i < mod->nmarkers; ++i) {
2018                                 char *line = mod->markers[i];
2019                                 buf_write(&buf, line, strlen(line));
2020                                 while (i + 1 < mod->nmarkers &&
2021                                        !strcmp(mod->markers[i],
2022                                                mod->markers[i + 1]))
2023                                         free(mod->markers[i++]);
2024                                 free(mod->markers[i]);
2025                         }
2026                         free(mod->markers);
2027                         mod->markers = NULL;
2028                 }
2029
2030         write_if_changed(&buf, fname);
2031 }
2032
2033 struct ext_sym_list {
2034         struct ext_sym_list *next;
2035         const char *file;
2036 };
2037
2038 int main(int argc, char **argv)
2039 {
2040         struct module *mod;
2041         struct buffer buf = { };
2042         char *kernel_read = NULL, *module_read = NULL;
2043         char *dump_write = NULL;
2044         char *markers_read = NULL;
2045         char *markers_write = NULL;
2046         int opt;
2047         int err;
2048         struct ext_sym_list *extsym_iter;
2049         struct ext_sym_list *extsym_start = NULL;
2050
2051         while ((opt = getopt(argc, argv, "i:I:e:cmsSo:awM:K:")) != -1) {
2052                 switch (opt) {
2053                 case 'i':
2054                         kernel_read = optarg;
2055                         break;
2056                 case 'I':
2057                         module_read = optarg;
2058                         external_module = 1;
2059                         break;
2060                 case 'c':
2061                         cross_build = 1;
2062                         break;
2063                 case 'e':
2064                         external_module = 1;
2065                         extsym_iter =
2066                            NOFAIL(malloc(sizeof(*extsym_iter)));
2067                         extsym_iter->next = extsym_start;
2068                         extsym_iter->file = optarg;
2069                         extsym_start = extsym_iter;
2070                         break;
2071                 case 'm':
2072                         modversions = 1;
2073                         break;
2074                 case 'o':
2075                         dump_write = optarg;
2076                         break;
2077                 case 'a':
2078                         all_versions = 1;
2079                         break;
2080                 case 's':
2081                         vmlinux_section_warnings = 0;
2082                         break;
2083                 case 'S':
2084                         sec_mismatch_verbose = 0;
2085                         break;
2086                 case 'w':
2087                         warn_unresolved = 1;
2088                         break;
2089                         case 'M':
2090                                 markers_write = optarg;
2091                                 break;
2092                         case 'K':
2093                                 markers_read = optarg;
2094                                 break;
2095                 default:
2096                         exit(1);
2097                 }
2098         }
2099
2100         if (kernel_read)
2101                 read_dump(kernel_read, 1);
2102         if (module_read)
2103                 read_dump(module_read, 0);
2104         while (extsym_start) {
2105                 read_dump(extsym_start->file, 0);
2106                 extsym_iter = extsym_start->next;
2107                 free(extsym_start);
2108                 extsym_start = extsym_iter;
2109         }
2110
2111         while (optind < argc)
2112                 read_symbols(argv[optind++]);
2113
2114         for (mod = modules; mod; mod = mod->next) {
2115                 if (mod->skip)
2116                         continue;
2117                 check_exports(mod);
2118         }
2119
2120         err = 0;
2121
2122         for (mod = modules; mod; mod = mod->next) {
2123                 char fname[strlen(mod->name) + 10];
2124
2125                 if (mod->skip)
2126                         continue;
2127
2128                 buf.pos = 0;
2129
2130                 add_header(&buf, mod);
2131                 add_staging_flag(&buf, mod->name);
2132                 err |= add_versions(&buf, mod);
2133                 add_depends(&buf, mod, modules);
2134                 add_moddevtable(&buf, mod);
2135                 add_srcversion(&buf, mod);
2136
2137                 sprintf(fname, "%s.mod.c", mod->name);
2138                 write_if_changed(&buf, fname);
2139         }
2140
2141         if (dump_write)
2142                 write_dump(dump_write);
2143         if (sec_mismatch_count && !sec_mismatch_verbose)
2144                 warn("modpost: Found %d section mismatch(es).\n"
2145                      "To see full details build your kernel with:\n"
2146                      "'make CONFIG_DEBUG_SECTION_MISMATCH=y'\n",
2147                      sec_mismatch_count);
2148
2149         if (markers_read)
2150                 read_markers(markers_read);
2151
2152         if (markers_write)
2153                 write_markers(markers_write);
2154
2155         return err;
2156 }