ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / scripts / modpost.c
1 /* Postprocess module symbol versions
2  *
3  * Copyright 2003       Kai Germaschewski
4  *           2002-2003  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
22 void
23 fatal(const char *fmt, ...)
24 {
25         va_list arglist;
26
27         fprintf(stderr, "FATAL: ");
28
29         va_start(arglist, fmt);
30         vfprintf(stderr, fmt, arglist);
31         va_end(arglist);
32
33         exit(1);
34 }
35
36 void
37 warn(const char *fmt, ...)
38 {
39         va_list arglist;
40
41         fprintf(stderr, "WARNING: ");
42
43         va_start(arglist, fmt);
44         vfprintf(stderr, fmt, arglist);
45         va_end(arglist);
46 }
47
48 void *do_nofail(void *ptr, const char *file, int line, const char *expr)
49 {
50         if (!ptr) {
51                 fatal("Memory allocation failure %s line %d: %s.\n",
52                       file, line, expr);
53         }
54         return ptr;
55 }
56
57 /* A list of all modules we processed */
58
59 static struct module *modules;
60
61 struct module *
62 find_module(char *modname)
63 {
64         struct module *mod;
65
66         for (mod = modules; mod; mod = mod->next)
67                 if (strcmp(mod->name, modname) == 0)
68                         break;
69         return mod;
70 }
71
72 struct module *
73 new_module(char *modname)
74 {
75         struct module *mod;
76         char *p, *s;
77         
78         mod = NOFAIL(malloc(sizeof(*mod)));
79         memset(mod, 0, sizeof(*mod));
80         p = NOFAIL(strdup(modname));
81
82         /* strip trailing .o */
83         if ((s = strrchr(p, '.')) != NULL)
84                 if (strcmp(s, ".o") == 0)
85                         *s = '\0';
86
87         /* add to list */
88         mod->name = p;
89         mod->next = modules;
90         modules = mod;
91
92         return mod;
93 }
94
95 /* A hash of all exported symbols,
96  * struct symbol is also used for lists of unresolved symbols */
97
98 #define SYMBOL_HASH_SIZE 1024
99
100 struct symbol {
101         struct symbol *next;
102         struct module *module;
103         unsigned int crc;
104         int crc_valid;
105         char name[0];
106 };
107
108 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
109
110 /* This is based on the hash agorithm from gdbm, via tdb */
111 static inline unsigned int tdb_hash(const char *name)
112 {
113         unsigned value; /* Used to compute the hash value.  */
114         unsigned   i;   /* Used to cycle through random values. */
115
116         /* Set the initial value from the key size. */
117         for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
118                 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
119
120         return (1103515243 * value + 12345);
121 }
122
123 /* Allocate a new symbols for use in the hash of exported symbols or
124  * the list of unresolved symbols per module */
125
126 struct symbol *
127 alloc_symbol(const char *name, struct symbol *next)
128 {
129         struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1));
130
131         memset(s, 0, sizeof(*s));
132         strcpy(s->name, name);
133         s->next = next;
134         return s;
135 }
136
137 /* For the hash of exported symbols */
138
139 void
140 new_symbol(const char *name, struct module *module, unsigned int *crc)
141 {
142         unsigned int hash;
143         struct symbol *new;
144
145         hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
146         new = symbolhash[hash] = alloc_symbol(name, symbolhash[hash]);
147         new->module = module;
148         if (crc) {
149                 new->crc = *crc;
150                 new->crc_valid = 1;
151         }
152 }
153
154 struct symbol *
155 find_symbol(const char *name)
156 {
157         struct symbol *s;
158
159         /* For our purposes, .foo matches foo.  PPC64 needs this. */
160         if (name[0] == '.')
161                 name++;
162
163         for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s=s->next) {
164                 if (strcmp(s->name, name) == 0)
165                         return s;
166         }
167         return NULL;
168 }
169
170 /* Add an exported symbol - it may have already been added without a
171  * CRC, in this case just update the CRC */
172 void
173 add_exported_symbol(const char *name, struct module *module, unsigned int *crc)
174 {
175         struct symbol *s = find_symbol(name);
176
177         if (!s) {
178                 new_symbol(name, module, crc);
179                 return;
180         }
181         if (crc) {
182                 s->crc = *crc;
183                 s->crc_valid = 1;
184         }
185 }
186
187 void *
188 grab_file(const char *filename, unsigned long *size)
189 {
190         struct stat st;
191         void *map;
192         int fd;
193
194         fd = open(filename, O_RDONLY);
195         if (fd < 0 || fstat(fd, &st) != 0)
196                 return NULL;
197
198         *size = st.st_size;
199         map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
200         close(fd);
201
202         if (map == MAP_FAILED)
203                 return NULL;
204         return map;
205 }
206
207 /*
208    Return a copy of the next line in a mmap'ed file.
209    spaces in the beginning of the line is trimmed away.
210    Return a pointer to a static buffer.
211 */
212 char*
213 get_next_line(unsigned long *pos, void *file, unsigned long size)
214 {
215         static char line[4096];
216         int skip = 1;
217         size_t len = 0;
218         char *p = (char *)file + *pos;
219         char *s = line;
220
221         for (; *pos < size ; (*pos)++)
222         {
223                 if (skip && isspace(*p)) {
224                         p++;
225                         continue;
226                 }
227                 skip = 0;
228                 if (*p != '\n' && (*pos < size)) {
229                         len++;
230                         *s++ = *p++;
231                         if (len > 4095)
232                                 break; /* Too long, stop */
233                 } else {
234                         /* End of string */
235                         *s = '\0';
236                         return line;
237                 }
238         }
239         /* End of buffer */
240         return NULL;
241 }
242
243 void
244 release_file(void *file, unsigned long size)
245 {
246         munmap(file, size);
247 }
248
249 void
250 parse_elf(struct elf_info *info, const char *filename)
251 {
252         unsigned int i;
253         Elf_Ehdr *hdr = info->hdr;
254         Elf_Shdr *sechdrs;
255         Elf_Sym  *sym;
256
257         hdr = grab_file(filename, &info->size);
258         if (!hdr) {
259                 perror(filename);
260                 abort();
261         }
262         info->hdr = hdr;
263         if (info->size < sizeof(*hdr))
264                 goto truncated;
265
266         /* Fix endianness in ELF header */
267         hdr->e_shoff    = TO_NATIVE(hdr->e_shoff);
268         hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx);
269         hdr->e_shnum    = TO_NATIVE(hdr->e_shnum);
270         sechdrs = (void *)hdr + hdr->e_shoff;
271         info->sechdrs = sechdrs;
272
273         /* Fix endianness in section headers */
274         for (i = 0; i < hdr->e_shnum; i++) {
275                 sechdrs[i].sh_type   = TO_NATIVE(sechdrs[i].sh_type);
276                 sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset);
277                 sechdrs[i].sh_size   = TO_NATIVE(sechdrs[i].sh_size);
278                 sechdrs[i].sh_link   = TO_NATIVE(sechdrs[i].sh_link);
279                 sechdrs[i].sh_name   = TO_NATIVE(sechdrs[i].sh_name);
280         }
281         /* Find symbol table. */
282         for (i = 1; i < hdr->e_shnum; i++) {
283                 const char *secstrings
284                         = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
285
286                 if (sechdrs[i].sh_offset > info->size)
287                         goto truncated;
288                 if (strcmp(secstrings+sechdrs[i].sh_name, ".modinfo") == 0) {
289                         info->modinfo = (void *)hdr + sechdrs[i].sh_offset;
290                         info->modinfo_len = sechdrs[i].sh_size;
291                 }
292                 if (sechdrs[i].sh_type != SHT_SYMTAB)
293                         continue;
294
295                 info->symtab_start = (void *)hdr + sechdrs[i].sh_offset;
296                 info->symtab_stop  = (void *)hdr + sechdrs[i].sh_offset 
297                                                  + sechdrs[i].sh_size;
298                 info->strtab       = (void *)hdr + 
299                                      sechdrs[sechdrs[i].sh_link].sh_offset;
300         }
301         if (!info->symtab_start) {
302                 fprintf(stderr, "modpost: %s no symtab?\n", filename);
303                 abort();
304         }
305         /* Fix endianness in symbols */
306         for (sym = info->symtab_start; sym < info->symtab_stop; sym++) {
307                 sym->st_shndx = TO_NATIVE(sym->st_shndx);
308                 sym->st_name  = TO_NATIVE(sym->st_name);
309                 sym->st_value = TO_NATIVE(sym->st_value);
310                 sym->st_size  = TO_NATIVE(sym->st_size);
311         }
312         return;
313
314  truncated:
315         fprintf(stderr, "modpost: %s is truncated.\n", filename);
316         abort();
317 }
318
319 void
320 parse_elf_finish(struct elf_info *info)
321 {
322         release_file(info->hdr, info->size);
323 }
324
325 #define CRC_PFX     MODULE_SYMBOL_PREFIX "__crc_"
326 #define KSYMTAB_PFX MODULE_SYMBOL_PREFIX "__ksymtab_"
327
328 void
329 handle_modversions(struct module *mod, struct elf_info *info,
330                    Elf_Sym *sym, const char *symname)
331 {
332         unsigned int crc;
333
334         switch (sym->st_shndx) {
335         case SHN_COMMON:
336                 fprintf(stderr, "*** Warning: \"%s\" [%s] is COMMON symbol\n",
337                         symname, mod->name);
338                 break;
339         case SHN_ABS:
340                 /* CRC'd symbol */
341                 if (memcmp(symname, CRC_PFX, strlen(CRC_PFX)) == 0) {
342                         crc = (unsigned int) sym->st_value;
343                         add_exported_symbol(symname + strlen(CRC_PFX),
344                                             mod, &crc);
345                         modversions = 1;
346                 }
347                 break;
348         case SHN_UNDEF:
349                 /* undefined symbol */
350                 if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL)
351                         break;
352                 /* ignore global offset table */
353                 if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0)
354                         break;
355                 /* ignore __this_module, it will be resolved shortly */
356                 if (strcmp(symname, MODULE_SYMBOL_PREFIX "__this_module") == 0)
357                         break;
358 #ifdef STT_REGISTER
359                 if (info->hdr->e_machine == EM_SPARC ||
360                     info->hdr->e_machine == EM_SPARCV9) {
361                         /* Ignore register directives. */
362                         if (ELF_ST_TYPE(sym->st_info) == STT_REGISTER)
363                                 break;
364                 }
365 #endif
366                 
367                 if (memcmp(symname, MODULE_SYMBOL_PREFIX,
368                            strlen(MODULE_SYMBOL_PREFIX)) == 0)
369                         mod->unres = alloc_symbol(symname +
370                                                   strlen(MODULE_SYMBOL_PREFIX),
371                                                   mod->unres);
372                 break;
373         default:
374                 /* All exported symbols */
375                 if (memcmp(symname, KSYMTAB_PFX, strlen(KSYMTAB_PFX)) == 0) {
376                         add_exported_symbol(symname + strlen(KSYMTAB_PFX),
377                                             mod, NULL);
378                 }
379                 break;
380         }
381 }
382
383 int
384 is_vmlinux(const char *modname)
385 {
386         const char *myname;
387
388         if ((myname = strrchr(modname, '/')))
389                 myname++;
390         else
391                 myname = modname;
392
393         return strcmp(myname, "vmlinux") == 0;
394 }
395
396 void
397 read_symbols(char *modname)
398 {
399         const char *symname;
400         struct module *mod;
401         struct elf_info info = { };
402         Elf_Sym *sym;
403
404         parse_elf(&info, modname);
405
406         mod = new_module(modname);
407
408         /* When there's no vmlinux, don't print warnings about
409          * unresolved symbols (since there'll be too many ;) */
410         if (is_vmlinux(modname)) {
411                 unsigned int fake_crc = 0;
412                 have_vmlinux = 1;
413                 /* May not have this if !CONFIG_MODULE_UNLOAD: fake it.
414                    If it appears, we'll get the real CRC. */
415                 add_exported_symbol("cleanup_module", mod, &fake_crc);
416                 add_exported_symbol("struct_module", mod, &fake_crc);
417                 mod->skip = 1;
418         }
419
420         for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
421                 symname = info.strtab + sym->st_name;
422
423                 handle_modversions(mod, &info, sym, symname);
424                 handle_moddevtable(mod, &info, sym, symname);
425         }
426         maybe_frob_version(modname, info.modinfo, info.modinfo_len,
427                            (void *)info.modinfo - (void *)info.hdr);
428         parse_elf_finish(&info);
429
430         /* Our trick to get versioning for struct_module - it's
431          * never passed as an argument to an exported function, so
432          * the automatic versioning doesn't pick it up, but it's really
433          * important anyhow */
434         if (modversions) {
435                 mod->unres = alloc_symbol("struct_module", mod->unres);
436
437                 /* Always version init_module and cleanup_module, in
438                  * case module doesn't have its own. */
439                 mod->unres = alloc_symbol("init_module", mod->unres);
440                 mod->unres = alloc_symbol("cleanup_module", mod->unres);
441         }
442 }
443
444 #define SZ 500
445
446 /* We first write the generated file into memory using the
447  * following helper, then compare to the file on disk and
448  * only update the later if anything changed */
449
450 void __attribute__((format(printf, 2, 3)))
451 buf_printf(struct buffer *buf, const char *fmt, ...)
452 {
453         char tmp[SZ];
454         int len;
455         va_list ap;
456         
457         va_start(ap, fmt);
458         len = vsnprintf(tmp, SZ, fmt, ap);
459         if (buf->size - buf->pos < len + 1) {
460                 buf->size += 128;
461                 buf->p = realloc(buf->p, buf->size);
462         }
463         strncpy(buf->p + buf->pos, tmp, len + 1);
464         buf->pos += len;
465         va_end(ap);
466 }
467
468 void
469 buf_write(struct buffer *buf, const char *s, int len)
470 {
471         if (buf->size - buf->pos < len) {
472                 buf->size += len;
473                 buf->p = realloc(buf->p, buf->size);
474         }
475         strncpy(buf->p + buf->pos, s, len);
476         buf->pos += len;
477 }
478
479 /* Header for the generated file */
480
481 void
482 add_header(struct buffer *b)
483 {
484         buf_printf(b, "#include <linux/module.h>\n");
485         buf_printf(b, "#include <linux/vermagic.h>\n");
486         buf_printf(b, "#include <linux/compiler.h>\n");
487         buf_printf(b, "\n");
488         buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n");
489         buf_printf(b, "\n");
490         buf_printf(b, "#undef unix\n"); /* We have a module called "unix" */
491         buf_printf(b, "struct module __this_module\n");
492         buf_printf(b, "__attribute__((section(\".gnu.linkonce.this_module\"))) = {\n");
493         buf_printf(b, " .name = __stringify(KBUILD_MODNAME),\n");
494         buf_printf(b, " .init = init_module,\n");
495         buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n");
496         buf_printf(b, " .exit = cleanup_module,\n");
497         buf_printf(b, "#endif\n");
498         buf_printf(b, "};\n");
499 }
500
501 /* Record CRCs for unresolved symbols */
502
503 void
504 add_versions(struct buffer *b, struct module *mod)
505 {
506         struct symbol *s, *exp;
507
508         for (s = mod->unres; s; s = s->next) {
509                 exp = find_symbol(s->name);
510                 if (!exp || exp->module == mod) {
511                         if (have_vmlinux)
512                                 fprintf(stderr, "*** Warning: \"%s\" [%s.ko] "
513                                 "undefined!\n", s->name, mod->name);
514                         continue;
515                 }
516                 s->module = exp->module;
517                 s->crc_valid = exp->crc_valid;
518                 s->crc = exp->crc;
519         }
520
521         if (!modversions)
522                 return;
523
524         buf_printf(b, "\n");
525         buf_printf(b, "static const struct modversion_info ____versions[]\n");
526         buf_printf(b, "__attribute_used__\n");
527         buf_printf(b, "__attribute__((section(\"__versions\"))) = {\n");
528
529         for (s = mod->unres; s; s = s->next) {
530                 if (!s->module) {
531                         continue;
532                 }
533                 if (!s->crc_valid) {
534                         fprintf(stderr, "*** Warning: \"%s\" [%s.ko] "
535                                 "has no CRC!\n",
536                                 s->name, mod->name);
537                         continue;
538                 }
539                 buf_printf(b, "\t{ %#8x, \"%s\" },\n", s->crc, s->name);
540         }
541
542         buf_printf(b, "};\n");
543 }
544
545 void
546 add_depends(struct buffer *b, struct module *mod, struct module *modules)
547 {
548         struct symbol *s;
549         struct module *m;
550         int first = 1;
551
552         for (m = modules; m; m = m->next) {
553                 m->seen = is_vmlinux(m->name);
554         }
555
556         buf_printf(b, "\n");
557         buf_printf(b, "static const char __module_depends[]\n");
558         buf_printf(b, "__attribute_used__\n");
559         buf_printf(b, "__attribute__((section(\".modinfo\"))) =\n");
560         buf_printf(b, "\"depends=");
561         for (s = mod->unres; s; s = s->next) {
562                 if (!s->module)
563                         continue;
564
565                 if (s->module->seen)
566                         continue;
567
568                 s->module->seen = 1;
569                 buf_printf(b, "%s%s", first ? "" : ",",
570                            strrchr(s->module->name, '/') + 1);
571                 first = 0;
572         }
573         buf_printf(b, "\";\n");
574 }
575
576 void
577 write_if_changed(struct buffer *b, const char *fname)
578 {
579         char *tmp;
580         FILE *file;
581         struct stat st;
582
583         file = fopen(fname, "r");
584         if (!file)
585                 goto write;
586
587         if (fstat(fileno(file), &st) < 0)
588                 goto close_write;
589
590         if (st.st_size != b->pos)
591                 goto close_write;
592
593         tmp = NOFAIL(malloc(b->pos));
594         if (fread(tmp, 1, b->pos, file) != b->pos)
595                 goto free_write;
596
597         if (memcmp(tmp, b->p, b->pos) != 0)
598                 goto free_write;
599
600         free(tmp);
601         fclose(file);
602         return;
603
604  free_write:
605         free(tmp);
606  close_write:
607         fclose(file);
608  write:
609         file = fopen(fname, "w");
610         if (!file) {
611                 perror(fname);
612                 exit(1);
613         }
614         if (fwrite(b->p, 1, b->pos, file) != b->pos) {
615                 perror(fname);
616                 exit(1);
617         }
618         fclose(file);
619 }
620
621 void
622 read_dump(const char *fname)
623 {
624         unsigned long size, pos = 0;
625         void *file = grab_file(fname, &size);
626         char *line;
627
628         if (!file)
629                 /* No symbol versions, silently ignore */
630                 return;
631
632         while ((line = get_next_line(&pos, file, size))) {
633                 char *symname, *modname, *d;
634                 unsigned int crc;
635                 struct module *mod;
636
637                 if (!(symname = strchr(line, '\t')))
638                         goto fail;
639                 *symname++ = '\0';
640                 if (!(modname = strchr(symname, '\t')))
641                         goto fail;
642                 *modname++ = '\0';
643                 if (strchr(modname, '\t'))
644                         goto fail;
645                 crc = strtoul(line, &d, 16);
646                 if (*symname == '\0' || *modname == '\0' || *d != '\0')
647                         goto fail;
648
649                 if (!(mod = find_module(modname))) {
650                         if (is_vmlinux(modname)) {
651                                 modversions = 1;
652                                 have_vmlinux = 1;
653                         }
654                         mod = new_module(NOFAIL(strdup(modname)));
655                         mod->skip = 1;
656                 }
657                 add_exported_symbol(symname, mod, &crc);
658         }
659         return;
660 fail:
661         fatal("parse error in symbol dump file\n");
662 }
663
664 void
665 write_dump(const char *fname)
666 {
667         struct buffer buf = { };
668         struct symbol *symbol;
669         int n;
670
671         for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
672                 symbol = symbolhash[n];
673                 while (symbol) {
674                         symbol = symbol->next;
675                 }
676         }
677
678         for (n = 0; n < SYMBOL_HASH_SIZE ; n++) {
679                 symbol = symbolhash[n];
680                 while (symbol) {
681                         buf_printf(&buf, "0x%08x\t%s\t%s\n", symbol->crc,
682                                 symbol->name, symbol->module->name);
683                         symbol = symbol->next;
684                 }
685         }
686         write_if_changed(&buf, fname);
687 }
688
689 int
690 main(int argc, char **argv)
691 {
692         struct module *mod;
693         struct buffer buf = { };
694         char fname[SZ];
695         char *dump_read = NULL, *dump_write = NULL;
696         int opt;
697
698         while ((opt = getopt(argc, argv, "i:o:")) != -1) {
699                 switch(opt) {
700                         case 'i':
701                                 dump_read = optarg;
702                                 break;
703                         case 'o':
704                                 dump_write = optarg;
705                                 break;
706                         default:
707                                 exit(1);
708                 }
709         }
710
711         if (dump_read)
712                 read_dump(dump_read);
713
714         while (optind < argc) {
715                 read_symbols(argv[optind++]);
716         }
717
718         for (mod = modules; mod; mod = mod->next) {
719                 if (mod->skip)
720                         continue;
721
722                 buf.pos = 0;
723
724                 add_header(&buf);
725                 add_versions(&buf, mod);
726                 add_depends(&buf, mod, modules);
727                 add_moddevtable(&buf, mod);
728
729                 sprintf(fname, "%s.mod.c", mod->name);
730                 write_if_changed(&buf, fname);
731         }
732
733         if (dump_write)
734                 write_dump(dump_write);
735
736         return 0;
737 }
738