TODO: fix the build system with respect to docs.
[mit.git] / depmod.c
blobb3892d73f893d3b403b25e5ffc42ab003d527e15
1 /* New simplified depmod without backwards compat stuff and not
2 requiring ksyms.
4 (C) 2002 Rusty Russell IBM Corporation
5 */
6 #define _GNU_SOURCE /* asprintf */
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <getopt.h>
11 #include <string.h>
12 #include <errno.h>
13 #include <unistd.h>
14 #include <elf.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <dirent.h>
19 #include <sys/utsname.h>
20 #include <sys/mman.h>
22 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
24 #include "zlibsupport.h"
25 #include "depmod.h"
26 #include "logging.h"
27 #include "index.h"
28 #include "moduleops.h"
29 #include "tables.h"
30 #include "config_filter.h"
32 #include "testing.h"
34 #ifndef MODULE_DIR
35 #define MODULE_DIR "/lib/modules/"
36 #endif
38 #ifndef MODULE_BUILTIN_KEY
39 #define MODULE_BUILTIN_KEY "built-in"
40 #endif
42 struct module_overrides
44 /* Next override */
45 struct module_overrides *next;
47 /* overridden module */
48 char *modfile;
51 struct module_search
53 /* Next search */
54 struct module_search *next;
56 /* search path */
57 char *search_path;
58 size_t len;
61 static int verbose;
62 static unsigned int skipchars;
63 static unsigned int make_map_files = 1; /* default to on */
64 static unsigned int force_map_files = 0; /* default to on */
66 #define SYMBOL_HASH_SIZE 1024
67 struct symbol
69 struct symbol *next;
70 struct module *owner;
71 char name[0];
74 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
76 /* This is based on the hash agorithm from gdbm, via tdb */
77 static inline unsigned int tdb_hash(const char *name)
79 unsigned value; /* Used to compute the hash value. */
80 unsigned i; /* Used to cycle through random values. */
82 /* Set the initial value from the key size. */
83 for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
84 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
86 return (1103515243 * value + 12345);
89 void add_symbol(const char *name, struct module *owner)
91 unsigned int hash;
92 struct symbol *new = NOFAIL(malloc(sizeof *new + strlen(name) + 1));
94 new->owner = owner;
95 strcpy(new->name, name);
97 hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
98 new->next = symbolhash[hash];
99 symbolhash[hash] = new;
102 static int print_unknown;
104 struct module *find_symbol(const char *name, const char *modname, int weak)
106 struct symbol *s;
108 /* For our purposes, .foo matches foo. PPC64 needs this. */
109 if (name[0] == '.')
110 name++;
112 for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s=s->next) {
113 if (streq(s->name, name))
114 return s->owner;
117 if (print_unknown && !weak)
118 warn("%s needs unknown symbol %s\n", modname, name);
120 return NULL;
123 void add_dep(struct module *mod, struct module *depends_on)
125 unsigned int i;
127 for (i = 0; i < mod->num_deps; i++)
128 if (mod->deps[i] == depends_on)
129 return;
131 mod->deps = NOFAIL(realloc(mod->deps, sizeof(mod->deps[0])*(mod->num_deps+1)));
132 mod->deps[mod->num_deps++] = depends_on;
135 static void load_system_map(const char *filename)
137 FILE *system_map;
138 char line[10240];
139 const char ksymstr[] = "__ksymtab_";
140 const int ksymstr_len = strlen(ksymstr);
142 system_map = fopen(filename, "r");
143 if (!system_map)
144 fatal("Could not open '%s': %s\n", filename, strerror(errno));
146 /* eg. c0294200 R __ksymtab_devfs_alloc_devnum */
147 while (fgets(line, sizeof(line)-1, system_map)) {
148 char *ptr;
150 /* Snip \n */
151 ptr = strchr(line, '\n');
152 if (ptr)
153 *ptr = '\0';
155 ptr = strchr(line, ' ');
156 if (!ptr || !(ptr = strchr(ptr + 1, ' ')))
157 continue;
159 /* Covers gpl-only and normal symbols. */
160 if (strncmp(ptr+1, ksymstr, ksymstr_len) == 0)
161 add_symbol(ptr+1+ksymstr_len, NULL);
164 fclose(system_map);
166 /* __this_module is magic inserted by kernel loader. */
167 add_symbol("__this_module", NULL);
168 /* On S390, this is faked up too */
169 add_symbol("_GLOBAL_OFFSET_TABLE_", NULL);
172 static struct option options[] = { { "all", 0, NULL, 'a' },
173 { "quick", 0, NULL, 'A' },
174 { "basedir", 1, NULL, 'b' },
175 { "errsyms", 0, NULL, 'e' },
176 { "filesyms", 1, NULL, 'F' },
177 { "help", 0, NULL, 'h' },
178 { "show", 0, NULL, 'n' },
179 { "dry-run", 0, NULL, 'n' },
180 { "quiet", 0, NULL, 'q' },
181 { "root", 0, NULL, 'r' },
182 { "unresolved-error", 0, NULL, 'u' },
183 { "verbose", 0, NULL, 'v' },
184 { "version", 0, NULL, 'V' },
185 { "config", 1, NULL, 'C' },
186 { "warn", 1, NULL, 'w' },
187 { "map", 0, NULL, 'm' },
188 { NULL, 0, NULL, 0 } };
190 /* Version number or module name? Don't assume extension. */
191 static int is_version_number(const char *version)
193 unsigned int dummy;
195 return (sscanf(version, "%u.%u.%u", &dummy, &dummy, &dummy) == 3);
198 static int old_module_version(const char *version)
200 /* Expect three part version. */
201 unsigned int major, sub, minor;
203 sscanf(version, "%u.%u.%u", &major, &sub, &minor);
205 if (major > 2) return 0;
206 if (major < 2) return 1;
208 /* 2.x */
209 if (sub > 5) return 0;
210 if (sub < 5) return 1;
212 /* 2.5.x */
213 if (minor >= 48) return 0;
214 return 1;
217 static void exec_old_depmod(char *argv[])
219 char *sep;
220 char pathname[strlen(argv[0])+1];
221 char oldname[strlen("depmod") + strlen(argv[0]) + sizeof(".old")];
223 memset(pathname, 0, strlen(argv[0])+1);
224 sep = strrchr(argv[0], '/');
225 if (sep)
226 memcpy(pathname, argv[0], sep - argv[0]+1);
227 sprintf(oldname, "%s%s.old", pathname, "depmod");
229 /* Recursion detection: we need an env var since we can't
230 change argv[0] (as older modutils uses it to determine
231 behavior). */
232 if (getenv("MODULE_RECURSE"))
233 return;
234 setenv("MODULE_RECURSE", "y", 0);
236 execvp(oldname, argv);
237 fprintf(stderr,
238 "Version requires old depmod, but couldn't run %s: %s\n",
239 oldname, strerror(errno));
240 exit(2);
243 static void grammar(const char *cmd, const char *filename, unsigned int line)
245 warn("%s line %u: ignoring bad line starting with '%s'\n",
246 filename, line, cmd);
250 static void print_usage(const char *name)
252 fprintf(stderr,
253 "%s " VERSION " -- part of " PACKAGE "\n"
254 "%s -[aA] [-n -e -v -q -V -r -u -w -m]\n"
255 " [-b basedirectory] [forced_version]\n"
256 "depmod [-n -e -v -q -r -u -w] [-F kernelsyms] module1.ko module2.ko ...\n"
257 "If no arguments (except options) are given, \"depmod -a\" is assumed\n"
258 "\n"
259 "depmod will output a dependancy list suitable for the modprobe utility.\n"
260 "\n"
261 "\n"
262 "Options:\n"
263 "\t-a, --all Probe all modules\n"
264 "\t-A, --quick Only does the work if there's a new module\n"
265 "\t-e, --errsyms Report not supplied symbols\n"
266 "\t-m, --map Create the legacy map files\n"
267 "\t-n, --show Write the dependency file on stdout only\n"
268 "\t-V, --version Print the release version\n"
269 "\t-v, --verbose Enable verbose mode\n"
270 "\t-w, --warn Warn on duplicates\n"
271 "\t-h, --help Print this usage message\n"
272 "\n"
273 "The following options are useful for people managing distributions:\n"
274 "\t-b basedirectory\n"
275 "\t --basedir basedirectory Use an image of a module tree.\n"
276 "\t-F kernelsyms\n"
277 "\t --filesyms kernelsyms Use the file instead of the\n"
278 "\t current kernel symbols.\n",
279 "depmod", "depmod");
282 static int ends_in(const char *name, const char *ext)
284 unsigned int namelen, extlen;
286 /* Grab lengths */
287 namelen = strlen(name);
288 extlen = strlen(ext);
290 if (namelen < extlen) return 0;
292 if (streq(name + namelen - extlen, ext))
293 return 1;
294 return 0;
297 /* "\177ELF" <byte> where byte = 001 for 32-bit, 002 for 64 */
298 int needconv(const char *elfhdr)
300 union { short s; char c[2]; } endian_test;
302 endian_test.s = 1;
303 if (endian_test.c[1] == 1) return elfhdr[EI_DATA] != ELFDATA2MSB;
304 if (endian_test.c[0] == 1) return elfhdr[EI_DATA] != ELFDATA2LSB;
305 else
306 abort();
309 static char *my_basename(const char *name)
311 const char *base = strrchr(name, '/');
312 if (base) return (char *)base + 1;
313 return (char *)name;
316 static struct module *grab_module(const char *dirname, const char *filename)
318 struct module *new;
320 new = NOFAIL(malloc(sizeof(*new)
321 + strlen(dirname?:"") + 1 + strlen(filename) + 1));
322 if (dirname)
323 sprintf(new->pathname, "%s/%s", dirname, filename);
324 else
325 strcpy(new->pathname, filename);
326 new->basename = my_basename(new->pathname);
328 INIT_LIST_HEAD(&new->dep_list);
329 new->order = INDEX_PRIORITY_MIN;
331 new->data = grab_file(new->pathname, &new->len);
332 if (!new->data) {
333 warn("Can't read module %s: %s\n",
334 new->pathname, strerror(errno));
335 goto fail_data;
338 /* "\177ELF" <byte> where byte = 001 for 32-bit, 002 for 64 */
339 if (memcmp(new->data, ELFMAG, SELFMAG) != 0) {
340 warn("Module %s is not an elf object\n", new->pathname);
341 goto fail;
344 switch (((char *)new->data)[EI_CLASS]) {
345 case ELFCLASS32:
346 new->ops = &mod_ops32;
347 break;
348 case ELFCLASS64:
349 new->ops = &mod_ops64;
350 break;
351 default:
352 warn("Module %s has elf unknown identifier %i\n",
353 new->pathname, ((char *)new->data)[EI_CLASS]);
354 goto fail;
356 new->conv = needconv(new->data);
357 return new;
359 fail:
360 release_file(new->data, new->len);
361 fail_data:
362 free(new);
363 return NULL;
366 struct module_traverse
368 struct module_traverse *prev;
369 struct module *mod;
372 static int in_loop(struct module *mod, const struct module_traverse *traverse)
374 const struct module_traverse *i;
376 for (i = traverse; i; i = i->prev) {
377 if (i->mod == mod)
378 return 1;
380 return 0;
383 /* Assume we are doing all the modules, so only report each loop once. */
384 static void report_loop(const struct module *mod,
385 const struct module_traverse *traverse)
387 const struct module_traverse *i;
389 /* Check that start is least alphabetically. eg. a depends
390 on b depends on a will get reported for a, not b. */
391 for (i = traverse->prev; i->prev; i = i->prev) {
392 if (strcmp(mod->pathname, i->mod->pathname) > 0)
393 return;
396 /* Is start in the loop? If not, don't report now. eg. a
397 depends on b which depends on c which depends on b. Don't
398 report when generating depends for a. */
399 if (mod != i->mod)
400 return;
402 warn("Loop detected: %s ", mod->pathname);
403 for (i = traverse->prev; i->prev; i = i->prev)
404 fprintf(stderr, "needs %s ", i->mod->basename);
405 fprintf(stderr, "which needs %s again!\n", i->mod->basename);
408 /* This is damn slow, but loops actually happen, and we don't want to
409 just exit() and leave the user without any modules. */
410 static int has_dep_loop(struct module *module, struct module_traverse *prev)
412 unsigned int i;
413 struct module_traverse traverse = { .prev = prev, .mod = module };
415 if (in_loop(module, prev)) {
416 report_loop(module, &traverse);
417 return 1;
420 for (i = 0; i < module->num_deps; i++)
421 if (has_dep_loop(module->deps[i], &traverse))
422 return 1;
423 return 0;
426 /* Uniquifies and orders a dependency list. */
427 static void order_dep_list(struct module *start, struct module *mod)
429 unsigned int i;
431 for (i = 0; i < mod->num_deps; i++) {
432 /* If it was previously depended on, move it to the
433 tail. ie. if a needs b and c, and c needs b, we
434 must order b after c. */
435 list_del(&mod->deps[i]->dep_list);
436 list_add_tail(&mod->deps[i]->dep_list, &start->dep_list);
437 order_dep_list(start, mod->deps[i]);
441 static struct module *deleted = NULL;
443 static void del_module(struct module **modules, struct module *delme)
445 struct module **i;
447 /* Find pointer to it. */
448 if (modules) {
449 for (i = modules; *i != delme; i = &(*i)->next);
451 *i = delme->next;
454 /* Save on a list to quiet valgrind.
455 Can't free - other modules may depend on them */
456 delme->next = deleted;
457 deleted = delme;
460 /* Convert filename to the module name. Works if filename == modname, too. */
461 static void filename2modname(char *modname, const char *filename)
463 const char *afterslash;
464 unsigned int i;
466 afterslash = strrchr(filename, '/');
467 if (!afterslash)
468 afterslash = filename;
469 else
470 afterslash++;
472 /* Convert to underscores, stop at first . */
473 for (i = 0; afterslash[i] && afterslash[i] != '.'; i++) {
474 if (afterslash[i] == '-')
475 modname[i] = '_';
476 else
477 modname[i] = afterslash[i];
479 modname[i] = '\0';
482 /* convert to relative path if possible */
483 static const char *compress_path(const char *path, const char *basedir)
485 int len = strlen(basedir);
487 if (strncmp(path, basedir, len) == 0)
488 path += len + 1;
489 return path;
492 static void output_deps(struct module *modules,
493 FILE *out, char *dirname)
495 struct module *i;
497 for (i = modules; i; i = i->next) {
498 struct list_head *j, *tmp;
499 order_dep_list(i, i);
501 fprintf(out, "%s:", compress_path(i->pathname, dirname));
502 list_for_each_safe(j, tmp, &i->dep_list) {
503 struct module *dep
504 = list_entry(j, struct module, dep_list);
505 fprintf(out, " %s",
506 compress_path(dep->pathname, dirname));
507 list_del_init(j);
509 fprintf(out, "\n");
513 /* warn whenever duplicate module aliases, deps, or symbols are found. */
514 int warn_dups = 0;
516 static void output_deps_bin(struct module *modules,
517 FILE *out, char *dirname)
519 struct module *i;
520 struct index_node *index;
521 char *line;
522 char *p;
524 index = index_create();
526 for (i = modules; i; i = i->next) {
527 struct list_head *j, *tmp;
528 char modname[strlen(i->pathname)+1];
530 order_dep_list(i, i);
532 filename2modname(modname, i->pathname);
533 nofail_asprintf(&line, "%s:",
534 compress_path(i->pathname, dirname));
535 p = line;
536 list_for_each_safe(j, tmp, &i->dep_list) {
537 struct module *dep
538 = list_entry(j, struct module, dep_list);
539 nofail_asprintf(&line, "%s %s",
541 compress_path(dep->pathname, dirname));
542 free(p);
543 p = line;
544 list_del_init(j);
546 if (index_insert(index, modname, line, i->order) && warn_dups)
547 warn("duplicate module deps:\n%s\n",line);
548 free(line);
551 index_write(index, out);
552 index_destroy(index);
556 static int smells_like_module(const char *name)
558 return ends_in(name,".ko") || ends_in(name, ".ko.gz");
561 typedef struct module *(*do_module_t)(const char *dirname,
562 const char *filename,
563 struct module *next,
564 struct module_search *search,
565 struct module_overrides *overrides);
567 static int is_higher_priority(const char *newpath, const char *oldpath,
568 struct module_search *search,
569 struct module_overrides *overrides)
571 struct module_search *tmp;
572 struct module_overrides *ovtmp;
573 int i = 0;
574 int prio_builtin = -1;
575 int prio_new = -1;
576 int prio_old = -1;
578 /* The names already match, now we check for overrides and directory search
579 * order
581 for (ovtmp = overrides; ovtmp != NULL; ovtmp = ovtmp->next) {
582 if (strcmp(ovtmp->modfile, newpath) == 0)
583 return 1;
584 if (strcmp(ovtmp->modfile, oldpath) == 0)
585 return 0;
587 for (i = 0, tmp = search; tmp != NULL; tmp = tmp->next, i++) {
588 if (strcmp(tmp->search_path, MODULE_BUILTIN_KEY) == 0)
589 prio_builtin = i;
590 else if (strncmp(tmp->search_path, newpath, tmp->len) == 0)
591 prio_new = i;
592 else if (strncmp(tmp->search_path, oldpath, tmp->len) == 0)
593 prio_old = i;
595 if (prio_new < 0)
596 prio_new = prio_builtin;
597 if (prio_old < 0)
598 prio_old = prio_builtin;
600 return prio_new > prio_old;
604 static struct module *do_module(const char *dirname,
605 const char *filename,
606 struct module *list,
607 struct module_search *search,
608 struct module_overrides *overrides)
610 struct module *new, **i;
612 new = grab_module(dirname, filename);
613 if (!new)
614 return list;
616 /* Check if module is already in the list. */
617 for (i = &list; *i; i = &(*i)->next) {
619 if (streq((*i)->basename, filename)) {
620 char newpath[strlen(dirname) + strlen("/")
621 + strlen(filename) + 1];
623 sprintf(newpath, "%s/%s", dirname, filename);
625 if (is_higher_priority(newpath, (*i)->pathname,search,
626 overrides)) {
627 del_module(i, *i);
629 new->next = *i;
630 *i = new;
631 } else
632 del_module(NULL, new);
634 return list;
638 /* Not in the list already. Just prepend. */
639 new->next = list;
640 return new;
643 static struct module *grab_dir(const char *dirname,
644 DIR *dir,
645 struct module *next,
646 do_module_t do_mod,
647 struct module_search *search,
648 struct module_overrides *overrides)
650 struct dirent *dirent;
652 while ((dirent = readdir(dir)) != NULL) {
653 if (smells_like_module(dirent->d_name))
654 next = do_mod(dirname, dirent->d_name, next,
655 search, overrides);
656 else if (!streq(dirent->d_name, ".")
657 && !streq(dirent->d_name, "..")
658 && !streq(dirent->d_name, "source")
659 && !streq(dirent->d_name, "build")) {
661 DIR *sub;
662 char subdir[strlen(dirname) + 1
663 + strlen(dirent->d_name) + 1];
664 sprintf(subdir, "%s/%s", dirname, dirent->d_name);
665 sub = opendir(subdir);
666 if (sub) {
667 next = grab_dir(subdir, sub, next, do_mod,
668 search, overrides);
669 closedir(sub);
673 return next;
676 static struct module *grab_basedir(const char *dirname,
677 struct module_search *search,
678 struct module_overrides *overrides)
680 DIR *dir;
681 struct module *list;
683 dir = opendir(dirname);
684 if (!dir) {
685 warn("Couldn't open directory %s: %s\n",
686 dirname, strerror(errno));
687 return NULL;
689 list = grab_dir(dirname, dir, NULL, do_module, search, overrides);
690 closedir(dir);
692 return list;
695 static struct module *sort_modules(const char *dirname, struct module *list)
697 struct module *tlist = NULL, **tpos = &tlist;
698 FILE *modorder;
699 int dir_len = strlen(dirname) + 1;
700 char file_name[dir_len + strlen("modules.order") + 1];
701 char line[10240];
702 unsigned int linenum = 0;
704 sprintf(file_name, "%s/%s", dirname, "modules.order");
706 modorder = fopen(file_name, "r");
707 if (!modorder) {
708 /* Older kernels don't generate modules.order. Just
709 return if the file doesn't exist. */
710 if (errno == ENOENT)
711 return list;
712 fatal("Could not open '%s': %s\n", file_name, strerror(errno));
715 sprintf(line, "%s/", dirname);
717 /* move modules listed in modorder file to tlist in order */
718 while (fgets(line, sizeof(line), modorder)) {
719 struct module **pos, *mod;
720 int len = strlen(line);
722 linenum++;
723 if (line[len - 1] == '\n')
724 line[len - 1] = '\0';
726 for (pos = &list; (mod = *pos); pos = &(*pos)->next) {
727 if (strcmp(line, mod->pathname + dir_len) == 0) {
728 mod->order = linenum;
729 *pos = mod->next;
730 mod->next = NULL;
731 *tpos = mod;
732 tpos = &mod->next;
733 break;
738 /* append the rest */
739 *tpos = list;
741 fclose(modorder);
743 return tlist;
746 static struct module *parse_modules(struct module *list)
748 struct module *i;
750 for (i = list; i; i = i->next) {
751 i->ops->load_symbols(i);
752 i->ops->fetch_tables(i);
755 for (i = list; i; i = i->next)
756 i->ops->calculate_deps(i, verbose);
758 /* Strip out modules with dependency loops. */
759 again:
760 for (i = list; i; i = i->next) {
761 if (has_dep_loop(i, NULL)) {
762 warn("Module %s ignored, due to loop\n",
763 i->pathname + skipchars);
764 del_module(&list, i);
765 goto again;
769 return list;
772 /* Simply dump hash table. */
773 static void output_symbols(struct module *unused, FILE *out, char *dirname)
775 unsigned int i;
777 fprintf(out, "# Aliases for symbols, used by symbol_request().\n");
778 for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
779 struct symbol *s;
781 for (s = symbolhash[i]; s; s = s->next) {
782 if (s->owner) {
783 char modname[strlen(s->owner->pathname)+1];
784 filename2modname(modname, s->owner->pathname);
785 fprintf(out, "alias symbol:%s %s\n",
786 s->name, modname);
792 static void output_symbols_bin(struct module *unused, FILE *out, char *dirname)
794 struct index_node *index;
795 unsigned int i;
796 char *alias;
797 int duplicate;
799 index = index_create();
801 for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
802 struct symbol *s;
804 for (s = symbolhash[i]; s; s = s->next) {
805 if (s->owner) {
806 char modname[strlen(s->owner->pathname)+1];
807 filename2modname(modname, s->owner->pathname);
808 nofail_asprintf(&alias, "symbol:%s", s->name);
809 duplicate = index_insert(index, alias, modname,
810 s->owner->order);
811 if (duplicate && warn_dups)
812 warn("duplicate module syms:\n%s %s\n",
813 alias, modname);
814 free(alias);
819 index_write(index, out);
820 index_destroy(index);
823 static const char *next_string(const char *string, unsigned long *secsize)
825 /* Skip non-zero chars */
826 while (string[0]) {
827 string++;
828 if ((*secsize)-- <= 1)
829 return NULL;
832 /* Skip any zero padding. */
833 while (!string[0]) {
834 string++;
835 if ((*secsize)-- <= 1)
836 return NULL;
838 return string;
841 /* Careful! Don't munge - in [ ] as per Debian Bug#350915 */
842 static char *underscores(char *string)
844 unsigned int i;
846 if (!string)
847 return NULL;
849 for (i = 0; string[i]; i++) {
850 switch (string[i]) {
851 case '-':
852 string[i] = '_';
853 break;
855 case ']':
856 warn("Unmatched bracket in %s\n", string);
857 break;
859 case '[':
860 i += strcspn(&string[i], "]");
861 if (!string[i])
862 warn("Unmatched bracket in %s\n", string);
865 return string;
868 static void output_aliases(struct module *modules, FILE *out, char *dirname)
870 struct module *i;
871 const char *p;
872 unsigned long size;
874 fprintf(out, "# Aliases extracted from modules themselves.\n");
875 for (i = modules; i; i = i->next) {
876 char modname[strlen(i->pathname)+1];
878 filename2modname(modname, i->pathname);
880 /* Grab from old-style .modalias section. */
881 for (p = i->ops->get_aliases(i, &size);
883 p = next_string(p, &size))
884 fprintf(out, "alias %s %s\n", p, modname);
886 /* Grab form new-style .modinfo section. */
887 for (p = i->ops->get_modinfo(i, &size);
889 p = next_string(p, &size)) {
890 if (strncmp(p, "alias=", strlen("alias=")) == 0)
891 fprintf(out, "alias %s %s\n",
892 p + strlen("alias="), modname);
897 static void output_aliases_bin(struct module *modules, FILE *out, char *dirname)
899 struct module *i;
900 const char *p;
901 char *alias;
902 unsigned long size;
903 struct index_node *index;
904 int duplicate;
906 index = index_create();
908 for (i = modules; i; i = i->next) {
909 char modname[strlen(i->pathname)+1];
911 filename2modname(modname, i->pathname);
913 /* Grab from old-style .modalias section. */
914 for (p = i->ops->get_aliases(i, &size);
916 p = next_string(p, &size)) {
917 alias = NOFAIL(strdup(p));
918 underscores(alias);
919 duplicate = index_insert(index, alias, modname, i->order);
920 if (duplicate && warn_dups)
921 warn("duplicate module alias:\n%s %s\n",
922 alias, modname);
923 free(alias);
926 /* Grab from new-style .modinfo section. */
927 for (p = i->ops->get_modinfo(i, &size);
929 p = next_string(p, &size)) {
930 if (strncmp(p, "alias=", strlen("alias=")) == 0) {
931 alias = NOFAIL(strdup(p + strlen("alias=")));
932 underscores(alias);
933 duplicate = index_insert(index, alias, modname, i->order);
934 if (duplicate && warn_dups)
935 warn("duplicate module alias:\n%s %s\n",
936 alias, modname);
937 free(alias);
942 index_write(index, out);
943 index_destroy(index);
946 struct depfile {
947 char *name;
948 void (*func)(struct module *, FILE *, char *dirname);
949 int map_file;
952 static struct depfile depfiles[] = {
953 { "modules.dep", output_deps, 0 }, /* This is what we check for '-A'. */
954 { "modules.dep.bin", output_deps_bin, 0 },
955 { "modules.pcimap", output_pci_table, 1 },
956 { "modules.usbmap", output_usb_table, 1 },
957 { "modules.ccwmap", output_ccw_table, 1 },
958 { "modules.ieee1394map", output_ieee1394_table, 1 },
959 { "modules.isapnpmap", output_isapnp_table, 1 },
960 { "modules.inputmap", output_input_table, 1 },
961 { "modules.ofmap", output_of_table, 1 },
962 { "modules.seriomap", output_serio_table, 1 },
963 { "modules.alias", output_aliases, 0 },
964 { "modules.alias.bin", output_aliases_bin, 0 },
965 { "modules.symbols", output_symbols, 0 },
966 { "modules.symbols.bin", output_symbols_bin, 0 }
969 /* If we can't figure it out, it's safe to say "true". */
970 static int any_modules_newer(const char *dirname, time_t mtime)
972 DIR *dir;
973 struct dirent *dirent;
975 dir = opendir(dirname);
976 if (!dir)
977 return 1;
979 while ((dirent = readdir(dir)) != NULL) {
980 struct stat st;
981 char file[strlen(dirname) + 1 + strlen(dirent->d_name) + 1];
983 if (streq(dirent->d_name, ".") || streq(dirent->d_name, ".."))
984 continue;
986 sprintf(file, "%s/%s", dirname, dirent->d_name);
987 if (lstat(file, &st) != 0)
988 goto ret_true;
990 if (smells_like_module(dirent->d_name)) {
991 if (st.st_mtime > mtime)
992 goto ret_true;
993 } else if (S_ISDIR(st.st_mode)) {
994 if (any_modules_newer(file, mtime))
995 goto ret_true;
998 closedir(dir);
999 return 0;
1001 ret_true:
1002 closedir(dir);
1003 return 1;
1006 static int depfile_out_of_date(const char *dirname)
1008 struct stat st;
1009 char depfile[strlen(dirname) + 1 + strlen(depfiles[0].name) + 1];
1011 sprintf(depfile, "%s/%s", dirname, depfiles[0].name);
1013 if (stat(depfile, &st) != 0)
1014 return 1;
1016 return any_modules_newer(dirname, st.st_mtime);
1019 static char *getline_wrapped(FILE *file, unsigned int *linenum)
1021 int size = 256;
1022 int i = 0;
1023 char *buf = NOFAIL(malloc(size));
1024 for(;;) {
1025 int ch = getc_unlocked(file);
1027 switch(ch) {
1028 case EOF:
1029 if (i == 0) {
1030 free(buf);
1031 return NULL;
1033 /* else fall through */
1035 case '\n':
1036 if (linenum)
1037 (*linenum)++;
1038 if (i == size)
1039 buf = NOFAIL(realloc(buf, size + 1));
1040 buf[i] = '\0';
1041 return buf;
1043 case '\\':
1044 ch = getc_unlocked(file);
1046 if (ch == '\n') {
1047 if (linenum)
1048 (*linenum)++;
1049 continue;
1051 /* else fall through */
1053 default:
1054 buf[i++] = ch;
1056 if (i == size) {
1057 size *= 2;
1058 buf = NOFAIL(realloc(buf, size));
1065 static char *strsep_skipspace(char **string, char *delim)
1067 if (!*string)
1068 return NULL;
1069 *string += strspn(*string, delim);
1070 return strsep(string, delim);
1073 static struct module_search *add_search(const char *search_path,
1074 size_t len,
1075 struct module_search *search)
1078 struct module_search *new;
1080 new = NOFAIL(malloc(sizeof(*new)));
1081 new->search_path = NOFAIL(strdup(search_path));
1082 new->len = len;
1083 new->next = search;
1085 return new;
1089 static struct module_overrides *add_override(const char *modfile,
1090 struct module_overrides *overrides)
1093 struct module_overrides *new;
1095 new = NOFAIL(malloc(sizeof(*new)));
1096 new->modfile = NOFAIL(strdup(modfile));
1097 new->next = overrides;
1099 return new;
1103 static int parse_config_scan(const char *filename,
1104 const char *basedir,
1105 const char *kernelversion,
1106 struct module_search **search,
1107 struct module_overrides **overrides);
1109 static int parse_config_file(const char *filename,
1110 const char *basedir,
1111 const char *kernelversion,
1112 struct module_search **search,
1113 struct module_overrides **overrides)
1115 char *line;
1116 unsigned int linenum = 0;
1117 FILE *cfile;
1119 cfile = fopen(filename, "r");
1120 if (!cfile) {
1121 if (errno != ENOENT)
1122 fatal("could not open '%s', reason: %s\n", filename,
1123 strerror(errno));
1124 return 0;
1127 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
1128 char *ptr = line;
1129 char *cmd, *modname;
1131 cmd = strsep_skipspace(&ptr, "\t ");
1133 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
1134 free(line);
1135 continue;
1138 if (strcmp(cmd, "search") == 0) {
1139 char *search_path;
1141 while ((search_path = strsep_skipspace(&ptr, "\t "))) {
1142 char *dirname;
1143 size_t len;
1145 if (strcmp(search_path,
1146 MODULE_BUILTIN_KEY) == 0) {
1147 *search = add_search(MODULE_BUILTIN_KEY,
1148 0, *search);
1149 continue;
1151 len = strlen(basedir)
1152 + strlen(MODULE_DIR)
1153 + strlen(kernelversion)
1155 + strlen(search_path);
1156 dirname = NOFAIL(malloc(len + 1));
1157 sprintf(dirname, "%s%s%s/%s", basedir,
1158 MODULE_DIR, kernelversion, search_path);
1159 *search = add_search(dirname, len, *search);
1160 free(dirname);
1162 } else if (strcmp(cmd, "override") == 0) {
1163 char *pathname = NULL, *version, *subdir;
1164 modname = strsep_skipspace(&ptr, "\t ");
1165 version = strsep_skipspace(&ptr, "\t ");
1166 subdir = strsep_skipspace(&ptr, "\t ");
1168 if (strcmp(version, kernelversion) != 0 &&
1169 strcmp(version, "*") != 0)
1170 continue;
1172 pathname = NOFAIL(malloc(strlen(basedir)
1173 + strlen(MODULE_DIR)
1174 + strlen(kernelversion)
1175 + strlen(subdir)
1176 + strlen(modname)
1177 + strlen(".ko")
1178 + 3));
1179 sprintf(pathname, "%s%s%s/%s/%s.ko", basedir,
1180 MODULE_DIR, kernelversion, subdir, modname);
1182 *overrides = add_override(pathname, *overrides);
1183 free(pathname);
1184 } else if (strcmp(cmd, "include") == 0) {
1185 char *newfilename;
1187 newfilename = strsep_skipspace(&ptr, "\t ");
1188 if (!newfilename) {
1189 grammar(cmd, filename, linenum);
1190 } else {
1191 warn("\"include %s\" is deprecated, "
1192 "please use /etc/depmod.d\n", newfilename);
1193 if (strncmp(newfilename, "/etc/depmod.d",
1194 strlen("/etc/depmod.d")) == 0) {
1195 warn("\"include /etc/depmod.d\" is "
1196 "the default, ignored\n");
1197 } else {
1198 if (!parse_config_scan(newfilename, basedir,
1199 kernelversion,
1200 search, overrides))
1201 warn("Failed to open included"
1202 " config file %s: %s\n",
1203 newfilename, strerror(errno));
1206 } else if (strcmp(cmd, "make_map_files") == 0) {
1207 char *option;
1209 option = strsep_skipspace(&ptr, "\t ");
1210 if (!option)
1211 grammar(cmd, filename, linenum);
1212 else {
1213 if (0 == strncmp(option, "yes", 3))
1214 make_map_files = 1;
1215 else if (0 == strncmp(option, "no", 2))
1216 make_map_files = 0;
1217 else
1218 grammar(cmd, filename, linenum);
1220 } else
1221 grammar(cmd, filename, linenum);
1223 free(line);
1225 fclose(cfile);
1226 return 1;
1229 static int parse_config_scan(const char *filename,
1230 const char *basedir,
1231 const char *kernelversion,
1232 struct module_search **search,
1233 struct module_overrides **overrides)
1235 DIR *dir;
1236 int ret = 0;
1238 dir = opendir(filename);
1239 if (dir) {
1240 struct file_entry {
1241 struct list_head node;
1242 char name[];
1244 LIST_HEAD(files_list);
1245 struct file_entry *fe, *fe_tmp;
1246 struct dirent *i;
1248 /* sort files from directory into list */
1249 while ((i = readdir(dir)) != NULL) {
1250 size_t len;
1252 if (i->d_name[0] == '.')
1253 continue;
1254 if (!config_filter(i->d_name))
1255 continue;
1257 len = strlen(i->d_name);
1258 if (len < 6 || strcmp(&i->d_name[len-5], ".conf") != 0)
1259 warn("All config files need .conf: %s/%s, "
1260 "it will be ignored in a future release.\n",
1261 filename, i->d_name);
1262 fe = malloc(sizeof(struct file_entry) + len + 1);
1263 if (fe == NULL)
1264 continue;
1265 strcpy(fe->name, i->d_name);
1266 list_for_each_entry(fe_tmp, &files_list, node)
1267 if (strcmp(fe_tmp->name, fe->name) >= 0)
1268 break;
1269 list_add_tail(&fe->node, &fe_tmp->node);
1271 closedir(dir);
1273 /* parse list of files */
1274 list_for_each_entry_safe(fe, fe_tmp, &files_list, node) {
1275 char *cfgfile;
1277 nofail_asprintf(&cfgfile, "%s/%s", filename, fe->name);
1278 if (!parse_config_file(cfgfile, basedir, kernelversion,
1279 search, overrides))
1280 warn("Failed to open config file "
1281 "%s: %s\n", fe->name, strerror(errno));
1282 free(cfgfile);
1283 list_del(&fe->node);
1284 free(fe);
1287 ret = 1;
1288 } else {
1289 if (parse_config_file(filename, basedir, kernelversion, search,
1290 overrides))
1291 ret = 1;
1294 return ret;
1297 static void parse_toplevel_config(const char *filename,
1298 const char *basedir,
1299 const char *kernelversion,
1300 struct module_search **search,
1301 struct module_overrides **overrides)
1303 if (filename) {
1304 if (!parse_config_scan(filename, basedir, kernelversion, search,
1305 overrides))
1306 fatal("Failed to open config file %s: %s\n",
1307 filename, strerror(errno));
1308 return;
1311 /* deprecated config file */
1312 if (parse_config_file("/etc/depmod.conf", basedir, kernelversion,
1313 search, overrides) > 0)
1314 warn("Deprecated config file /etc/depmod.conf, "
1315 "all config files belong into /etc/depmod.d/.\n");
1317 /* default config */
1318 parse_config_scan("/etc/depmod.d", basedir, kernelversion,
1319 search, overrides);
1322 /* Local to main, but not freed on exit. Keep valgrind quiet. */
1323 struct module *list = NULL;
1324 struct module_search *search = NULL;
1325 struct module_overrides *overrides = NULL;
1327 int main(int argc, char *argv[])
1329 int opt, all = 0, maybe_all = 0, doing_stdout = 0;
1330 char *basedir = "", *dirname, *version, *badopt = NULL,
1331 *system_map = NULL;
1332 int i;
1333 const char *config = NULL;
1335 /* Don't print out any errors just yet, we might want to exec
1336 backwards compat version. */
1337 opterr = 0;
1338 while ((opt = getopt_long(argc, argv, "ab:ArehnqruvVF:C:wm", options, NULL))
1339 != -1) {
1340 switch (opt) {
1341 case 'a':
1342 all = 1;
1343 break;
1344 case 'b':
1345 basedir = optarg;
1346 skipchars = strlen(basedir);
1347 break;
1348 case 'A':
1349 maybe_all = 1;
1350 break;
1351 case 'F':
1352 system_map = optarg;
1353 break;
1354 case 'e':
1355 print_unknown = 1;
1356 break;
1357 case 'v':
1358 verbose = 1;
1359 break;
1360 case 'u':
1361 case 'q':
1362 case 'r':
1363 break;
1364 case 'C':
1365 config = optarg;
1366 break;
1367 case 'h':
1368 print_usage(argv[0]);
1369 exit(0);
1370 break;
1371 case 'n':
1372 doing_stdout = 1;
1373 break;
1374 case 'V':
1375 printf("%s %s\n", PACKAGE, VERSION);
1376 exit(0);
1377 case 'w':
1378 warn_dups = 1;
1379 break;
1380 case 'm':
1381 force_map_files = 1;
1382 break;
1383 default:
1384 badopt = argv[optind-1];
1388 /* We can't print unknowns without a System.map */
1389 if (!system_map)
1390 print_unknown = 0;
1391 else
1392 load_system_map(system_map);
1394 /* They can specify the version naked on the command line */
1395 if (optind < argc && is_version_number(argv[optind])) {
1396 version = NOFAIL(strdup(argv[optind]));
1397 optind++;
1398 } else {
1399 struct utsname buf;
1400 uname(&buf);
1401 version = NOFAIL(strdup(buf.release));
1404 /* Run old version if required. */
1405 if (old_module_version(version))
1406 exec_old_depmod(argv);
1408 if (badopt) {
1409 fprintf(stderr, "%s: malformed/unrecognized option '%s'\n",
1410 argv[0], badopt);
1411 print_usage(argv[0]);
1412 exit(1);
1415 /* Depmod -a by default if no names. */
1416 if (optind == argc)
1417 all = 1;
1419 dirname = NOFAIL(malloc(strlen(basedir)
1420 + strlen(MODULE_DIR)
1421 + strlen(version) + 1));
1422 sprintf(dirname, "%s%s%s", basedir, MODULE_DIR, version);
1424 if (maybe_all) {
1425 if (!doing_stdout && !depfile_out_of_date(dirname))
1426 exit(0);
1427 all = 1;
1430 parse_toplevel_config(config, basedir, version, &search, &overrides);
1432 /* For backward compatibility add "updates" to the head of the search
1433 * list here. But only if there was no "search" option specified.
1435 if (!search) {
1436 char *dirname;
1437 size_t len;
1439 len = strlen(basedir)
1440 + strlen(MODULE_DIR)
1441 + strlen(version)
1442 + strlen("/updates");
1443 dirname = NOFAIL(malloc(len + 1));
1444 sprintf(dirname, "%s%s%s/updates", basedir,
1445 MODULE_DIR, version);
1446 search = add_search(dirname, len, search);
1448 if (!all) {
1449 /* Do command line args. */
1450 for (opt = optind; opt < argc; opt++) {
1451 struct module *new;
1453 if (argv[opt][0] != '/')
1454 fatal("modules must be specified using absolute paths.\n"
1455 "\"%s\" is a relative path\n", argv[opt]);
1457 new = grab_module(NULL, argv[opt]);
1458 if (!new) {
1459 /* cmd-line specified modules must exist */
1460 fatal("grab_module() failed for module %s\n", argv[opt]);
1462 new->next = list;
1463 list = new;
1465 } else {
1466 list = grab_basedir(dirname,search,overrides);
1468 list = sort_modules(dirname,list);
1469 list = parse_modules(list);
1471 for (i = 0; i < sizeof(depfiles)/sizeof(depfiles[0]); i++) {
1472 FILE *out;
1473 struct depfile *d = &depfiles[i];
1474 char depname[strlen(dirname) + 1 + strlen(d->name) + 1];
1475 char tmpname[strlen(dirname) + 1 + strlen(d->name) +
1476 strlen(".temp") + 1];
1478 if (d->map_file && !make_map_files && !force_map_files)
1479 continue;
1481 sprintf(depname, "%s/%s", dirname, d->name);
1482 sprintf(tmpname, "%s/%s.temp", dirname, d->name);
1483 if (!doing_stdout) {
1484 out = fopen(tmpname, "w");
1485 if (!out)
1486 fatal("Could not open %s for writing: %s\n",
1487 tmpname, strerror(errno));
1488 } else {
1489 out = stdout;
1490 if (ends_in(depname, ".bin"))
1491 continue;
1493 d->func(list, out, dirname);
1494 if (!doing_stdout) {
1495 fclose(out);
1496 if (rename(tmpname, depname) < 0)
1497 fatal("Could not rename %s into %s: %s\n",
1498 tmpname, depname, strerror(errno));
1502 free(dirname);
1503 free(version);
1505 return 0;