kbuild: check for section mismatch during modpost stage
[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  *
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
26 void fatal(const char *fmt, ...)
27 {
28         va_list arglist;
29
30         fprintf(stderr, "FATAL: ");
31
32         va_start(arglist, fmt);
33         vfprintf(stderr, fmt, arglist);
34         va_end(arglist);
35
36         exit(1);
37 }
38
39 void warn(const char *fmt, ...)
40 {
41         va_list arglist;
42
43         fprintf(stderr, "WARNING: ");
44
45         va_start(arglist, fmt);
46         vfprintf(stderr, fmt, arglist);
47         va_end(arglist);
48 }
49
50 static int is_vmlinux(const char *modname)
51 {
52         const char *myname;
53
54         if ((myname = strrchr(modname, '/')))
55                 myname++;
56         else
57                 myname = modname;
58
59         return strcmp(myname, "vmlinux") == 0;
60 }
61
62 void *do_nofail(void *ptr, const char *expr)
63 {
64         if (!ptr) {
65                 fatal("modpost: Memory allocation failure: %s.\n", expr);
66         }
67         return ptr;
68 }
69
70 /* A list of all modules we processed */
71
72 static struct module *modules;
73
74 static struct module *find_module(char *modname)
75 {
76         struct module *mod;
77
78         for (mod = modules; mod; mod = mod->next)
79                 if (strcmp(mod->name, modname) == 0)
80                         break;
81         return mod;
82 }
83
84 static struct module *new_module(char *modname)
85 {
86         struct module *mod;
87         char *p, *s;
88         
89         mod = NOFAIL(malloc(sizeof(*mod)));
90         memset(mod, 0, sizeof(*mod));
91         p = NOFAIL(strdup(modname));
92
93         /* strip trailing .o */
94         if ((s = strrchr(p, '.')) != NULL)
95                 if (strcmp(s, ".o") == 0)
96                         *s = '\0';
97
98         /* add to list */
99         mod->name = p;
100         mod->next = modules;
101         modules = mod;
102
103         return mod;
104 }
105
106 /* A hash of all exported symbols,
107  * struct symbol is also used for lists of unresolved symbols */
108
109 #define SYMBOL_HASH_SIZE 1024
110
111 struct symbol {
112         struct symbol *next;
113         struct module *module;
114         unsigned int crc;
115         int crc_valid;
116         unsigned int weak:1;
117         unsigned int vmlinux:1;    /* 1 if symbol is defined in vmlinux */
118         unsigned int kernel:1;     /* 1 if symbol is from kernel
119                                     *  (only for external modules) **/
120         unsigned int preloaded:1;  /* 1 if symbol from Module.symvers */
121         char name[0];
122 };
123
124 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
125
126 /* This is based on the hash agorithm from gdbm, via tdb */
127 static inline unsigned int tdb_hash(const char *name)
128 {
129         unsigned value; /* Used to compute the hash value.  */
130         unsigned   i;   /* Used to cycle through random values. */
131
132         /* Set the initial value from the key size. */
133         for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
134                 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
135
136         return (1103515243 * value + 12345);
137 }
138
139 /**
140  * Allocate a new symbols for use in the hash of exported symbols or
141  * the list of unresolved symbols per module
142  **/
143 static struct symbol *alloc_symbol(const char *name, unsigned int weak,
144                                    struct symbol *next)
145 {
146         struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
147
148         memset(s, 0, sizeof(*s));
149         strcpy(s->name, name);
150         s->weak = weak;
151         s->next = next;
152         return s;
153 }
154
155 /* For the hash of exported symbols */
156 static struct symbol *new_symbol(const char *name, struct module *module)
157 {
158         unsigned int hash;
159         struct symbol *new;
160
161         hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
162         new = symbolhash[hash] = alloc_symbol(name, 0, symbolhash[hash]);
163         new->module = module;
164         return new;
165 }
166
167 static struct symbol *find_symbol(const char *name)
168 {
169         struct symbol *s;
170
171         /* For our purposes, .foo matches foo.  PPC64 needs this. */
172         if (name[0] == '.')
173                 name++;
174
175         for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s=s->next) {
176                 if (strcmp(s->name, name) == 0)
177                         return s;
178         }
179         return NULL;
180 }
181
182 /**
183  * Add an exported symbol - it may have already been added without a
184  * CRC, in this case just update the CRC
185  **/
186 static struct symbol *sym_add_exported(const char *name, struct module *mod)
187 {
188         struct symbol *s = find_symbol(name);
189
190         if (!s) {
191                 s = new_symbol(name, mod);
192         } else {
193                 if (!s->preloaded) {
194                         warn("%s: duplicate symbol '%s' previous definition "
195                              "was in %s%s\n", mod->name, name,
196                              s->module->name,
197                              is_vmlinux(s->module->name) ?"":".ko");
198                 }
199         }
200         s->preloaded = 0;
201         s->vmlinux   = is_vmlinux(mod->name);
202         s->kernel    = 0;
203         return s;
204 }
205
206 static void sym_update_crc(const char *name, struct module *mod,
207                            unsigned int crc)
208 {
209         struct symbol *s = find_symbol(name);
210
211         if (!s)
212                 s = new_symbol(name, mod);
213         s->crc = crc;
214         s->crc_valid = 1;
215 }
216
217 void *grab_file(const char *filename, unsigned long *size)
218 {
219         struct stat st;
220         void *map;
221         int fd;
222
223         fd = open(filename, O_RDONLY);
224         if (fd < 0 || fstat(fd, &st) != 0)
225                 return NULL;
226
227         *size = st.st_size;
228         map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
229         close(fd);
230
231         if (map == MAP_FAILED)
232                 return NULL;
233         return map;
234 }
235
236 /**
237   * Return a copy of the next line in a mmap'ed file.
238   * spaces in the beginning of the line is trimmed away.
239   * Return a pointer to a static buffer.
240   **/
241 char* get_next_line(unsigned long *pos, void *file, unsigned long size)
242 {
243         static char line[4096];
244         int skip = 1;
245         size_t len = 0;
246         signed char *p = (signed char *)file + *pos;
247         char *s = line;
248
249         for (; *pos < size ; (*pos)++)
250         {
251                 if (skip && isspace(*p)) {
252                         p++;
253                         continue;
254                 }
255                 skip = 0;
256                 if (*p != '\n' && (*pos < size)) {
257                         len++;
258                         *s++ = *p++;
259                         if (len > 4095)
260                                 break; /* Too long, stop */
261                 } else {
262                         /* End of string */
263                         *s = '\0';
264                         return line;
265                 }
266         }
267         /* End of buffer */
268         return NULL;
269 }
270
271 void release_file(void *file, unsigned long size)
272 {
273         munmap(file, size);
274 }
275
276 static void parse_elf(struct elf_info *info, const char *filename)
277 {
278         unsigned int i;
279         Elf_Ehdr *hdr = info->hdr;
280         Elf_Shdr *sechdrs;
281         Elf_Sym  *sym;
282
283         hdr = grab_file(filename, &info->size);
284         if (!hdr) {
285                 perror(filename);
286                 abort();
287         }
288         info->hdr = hdr;
289         if (info->size < sizeof(*hdr))
290                 goto truncated;
291
292         /* Fix endianness in ELF header */
293         hdr->e_shoff    = TO_NATIVE(hdr->e_shoff);
294         hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
295         hdr->e_shnum    = TO_NATIVE(hdr->e_shnum);
296         hdr->e_machine  = TO_NATIVE(hdr->e_machine);
297         sechdrs = (void *)hdr + hdr->e_shoff;
298         info->sechdrs = sechdrs;
299
300         /* Fix endianness in section headers */
301         for (i = 0; i < hdr->e_shnum; i++) {
302                 sechdrs[i].sh_type   = TO_NATIVE(sechdrs[i].sh_type);
303                 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
304                 sechdrs[i].sh_size   = TO_NATIVE(sechdrs[i].sh_size);
305                 sechdrs[i].sh_link   = TO_NATIVE(sechdrs[i].sh_link);
306                 sechdrs[i].sh_name   = TO_NATIVE(sechdrs[i].sh_name);
307         }
308         /* Find symbol table. */
309         for (i = 1; i < hdr->e_shnum; i++) {
310                 const char *secstrings
311                         = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
312
313                 if (sechdrs[i].sh_offset > info->size)
314                         goto truncated;
315                 if (strcmp(secstrings+sechdrs[i].sh_name, ".modinfo") == 0) {
316                         info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
317                         info->modinfo_len = sechdrs[i].sh_size;
318                 }
319                 if (sechdrs[i].sh_type != SHT_SYMTAB)
320                         continue;
321
322                 info->symtab_start = (void *)hdr + sechdrs[i].sh_offset;
323                 info->symtab_stop  = (void *)hdr + sechdrs[i].sh_offset 
324                                                  + sechdrs[i].sh_size;
325                 info->strtab       = (void *)hdr + 
326                                      sechdrs[sechdrs[i].sh_link].sh_offset;
327         }
328         if (!info->symtab_start) {
329                 fatal("%s has no symtab?\n", filename);
330         }
331         /* Fix endianness in symbols */
332         for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
333                 sym->st_shndx = TO_NATIVE(sym->st_shndx);
334                 sym->st_name  = TO_NATIVE(sym->st_name);
335                 sym->st_value = TO_NATIVE(sym->st_value);
336                 sym->st_size  = TO_NATIVE(sym->st_size);
337         }
338         return;
339
340  truncated:
341         fatal("%s is truncated.\n", filename);
342 }
343
344 static void parse_elf_finish(struct elf_info *info)
345 {
346         release_file(info->hdr, info->size);
347 }
348
349 #define CRC_PFX     "__crc_"
350 #define KSYMTAB_PFX "__ksymtab_"
351
352 static void handle_modversions(struct module *mod, struct elf_info *info,
353                                Elf_Sym *sym, const char *symname)
354 {
355         unsigned int crc;
356
357         switch (sym->st_shndx) {
358         case SHN_COMMON:
359                 warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name);
360                 break;
361         case SHN_ABS:
362                 /* CRC'd symbol */
363                 if (memcmp(symname, CRC_PFX, strlen(CRC_PFX)) == 0) {
364                         crc = (unsigned int) sym->st_value;
365                         sym_update_crc(symname + strlen(CRC_PFX), mod, crc);
366                 }
367                 break;
368         case SHN_UNDEF:
369                 /* undefined symbol */
370                 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL &&
371                     ELF_ST_BIND(sym->st_info) != STB_WEAK)
372                         break;
373                 /* ignore global offset table */
374                 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
375                         break;
376                 /* ignore __this_module, it will be resolved shortly */
377                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "__this_module") == 0)
378                         break;
379 /* cope with newer glibc (2.3.4 or higher) STT_ definition in elf.h */
380 #if defined(STT_REGISTER) || defined(STT_SPARC_REGISTER)
381 /* add compatibility with older glibc */
382 #ifndef STT_SPARC_REGISTER
383 #define STT_SPARC_REGISTER STT_REGISTER
384 #endif
385                 if (info->hdr->e_machine == EM_SPARC ||
386                     info->hdr->e_machine == EM_SPARCV9) {
387                         /* Ignore register directives. */
388                         if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER)
389                                 break;
390                         if (symname[0] == '.') {
391                                 char *munged = strdup(symname);
392                                 munged[0] = '_';
393                                 munged[1] = toupper(munged[1]);
394                                 symname = munged;
395                         }
396                 }
397 #endif
398                 
399                 if (memcmp(symname, MODULE_SYMBOL_PREFIX,
400                            strlen(MODULE_SYMBOL_PREFIX)) == 0)
401                         mod->unres = alloc_symbol(symname +
402                                                   strlen(MODULE_SYMBOL_PREFIX),
403                                                   ELF_ST_BIND(sym->st_info) == STB_WEAK,
404                                                   mod->unres);
405                 break;
406         default:
407                 /* All exported symbols */
408                 if (memcmp(symname, KSYMTAB_PFX, strlen(KSYMTAB_PFX)) == 0) {
409                         sym_add_exported(symname + strlen(KSYMTAB_PFX), mod);
410                 }
411                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "init_module") == 0)
412                         mod->has_init = 1;
413                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "cleanup_module") == 0)
414                         mod->has_cleanup = 1;
415                 break;
416         }
417 }
418
419 /**
420  * Parse tag=value strings from .modinfo section
421  **/
422 static char *next_string(char *string, unsigned long *secsize)
423 {
424         /* Skip non-zero chars */
425         while (string[0]) {
426                 string++;
427                 if ((*secsize)-- <= 1)
428                         return NULL;
429         }
430
431         /* Skip any zero padding. */
432         while (!string[0]) {
433                 string++;
434                 if ((*secsize)-- <= 1)
435                         return NULL;
436         }
437         return string;
438 }
439
440 static char *get_modinfo(void *modinfo, unsigned long modinfo_len,
441                          const char *tag)
442 {
443         char *p;
444         unsigned int taglen = strlen(tag);
445         unsigned long size = modinfo_len;
446
447         for (p = modinfo; p; p = next_string(p, &size)) {
448                 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
449                         return p + taglen + 1;
450         }
451         return NULL;
452 }
453
454 /*
455  * Find symbols before or equal addr and after addr - in the section sec
456  **/
457 static void find_symbols_between(struct elf_info *elf, Elf_Addr addr,
458                                  const char *sec,
459                                  Elf_Sym **before, Elf_Sym **after)
460 {
461         Elf_Sym *sym;
462         Elf_Ehdr *hdr = elf->hdr;
463         Elf_Addr beforediff = ~0;
464         Elf_Addr afterdiff = ~0;
465         const char *secstrings = (void *)hdr +
466                                  elf->sechdrs[hdr->e_shstrndx].sh_offset;
467         
468         *before = NULL;
469         *after = NULL;
470
471         for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) {
472                 const char *symsec;
473
474                 if (sym->st_shndx >= SHN_LORESERVE)
475                         continue;
476                 symsec = secstrings + elf->sechdrs[sym->st_shndx].sh_name;
477                 if (strcmp(symsec, sec) != 0)
478                         continue;
479                 if (sym->st_value <= addr) {
480                         if ((addr - sym->st_value) < beforediff) {
481                                 beforediff = addr - sym->st_value;
482                                 *before = sym;
483                         }
484                 }
485                 else
486                 {
487                         if ((sym->st_value - addr) < afterdiff) {
488                                 afterdiff = sym->st_value - addr;
489                                 *after = sym;
490                         }
491                 }
492         }
493 }
494
495 /**
496  * Print a warning about a section mismatch.
497  * Try to find symbols near it so user can find it.
498  **/
499 static void warn_sec_mismatch(const char *modname, const char *fromsec,
500                               struct elf_info *elf, Elf_Sym *sym, Elf_Rela r)
501 {
502         Elf_Sym *before;
503         Elf_Sym *after;
504         Elf_Ehdr *hdr = elf->hdr;
505         Elf_Shdr *sechdrs = elf->sechdrs;
506         const char *secstrings = (void *)hdr +
507                                  sechdrs[hdr->e_shstrndx].sh_offset;
508         const char *secname = secstrings + sechdrs[sym->st_shndx].sh_name;
509         
510         find_symbols_between(elf, r.r_offset, fromsec, &before, &after);
511
512         if (before && after) {
513                 warn("%s - Section mismatch: reference to %s from %s "
514                      "between '%s' (at offset 0x%lx) and '%s'\n",
515                      modname, secname, fromsec,
516                      elf->strtab + before->st_name,
517                      (long)(r.r_offset - before->st_value),
518                      elf->strtab + after->st_name);
519         } else if (before) {
520                 warn("%s - Section mismatch: reference to %s from %s "
521                      "after '%s' (at offset 0x%lx)\n",
522                      modname, secname, fromsec, 
523                      elf->strtab + before->st_name,
524                      (long)(r.r_offset - before->st_value));
525         } else if (after) {
526                 warn("%s - Section mismatch: reference to %s from %s "
527                      "before '%s' (at offset -0x%lx)\n",
528                      modname, secname, fromsec, 
529                      elf->strtab + before->st_name,
530                      (long)(before->st_value - r.r_offset));
531         } else {
532                 warn("%s - Section mismatch: reference to %s from %s "
533                      "(offset 0x%lx)\n",
534                      modname, secname, fromsec, (long)r.r_offset);
535         }
536 }
537
538 /**
539  * A module includes a number of sections that are discarded
540  * either when loaded or when used as built-in.
541  * For loaded modules all functions marked __init and all data
542  * marked __initdata will be discarded when the module has been intialized.
543  * Likewise for modules used built-in the sections marked __exit
544  * are discarded because __exit marked function are supposed to be called
545  * only when a moduel is unloaded which never happes for built-in modules.
546  * The check_sec_ref() function traverses all relocation records
547  * to find all references to a section that reference a section that will
548  * be discarded and warns about it.
549  **/
550 static void check_sec_ref(struct module *mod, const char *modname,
551                           struct elf_info *elf,
552                           int section(const char*),
553                           int section_ref_ok(const char *))
554 {
555         int i;
556         Elf_Sym  *sym;
557         Elf_Ehdr *hdr = elf->hdr;
558         Elf_Shdr *sechdrs = elf->sechdrs;
559         const char *secstrings = (void *)hdr +
560                                  sechdrs[hdr->e_shstrndx].sh_offset;
561                 
562         /* Walk through all sections */
563         for (i = 0; i < hdr->e_shnum; i++) {
564                 const char *name = secstrings + sechdrs[i].sh_name +
565                                                 strlen(".rela");
566                 /* We want to process only relocation sections and not .init */
567                 if (section_ref_ok(name) || (sechdrs[i].sh_type != SHT_RELA))
568                         continue;
569                 Elf_Rela *rela;
570                 Elf_Rela *start = (void *)hdr + sechdrs[i].sh_offset;
571                 Elf_Rela *stop  = (void*)start + sechdrs[i].sh_size;
572
573                 for (rela = start; rela < stop; rela++) {
574                         Elf_Rela r;
575                         const char *secname;
576                         r.r_offset = TO_NATIVE(rela->r_offset);
577                         r.r_info   = TO_NATIVE(rela->r_info);
578                         sym = elf->symtab_start + ELF_R_SYM(r.r_info);
579                         secname = secstrings + sechdrs[sym->st_shndx].sh_name;
580                         /* Skip special sections */
581                         if (sym->st_shndx >= SHN_LORESERVE)
582                                 continue;
583
584                         if (section(secname))
585                                 warn_sec_mismatch(modname, name, elf, sym, r);
586                 }
587         }
588 }
589
590 /**
591  * Functions used only during module init is marked __init and is stored in
592  * a .init.text section. Likewise data is marked __initdata and stored in
593  * a .init.data section.
594  * If this section is one of these sections return 1
595  * See include/linux/init.h for the details
596  **/
597 static int init_section(const char *name)
598 {
599         if (strcmp(name, ".init") == 0)
600                 return 1;
601         if (strncmp(name, ".init.", strlen(".init.")) == 0)
602                 return 1;
603         return 0;
604 }
605
606 /**
607  * Identify sections from which references to a .init section is OK.
608  * 
609  * Unfortunately references to read only data that referenced .init
610  * sections had to be excluded. Almost all of these are false
611  * positives, they are created by gcc. The downside of excluding rodata
612  * is that there really are some user references from rodata to
613  * init code, e.g. drivers/video/vgacon.c:
614  * 
615  * const struct consw vga_con = {
616  *        con_startup:            vgacon_startup,
617  *
618  * where vgacon_startup is __init.  If you want to wade through the false
619  * positives, take out the check for rodata.
620  **/
621 static int init_section_ref_ok(const char *name)
622 {
623         const char **s;
624         /* Absolute section names */
625         const char *namelist1[] = {
626                 ".init",
627                 ".stab",
628                 ".rodata",
629                 ".text.lock",
630                 ".pci_fixup_header",
631                 ".pci_fixup_final",
632                 ".pdr",
633                 "__param",
634                 NULL
635         };
636         /* Start of section names */
637         const char *namelist2[] = {
638                 ".init.",
639                 ".altinstructions",
640                 ".eh_frame",
641                 ".debug",
642                 NULL
643         };
644         
645         for (s = namelist1; *s; s++)
646                 if (strcmp(*s, name) == 0)
647                         return 1;
648         for (s = namelist2; *s; s++)    
649                 if (strncmp(*s, name, strlen(*s)) == 0)
650                         return 1;
651         return 0;
652 }
653
654 /*
655  * Functions used only during module exit is marked __exit and is stored in
656  * a .exit.text section. Likewise data is marked __exitdata and stored in
657  * a .exit.data section.
658  * If this section is one of these sections return 1
659  * See include/linux/init.h for the details
660  **/
661 static int exit_section(const char *name)
662 {
663         if (strcmp(name, ".exit.text") == 0)
664                 return 1;
665         if (strcmp(name, ".exit.data") == 0)
666                 return 1;
667         return 0;
668         
669 }
670
671 /*
672  * Identify sections from which references to a .exit section is OK.
673  * 
674  * [OPD] Keith Ownes <kaos@sgi.com> commented:
675  * For our future {in}sanity, add a comment that this is the ppc .opd
676  * section, not the ia64 .opd section.
677  * ia64 .opd should not point to discarded sections.
678  **/
679 static int exit_section_ref_ok(const char *name)
680 {
681         const char **s;
682         /* Absolute section names */
683         const char *namelist1[] = {
684                 ".exit.text",
685                 ".exit.data",
686                 ".init.text",
687                 ".opd", /* See comment [OPD] */
688                 ".altinstructions",
689                 ".pdr",
690                 ".exitcall.exit",
691                 ".eh_frame",
692                 ".stab",
693                 NULL
694         };
695         /* Start of section names */
696         const char *namelist2[] = {
697                 ".debug",
698                 NULL
699         };
700         
701         for (s = namelist1; *s; s++)
702                 if (strcmp(*s, name) == 0)
703                         return 1;
704         for (s = namelist2; *s; s++)    
705                 if (strncmp(*s, name, strlen(*s)) == 0)
706                         return 1;
707         return 0;
708 }
709
710 static void read_symbols(char *modname)
711 {
712         const char *symname;
713         char *version;
714         struct module *mod;
715         struct elf_info info = { };
716         Elf_Sym *sym;
717
718         parse_elf(&info, modname);
719
720         mod = new_module(modname);
721
722         /* When there's no vmlinux, don't print warnings about
723          * unresolved symbols (since there'll be too many ;) */
724         if (is_vmlinux(modname)) {
725                 have_vmlinux = 1;
726                 mod->skip = 1;
727         }
728
729         for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
730                 symname = info.strtab + sym->st_name;
731
732                 handle_modversions(mod, &info, sym, symname);
733                 handle_moddevtable(mod, &info, sym, symname);
734         }
735         check_sec_ref(mod, modname, &info, init_section, init_section_ref_ok);
736         check_sec_ref(mod, modname, &info, exit_section, exit_section_ref_ok);
737
738         version = get_modinfo(info.modinfo, info.modinfo_len, "version");
739         if (version)
740                 maybe_frob_rcs_version(modname, version, info.modinfo,
741                                        version - (char *)info.hdr);
742         if (version || (all_versions && !is_vmlinux(modname)))
743                 get_src_version(modname, mod->srcversion,
744                                 sizeof(mod->srcversion)-1);
745
746         parse_elf_finish(&info);
747
748         /* Our trick to get versioning for struct_module - it's
749          * never passed as an argument to an exported function, so
750          * the automatic versioning doesn't pick it up, but it's really
751          * important anyhow */
752         if (modversions)
753                 mod->unres = alloc_symbol("struct_module", 0, mod->unres);
754 }
755
756 #define SZ 500
757
758 /* We first write the generated file into memory using the
759  * following helper, then compare to the file on disk and
760  * only update the later if anything changed */
761
762 void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf,
763                                                       const char *fmt, ...)
764 {
765         char tmp[SZ];
766         int len;
767         va_list ap;
768         
769         va_start(ap, fmt);
770         len = vsnprintf(tmp, SZ, fmt, ap);
771         if (buf->size - buf->pos < len + 1) {
772                 buf->size += 128;
773                 buf->p = realloc(buf->p, buf->size);
774         }
775         strncpy(buf->p + buf->pos, tmp, len + 1);
776         buf->pos += len;
777         va_end(ap);
778 }
779
780 void buf_write(struct buffer *buf, const char *s, int len)
781 {
782         if (buf->size - buf->pos < len) {
783                 buf->size += len;
784                 buf->p = realloc(buf->p, buf->size);
785         }
786         strncpy(buf->p + buf->pos, s, len);
787         buf->pos += len;
788 }
789
790 /**
791  * Header for the generated file
792  **/
793 static void add_header(struct buffer *b, struct module *mod)
794 {
795         buf_printf(b, "#include <linux/module.h>\n");
796         buf_printf(b, "#include <linux/vermagic.h>\n");
797         buf_printf(b, "#include <linux/compiler.h>\n");
798         buf_printf(b, "\n");
799         buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
800         buf_printf(b, "\n");
801         buf_printf(b, "struct module __this_module\n");
802         buf_printf(b, "__attribute__((section(\".gnu.linkonce.this_module\"))) = {\n");
803         buf_printf(b, " .name = KBUILD_MODNAME,\n");
804         if (mod->has_init)
805                 buf_printf(b, " .init = init_module,\n");
806         if (mod->has_cleanup)
807                 buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n"
808                               " .exit = cleanup_module,\n"
809                               "#endif\n");
810         buf_printf(b, "};\n");
811 }
812
813 /**
814  * Record CRCs for unresolved symbols
815  **/
816 static void add_versions(struct buffer *b, struct module *mod)
817 {
818         struct symbol *s, *exp;
819
820         for (s = mod->unres; s; s = s->next) {
821                 exp = find_symbol(s->name);
822                 if (!exp || exp->module == mod) {
823                         if (have_vmlinux && !s->weak)
824                                 warn("\"%s\" [%s.ko] undefined!\n",
825                                      s->name, mod->name);
826                         continue;
827                 }
828                 s->module = exp->module;
829                 s->crc_valid = exp->crc_valid;
830                 s->crc = exp->crc;
831         }
832
833         if (!modversions)
834                 return;
835
836         buf_printf(b, "\n");
837         buf_printf(b, "static const struct modversion_info ____versions[]\n");
838         buf_printf(b, "__attribute_used__\n");
839         buf_printf(b, "__attribute__((section(\"__versions\"))) = {\n");
840
841         for (s = mod->unres; s; s = s->next) {
842                 if (!s->module) {
843                         continue;
844                 }
845                 if (!s->crc_valid) {
846                         warn("\"%s\" [%s.ko] has no CRC!\n",
847                                 s->name, mod->name);
848                         continue;
849                 }
850                 buf_printf(b, "\t{ %#8x, \"%s\" },\n", s->crc, s->name);
851         }
852
853         buf_printf(b, "};\n");
854 }
855
856 static void add_depends(struct buffer *b, struct module *mod,
857                         struct module *modules)
858 {
859         struct symbol *s;
860         struct module *m;
861         int first = 1;
862
863         for (m = modules; m; m = m->next) {
864                 m->seen = is_vmlinux(m->name);
865         }
866
867         buf_printf(b, "\n");
868         buf_printf(b, "static const char __module_depends[]\n");
869         buf_printf(b, "__attribute_used__\n");
870         buf_printf(b, "__attribute__((section(\".modinfo\"))) =\n");
871         buf_printf(b, "\"depends=");
872         for (s = mod->unres; s; s = s->next) {
873                 if (!s->module)
874                         continue;
875
876                 if (s->module->seen)
877                         continue;
878
879                 s->module->seen = 1;
880                 buf_printf(b, "%s%s", first ? "" : ",",
881                            strrchr(s->module->name, '/') + 1);
882                 first = 0;
883         }
884         buf_printf(b, "\";\n");
885 }
886
887 static void add_srcversion(struct buffer *b, struct module *mod)
888 {
889         if (mod->srcversion[0]) {
890                 buf_printf(b, "\n");
891                 buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n",
892                            mod->srcversion);
893         }
894 }
895
896 static void write_if_changed(struct buffer *b, const char *fname)
897 {
898         char *tmp;
899         FILE *file;
900         struct stat st;
901
902         file = fopen(fname, "r");
903         if (!file)
904                 goto write;
905
906         if (fstat(fileno(file), &st) < 0)
907                 goto close_write;
908
909         if (st.st_size != b->pos)
910                 goto close_write;
911
912         tmp = NOFAIL(malloc(b->pos));
913         if (fread(tmp, 1, b->pos, file) != b->pos)
914                 goto free_write;
915
916         if (memcmp(tmp, b->p, b->pos) != 0)
917                 goto free_write;
918
919         free(tmp);
920         fclose(file);
921         return;
922
923  free_write:
924         free(tmp);
925  close_write:
926         fclose(file);
927  write:
928         file = fopen(fname, "w");
929         if (!file) {
930                 perror(fname);
931                 exit(1);
932         }
933         if (fwrite(b->p, 1, b->pos, file) != b->pos) {
934                 perror(fname);
935                 exit(1);
936         }
937         fclose(file);
938 }
939
940 static void read_dump(const char *fname, unsigned int kernel)
941 {
942         unsigned long size, pos = 0;
943         void *file = grab_file(fname, &size);
944         char *line;
945
946         if (!file)
947                 /* No symbol versions, silently ignore */
948                 return;
949
950         while ((line = get_next_line(&pos, file, size))) {
951                 char *symname, *modname, *d;
952                 unsigned int crc;
953                 struct module *mod;
954                 struct symbol *s;
955
956                 if (!(symname = strchr(line, '\t')))
957                         goto fail;
958                 *symname++ = '\0';
959                 if (!(modname = strchr(symname, '\t')))
960                         goto fail;
961                 *modname++ = '\0';
962                 if (strchr(modname, '\t'))
963                         goto fail;
964                 crc = strtoul(line, &d, 16);
965                 if (*symname == '\0' || *modname == '\0' || *d != '\0')
966                         goto fail;
967
968                 if (!(mod = find_module(modname))) {
969                         if (is_vmlinux(modname)) {
970                                 have_vmlinux = 1;
971                         }
972                         mod = new_module(NOFAIL(strdup(modname)));
973                         mod->skip = 1;
974                 }
975                 s = sym_add_exported(symname, mod);
976                 s->kernel    = kernel;
977                 s->preloaded = 1;
978                 sym_update_crc(symname, mod, crc);
979         }
980         return;
981 fail:
982         fatal("parse error in symbol dump file\n");
983 }
984
985 /* For normal builds always dump all symbols.
986  * For external modules only dump symbols
987  * that are not read from kernel Module.symvers.
988  **/
989 static int dump_sym(struct symbol *sym)
990 {
991         if (!external_module)
992                 return 1;
993         if (sym->vmlinux || sym->kernel)
994                 return 0;
995         return 1;
996 }
997                 
998 static void write_dump(const char *fname)
999 {
1000         struct buffer buf = { };
1001         struct symbol *symbol;
1002         int n;
1003
1004         for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
1005                 symbol = symbolhash[n];
1006                 while (symbol) {
1007                         if (dump_sym(symbol))
1008                                 buf_printf(&buf, "0x%08x\t%s\t%s\n",
1009                                         symbol->crc, symbol->name, 
1010                                         symbol->module->name);
1011                         symbol = symbol->next;
1012                 }
1013         }
1014         write_if_changed(&buf, fname);
1015 }
1016
1017 int main(int argc, char **argv)
1018 {
1019         struct module *mod;
1020         struct buffer buf = { };
1021         char fname[SZ];
1022         char *kernel_read = NULL, *module_read = NULL;
1023         char *dump_write = NULL;
1024         int opt;
1025
1026         while ((opt = getopt(argc, argv, "i:I:mo:a")) != -1) {
1027                 switch(opt) {
1028                         case 'i':
1029                                 kernel_read = optarg;
1030                                 break;
1031                         case 'I':
1032                                 module_read = optarg;
1033                                 external_module = 1;
1034                                 break;
1035                         case 'm':
1036                                 modversions = 1;
1037                                 break;
1038                         case 'o':
1039                                 dump_write = optarg;
1040                                 break;
1041                         case 'a':
1042                                 all_versions = 1;
1043                                 break;
1044                         default:
1045                                 exit(1);
1046                 }
1047         }
1048
1049         if (kernel_read)
1050                 read_dump(kernel_read, 1);
1051         if (module_read)
1052                 read_dump(module_read, 0);
1053
1054         while (optind < argc) {
1055                 read_symbols(argv[optind++]);
1056         }
1057
1058         for (mod = modules; mod; mod = mod->next) {
1059                 if (mod->skip)
1060                         continue;
1061
1062                 buf.pos = 0;
1063
1064                 add_header(&buf, mod);
1065                 add_versions(&buf, mod);
1066                 add_depends(&buf, mod, modules);
1067                 add_moddevtable(&buf, mod);
1068                 add_srcversion(&buf, mod);
1069
1070                 sprintf(fname, "%s.mod.c", mod->name);
1071                 write_if_changed(&buf, fname);
1072         }
1073
1074         if (dump_write)
1075                 write_dump(dump_write);
1076
1077         return 0;
1078 }