Tizen 2.0 Release
[external/module-init-tools.git] / depmod.c
1 /* New simplified depmod without backwards compat stuff and not
2    requiring ksyms.
3
4    (C) 2010 Jon Masters <jcm@jonmasters.org>, and others.
5    (C) 2002 Rusty Russell IBM Corporation
6  */
7 #define _GNU_SOURCE /* asprintf */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <getopt.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <unistd.h>
15 #include <elf.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <dirent.h>
20 #include <sys/utsname.h>
21 #include <sys/mman.h>
22
23 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
24
25 #include "util.h"
26 #include "zlibsupport.h"
27 #include "depmod.h"
28 #include "logging.h"
29 #include "index.h"
30 #include "elfops.h"
31 #include "tables.h"
32 #include "config_filter.h"
33
34 #include "testing.h"
35
36 #ifndef MODULE_DIR
37 #define MODULE_DIR "/lib/modules/"
38 #endif
39
40 #ifndef MODULE_BUILTIN_KEY
41 #define MODULE_BUILTIN_KEY "built-in"
42 #endif
43
44 struct module_overrides
45 {
46         /* Next override */
47         struct module_overrides *next;
48
49         /* overridden module */
50         char *modfile;
51 };
52
53 struct module_search
54 {
55         /* Next search */
56         struct module_search *next;
57
58         /* search path */
59         char *search_path;
60         size_t len;
61 };
62
63 static unsigned int skipchars;
64 static unsigned int make_map_files = 1; /* default to on */
65 static unsigned int force_map_files = 0; /* default to on */
66
67 #define SYMBOL_HASH_SIZE 1024
68 struct symbol
69 {
70         struct symbol *next;
71         struct module *owner;
72         uint64_t ver;
73         char name[0];
74 };
75
76 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
77
78 /* This is based on the hash agorithm from gdbm, via tdb */
79 static inline unsigned int tdb_hash(const char *name)
80 {
81         unsigned value; /* Used to compute the hash value.  */
82         unsigned   i;   /* Used to cycle through random values. */
83
84         /* Set the initial value from the key size. */
85         for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
86                 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
87
88         return (1103515243 * value + 12345);
89 }
90
91 void add_symbol(const char *name, uint64_t ver, struct module *owner)
92 {
93         unsigned int hash;
94         struct symbol *new = NOFAIL(malloc(sizeof *new + strlen(name) + 1));
95
96         new->owner = owner;
97         new->ver = ver;
98         strcpy(new->name, name);
99
100         hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
101         new->next = symbolhash[hash];
102         symbolhash[hash] = new;
103 }
104
105 static int print_unknown, check_symvers;
106
107 struct module *find_symbol(const char *name, uint64_t ver,
108                 const char *modname, int weak)
109 {
110         struct symbol *s;
111
112         /* For our purposes, .foo matches foo.  PPC64 needs this. */
113         if (name[0] == '.')
114                 name++;
115
116         for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s=s->next) {
117                 if (streq(s->name, name))
118                         break;
119         }
120         if (s) {
121                 if (ver && s->ver && s->ver != ver && print_unknown && !weak)
122                         warn("%s disagrees about version of symbol %s\n",
123                                         modname, name);
124                 return s->owner;
125         }
126
127         if (print_unknown && !weak)
128                 warn("%s needs unknown symbol %s\n", modname, name);
129
130         return NULL;
131 }
132
133 void add_dep(struct module *mod, struct module *depends_on)
134 {
135         unsigned int i;
136
137         for (i = 0; i < mod->num_deps; i++)
138                 if (mod->deps[i] == depends_on)
139                         return;
140
141         mod->deps = NOFAIL(realloc(mod->deps, sizeof(mod->deps[0])*(mod->num_deps+1)));
142         mod->deps[mod->num_deps++] = depends_on;
143 }
144
145 static void add_fake_syms(void)
146 {
147         /* __this_module is magic inserted by kernel loader. */
148         add_symbol("__this_module", 0, NULL);
149         /* On S390, this is faked up too */
150         add_symbol("_GLOBAL_OFFSET_TABLE_", 0, NULL);
151 }
152
153 static void load_system_map(const char *filename)
154 {
155         FILE *system_map;
156         char line[10240];
157         const char ksymstr[] = "__ksymtab_";
158         const int ksymstr_len = strlen(ksymstr);
159
160         system_map = fopen(filename, "r");
161         if (!system_map)
162                 fatal("Could not open '%s': %s\n", filename, strerror(errno));
163
164         /* eg. c0294200 R __ksymtab_devfs_alloc_devnum */
165         while (fgets(line, sizeof(line)-1, system_map)) {
166                 char *ptr;
167
168                 /* Snip \n */
169                 ptr = strchr(line, '\n');
170                 if (ptr)
171                         *ptr = '\0';
172
173                 ptr = strchr(line, ' ');
174                 if (!ptr || !(ptr = strchr(ptr + 1, ' ')))
175                         continue;
176
177                 /* Covers gpl-only and normal symbols. */
178                 if (strstarts(ptr+1, ksymstr))
179                         add_symbol(ptr+1+ksymstr_len, 0, NULL);
180         }
181
182         fclose(system_map);
183         add_fake_syms();
184 }
185
186 static void load_module_symvers(const char *filename)
187 {
188         FILE *module_symvers;
189         char line[10240];
190
191         module_symvers = fopen(filename, "r");
192         if (!module_symvers)
193                 fatal("Could not open '%s': %s\n", filename, strerror(errno));
194
195         /* eg. "0xb352177e\tfind_first_bit\tvmlinux\tEXPORT_SYMBOL" */
196         while (fgets(line, sizeof(line)-1, module_symvers)) {
197                 const char *ver, *sym, *where;
198
199                 ver = strtok(line, " \t");
200                 sym = strtok(NULL, " \t");
201                 where = strtok(NULL, " \t");
202                 if (!ver || !sym || !where)
203                         continue;
204
205                 if (streq(where, "vmlinux"))
206                         add_symbol(sym, strtoull(ver, NULL, 16), NULL);
207         }
208
209         fclose(module_symvers);
210         add_fake_syms();
211 }
212
213 static struct option options[] = { { "all", 0, NULL, 'a' },
214                                    { "quick", 0, NULL, 'A' },
215                                    { "basedir", 1, NULL, 'b' },
216                                    { "config", 1, NULL, 'C' },
217                                    { "symvers", 1, NULL, 'E' },
218                                    { "filesyms", 1, NULL, 'F' },
219                                    { "errsyms", 0, NULL, 'e' },
220                                    { "unresolved-error", 0, NULL, 'u' },
221                                    { "quiet", 0, NULL, 'q' },
222                                    { "root", 0, NULL, 'r' },
223                                    { "verbose", 0, NULL, 'v' },
224                                    { "show", 0, NULL, 'n' },
225                                    { "dry-run", 0, NULL, 'n' },
226                                    { "help", 0, NULL, 'h' },
227                                    { "version", 0, NULL, 'V' },
228                                    { "warn", 0, NULL, 'w' },
229                                    { "map", 0, NULL, 'm' },
230                                    { NULL, 0, NULL, 0 } };
231
232 /* Version number or module name?  Don't assume extension. */
233 static int is_version_number(const char *version)
234 {
235         unsigned int dummy;
236
237         return (sscanf(version, "%u.%u.%u", &dummy, &dummy, &dummy) == 3);
238 }
239
240 static int old_module_version(const char *version)
241 {
242         /* Expect three part version. */
243         unsigned int major, sub, minor;
244
245         sscanf(version, "%u.%u.%u", &major, &sub, &minor);
246
247         if (major > 2) return 0;
248         if (major < 2) return 1;
249
250         /* 2.x */
251         if (sub > 5) return 0;
252         if (sub < 5) return 1;
253
254         /* 2.5.x */
255         if (minor >= 48) return 0;
256         return 1;
257 }
258
259 static void print_usage(const char *name)
260 {
261         fprintf(stderr,
262         "%s " VERSION " -- part of " PACKAGE "\n"
263         "%s -[aA] [-n -e -v -q -V -r -u -w -m]\n"
264         "      [-b basedirectory] [forced_version]\n"
265         "depmod [-n -e -v -q -r -u -w] [-F kernelsyms] module1.ko module2.ko ...\n"
266         "If no arguments (except options) are given, \"depmod -a\" is assumed\n"
267         "\n"
268         "depmod will output a dependancy list suitable for the modprobe utility.\n"
269         "\n"
270         "\n"
271         "Options:\n"
272         "\t-a, --all            Probe all modules\n"
273         "\t-A, --quick          Only does the work if there's a new module\n"
274         "\t-e, --errsyms        Report not supplied symbols\n"
275         "\t-m, --map            Create the legacy map files\n"
276         "\t-n, --show           Write the dependency file on stdout only\n"
277         "\t-V, --version        Print the release version\n"
278         "\t-v, --verbose        Enable verbose mode\n"
279         "\t-w, --warn           Warn on duplicates\n"
280         "\t-h, --help           Print this usage message\n"
281         "\n"
282         "The following options are useful for people managing distributions:\n"
283         "\t-b basedirectory\n"
284         "\t    --basedir basedirectory    Use an image of a module tree.\n"
285         "\t-F kernelsyms\n"
286         "\t    --filesyms kernelsyms      Use the file instead of the\n"
287         "\t                               current kernel symbols.\n"
288         "\t-E Module.symvers\n"
289         "\t    --symvers Module.symvers   Use Module.symvers file to check\n"
290         "\t                               symbol versions.\n",
291         "depmod", "depmod");
292 }
293
294 static int ends_in(const char *name, const char *ext)
295 {
296         unsigned int namelen, extlen;
297
298         /* Grab lengths */
299         namelen = strlen(name);
300         extlen = strlen(ext);
301
302         if (namelen < extlen) return 0;
303
304         if (streq(name + namelen - extlen, ext))
305                 return 1;
306         return 0;
307 }
308
309 static struct module *grab_module(const char *dirname, const char *filename)
310 {
311         struct module *new;
312
313         new = NOFAIL(malloc(sizeof(*new)
314                             + strlen(dirname?:"") + 1 + strlen(filename) + 1));
315         if (dirname)
316                 sprintf(new->pathname, "%s/%s", dirname, filename);
317         else
318                 strcpy(new->pathname, filename);
319         new->basename = my_basename(new->pathname);
320
321         INIT_LIST_HEAD(&new->dep_list);
322         new->order = INDEX_PRIORITY_MIN;
323
324         new->file = grab_elf_file(new->pathname);
325         if (!new->file) {
326                 warn("Can't read module %s: %s\n",
327                      new->pathname, strerror(errno));
328                 free(new);
329                 return NULL;
330         }
331         return new;
332 }
333
334 struct module_traverse
335 {
336         struct module_traverse *prev;
337         struct module *mod;
338 };
339
340 static int in_loop(struct module *mod, const struct module_traverse *traverse)
341 {
342         const struct module_traverse *i;
343
344         for (i = traverse; i; i = i->prev) {
345                 if (i->mod == mod)
346                         return 1;
347         }
348         return 0;
349 }
350
351 /* Assume we are doing all the modules, so only report each loop once. */
352 static void report_loop(const struct module *mod,
353                         const struct module_traverse *traverse)
354 {
355         const struct module_traverse *i;
356
357         /* Check that start is least alphabetically.  eg.  a depends
358            on b depends on a will get reported for a, not b.  */
359         for (i = traverse->prev; i->prev; i = i->prev) {
360                 if (strcmp(mod->pathname, i->mod->pathname) > 0)
361                         return;
362         }
363
364         /* Is start in the loop?  If not, don't report now. eg. a
365            depends on b which depends on c which depends on b.  Don't
366            report when generating depends for a. */
367         if (mod != i->mod)
368                 return;
369
370         warn("Loop detected: %s ", mod->pathname);
371         for (i = traverse->prev; i->prev; i = i->prev)
372                 fprintf(stderr, "needs %s ", i->mod->basename);
373         fprintf(stderr, "which needs %s again!\n", i->mod->basename);
374 }
375
376 /* This is damn slow, but loops actually happen, and we don't want to
377    just exit() and leave the user without any modules. */
378 static int has_dep_loop(struct module *module, struct module_traverse *prev)
379 {
380         unsigned int i;
381         struct module_traverse traverse = { .prev = prev, .mod = module };
382
383         if (in_loop(module, prev)) {
384                 report_loop(module, &traverse);
385                 return 1;
386         }
387
388         for (i = 0; i < module->num_deps; i++)
389                 if (has_dep_loop(module->deps[i], &traverse))
390                         return 1;
391         return 0;
392 }
393
394 /* Uniquifies and orders a dependency list. */
395 static void order_dep_list(struct module *start, struct module *mod)
396 {
397         unsigned int i;
398
399         for (i = 0; i < mod->num_deps; i++) {
400                 /* If it was previously depended on, move it to the
401                    tail.  ie. if a needs b and c, and c needs b, we
402                    must order b after c. */
403                 list_del(&mod->deps[i]->dep_list);
404                 list_add_tail(&mod->deps[i]->dep_list, &start->dep_list);
405                 order_dep_list(start, mod->deps[i]);
406         }
407 }
408
409 static struct module *deleted = NULL;
410
411 static void del_module(struct module **modules, struct module *delme)
412 {
413         struct module **i;
414
415         /* Find pointer to it. */ 
416         if (modules) {
417                 for (i = modules; *i != delme; i = &(*i)->next);
418                 
419                 *i = delme->next;
420         }
421         
422         /* Save on a list to quiet valgrind.
423            Can't free - other modules may depend on them */
424         delme->next = deleted;
425         deleted = delme;
426 }
427
428 /* convert to relative path if possible */
429 static const char *compress_path(const char *path, const char *basedir)
430 {
431         int len = strlen(basedir);
432
433         if (strncmp(path, basedir, len) == 0)
434                 path += len + 1;
435         return path;
436 }
437
438 static int output_deps(struct module *modules,
439                         FILE *out, char *dirname)
440 {
441         struct module *i;
442
443         for (i = modules; i; i = i->next) {
444                 struct list_head *j, *tmp;
445                 order_dep_list(i, i);
446
447                 fprintf(out, "%s:", compress_path(i->pathname, dirname));
448                 list_for_each_safe(j, tmp, &i->dep_list) {
449                         struct module *dep
450                                 = list_entry(j, struct module, dep_list);
451                         fprintf(out, " %s",
452                                 compress_path(dep->pathname, dirname));
453                         list_del_init(j);
454                 }
455                 fprintf(out, "\n");
456         }
457         return 1;
458 }
459
460 /* warn whenever duplicate module aliases, deps, or symbols are found. */
461 int warn_dups = 0;
462
463 static int output_deps_bin(struct module *modules,
464                         FILE *out, char *dirname)
465 {
466         struct module *i;
467         struct index_node *index;
468         char *line;
469         char *p;
470
471         index = index_create();
472
473         for (i = modules; i; i = i->next) {
474                 struct list_head *j, *tmp;
475                 char modname[strlen(i->pathname)+1];
476                 
477                 order_dep_list(i, i);
478                 
479                 filename2modname(modname, i->pathname);
480                 nofail_asprintf(&line, "%s:",
481                                 compress_path(i->pathname, dirname));
482                 p = line;
483                 list_for_each_safe(j, tmp, &i->dep_list) {
484                         struct module *dep
485                                 = list_entry(j, struct module, dep_list);
486                         nofail_asprintf(&line, "%s %s",
487                                         p,
488                                         compress_path(dep->pathname, dirname));
489                         free(p);
490                         p = line;
491                         list_del_init(j);
492                 }
493                 if (index_insert(index, modname, line, i->order) && warn_dups)
494                         warn("duplicate module deps:\n%s\n",line);
495                 free(line);
496         }
497         
498         index_write(index, out);
499         index_destroy(index);
500
501         return 1;
502 }
503
504
505 static int smells_like_module(const char *name)
506 {
507         return ends_in(name,".ko") || ends_in(name, ".ko.gz");
508 }
509
510 typedef struct module *(*do_module_t)(const char *dirname,
511                                       const char *filename,
512                                       struct module *next,
513                                       struct module_search *search,
514                                       struct module_overrides *overrides);
515
516 static int is_higher_priority(const char *newpath, const char *oldpath,
517                               struct module_search *search,
518                               struct module_overrides *overrides)
519 {
520         struct module_search *tmp;
521         struct module_overrides *ovtmp;
522         int i = 0;
523         int prio_builtin = -1;
524         int prio_new = -1;
525         int prio_old = -1;
526
527 /* The names already match, now we check for overrides and directory search
528  * order
529  */
530         for (ovtmp = overrides; ovtmp != NULL; ovtmp = ovtmp->next) {
531                 if (streq(ovtmp->modfile, newpath))
532                         return 1;
533                 if (streq(ovtmp->modfile, oldpath))
534                         return 0;
535         }
536         for (i = 0, tmp = search; tmp != NULL; tmp = tmp->next, i++) {
537                 if (streq(tmp->search_path, MODULE_BUILTIN_KEY))
538                         prio_builtin = i;
539                 else if (strncmp(tmp->search_path, newpath, tmp->len) == 0)
540                         prio_new = i;
541                 else if (strncmp(tmp->search_path, oldpath, tmp->len) == 0)
542                         prio_old = i;
543         }
544         if (prio_new < 0)
545                 prio_new = prio_builtin;
546         if (prio_old < 0)
547                 prio_old = prio_builtin;
548
549         return prio_new > prio_old;
550 }
551
552
553 static struct module *do_module(const char *dirname,
554                                        const char *filename,
555                                        struct module *list,
556                                        struct module_search *search,
557                                        struct module_overrides *overrides)
558 {
559         struct module *new, **i;
560
561         new = grab_module(dirname, filename);
562         if (!new)
563                 return list;
564
565         /* Check if module is already in the list. */
566         for (i = &list; *i; i = &(*i)->next) {
567
568                 if (streq((*i)->basename, filename)) {
569                         char newpath[strlen(dirname) + strlen("/")
570                                       + strlen(filename) + 1];
571
572                         sprintf(newpath, "%s/%s", dirname, filename);
573
574                         if (is_higher_priority(newpath, (*i)->pathname,search,
575                                                overrides)) {
576                                 del_module(i, *i);
577                                 
578                                 new->next = *i;
579                                 *i = new;
580                         } else
581                                 del_module(NULL, new);
582
583                         return list;
584                 }
585         }
586
587         /* Not in the list already. Just prepend. */
588         new->next = list;
589         return new;
590 }
591
592 static struct module *grab_dir(const char *dirname,
593                                DIR *dir,
594                                struct module *next,
595                                do_module_t do_mod,
596                                struct module_search *search,
597                                struct module_overrides *overrides)
598 {
599         struct dirent *dirent;
600
601         while ((dirent = readdir(dir)) != NULL) {
602                 if (smells_like_module(dirent->d_name))
603                         next = do_mod(dirname, dirent->d_name, next,
604                                       search, overrides);
605                 else if (!streq(dirent->d_name, ".")
606                          && !streq(dirent->d_name, "..")
607                          && !streq(dirent->d_name, "source")
608                          && !streq(dirent->d_name, "build")) {
609
610                         DIR *sub;
611                         char subdir[strlen(dirname) + 1
612                                    + strlen(dirent->d_name) + 1];
613                         sprintf(subdir, "%s/%s", dirname, dirent->d_name);
614                         sub = opendir(subdir);
615                         if (sub) {
616                                 next = grab_dir(subdir, sub, next, do_mod,
617                                                 search, overrides);
618                                 closedir(sub);
619                         }
620                 }
621         }
622         return next;
623 }
624
625 static struct module *grab_basedir(const char *dirname,
626                                    struct module_search *search,
627                                    struct module_overrides *overrides)
628 {
629         DIR *dir;
630         struct module *list;
631
632         dir = opendir(dirname);
633         if (!dir) {
634                 warn("Couldn't open directory %s: %s\n",
635                      dirname, strerror(errno));
636                 return NULL;
637         }
638         list = grab_dir(dirname, dir, NULL, do_module, search, overrides);
639         closedir(dir);
640
641         return list;
642 }
643
644 static struct module *sort_modules(const char *dirname, struct module *list)
645 {
646         struct module *tlist = NULL, **tpos = &tlist;
647         FILE *modorder;
648         int dir_len = strlen(dirname) + 1;
649         char file_name[dir_len + strlen("modules.order") + 1];
650         char line[10240];
651         unsigned int linenum = 0;
652
653         sprintf(file_name, "%s/%s", dirname, "modules.order");
654
655         modorder = fopen(file_name, "r");
656         if (!modorder) {
657                 /* Older kernels don't generate modules.order.  Just
658                    return if the file doesn't exist. */
659                 if (errno == ENOENT)
660                         return list;
661                 fatal("Could not open '%s': %s\n", file_name, strerror(errno));
662         }
663
664         sprintf(line, "%s/", dirname);
665
666         /* move modules listed in modorder file to tlist in order */
667         while (fgets(line, sizeof(line), modorder)) {
668                 struct module **pos, *mod;
669                 int len = strlen(line);
670
671                 linenum++;
672                 if (line[len - 1] == '\n')
673                         line[len - 1] = '\0';
674
675                 for (pos = &list; (mod = *pos); pos = &(*pos)->next) {
676                         if (streq(line, mod->pathname + dir_len)) {
677                                 mod->order = linenum;
678                                 *pos = mod->next;
679                                 mod->next = NULL;
680                                 *tpos = mod;
681                                 tpos = &mod->next;
682                                 break;
683                         }
684                 }
685         }
686
687         /* append the rest */
688         *tpos = list;
689
690         fclose(modorder);
691
692         return tlist;
693 }
694
695 /* Calculate the dependencies for this module */
696 static void calculate_deps(struct module *module)
697 {
698         unsigned int i;
699         struct string_table *symnames;
700         struct string_table *symtypes;
701         uint64_t *symvers = NULL;
702         struct elf_file *file;
703
704         module->num_deps = 0;
705         module->deps = NULL;
706         file = module->file;
707
708         symnames = file->ops->load_dep_syms(file, &symtypes,
709                         check_symvers ? &symvers : NULL);
710         if (!symnames || !symtypes)
711                 return;
712
713         for (i = 0; i < symnames->cnt; i++) {
714                 const char *name;
715                 uint64_t ver;
716                 struct module *owner;
717                 int weak;
718
719                 name = symnames->str[i];
720                 ver = symvers ? symvers[i] : 0;
721                 weak = (*(symtypes->str[i]) == 'W');
722                 owner = find_symbol(name, ver, module->pathname, weak);
723                 if (owner) {
724                         info("%s needs \"%s\": %s\n",
725                                module->pathname, name,
726                                owner->pathname);
727                         add_dep(module, owner);
728                 }
729         }
730
731         free(symnames);
732         free(symtypes);
733         free(symvers);
734 }
735
736 static struct module *parse_modules(struct module *list)
737 {
738         struct module *i;
739         struct elf_file *file;
740         struct string_table *syms;
741         int j;
742
743         for (i = list; i; i = i->next) {
744                 uint64_t *symvers = NULL;
745                 file = i->file;
746                 syms = file->ops->load_symbols(file,
747                                 check_symvers ? &symvers : NULL);
748                 if (syms) {
749                         for (j = 0; j < syms->cnt; j++)
750                                 add_symbol(syms->str[j],
751                                         symvers ? symvers[j] : 0, i);
752                         strtbl_free(syms);
753                 }
754                 free(symvers);
755                 file->ops->fetch_tables(file, &i->tables);
756         }
757         
758         for (i = list; i; i = i->next)
759                 calculate_deps(i);
760         
761         /* Strip out modules with dependency loops. */
762  again:
763         for (i = list; i; i = i->next) {
764                 if (has_dep_loop(i, NULL)) {
765                         warn("Module %s ignored, due to loop\n",
766                              i->pathname + skipchars);
767                         del_module(&list, i);
768                         goto again;
769                 }
770         }
771         
772         return list;
773 }
774
775 /* Simply dump hash table. */
776 static int output_symbols(struct module *unused, FILE *out, char *dirname)
777 {
778         unsigned int i;
779
780         fprintf(out, "# Aliases for symbols, used by symbol_request().\n");
781         for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
782                 struct symbol *s;
783
784                 for (s = symbolhash[i]; s; s = s->next) {
785                         if (s->owner) {
786                                 char modname[strlen(s->owner->pathname)+1];
787                                 filename2modname(modname, s->owner->pathname);
788                                 fprintf(out, "alias symbol:%s %s\n",
789                                         s->name, modname);
790                         }
791                 }
792         }
793         return 1;
794 }
795
796 static int output_symbols_bin(struct module *unused, FILE *out, char *dirname)
797 {
798         struct index_node *index;
799         unsigned int i;
800         char *alias;
801         int duplicate;
802
803         index = index_create();
804         
805         for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
806                 struct symbol *s;
807
808                 for (s = symbolhash[i]; s; s = s->next) {
809                         if (s->owner) {
810                                 char modname[strlen(s->owner->pathname)+1];
811                                 filename2modname(modname, s->owner->pathname);
812                                 nofail_asprintf(&alias, "symbol:%s", s->name);
813                                 duplicate = index_insert(index, alias, modname,
814                                                          s->owner->order);
815                                 if (duplicate && warn_dups)
816                                         warn("duplicate module syms:\n%s %s\n",
817                                                 alias, modname);
818                                 free(alias);
819                         }
820                 }
821         }
822         
823         index_write(index, out);
824         index_destroy(index);
825
826         return 1;
827 }
828
829 static int output_builtin_bin(struct module *unused, FILE *out, char *dirname)
830 {
831         struct index_node *index;
832         char *textfile, *line;
833         unsigned int linenum;
834         FILE *f;
835
836         nofail_asprintf(&textfile, "%s/modules.builtin", dirname);
837         if (!(f = fopen(textfile, "r"))) {
838                 if (errno != ENOENT)
839                         fatal("Could not open '%s': %s\n",
840                                         textfile, strerror(errno));
841                 free(textfile);
842                 return 0;
843         }
844         free(textfile);
845         index = index_create();
846
847         while ((line = getline_wrapped(f, &linenum)) != NULL) {
848                 char *module = line;
849
850                 if (!*line || *line == '#') {
851                         free(line);
852                         continue;
853                 }
854                 filename2modname(module, module);
855                 index_insert(index, module, "", 0);
856                 free(line);
857         }
858         fclose(f);
859         index_write(index, out);
860         index_destroy(index);
861
862         return 1;
863 }
864
865 static int output_aliases(struct module *modules, FILE *out, char *dirname)
866 {
867         struct module *i;
868         struct elf_file *file;
869         struct string_table *tbl;
870         int j;
871
872         fprintf(out, "# Aliases extracted from modules themselves.\n");
873         for (i = modules; i; i = i->next) {
874                 char modname[strlen(i->pathname)+1];
875
876                 file = i->file;
877                 filename2modname(modname, i->pathname);
878
879                 /* Grab from old-style .modalias section. */
880                 tbl = file->ops->load_strings(file, ".modalias", NULL);
881                 for (j = 0; tbl && j < tbl->cnt; j++)
882                         fprintf(out, "alias %s %s\n", tbl->str[j], modname);
883                 strtbl_free(tbl);
884
885                 /* Grab from new-style .modinfo section. */
886                 tbl = file->ops->load_strings(file, ".modinfo", NULL);
887                 for (j = 0; tbl && j < tbl->cnt; j++) {
888                         const char *p = tbl->str[j];
889                         if (strstarts(p, "alias="))
890                                 fprintf(out, "alias %s %s\n",
891                                         p + strlen("alias="), modname);
892                 }
893                 strtbl_free(tbl);
894         }
895         return 1;
896 }
897
898 static int output_aliases_bin(struct module *modules, FILE *out, char *dirname)
899 {
900         struct module *i;
901         struct elf_file *file;
902         struct string_table *tbl;
903         int j;
904         char *alias;
905         struct index_node *index;
906         int duplicate;
907
908         index = index_create();
909         
910         for (i = modules; i; i = i->next) {
911                 char modname[strlen(i->pathname)+1];
912
913                 file = i->file;
914                 filename2modname(modname, i->pathname);
915
916                 /* Grab from old-style .modalias section. */
917                 tbl = file->ops->load_strings(file, ".modalias", NULL);
918                 for (j = 0; tbl && j < tbl->cnt; j++) {
919                         alias = NOFAIL(strdup(tbl->str[j]));
920                         underscores(alias);
921                         duplicate = index_insert(index, alias, modname, i->order);
922                         if (duplicate && warn_dups)
923                                 warn("duplicate module alias:\n%s %s\n",
924                                         alias, modname);
925                         free(alias);
926                 }
927                 strtbl_free(tbl);
928
929                 /* Grab from new-style .modinfo section. */
930                 tbl = file->ops->load_strings(file, ".modinfo", NULL);
931                 for (j = 0; tbl && j < tbl->cnt; j++) {
932                         const char *p = tbl->str[j];
933                         if (strstarts(p, "alias=")) {
934                                 alias = NOFAIL(strdup(p + strlen("alias=")));
935                                 underscores(alias);
936                                 duplicate = index_insert(index, alias, modname, i->order);
937                                 if (duplicate && warn_dups)
938                                         warn("duplicate module alias:\n%s %s\n",
939                                                 alias, modname);
940                                 free(alias);
941                         }
942                 }
943                 strtbl_free(tbl);
944         }
945         
946         index_write(index, out);
947         index_destroy(index);
948
949         return 1;
950 }
951
952 static int output_softdeps(struct module *modules, FILE *out, char *dirname)
953 {
954         struct module *i;
955         struct elf_file *file;
956         struct string_table *tbl;
957         int j;
958
959         fprintf(out, "# Soft dependencies extracted from modules themselves.\n");
960         fprintf(out, "# Copy, with a .conf extension, to /etc/modprobe.d to use "
961                 "it with modprobe.\n");
962         for (i = modules; i; i = i->next) {
963                 char modname[strlen(i->pathname)+1];
964
965                 file = i->file;
966                 filename2modname(modname, i->pathname);
967
968                 /* Grab from new-style .modinfo section. */
969                 tbl = file->ops->load_strings(file, ".modinfo", NULL);
970                 for (j = 0; tbl && j < tbl->cnt; j++) {
971                         const char *p = tbl->str[j];
972                         if (strstarts(p, "softdep="))
973                                 fprintf(out, "softdep %s %s\n",
974                                         modname, p + strlen("softdep="));
975                 }
976                 strtbl_free(tbl);
977         }
978         return 1;
979 }
980
981 struct depfile {
982         char *name;
983         int (*func)(struct module *, FILE *, char *dirname);
984         int map_file;
985 };
986
987 static struct depfile depfiles[] = {
988         { "modules.dep", output_deps, 0 }, /* This is what we check for '-A'. */
989         { "modules.dep.bin", output_deps_bin, 0 },
990         { "modules.pcimap", output_pci_table, 1 },
991         { "modules.usbmap", output_usb_table, 1 },
992         { "modules.ccwmap", output_ccw_table, 1 },
993         { "modules.ieee1394map", output_ieee1394_table, 1 },
994         { "modules.isapnpmap", output_isapnp_table, 1 },
995         { "modules.inputmap", output_input_table, 1 },
996         { "modules.ofmap", output_of_table, 1 },
997         { "modules.seriomap", output_serio_table, 1 },
998         { "modules.alias", output_aliases, 0 },
999         { "modules.alias.bin", output_aliases_bin, 0 },
1000         { "modules.softdep", output_softdeps, 0 },
1001         { "modules.symbols", output_symbols, 0 },
1002         { "modules.symbols.bin", output_symbols_bin, 0 },
1003         { "modules.builtin.bin", output_builtin_bin, 0 },
1004 };
1005
1006 /* If we can't figure it out, it's safe to say "true". */
1007 static int any_modules_newer(const char *dirname, time_t mtime)
1008 {
1009         DIR *dir;
1010         struct dirent *dirent;
1011
1012         dir = opendir(dirname);
1013         if (!dir)
1014                 return 1;
1015
1016         while ((dirent = readdir(dir)) != NULL) {
1017                 struct stat st;
1018                 char file[strlen(dirname) + 1 + strlen(dirent->d_name) + 1];
1019
1020                 if (streq(dirent->d_name, ".") || streq(dirent->d_name, ".."))
1021                         continue;
1022
1023                 sprintf(file, "%s/%s", dirname, dirent->d_name);
1024                 if (lstat(file, &st) != 0)
1025                         goto ret_true;
1026
1027                 if (smells_like_module(dirent->d_name)) {
1028                         if (st.st_mtime > mtime)
1029                                 goto ret_true;
1030                 } else if (S_ISDIR(st.st_mode)) {
1031                         if (any_modules_newer(file, mtime))
1032                                 goto ret_true;
1033                 }
1034         }
1035         closedir(dir);
1036         return 0;
1037
1038 ret_true:
1039         closedir(dir);
1040         return 1;
1041 }
1042
1043 static int depfile_out_of_date(const char *dirname)
1044 {
1045         struct stat st;
1046         char depfile[strlen(dirname) + 1 + strlen(depfiles[0].name) + 1];
1047
1048         sprintf(depfile, "%s/%s", dirname, depfiles[0].name);
1049
1050         if (stat(depfile, &st) != 0)
1051                 return 1;
1052
1053         return any_modules_newer(dirname, st.st_mtime);
1054 }
1055
1056 static char *strsep_skipspace(char **string, char *delim)
1057 {
1058         if (!*string)
1059                 return NULL;
1060         *string += strspn(*string, delim);
1061         return strsep(string, delim);
1062 }
1063
1064 static struct module_search *add_search(const char *search_path,
1065                                         size_t len,
1066                                         struct module_search *search)
1067 {
1068
1069         struct module_search *new;
1070         
1071         new = NOFAIL(malloc(sizeof(*new)));
1072         new->search_path = NOFAIL(strdup(search_path));
1073         new->len = len;
1074         new->next = search;
1075
1076         return new;
1077         
1078 }
1079
1080 static struct module_overrides *add_override(const char *modfile,
1081                                              struct module_overrides *overrides)
1082 {
1083
1084         struct module_overrides *new;
1085         
1086         new = NOFAIL(malloc(sizeof(*new)));
1087         new->modfile = NOFAIL(strdup(modfile));
1088         new->next = overrides;
1089
1090         return new;
1091         
1092 }
1093
1094 static int parse_config_scan(const char *filename,
1095                              const char *basedir,
1096                              const char *kernelversion,
1097                              struct module_search **search,
1098                              struct module_overrides **overrides);
1099
1100 static int parse_config_file(const char *filename,
1101                              const char *basedir,
1102                              const char *kernelversion,
1103                              struct module_search **search,
1104                              struct module_overrides **overrides)
1105 {
1106         char *line;
1107         unsigned int linenum = 0;
1108         FILE *cfile;
1109
1110         cfile = fopen(filename, "r");
1111         if (!cfile) {
1112                 if (errno != ENOENT)
1113                         fatal("could not open '%s', reason: %s\n", filename,
1114                               strerror(errno));
1115                 return 0;
1116         }
1117
1118         while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
1119                 char *ptr = line;
1120                 char *cmd, *modname;
1121
1122                 cmd = strsep_skipspace(&ptr, "\t ");
1123
1124                 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
1125                         free(line);
1126                         continue;
1127                 }
1128
1129                 if (streq(cmd, "search")) {
1130                         char *search_path;
1131                         
1132                         while ((search_path = strsep_skipspace(&ptr, "\t "))) {
1133                                 char *dirname;
1134                                 size_t len;
1135
1136                                 if (strcmp(search_path,
1137                                                 MODULE_BUILTIN_KEY) == 0) {
1138                                         *search = add_search(MODULE_BUILTIN_KEY,
1139                                                              0, *search);
1140                                         continue;
1141                                 }
1142                                 nofail_asprintf(&dirname, "%s%s%s/%s", basedir,
1143                                         MODULE_DIR, kernelversion, search_path);
1144                                 len = strlen(dirname);
1145                                 *search = add_search(dirname, len, *search);
1146                                 free(dirname);
1147                         }
1148                 } else if (streq(cmd, "override")) {
1149                         char *pathname = NULL, *version, *subdir;
1150                         modname = strsep_skipspace(&ptr, "\t ");
1151                         version = strsep_skipspace(&ptr, "\t ");
1152                         subdir = strsep_skipspace(&ptr, "\t ");
1153
1154                         if (!regex_match(kernelversion, (const char *)version))
1155                                 continue;
1156
1157                         nofail_asprintf(&pathname, "%s%s%s/%s/%s.ko", basedir,
1158                                 MODULE_DIR, kernelversion, subdir, modname);
1159
1160                         *overrides = add_override(pathname, *overrides);
1161                         free(pathname);
1162                 } else if (streq(cmd, "include")) {
1163                         char *newfilename;
1164
1165                         newfilename = strsep_skipspace(&ptr, "\t ");
1166                         if (!newfilename) {
1167                                 grammar(cmd, filename, linenum);
1168                         } else {
1169                                 warn("\"include %s\" is deprecated, "
1170                                      "please use /etc/depmod.d\n", newfilename);
1171                                 if (strstarts(newfilename, "/etc/depmod.d")) {
1172                                         warn("\"include /etc/depmod.d\" is "
1173                                              "the default, ignored\n");
1174                                 } else {
1175                                         if (!parse_config_scan(newfilename, basedir,
1176                                                                kernelversion,
1177                                                                search, overrides))
1178                                         warn("Failed to open included"
1179                                              " config file %s: %s\n",
1180                                              newfilename, strerror(errno));
1181                                 }
1182                         }
1183                 } else if (streq(cmd, "make_map_files")) {
1184                         char *option;
1185
1186                         option = strsep_skipspace(&ptr, "\t ");
1187                         if (!option)
1188                                 grammar(cmd, filename, linenum);
1189                         else {
1190                                 if (streq(option, "yes"))
1191                                         make_map_files = 1;
1192                                 else if (streq(option, "no"))
1193                                         make_map_files = 0;
1194                                 else
1195                                         grammar(cmd, filename, linenum);
1196                         }
1197                 } else
1198                         grammar(cmd, filename, linenum);
1199
1200                 free(line);
1201         }
1202         fclose(cfile);
1203         return 1;
1204 }
1205
1206 static int parse_config_scan(const char *filename,
1207                              const char *basedir,
1208                              const char *kernelversion,
1209                              struct module_search **search,
1210                              struct module_overrides **overrides)
1211 {
1212         DIR *dir;
1213         int ret = 0;
1214
1215         dir = opendir(filename);
1216         if (dir) {
1217                 struct file_entry {
1218                         struct list_head node;
1219                         char name[];
1220                 };
1221                 LIST_HEAD(files_list);
1222                 struct file_entry *fe, *fe_tmp;
1223                 struct dirent *i;
1224
1225                 /* sort files from directory into list */
1226                 while ((i = readdir(dir)) != NULL) {
1227                         size_t len;
1228
1229                         if (i->d_name[0] == '.')
1230                                 continue;
1231                         if (!config_filter(i->d_name))
1232                                 continue;
1233
1234                         len = strlen(i->d_name);
1235                         if (len < 6 || strcmp(&i->d_name[len-5], ".conf") != 0)
1236                                 warn("All config files need .conf: %s/%s, "
1237                                      "it will be ignored in a future release.\n",
1238                                      filename, i->d_name);
1239                         fe = malloc(sizeof(struct file_entry) + len + 1);
1240                         if (fe == NULL)
1241                                 continue;
1242                         strcpy(fe->name, i->d_name);
1243                         list_for_each_entry(fe_tmp, &files_list, node)
1244                                 if (strcmp(fe_tmp->name, fe->name) >= 0)
1245                                         break;
1246                         list_add_tail(&fe->node, &fe_tmp->node);
1247                 }
1248                 closedir(dir);
1249
1250                 /* parse list of files */
1251                 list_for_each_entry_safe(fe, fe_tmp, &files_list, node) {
1252                         char *cfgfile;
1253
1254                         nofail_asprintf(&cfgfile, "%s/%s", filename, fe->name);
1255                         if (!parse_config_file(cfgfile, basedir, kernelversion,
1256                                                search, overrides))
1257                                 warn("Failed to open config file "
1258                                      "%s: %s\n", fe->name, strerror(errno));
1259                         free(cfgfile);
1260                         list_del(&fe->node);
1261                         free(fe);
1262                 }
1263
1264                 ret = 1;
1265         } else {
1266                 if (parse_config_file(filename, basedir, kernelversion, search,
1267                                       overrides))
1268                         ret = 1;
1269         }
1270
1271         return ret;
1272 }
1273
1274 static void parse_toplevel_config(const char *filename,
1275                                   const char *basedir,
1276                                   const char *kernelversion,
1277                                   struct module_search **search,
1278                                   struct module_overrides **overrides)
1279 {
1280         if (filename) {
1281                 if (!parse_config_scan(filename, basedir, kernelversion, search,
1282                                  overrides))
1283                         fatal("Failed to open config file %s: %s\n",
1284                               filename, strerror(errno));
1285                 return;
1286         }
1287
1288         /* deprecated config file */
1289         if (parse_config_file("/etc/depmod.conf", basedir, kernelversion,
1290                               search, overrides) > 0)
1291                 warn("Deprecated config file /etc/depmod.conf, "
1292                       "all config files belong into /etc/depmod.d/.\n");
1293
1294         /* default config */
1295         parse_config_scan("/etc/depmod.d", basedir, kernelversion,
1296                           search, overrides);
1297 }
1298
1299 /* Local to main, but not freed on exit.  Keep valgrind quiet. */
1300 struct module *list = NULL;
1301 struct module_search *search = NULL;
1302 struct module_overrides *overrides = NULL;
1303
1304 int main(int argc, char *argv[])
1305 {
1306         int opt, all = 0, maybe_all = 0, doing_stdout = 0;
1307         char *basedir = "", *dirname, *version;
1308         char *system_map = NULL, *module_symvers = NULL;
1309         int i;
1310         const char *config = NULL;
1311
1312         if (native_endianness() == 0)
1313                 abort();
1314
1315         while ((opt = getopt_long(argc, argv, "aAb:C:E:F:euqrvnhVwm", options, NULL))
1316                != -1) {
1317                 switch (opt) {
1318                 case 'a':
1319                         all = 1;
1320                         break;
1321                 case 'A':
1322                         maybe_all = 1;
1323                         break;
1324                 case 'b':
1325                         basedir = optarg;
1326                         skipchars = strlen(basedir);
1327                         break;
1328                 case 'C':
1329                         config = optarg;
1330                         break;
1331                 case 'E':
1332                         module_symvers = optarg;
1333                         check_symvers = 1;
1334                         break;
1335                 case 'F':
1336                         system_map = optarg;
1337                         break;
1338                 case 'e':
1339                         print_unknown = 1;
1340                         break;
1341                 case 'u':
1342                 case 'q':
1343                 case 'r':
1344                         break;
1345                 case 'v':
1346                         verbose = 1;
1347                         break;
1348                 case 'n':
1349                         doing_stdout = 1;
1350                         break;
1351                 case 'h':
1352                         print_usage(argv[0]);
1353                         exit(0);
1354                         break;
1355                 case 'V':
1356                         printf("%s %s\n", PACKAGE, VERSION);
1357                         exit(0);
1358                 case 'w':
1359                         warn_dups = 1;
1360                         break;
1361                 case 'm':
1362                         force_map_files = 1;
1363                         break;
1364                 default:
1365                         print_usage(argv[0]);
1366                         exit(1);
1367                 }
1368         }
1369
1370         if (module_symvers)
1371                 load_module_symvers(module_symvers);
1372         else if (system_map)
1373                 load_system_map(system_map);
1374         else if (print_unknown) {
1375                 warn("-e needs -E or -F\n");
1376                 print_unknown = 0;
1377         }
1378
1379         /* They can specify the version naked on the command line */
1380         if (optind < argc && is_version_number(argv[optind])) {
1381                 version = NOFAIL(strdup(argv[optind]));
1382                 optind++;
1383         } else {
1384                 struct utsname buf;
1385                 uname(&buf);
1386                 version = NOFAIL(strdup(buf.release));
1387         }
1388
1389         /* Check for old version. */
1390         if (old_module_version(version)) {
1391                 fprintf(stderr, "Kernel version %s requires old depmod\n",
1392                         version);
1393                 exit(2);
1394         }
1395
1396         /* Depmod -a by default if no names. */
1397         if (optind == argc)
1398                 all = 1;
1399
1400         nofail_asprintf(&dirname, "%s%s%s", basedir, MODULE_DIR, version);
1401
1402         if (maybe_all) {
1403                 if (!doing_stdout && !depfile_out_of_date(dirname))
1404                         exit(0);
1405                 all = 1;
1406         }
1407
1408         parse_toplevel_config(config, basedir, version, &search, &overrides);
1409
1410         /* For backward compatibility add "updates" to the head of the search
1411          * list here. But only if there was no "search" option specified.
1412          */
1413         if (!search) {
1414                 char *dirname;
1415                 size_t len;
1416
1417                 nofail_asprintf(&dirname, "%s%s%s/updates", basedir,
1418                                 MODULE_DIR, version);
1419                 len = strlen(dirname);
1420                 search = add_search(dirname, len, search);
1421         }
1422         if (!all) {
1423                 /* Do command line args. */
1424                 for (opt = optind; opt < argc; opt++) {
1425                         struct module *new;
1426
1427                         if (argv[opt][0] != '/')
1428                                 fatal("modules must be specified using absolute paths.\n"
1429                                         "\"%s\" is a relative path\n", argv[opt]);
1430
1431                         new = grab_module(NULL, argv[opt]);
1432                         if (!new) {
1433                                 /* cmd-line specified modules must exist */
1434                                 fatal("grab_module() failed for module %s\n", argv[opt]);
1435                         }
1436                         new->next = list;
1437                         list = new;
1438                 }
1439         } else {
1440                 list = grab_basedir(dirname,search,overrides);
1441         }
1442         list = sort_modules(dirname,list);
1443         list = parse_modules(list);
1444
1445         for (i = 0; i < sizeof(depfiles)/sizeof(depfiles[0]); i++) {
1446                 FILE *out;
1447                 int res;
1448                 struct depfile *d = &depfiles[i];
1449                 char depname[strlen(dirname) + 1 + strlen(d->name) + 1];
1450                 char tmpname[strlen(dirname) + 1 + strlen(d->name) +
1451                                                 strlen(".temp") + 1];
1452
1453                 if (d->map_file && !make_map_files && !force_map_files)
1454                         continue;
1455
1456                 sprintf(depname, "%s/%s", dirname, d->name);
1457                 sprintf(tmpname, "%s/%s.temp", dirname, d->name);
1458                 if (!doing_stdout) {
1459                         out = fopen(tmpname, "w");
1460                         if (!out)
1461                                 fatal("Could not open %s for writing: %s\n",
1462                                         tmpname, strerror(errno));
1463                 } else {
1464                         out = stdout;
1465                         if (ends_in(depname, ".bin"))
1466                                 continue;
1467                 }
1468                 res = d->func(list, out, dirname);
1469                 if (doing_stdout)
1470                         continue;
1471                 fclose(out);
1472                 if (res) {
1473                         if (rename(tmpname, depname) < 0)
1474                                 fatal("Could not rename %s into %s: %s\n",
1475                                         tmpname, depname, strerror(errno));
1476                 } else {
1477                         if (unlink(tmpname) < 0)
1478                                 warn("Could not delete %s: %s\n",
1479                                         tmpname, strerror(errno));
1480                 }
1481         }
1482
1483         free(dirname);
1484         free(version);
1485         
1486         return 0;
1487 }