ba2e4fc2af20e2b816c3ddfd6bc8e491c304eadc
[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       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
17 /* Are we using CONFIG_MODVERSIONS? */
18 int modversions = 0;
19 /* Warn about undefined symbols? (do so if we have vmlinux) */
20 int have_vmlinux = 0;
21 /* Is CONFIG_MODULE_SRCVERSION_ALL set? */
22 static int all_versions = 0;
23 /* If we are modposting external module set to 1 */
24 static int external_module = 0;
25 /* How a symbol is exported */
26 enum export {export_plain, export_gpl, export_gpl_future, export_unknown};
27
28 void fatal(const char *fmt, ...)
29 {
30         va_list arglist;
31
32         fprintf(stderr, "FATAL: ");
33
34         va_start(arglist, fmt);
35         vfprintf(stderr, fmt, arglist);
36         va_end(arglist);
37
38         exit(1);
39 }
40
41 void warn(const char *fmt, ...)
42 {
43         va_list arglist;
44
45         fprintf(stderr, "WARNING: ");
46
47         va_start(arglist, fmt);
48         vfprintf(stderr, fmt, arglist);
49         va_end(arglist);
50 }
51
52 static int is_vmlinux(const char *modname)
53 {
54         const char *myname;
55
56         if ((myname = strrchr(modname, '/')))
57                 myname++;
58         else
59                 myname = modname;
60
61         return strcmp(myname, "vmlinux") == 0;
62 }
63
64 void *do_nofail(void *ptr, const char *expr)
65 {
66         if (!ptr) {
67                 fatal("modpost: Memory allocation failure: %s.\n", expr);
68         }
69         return ptr;
70 }
71
72 /* A list of all modules we processed */
73
74 static struct module *modules;
75
76 static struct module *find_module(char *modname)
77 {
78         struct module *mod;
79
80         for (mod = modules; mod; mod = mod->next)
81                 if (strcmp(mod->name, modname) == 0)
82                         break;
83         return mod;
84 }
85
86 static struct module *new_module(char *modname)
87 {
88         struct module *mod;
89         char *p, *s;
90
91         mod = NOFAIL(malloc(sizeof(*mod)));
92         memset(mod, 0, sizeof(*mod));
93         p = NOFAIL(strdup(modname));
94
95         /* strip trailing .o */
96         if ((s = strrchr(p, '.')) != NULL)
97                 if (strcmp(s, ".o") == 0)
98                         *s = '\0';
99
100         /* add to list */
101         mod->name = p;
102         mod->next = modules;
103         modules = mod;
104
105         return mod;
106 }
107
108 /* A hash of all exported symbols,
109  * struct symbol is also used for lists of unresolved symbols */
110
111 #define SYMBOL_HASH_SIZE 1024
112
113 struct symbol {
114         struct symbol *next;
115         struct module *module;
116         unsigned int crc;
117         int crc_valid;
118         unsigned int weak:1;
119         unsigned int vmlinux:1;    /* 1 if symbol is defined in vmlinux */
120         unsigned int kernel:1;     /* 1 if symbol is from kernel
121                                     *  (only for external modules) **/
122         unsigned int preloaded:1;  /* 1 if symbol from Module.symvers */
123         enum export  export;       /* Type of export */
124         char name[0];
125 };
126
127 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
128
129 /* This is based on the hash agorithm from gdbm, via tdb */
130 static inline unsigned int tdb_hash(const char *name)
131 {
132         unsigned value; /* Used to compute the hash value.  */
133         unsigned   i;   /* Used to cycle through random values. */
134
135         /* Set the initial value from the key size. */
136         for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
137                 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
138
139         return (1103515243 * value + 12345);
140 }
141
142 /**
143  * Allocate a new symbols for use in the hash of exported symbols or
144  * the list of unresolved symbols per module
145  **/
146 static struct symbol *alloc_symbol(const char *name, unsigned int weak,
147                                    struct symbol *next)
148 {
149         struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
150
151         memset(s, 0, sizeof(*s));
152         strcpy(s->name, name);
153         s->weak = weak;
154         s->next = next;
155         return s;
156 }
157
158 /* For the hash of exported symbols */
159 static struct symbol *new_symbol(const char *name, struct module *module,
160                                  enum export export)
161 {
162         unsigned int hash;
163         struct symbol *new;
164
165         hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
166         new = symbolhash[hash] = alloc_symbol(name, 0, symbolhash[hash]);
167         new->module = module;
168         new->export = export;
169         return new;
170 }
171
172 static struct symbol *find_symbol(const char *name)
173 {
174         struct symbol *s;
175
176         /* For our purposes, .foo matches foo.  PPC64 needs this. */
177         if (name[0] == '.')
178                 name++;
179
180         for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s=s->next) {
181                 if (strcmp(s->name, name) == 0)
182                         return s;
183         }
184         return NULL;
185 }
186
187 static struct {
188         const char *str;
189         enum export export;
190 } export_list[] = {
191         { .str = "EXPORT_SYMBOL",            .export = export_plain },
192         { .str = "EXPORT_SYMBOL_GPL",        .export = export_gpl },
193         { .str = "EXPORT_SYMBOL_GPL_FUTURE", .export = export_gpl_future },
194         { .str = "(unknown)",                .export = export_unknown },
195 };
196
197
198 static const char *export_str(enum export ex)
199 {
200         return export_list[ex].str;
201 }
202
203 static enum export export_no(const char * s)
204 {
205         int i;
206         for (i = 0; export_list[i].export != export_unknown; i++) {
207                 if (strcmp(export_list[i].str, s) == 0)
208                         return export_list[i].export;
209         }
210         return export_unknown;
211 }
212
213 static enum export export_from_sec(struct elf_info *elf, Elf_Section sec)
214 {
215         if (sec == elf->export_sec)
216                 return export_plain;
217         else if (sec == elf->export_gpl_sec)
218                 return export_gpl;
219         else if (sec == elf->export_gpl_future_sec)
220                 return export_gpl_future;
221         else
222                 return export_unknown;
223 }
224
225 /**
226  * Add an exported symbol - it may have already been added without a
227  * CRC, in this case just update the CRC
228  **/
229 static struct symbol *sym_add_exported(const char *name, struct module *mod,
230                                        enum export export)
231 {
232         struct symbol *s = find_symbol(name);
233
234         if (!s) {
235                 s = new_symbol(name, mod, export);
236         } else {
237                 if (!s->preloaded) {
238                         warn("%s: '%s' exported twice. Previous export "
239                              "was in %s%s\n", mod->name, name,
240                              s->module->name,
241                              is_vmlinux(s->module->name) ?"":".ko");
242                 }
243         }
244         s->preloaded = 0;
245         s->vmlinux   = is_vmlinux(mod->name);
246         s->kernel    = 0;
247         s->export    = export;
248         return s;
249 }
250
251 static void sym_update_crc(const char *name, struct module *mod,
252                            unsigned int crc, enum export export)
253 {
254         struct symbol *s = find_symbol(name);
255
256         if (!s)
257                 s = new_symbol(name, mod, export);
258         s->crc = crc;
259         s->crc_valid = 1;
260 }
261
262 void *grab_file(const char *filename, unsigned long *size)
263 {
264         struct stat st;
265         void *map;
266         int fd;
267
268         fd = open(filename, O_RDONLY);
269         if (fd < 0 || fstat(fd, &st) != 0)
270                 return NULL;
271
272         *size = st.st_size;
273         map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
274         close(fd);
275
276         if (map == MAP_FAILED)
277                 return NULL;
278         return map;
279 }
280
281 /**
282   * Return a copy of the next line in a mmap'ed file.
283   * spaces in the beginning of the line is trimmed away.
284   * Return a pointer to a static buffer.
285   **/
286 char* get_next_line(unsigned long *pos, void *file, unsigned long size)
287 {
288         static char line[4096];
289         int skip = 1;
290         size_t len = 0;
291         signed char *p = (signed char *)file + *pos;
292         char *s = line;
293
294         for (; *pos < size ; (*pos)++)
295         {
296                 if (skip && isspace(*p)) {
297                         p++;
298                         continue;
299                 }
300                 skip = 0;
301                 if (*p != '\n' && (*pos < size)) {
302                         len++;
303                         *s++ = *p++;
304                         if (len > 4095)
305                                 break; /* Too long, stop */
306                 } else {
307                         /* End of string */
308                         *s = '\0';
309                         return line;
310                 }
311         }
312         /* End of buffer */
313         return NULL;
314 }
315
316 void release_file(void *file, unsigned long size)
317 {
318         munmap(file, size);
319 }
320
321 static void parse_elf(struct elf_info *info, const char *filename)
322 {
323         unsigned int i;
324         Elf_Ehdr *hdr = info->hdr;
325         Elf_Shdr *sechdrs;
326         Elf_Sym  *sym;
327
328         hdr = grab_file(filename, &info->size);
329         if (!hdr) {
330                 perror(filename);
331                 abort();
332         }
333         info->hdr = hdr;
334         if (info->size < sizeof(*hdr))
335                 goto truncated;
336
337         /* Fix endianness in ELF header */
338         hdr->e_shoff    = TO_NATIVE(hdr->e_shoff);
339         hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
340         hdr->e_shnum    = TO_NATIVE(hdr->e_shnum);
341         hdr->e_machine  = TO_NATIVE(hdr->e_machine);
342         sechdrs = (void *)hdr + hdr->e_shoff;
343         info->sechdrs = sechdrs;
344
345         /* Fix endianness in section headers */
346         for (i = 0; i < hdr->e_shnum; i++) {
347                 sechdrs[i].sh_type   = TO_NATIVE(sechdrs[i].sh_type);
348                 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
349                 sechdrs[i].sh_size   = TO_NATIVE(sechdrs[i].sh_size);
350                 sechdrs[i].sh_link   = TO_NATIVE(sechdrs[i].sh_link);
351                 sechdrs[i].sh_name   = TO_NATIVE(sechdrs[i].sh_name);
352         }
353         /* Find symbol table. */
354         for (i = 1; i < hdr->e_shnum; i++) {
355                 const char *secstrings
356                         = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
357                 const char *secname;
358
359                 if (sechdrs[i].sh_offset > info->size)
360                         goto truncated;
361                 secname = secstrings + sechdrs[i].sh_name;
362                 if (strcmp(secname, ".modinfo") == 0) {
363                         info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
364                         info->modinfo_len = sechdrs[i].sh_size;
365                 } else if (strcmp(secname, "__ksymtab") == 0)
366                         info->export_sec = i;
367                 else if (strcmp(secname, "__ksymtab_gpl") == 0)
368                         info->export_gpl_sec = i;
369                 else if (strcmp(secname, "__ksymtab_gpl_future") == 0)
370                         info->export_gpl_future_sec = i;
371
372                 if (sechdrs[i].sh_type != SHT_SYMTAB)
373                         continue;
374
375                 info->symtab_start = (void *)hdr + sechdrs[i].sh_offset;
376                 info->symtab_stop  = (void *)hdr + sechdrs[i].sh_offset
377                                                  + sechdrs[i].sh_size;
378                 info->strtab       = (void *)hdr +
379                                      sechdrs[sechdrs[i].sh_link].sh_offset;
380         }
381         if (!info->symtab_start) {
382                 fatal("%s has no symtab?\n", filename);
383         }
384         /* Fix endianness in symbols */
385         for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
386                 sym->st_shndx = TO_NATIVE(sym->st_shndx);
387                 sym->st_name  = TO_NATIVE(sym->st_name);
388                 sym->st_value = TO_NATIVE(sym->st_value);
389                 sym->st_size  = TO_NATIVE(sym->st_size);
390         }
391         return;
392
393  truncated:
394         fatal("%s is truncated.\n", filename);
395 }
396
397 static void parse_elf_finish(struct elf_info *info)
398 {
399         release_file(info->hdr, info->size);
400 }
401
402 #define CRC_PFX     MODULE_SYMBOL_PREFIX "__crc_"
403 #define KSYMTAB_PFX MODULE_SYMBOL_PREFIX "__ksymtab_"
404
405 static void handle_modversions(struct module *mod, struct elf_info *info,
406                                Elf_Sym *sym, const char *symname)
407 {
408         unsigned int crc;
409         enum export export = export_from_sec(info, sym->st_shndx);
410
411         switch (sym->st_shndx) {
412         case SHN_COMMON:
413                 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
414                 break;
415         case SHN_ABS:
416                 /* CRC'd symbol */
417                 if (memcmp(symname, CRC_PFX, strlen(CRC_PFX)) == 0) {
418                         crc = (unsigned int) sym->st_value;
419                         sym_update_crc(symname + strlen(CRC_PFX), mod, crc,
420                                         export);
421                 }
422                 break;
423         case SHN_UNDEF:
424                 /* undefined symbol */
425                 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
426                     ELF_ST_BIND(sym->st_info) != STB_WEAK)
427                         break;
428                 /* ignore global offset table */
429                 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
430                         break;
431                 /* ignore __this_module, it will be resolved shortly */
432                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "__this_module") == 0)
433                         break;
434 /* cope with newer glibc (2.3.4 or higher) STT_ definition in elf.h */
435 #if defined(STT_REGISTER) || defined(STT_SPARC_REGISTER)
436 /* add compatibility with older glibc */
437 #ifndef STT_SPARC_REGISTER
438 #define STT_SPARC_REGISTER STT_REGISTER
439 #endif
440                 if (info->hdr->e_machine == EM_SPARC ||
441                     info->hdr->e_machine == EM_SPARCV9) {
442                         /* Ignore register directives. */
443                         if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
444                                 break;
445                         if (symname[0] == '.') {
446                                 char *munged = strdup(symname);
447                                 munged[0] = '_';
448                                 munged[1] = toupper(munged[1]);
449                                 symname = munged;
450                         }
451                 }
452 #endif
453
454                 if (memcmp(symname, MODULE_SYMBOL_PREFIX,
455                            strlen(MODULE_SYMBOL_PREFIX)) == 0)
456                         mod->unres = alloc_symbol(symname +
457                                                   strlen(MODULE_SYMBOL_PREFIX),
458                                                   ELF_ST_BIND(sym->st_info) == STB_WEAK,
459                                                   mod->unres);
460                 break;
461         default:
462                 /* All exported symbols */
463                 if (memcmp(symname, KSYMTAB_PFX, strlen(KSYMTAB_PFX)) == 0) {
464                         sym_add_exported(symname + strlen(KSYMTAB_PFX), mod,
465                                         export);
466                 }
467                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "init_module") == 0)
468                         mod->has_init = 1;
469                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "cleanup_module") == 0)
470                         mod->has_cleanup = 1;
471                 break;
472         }
473 }
474
475 /**
476  * Parse tag=value strings from .modinfo section
477  **/
478 static char *next_string(char *string, unsigned long *secsize)
479 {
480         /* Skip non-zero chars */
481         while (string[0]) {
482                 string++;
483                 if ((*secsize)-- <= 1)
484                         return NULL;
485         }
486
487         /* Skip any zero padding. */
488         while (!string[0]) {
489                 string++;
490                 if ((*secsize)-- <= 1)
491                         return NULL;
492         }
493         return string;
494 }
495
496 static char *get_modinfo(void *modinfo, unsigned long modinfo_len,
497                          const char *tag)
498 {
499         char *p;
500         unsigned int taglen = strlen(tag);
501         unsigned long size = modinfo_len;
502
503         for (p = modinfo; p; p = next_string(p, &size)) {
504                 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
505                         return p + taglen + 1;
506         }
507         return NULL;
508 }
509
510 /**
511  * Test if string s ends in string sub
512  * return 0 if match
513  **/
514 static int strrcmp(const char *s, const char *sub)
515 {
516         int slen, sublen;
517
518         if (!s || !sub)
519                 return 1;
520
521         slen = strlen(s);
522         sublen = strlen(sub);
523
524         if ((slen == 0) || (sublen == 0))
525                 return 1;
526
527         if (sublen > slen)
528                 return 1;
529
530         return memcmp(s + slen - sublen, sub, sublen);
531 }
532
533 /**
534  * Whitelist to allow certain references to pass with no warning.
535  * Pattern 1:
536  *   If a module parameter is declared __initdata and permissions=0
537  *   then this is legal despite the warning generated.
538  *   We cannot see value of permissions here, so just ignore
539  *   this pattern.
540  *   The pattern is identified by:
541  *   tosec   = .init.data
542  *   fromsec = .data*
543  *   atsym   =__param*
544  *
545  * Pattern 2:
546  *   Many drivers utilise a *driver container with references to
547  *   add, remove, probe functions etc.
548  *   These functions may often be marked __init and we do not want to
549  *   warn here.
550  *   the pattern is identified by:
551  *   tosec   = .init.text | .exit.text | .init.data
552  *   fromsec = .data
553  *   atsym = *driver, *_template, *_sht, *_ops, *_probe, *probe_one
554  **/
555 static int secref_whitelist(const char *tosec, const char *fromsec,
556                             const char *atsym)
557 {
558         int f1 = 1, f2 = 1;
559         const char **s;
560         const char *pat2sym[] = {
561                 "driver",
562                 "_template", /* scsi uses *_template a lot */
563                 "_sht",      /* scsi also used *_sht to some extent */
564                 "_ops",
565                 "_probe",
566                 "_probe_one",
567                 NULL
568         };
569
570         /* Check for pattern 1 */
571         if (strcmp(tosec, ".init.data") != 0)
572                 f1 = 0;
573         if (strncmp(fromsec, ".data", strlen(".data")) != 0)
574                 f1 = 0;
575         if (strncmp(atsym, "__param", strlen("__param")) != 0)
576                 f1 = 0;
577
578         if (f1)
579                 return f1;
580
581         /* Check for pattern 2 */
582         if ((strcmp(tosec, ".init.text") != 0) &&
583             (strcmp(tosec, ".exit.text") != 0) &&
584             (strcmp(tosec, ".init.data") != 0))
585                 f2 = 0;
586         if (strcmp(fromsec, ".data") != 0)
587                 f2 = 0;
588
589         for (s = pat2sym; *s; s++)
590                 if (strrcmp(atsym, *s) == 0)
591                         f1 = 1;
592
593         return f1 && f2;
594 }
595
596 /**
597  * Find symbol based on relocation record info.
598  * In some cases the symbol supplied is a valid symbol so
599  * return refsym. If st_name != 0 we assume this is a valid symbol.
600  * In other cases the symbol needs to be looked up in the symbol table
601  * based on section and address.
602  *  **/
603 static Elf_Sym *find_elf_symbol(struct elf_info *elf, Elf_Addr addr,
604                                 Elf_Sym *relsym)
605 {
606         Elf_Sym *sym;
607
608         if (relsym->st_name != 0)
609                 return relsym;
610         for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
611                 if (sym->st_shndx != relsym->st_shndx)
612                         continue;
613                 if (sym->st_value == addr)
614                         return sym;
615         }
616         return NULL;
617 }
618
619 /*
620  * Find symbols before or equal addr and after addr - in the section sec.
621  * If we find two symbols with equal offset prefer one with a valid name.
622  * The ELF format may have a better way to detect what type of symbol
623  * it is, but this works for now.
624  **/
625 static void find_symbols_between(struct elf_info *elf, Elf_Addr addr,
626                                  const char *sec,
627                                  Elf_Sym **before, Elf_Sym **after)
628 {
629         Elf_Sym *sym;
630         Elf_Ehdr *hdr = elf->hdr;
631         Elf_Addr beforediff = ~0;
632         Elf_Addr afterdiff = ~0;
633         const char *secstrings = (void *)hdr +
634                                  elf->sechdrs[hdr->e_shstrndx].sh_offset;
635
636         *before = NULL;
637         *after = NULL;
638
639         for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
640                 const char *symsec;
641
642                 if (sym->st_shndx >= SHN_LORESERVE)
643                         continue;
644                 symsec = secstrings + elf->sechdrs[sym->st_shndx].sh_name;
645                 if (strcmp(symsec, sec) != 0)
646                         continue;
647                 if (sym->st_value <= addr) {
648                         if ((addr - sym->st_value) < beforediff) {
649                                 beforediff = addr - sym->st_value;
650                                 *before = sym;
651                         }
652                         else if ((addr - sym->st_value) == beforediff) {
653                                 /* equal offset, valid name? */
654                                 const char *name = elf->strtab + sym->st_name;
655                                 if (name && strlen(name))
656                                         *before = sym;
657                         }
658                 }
659                 else
660                 {
661                         if ((sym->st_value - addr) < afterdiff) {
662                                 afterdiff = sym->st_value - addr;
663                                 *after = sym;
664                         }
665                         else if ((sym->st_value - addr) == afterdiff) {
666                                 /* equal offset, valid name? */
667                                 const char *name = elf->strtab + sym->st_name;
668                                 if (name && strlen(name))
669                                         *after = sym;
670                         }
671                 }
672         }
673 }
674
675 /**
676  * Print a warning about a section mismatch.
677  * Try to find symbols near it so user can find it.
678  * Check whitelist before warning - it may be a false positive.
679  **/
680 static void warn_sec_mismatch(const char *modname, const char *fromsec,
681                               struct elf_info *elf, Elf_Sym *sym, Elf_Rela r)
682 {
683         const char *refsymname = "";
684         Elf_Sym *before, *after;
685         Elf_Sym *refsym;
686         Elf_Ehdr *hdr = elf->hdr;
687         Elf_Shdr *sechdrs = elf->sechdrs;
688         const char *secstrings = (void *)hdr +
689                                  sechdrs[hdr->e_shstrndx].sh_offset;
690         const char *secname = secstrings + sechdrs[sym->st_shndx].sh_name;
691
692         find_symbols_between(elf, r.r_offset, fromsec, &before, &after);
693
694         refsym = find_elf_symbol(elf, r.r_addend, sym);
695         if (refsym && strlen(elf->strtab + refsym->st_name))
696                 refsymname = elf->strtab + refsym->st_name;
697
698         /* check whitelist - we may ignore it */
699         if (before &&
700             secref_whitelist(secname, fromsec, elf->strtab + before->st_name))
701                 return;
702
703         if (before && after) {
704                 warn("%s - Section mismatch: reference to %s:%s from %s "
705                      "between '%s' (at offset 0x%llx) and '%s'\n",
706                      modname, secname, refsymname, fromsec,
707                      elf->strtab + before->st_name,
708                      (long long)r.r_offset,
709                      elf->strtab + after->st_name);
710         } else if (before) {
711                 warn("%s - Section mismatch: reference to %s:%s from %s "
712                      "after '%s' (at offset 0x%llx)\n",
713                      modname, secname, refsymname, fromsec,
714                      elf->strtab + before->st_name,
715                      (long long)r.r_offset);
716         } else if (after) {
717                 warn("%s - Section mismatch: reference to %s:%s from %s "
718                      "before '%s' (at offset -0x%llx)\n",
719                      modname, secname, refsymname, fromsec,
720                      elf->strtab + after->st_name,
721                      (long long)r.r_offset);
722         } else {
723                 warn("%s - Section mismatch: reference to %s:%s from %s "
724                      "(offset 0x%llx)\n",
725                      modname, secname, fromsec, refsymname,
726                      (long long)r.r_offset);
727         }
728 }
729
730 /**
731  * A module includes a number of sections that are discarded
732  * either when loaded or when used as built-in.
733  * For loaded modules all functions marked __init and all data
734  * marked __initdata will be discarded when the module has been intialized.
735  * Likewise for modules used built-in the sections marked __exit
736  * are discarded because __exit marked function are supposed to be called
737  * only when a moduel is unloaded which never happes for built-in modules.
738  * The check_sec_ref() function traverses all relocation records
739  * to find all references to a section that reference a section that will
740  * be discarded and warns about it.
741  **/
742 static void check_sec_ref(struct module *mod, const char *modname,
743                           struct elf_info *elf,
744                           int section(const char*),
745                           int section_ref_ok(const char *))
746 {
747         int i;
748         Elf_Sym  *sym;
749         Elf_Ehdr *hdr = elf->hdr;
750         Elf_Shdr *sechdrs = elf->sechdrs;
751         const char *secstrings = (void *)hdr +
752                                  sechdrs[hdr->e_shstrndx].sh_offset;
753
754         /* Walk through all sections */
755         for (i = 0; i < hdr->e_shnum; i++) {
756                 const char *name = secstrings + sechdrs[i].sh_name;
757                 const char *secname;
758                 Elf_Rela r;
759                 unsigned int r_sym;
760                 /* We want to process only relocation sections and not .init */
761                 if (sechdrs[i].sh_type == SHT_RELA) {
762                         Elf_Rela *rela;
763                         Elf_Rela *start = (void *)hdr + sechdrs[i].sh_offset;
764                         Elf_Rela *stop  = (void*)start + sechdrs[i].sh_size;
765                         name += strlen(".rela");
766                         if (section_ref_ok(name))
767                                 continue;
768
769                         for (rela = start; rela < stop; rela++) {
770                                 r.r_offset = TO_NATIVE(rela->r_offset);
771 #if KERNEL_ELFCLASS == ELFCLASS64
772                                 if (hdr->e_machine == EM_MIPS) {
773                                         r_sym = ELF64_MIPS_R_SYM(rela->r_info);
774                                         r_sym = TO_NATIVE(r_sym);
775                                 } else {
776                                         r.r_info = TO_NATIVE(rela->r_info);
777                                         r_sym = ELF_R_SYM(r.r_info);
778                                 }
779 #else
780                                 r.r_info = TO_NATIVE(rela->r_info);
781                                 r_sym = ELF_R_SYM(r.r_info);
782 #endif
783                                 r.r_addend = TO_NATIVE(rela->r_addend);
784                                 sym = elf->symtab_start + r_sym;
785                                 /* Skip special sections */
786                                 if (sym->st_shndx >= SHN_LORESERVE)
787                                         continue;
788
789                                 secname = secstrings +
790                                         sechdrs[sym->st_shndx].sh_name;
791                                 if (section(secname))
792                                         warn_sec_mismatch(modname, name,
793                                                           elf, sym, r);
794                         }
795                 } else if (sechdrs[i].sh_type == SHT_REL) {
796                         Elf_Rel *rel;
797                         Elf_Rel *start = (void *)hdr + sechdrs[i].sh_offset;
798                         Elf_Rel *stop  = (void*)start + sechdrs[i].sh_size;
799                         name += strlen(".rel");
800                         if (section_ref_ok(name))
801                                 continue;
802
803                         for (rel = start; rel < stop; rel++) {
804                                 r.r_offset = TO_NATIVE(rel->r_offset);
805 #if KERNEL_ELFCLASS == ELFCLASS64
806                                 if (hdr->e_machine == EM_MIPS) {
807                                         r_sym = ELF64_MIPS_R_SYM(rel->r_info);
808                                         r_sym = TO_NATIVE(r_sym);
809                                 } else {
810                                         r.r_info = TO_NATIVE(rel->r_info);
811                                         r_sym = ELF_R_SYM(r.r_info);
812                                 }
813 #else
814                                 r.r_info = TO_NATIVE(rel->r_info);
815                                 r_sym = ELF_R_SYM(r.r_info);
816 #endif
817                                 r.r_addend = 0;
818                                 sym = elf->symtab_start + r_sym;
819                                 /* Skip special sections */
820                                 if (sym->st_shndx >= SHN_LORESERVE)
821                                         continue;
822
823                                 secname = secstrings +
824                                         sechdrs[sym->st_shndx].sh_name;
825                                 if (section(secname))
826                                         warn_sec_mismatch(modname, name,
827                                                           elf, sym, r);
828                         }
829                 }
830         }
831 }
832
833 /**
834  * Functions used only during module init is marked __init and is stored in
835  * a .init.text section. Likewise data is marked __initdata and stored in
836  * a .init.data section.
837  * If this section is one of these sections return 1
838  * See include/linux/init.h for the details
839  **/
840 static int init_section(const char *name)
841 {
842         if (strcmp(name, ".init") == 0)
843                 return 1;
844         if (strncmp(name, ".init.", strlen(".init.")) == 0)
845                 return 1;
846         return 0;
847 }
848
849 /**
850  * Identify sections from which references to a .init section is OK.
851  *
852  * Unfortunately references to read only data that referenced .init
853  * sections had to be excluded. Almost all of these are false
854  * positives, they are created by gcc. The downside of excluding rodata
855  * is that there really are some user references from rodata to
856  * init code, e.g. drivers/video/vgacon.c:
857  *
858  * const struct consw vga_con = {
859  *        con_startup:            vgacon_startup,
860  *
861  * where vgacon_startup is __init.  If you want to wade through the false
862  * positives, take out the check for rodata.
863  **/
864 static int init_section_ref_ok(const char *name)
865 {
866         const char **s;
867         /* Absolute section names */
868         const char *namelist1[] = {
869                 ".init",
870                 ".opd",   /* see comment [OPD] at exit_section_ref_ok() */
871                 ".toc1",  /* used by ppc64 */
872                 ".stab",
873                 ".rodata",
874                 ".text.lock",
875                 "__bug_table", /* used by powerpc for BUG() */
876                 ".pci_fixup_header",
877                 ".pci_fixup_final",
878                 ".pdr",
879                 "__param",
880                 ".smp_locks",
881                 ".plt",  /* seen on ARCH=um build on x86_64. Harmless */
882                 NULL
883         };
884         /* Start of section names */
885         const char *namelist2[] = {
886                 ".init.",
887                 ".altinstructions",
888                 ".eh_frame",
889                 ".debug",
890                 NULL
891         };
892         /* part of section name */
893         const char *namelist3 [] = {
894                 ".unwind",  /* sample: IA_64.unwind.init.text */
895                 NULL
896         };
897
898         for (s = namelist1; *s; s++)
899                 if (strcmp(*s, name) == 0)
900                         return 1;
901         for (s = namelist2; *s; s++)
902                 if (strncmp(*s, name, strlen(*s)) == 0)
903                         return 1;
904         for (s = namelist3; *s; s++)
905                 if (strstr(name, *s) != NULL)
906                         return 1;
907         return 0;
908 }
909
910 /*
911  * Functions used only during module exit is marked __exit and is stored in
912  * a .exit.text section. Likewise data is marked __exitdata and stored in
913  * a .exit.data section.
914  * If this section is one of these sections return 1
915  * See include/linux/init.h for the details
916  **/
917 static int exit_section(const char *name)
918 {
919         if (strcmp(name, ".exit.text") == 0)
920                 return 1;
921         if (strcmp(name, ".exit.data") == 0)
922                 return 1;
923         return 0;
924
925 }
926
927 /*
928  * Identify sections from which references to a .exit section is OK.
929  *
930  * [OPD] Keith Ownes <kaos@sgi.com> commented:
931  * For our future {in}sanity, add a comment that this is the ppc .opd
932  * section, not the ia64 .opd section.
933  * ia64 .opd should not point to discarded sections.
934  * [.rodata] like for .init.text we ignore .rodata references -same reason
935  **/
936 static int exit_section_ref_ok(const char *name)
937 {
938         const char **s;
939         /* Absolute section names */
940         const char *namelist1[] = {
941                 ".exit.text",
942                 ".exit.data",
943                 ".init.text",
944                 ".rodata",
945                 ".opd", /* See comment [OPD] */
946                 ".toc1",  /* used by ppc64 */
947                 ".altinstructions",
948                 ".pdr",
949                 "__bug_table", /* used by powerpc for BUG() */
950                 ".exitcall.exit",
951                 ".eh_frame",
952                 ".stab",
953                 ".smp_locks",
954                 ".plt",  /* seen on ARCH=um build on x86_64. Harmless */
955                 NULL
956         };
957         /* Start of section names */
958         const char *namelist2[] = {
959                 ".debug",
960                 NULL
961         };
962         /* part of section name */
963         const char *namelist3 [] = {
964                 ".unwind",  /* Sample: IA_64.unwind.exit.text */
965                 NULL
966         };
967
968         for (s = namelist1; *s; s++)
969                 if (strcmp(*s, name) == 0)
970                         return 1;
971         for (s = namelist2; *s; s++)
972                 if (strncmp(*s, name, strlen(*s)) == 0)
973                         return 1;
974         for (s = namelist3; *s; s++)
975                 if (strstr(name, *s) != NULL)
976                         return 1;
977         return 0;
978 }
979
980 static void read_symbols(char *modname)
981 {
982         const char *symname;
983         char *version;
984         struct module *mod;
985         struct elf_info info = { };
986         Elf_Sym *sym;
987
988         parse_elf(&info, modname);
989
990         mod = new_module(modname);
991
992         /* When there's no vmlinux, don't print warnings about
993          * unresolved symbols (since there'll be too many ;) */
994         if (is_vmlinux(modname)) {
995                 have_vmlinux = 1;
996                 mod->skip = 1;
997         }
998
999         for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
1000                 symname = info.strtab + sym->st_name;
1001
1002                 handle_modversions(mod, &info, sym, symname);
1003                 handle_moddevtable(mod, &info, sym, symname);
1004         }
1005         check_sec_ref(mod, modname, &info, init_section, init_section_ref_ok);
1006         check_sec_ref(mod, modname, &info, exit_section, exit_section_ref_ok);
1007
1008         version = get_modinfo(info.modinfo, info.modinfo_len, "version");
1009         if (version)
1010                 maybe_frob_rcs_version(modname, version, info.modinfo,
1011                                        version - (char *)info.hdr);
1012         if (version || (all_versions && !is_vmlinux(modname)))
1013                 get_src_version(modname, mod->srcversion,
1014                                 sizeof(mod->srcversion)-1);
1015
1016         parse_elf_finish(&info);
1017
1018         /* Our trick to get versioning for struct_module - it's
1019          * never passed as an argument to an exported function, so
1020          * the automatic versioning doesn't pick it up, but it's really
1021          * important anyhow */
1022         if (modversions)
1023                 mod->unres = alloc_symbol("struct_module", 0, mod->unres);
1024 }
1025
1026 #define SZ 500
1027
1028 /* We first write the generated file into memory using the
1029  * following helper, then compare to the file on disk and
1030  * only update the later if anything changed */
1031
1032 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
1033                                                       const char *fmt, ...)
1034 {
1035         char tmp[SZ];
1036         int len;
1037         va_list ap;
1038
1039         va_start(ap, fmt);
1040         len = vsnprintf(tmp, SZ, fmt, ap);
1041         buf_write(buf, tmp, len);
1042         va_end(ap);
1043 }
1044
1045 void buf_write(struct buffer *buf, const char *s, int len)
1046 {
1047         if (buf->size - buf->pos < len) {
1048                 buf->size += len + SZ;
1049                 buf->p = realloc(buf->p, buf->size);
1050         }
1051         strncpy(buf->p + buf->pos, s, len);
1052         buf->pos += len;
1053 }
1054
1055 /**
1056  * Header for the generated file
1057  **/
1058 static void add_header(struct buffer *b, struct module *mod)
1059 {
1060         buf_printf(b, "#include <linux/module.h>\n");
1061         buf_printf(b, "#include <linux/vermagic.h>\n");
1062         buf_printf(b, "#include <linux/compiler.h>\n");
1063         buf_printf(b, "\n");
1064         buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
1065         buf_printf(b, "\n");
1066         buf_printf(b, "struct module __this_module\n");
1067         buf_printf(b, "__attribute__((section(\".gnu.linkonce.this_module\"))) = {\n");
1068         buf_printf(b, " .name = KBUILD_MODNAME,\n");
1069         if (mod->has_init)
1070                 buf_printf(b, " .init = init_module,\n");
1071         if (mod->has_cleanup)
1072                 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
1073                               " .exit = cleanup_module,\n"
1074                               "#endif\n");
1075         buf_printf(b, "};\n");
1076 }
1077
1078 /**
1079  * Record CRCs for unresolved symbols
1080  **/
1081 static void add_versions(struct buffer *b, struct module *mod)
1082 {
1083         struct symbol *s, *exp;
1084
1085         for (s = mod->unres; s; s = s->next) {
1086                 exp = find_symbol(s->name);
1087                 if (!exp || exp->module == mod) {
1088                         if (have_vmlinux && !s->weak)
1089                                 warn("\"%s\" [%s.ko] undefined!\n",
1090                                      s->name, mod->name);
1091                         continue;
1092                 }
1093                 s->module = exp->module;
1094                 s->crc_valid = exp->crc_valid;
1095                 s->crc = exp->crc;
1096         }
1097
1098         if (!modversions)
1099                 return;
1100
1101         buf_printf(b, "\n");
1102         buf_printf(b, "static const struct modversion_info ____versions[]\n");
1103         buf_printf(b, "__attribute_used__\n");
1104         buf_printf(b, "__attribute__((section(\"__versions\"))) = {\n");
1105
1106         for (s = mod->unres; s; s = s->next) {
1107                 if (!s->module) {
1108                         continue;
1109                 }
1110                 if (!s->crc_valid) {
1111                         warn("\"%s\" [%s.ko] has no CRC!\n",
1112                                 s->name, mod->name);
1113                         continue;
1114                 }
1115                 buf_printf(b, "\t{ %#8x, \"%s\" },\n", s->crc, s->name);
1116         }
1117
1118         buf_printf(b, "};\n");
1119 }
1120
1121 static void add_depends(struct buffer *b, struct module *mod,
1122                         struct module *modules)
1123 {
1124         struct symbol *s;
1125         struct module *m;
1126         int first = 1;
1127
1128         for (m = modules; m; m = m->next) {
1129                 m->seen = is_vmlinux(m->name);
1130         }
1131
1132         buf_printf(b, "\n");
1133         buf_printf(b, "static const char __module_depends[]\n");
1134         buf_printf(b, "__attribute_used__\n");
1135         buf_printf(b, "__attribute__((section(\".modinfo\"))) =\n");
1136         buf_printf(b, "\"depends=");
1137         for (s = mod->unres; s; s = s->next) {
1138                 if (!s->module)
1139                         continue;
1140
1141                 if (s->module->seen)
1142                         continue;
1143
1144                 s->module->seen = 1;
1145                 buf_printf(b, "%s%s", first ? "" : ",",
1146                            strrchr(s->module->name, '/') + 1);
1147                 first = 0;
1148         }
1149         buf_printf(b, "\";\n");
1150 }
1151
1152 static void add_srcversion(struct buffer *b, struct module *mod)
1153 {
1154         if (mod->srcversion[0]) {
1155                 buf_printf(b, "\n");
1156                 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
1157                            mod->srcversion);
1158         }
1159 }
1160
1161 static void write_if_changed(struct buffer *b, const char *fname)
1162 {
1163         char *tmp;
1164         FILE *file;
1165         struct stat st;
1166
1167         file = fopen(fname, "r");
1168         if (!file)
1169                 goto write;
1170
1171         if (fstat(fileno(file), &st) < 0)
1172                 goto close_write;
1173
1174         if (st.st_size != b->pos)
1175                 goto close_write;
1176
1177         tmp = NOFAIL(malloc(b->pos));
1178         if (fread(tmp, 1, b->pos, file) != b->pos)
1179                 goto free_write;
1180
1181         if (memcmp(tmp, b->p, b->pos) != 0)
1182                 goto free_write;
1183
1184         free(tmp);
1185         fclose(file);
1186         return;
1187
1188  free_write:
1189         free(tmp);
1190  close_write:
1191         fclose(file);
1192  write:
1193         file = fopen(fname, "w");
1194         if (!file) {
1195                 perror(fname);
1196                 exit(1);
1197         }
1198         if (fwrite(b->p, 1, b->pos, file) != b->pos) {
1199                 perror(fname);
1200                 exit(1);
1201         }
1202         fclose(file);
1203 }
1204
1205 /* parse Module.symvers file. line format:
1206  * 0x12345678<tab>symbol<tab>module[<tab>export]
1207  **/
1208 static void read_dump(const char *fname, unsigned int kernel)
1209 {
1210         unsigned long size, pos = 0;
1211         void *file = grab_file(fname, &size);
1212         char *line;
1213
1214         if (!file)
1215                 /* No symbol versions, silently ignore */
1216                 return;
1217
1218         while ((line = get_next_line(&pos, file, size))) {
1219                 char *symname, *modname, *d, *export;
1220                 unsigned int crc;
1221                 struct module *mod;
1222                 struct symbol *s;
1223
1224                 if (!(symname = strchr(line, '\t')))
1225                         goto fail;
1226                 *symname++ = '\0';
1227                 if (!(modname = strchr(symname, '\t')))
1228                         goto fail;
1229                 *modname++ = '\0';
1230                 if (!(export = strchr(modname, '\t')))
1231                         *export++ = '\0';
1232
1233                 crc = strtoul(line, &d, 16);
1234                 if (*symname == '\0' || *modname == '\0' || *d != '\0')
1235                         goto fail;
1236
1237                 if (!(mod = find_module(modname))) {
1238                         if (is_vmlinux(modname)) {
1239                                 have_vmlinux = 1;
1240                         }
1241                         mod = new_module(NOFAIL(strdup(modname)));
1242                         mod->skip = 1;
1243                 }
1244                 s = sym_add_exported(symname, mod, export_no(export));
1245                 s->kernel    = kernel;
1246                 s->preloaded = 1;
1247                 sym_update_crc(symname, mod, crc, export_no(export));
1248         }
1249         return;
1250 fail:
1251         fatal("parse error in symbol dump file\n");
1252 }
1253
1254 /* For normal builds always dump all symbols.
1255  * For external modules only dump symbols
1256  * that are not read from kernel Module.symvers.
1257  **/
1258 static int dump_sym(struct symbol *sym)
1259 {
1260         if (!external_module)
1261                 return 1;
1262         if (sym->vmlinux || sym->kernel)
1263                 return 0;
1264         return 1;
1265 }
1266
1267 static void write_dump(const char *fname)
1268 {
1269         struct buffer buf = { };
1270         struct symbol *symbol;
1271         int n;
1272
1273         for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
1274                 symbol = symbolhash[n];
1275                 while (symbol) {
1276                         if (dump_sym(symbol))
1277                                 buf_printf(&buf, "0x%08x\t%s\t%s\t%s\n",
1278                                         symbol->crc, symbol->name,
1279                                         symbol->module->name,
1280                                         export_str(symbol->export));
1281                         symbol = symbol->next;
1282                 }
1283         }
1284         write_if_changed(&buf, fname);
1285 }
1286
1287 int main(int argc, char **argv)
1288 {
1289         struct module *mod;
1290         struct buffer buf = { };
1291         char fname[SZ];
1292         char *kernel_read = NULL, *module_read = NULL;
1293         char *dump_write = NULL;
1294         int opt;
1295
1296         while ((opt = getopt(argc, argv, "i:I:mo:a")) != -1) {
1297                 switch(opt) {
1298                         case 'i':
1299                                 kernel_read = optarg;
1300                                 break;
1301                         case 'I':
1302                                 module_read = optarg;
1303                                 external_module = 1;
1304                                 break;
1305                         case 'm':
1306                                 modversions = 1;
1307                                 break;
1308                         case 'o':
1309                                 dump_write = optarg;
1310                                 break;
1311                         case 'a':
1312                                 all_versions = 1;
1313                                 break;
1314                         default:
1315                                 exit(1);
1316                 }
1317         }
1318
1319         if (kernel_read)
1320                 read_dump(kernel_read, 1);
1321         if (module_read)
1322                 read_dump(module_read, 0);
1323
1324         while (optind < argc) {
1325                 read_symbols(argv[optind++]);
1326         }
1327
1328         for (mod = modules; mod; mod = mod->next) {
1329                 if (mod->skip)
1330                         continue;
1331
1332                 buf.pos = 0;
1333
1334                 add_header(&buf, mod);
1335                 add_versions(&buf, mod);
1336                 add_depends(&buf, mod, modules);
1337                 add_moddevtable(&buf, mod);
1338                 add_srcversion(&buf, mod);
1339
1340                 sprintf(fname, "%s.mod.c", mod->name);
1341                 write_if_changed(&buf, fname);
1342         }
1343
1344         if (dump_write)
1345                 write_dump(dump_write);
1346
1347         return 0;
1348 }