depmod: fix is_higher_priority()
[mit.git] / depmod.c
blobae663d92b0a354685496ad80beb52aa97a731f0c
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 static void output_deps(struct module *modules,
483 FILE *out, char *dirname)
485 struct module *i;
487 for (i = modules; i; i = i->next) {
488 struct list_head *j, *tmp;
489 order_dep_list(i, i);
491 fprintf(out, "%s:", i->pathname + strlen(dirname)+1);
492 list_for_each_safe(j, tmp, &i->dep_list) {
493 struct module *dep
494 = list_entry(j, struct module, dep_list);
495 fprintf(out, " %s", dep->pathname + strlen(dirname)+1);
496 list_del_init(j);
498 fprintf(out, "\n");
502 /* warn whenever duplicate module aliases, deps, or symbols are found. */
503 int warn_dups = 0;
505 static void output_deps_bin(struct module *modules,
506 FILE *out, char *dirname)
508 struct module *i;
509 struct index_node *index;
510 char *line;
511 char *p;
513 index = index_create();
515 for (i = modules; i; i = i->next) {
516 struct list_head *j, *tmp;
517 char modname[strlen(i->pathname)+1];
519 order_dep_list(i, i);
521 filename2modname(modname, i->pathname + strlen(dirname)+1);
522 nofail_asprintf(&line, "%s:", i->pathname + strlen(dirname)+1);
523 p = line;
524 list_for_each_safe(j, tmp, &i->dep_list) {
525 struct module *dep
526 = list_entry(j, struct module, dep_list);
527 nofail_asprintf(&line, "%s %s", p, dep->pathname + strlen(dirname)+1);
528 free(p);
529 p = line;
530 list_del_init(j);
532 if (index_insert(index, modname, line, i->order) && warn_dups)
533 warn("duplicate module deps:\n%s\n",line);
534 free(line);
537 index_write(index, out);
538 index_destroy(index);
542 static int smells_like_module(const char *name)
544 return ends_in(name,".ko") || ends_in(name, ".ko.gz");
547 typedef struct module *(*do_module_t)(const char *dirname,
548 const char *filename,
549 struct module *next,
550 struct module_search *search,
551 struct module_overrides *overrides);
553 static int is_higher_priority(const char *newpath, const char *oldpath,
554 struct module_search *search,
555 struct module_overrides *overrides)
557 struct module_search *tmp;
558 struct module_overrides *ovtmp;
559 int i = 0;
560 int prio_builtin = -1;
561 int prio_new = -1;
562 int prio_old = -1;
564 /* The names already match, now we check for overrides and directory search
565 * order
567 for (ovtmp = overrides; ovtmp != NULL; ovtmp = ovtmp->next) {
568 if (strcmp(ovtmp->modfile, newpath) == 0)
569 return 1;
570 if (strcmp(ovtmp->modfile, oldpath) == 0)
571 return 0;
573 for (i = 0, tmp = search; tmp != NULL; tmp = tmp->next, i++) {
574 if (strcmp(tmp->search_path, MODULE_BUILTIN_KEY) == 0)
575 prio_builtin = i;
576 else if (strncmp(tmp->search_path, newpath, tmp->len) == 0)
577 prio_new = i;
578 else if (strncmp(tmp->search_path, oldpath, tmp->len) == 0)
579 prio_old = i;
581 if (prio_builtin < 0)
582 prio_builtin = i;
583 if (prio_new < 0)
584 prio_new = prio_builtin;
585 if (prio_old < 0)
586 prio_old = prio_builtin;
588 return prio_new > prio_old;
592 static struct module *do_module(const char *dirname,
593 const char *filename,
594 struct module *list,
595 struct module_search *search,
596 struct module_overrides *overrides)
598 struct module *new, **i;
600 new = grab_module(dirname, filename);
601 if (!new)
602 return list;
604 /* Check if module is already in the list. */
605 for (i = &list; *i; i = &(*i)->next) {
607 if (streq((*i)->basename, filename)) {
608 char newpath[strlen(dirname) + strlen("/")
609 + strlen(filename) + 1];
611 sprintf(newpath, "%s/%s", dirname, filename);
613 if (is_higher_priority(newpath, (*i)->pathname,search,
614 overrides)) {
615 del_module(i, *i);
617 new->next = *i;
618 *i = new;
619 } else
620 del_module(NULL, new);
622 return list;
626 /* Not in the list already. Just prepend. */
627 new->next = list;
628 return new;
631 static struct module *grab_dir(const char *dirname,
632 DIR *dir,
633 struct module *next,
634 do_module_t do_mod,
635 struct module_search *search,
636 struct module_overrides *overrides)
638 struct dirent *dirent;
640 while ((dirent = readdir(dir)) != NULL) {
641 if (smells_like_module(dirent->d_name))
642 next = do_mod(dirname, dirent->d_name, next,
643 search, overrides);
644 else if (!streq(dirent->d_name, ".")
645 && !streq(dirent->d_name, "..")
646 && !streq(dirent->d_name, "source")
647 && !streq(dirent->d_name, "build")) {
649 DIR *sub;
650 char subdir[strlen(dirname) + 1
651 + strlen(dirent->d_name) + 1];
652 sprintf(subdir, "%s/%s", dirname, dirent->d_name);
653 sub = opendir(subdir);
654 if (sub) {
655 next = grab_dir(subdir, sub, next, do_mod,
656 search, overrides);
657 closedir(sub);
661 return next;
664 static struct module *grab_basedir(const char *dirname,
665 struct module_search *search,
666 struct module_overrides *overrides)
668 DIR *dir;
669 struct module *list;
671 dir = opendir(dirname);
672 if (!dir) {
673 warn("Couldn't open directory %s: %s\n",
674 dirname, strerror(errno));
675 return NULL;
677 list = grab_dir(dirname, dir, NULL, do_module, search, overrides);
678 closedir(dir);
680 return list;
683 static struct module *sort_modules(const char *dirname, struct module *list)
685 struct module *tlist = NULL, **tpos = &tlist;
686 FILE *modorder;
687 int dir_len = strlen(dirname) + 1;
688 char file_name[dir_len + strlen("modules.order") + 1];
689 char line[10240];
690 unsigned int linenum = 0;
692 sprintf(file_name, "%s/%s", dirname, "modules.order");
694 modorder = fopen(file_name, "r");
695 if (!modorder) {
696 /* Older kernels don't generate modules.order. Just
697 return if the file doesn't exist. */
698 if (errno == ENOENT)
699 return list;
700 fatal("Could not open '%s': %s\n", file_name, strerror(errno));
703 sprintf(line, "%s/", dirname);
705 /* move modules listed in modorder file to tlist in order */
706 while (fgets(line, sizeof(line), modorder)) {
707 struct module **pos, *mod;
708 int len = strlen(line);
710 linenum++;
711 if (line[len - 1] == '\n')
712 line[len - 1] = '\0';
714 for (pos = &list; (mod = *pos); pos = &(*pos)->next) {
715 if (strcmp(line, mod->pathname + dir_len) == 0) {
716 mod->order = linenum;
717 *pos = mod->next;
718 mod->next = NULL;
719 *tpos = mod;
720 tpos = &mod->next;
721 break;
726 /* append the rest */
727 *tpos = list;
729 fclose(modorder);
731 return tlist;
734 static struct module *parse_modules(struct module *list)
736 struct module *i;
738 for (i = list; i; i = i->next) {
739 i->ops->load_symbols(i);
740 i->ops->fetch_tables(i);
743 for (i = list; i; i = i->next)
744 i->ops->calculate_deps(i, verbose);
746 /* Strip out modules with dependency loops. */
747 again:
748 for (i = list; i; i = i->next) {
749 if (has_dep_loop(i, NULL)) {
750 warn("Module %s ignored, due to loop\n",
751 i->pathname + skipchars);
752 del_module(&list, i);
753 goto again;
757 return list;
760 /* Simply dump hash table. */
761 static void output_symbols(struct module *unused, FILE *out, char *dirname)
763 unsigned int i;
765 fprintf(out, "# Aliases for symbols, used by symbol_request().\n");
766 for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
767 struct symbol *s;
769 for (s = symbolhash[i]; s; s = s->next) {
770 if (s->owner) {
771 char modname[strlen(s->owner->pathname)+1];
772 filename2modname(modname, s->owner->pathname);
773 fprintf(out, "alias symbol:%s %s\n",
774 s->name, modname);
780 static void output_symbols_bin(struct module *unused, FILE *out, char *dirname)
782 struct index_node *index;
783 unsigned int i;
784 char *alias;
785 int duplicate;
787 index = index_create();
789 for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
790 struct symbol *s;
792 for (s = symbolhash[i]; s; s = s->next) {
793 if (s->owner) {
794 char modname[strlen(s->owner->pathname)+1];
795 filename2modname(modname, s->owner->pathname);
796 nofail_asprintf(&alias, "symbol:%s", s->name);
797 duplicate = index_insert(index, alias, modname,
798 s->owner->order);
799 if (duplicate && warn_dups)
800 warn("duplicate module syms:\n%s %s\n",
801 alias, modname);
802 free(alias);
807 index_write(index, out);
808 index_destroy(index);
811 static const char *next_string(const char *string, unsigned long *secsize)
813 /* Skip non-zero chars */
814 while (string[0]) {
815 string++;
816 if ((*secsize)-- <= 1)
817 return NULL;
820 /* Skip any zero padding. */
821 while (!string[0]) {
822 string++;
823 if ((*secsize)-- <= 1)
824 return NULL;
826 return string;
829 /* Careful! Don't munge - in [ ] as per Debian Bug#350915 */
830 static char *underscores(char *string)
832 unsigned int i;
834 if (!string)
835 return NULL;
837 for (i = 0; string[i]; i++) {
838 switch (string[i]) {
839 case '-':
840 string[i] = '_';
841 break;
843 case '[':
844 i += strcspn(&string[i], "]");
845 if (!string[i])
846 warn("Unmatched bracket in %s\n", string);
849 return string;
852 static void output_aliases(struct module *modules, FILE *out, char *dirname)
854 struct module *i;
855 const char *p;
856 unsigned long size;
858 fprintf(out, "# Aliases extracted from modules themselves.\n");
859 for (i = modules; i; i = i->next) {
860 char modname[strlen(i->pathname)+1];
862 filename2modname(modname, i->pathname);
864 /* Grab from old-style .modalias section. */
865 for (p = i->ops->get_aliases(i, &size);
867 p = next_string(p, &size))
868 fprintf(out, "alias %s %s\n", p, modname);
870 /* Grab form new-style .modinfo section. */
871 for (p = i->ops->get_modinfo(i, &size);
873 p = next_string(p, &size)) {
874 if (strncmp(p, "alias=", strlen("alias=")) == 0)
875 fprintf(out, "alias %s %s\n",
876 p + strlen("alias="), modname);
881 static void output_aliases_bin(struct module *modules, FILE *out, char *dirname)
883 struct module *i;
884 const char *p;
885 char *alias;
886 unsigned long size;
887 struct index_node *index;
888 int duplicate;
890 index = index_create();
892 for (i = modules; i; i = i->next) {
893 char modname[strlen(i->pathname)+1];
895 filename2modname(modname, i->pathname);
897 /* Grab from old-style .modalias section. */
898 for (p = i->ops->get_aliases(i, &size);
900 p = next_string(p, &size)) {
901 alias = NOFAIL(strdup(p));
902 underscores(alias);
903 duplicate = index_insert(index, alias, modname, i->order);
904 if (duplicate && warn_dups)
905 warn("duplicate module alias:\n%s %s\n",
906 alias, modname);
907 free(alias);
910 /* Grab from new-style .modinfo section. */
911 for (p = i->ops->get_modinfo(i, &size);
913 p = next_string(p, &size)) {
914 if (strncmp(p, "alias=", strlen("alias=")) == 0) {
915 alias = NOFAIL(strdup(p + strlen("alias=")));
916 underscores(alias);
917 duplicate = index_insert(index, alias, modname, i->order);
918 if (duplicate && warn_dups)
919 warn("duplicate module alias:\n%s %s\n",
920 alias, modname);
921 free(alias);
926 index_write(index, out);
927 index_destroy(index);
930 struct depfile {
931 char *name;
932 void (*func)(struct module *, FILE *, char *dirname);
933 int map_file;
936 static struct depfile depfiles[] = {
937 { "modules.dep", output_deps, 0 }, /* This is what we check for '-A'. */
938 { "modules.dep.bin", output_deps_bin, 0 },
939 { "modules.pcimap", output_pci_table, 1 },
940 { "modules.usbmap", output_usb_table, 1 },
941 { "modules.ccwmap", output_ccw_table, 1 },
942 { "modules.ieee1394map", output_ieee1394_table, 1 },
943 { "modules.isapnpmap", output_isapnp_table, 1 },
944 { "modules.inputmap", output_input_table, 1 },
945 { "modules.ofmap", output_of_table, 1 },
946 { "modules.seriomap", output_serio_table, 1 },
947 { "modules.alias", output_aliases, 0 },
948 { "modules.alias.bin", output_aliases_bin, 0 },
949 { "modules.symbols", output_symbols, 0 },
950 { "modules.symbols.bin", output_symbols_bin, 0 }
953 /* If we can't figure it out, it's safe to say "true". */
954 static int any_modules_newer(const char *dirname, time_t mtime)
956 DIR *dir;
957 struct dirent *dirent;
959 dir = opendir(dirname);
960 if (!dir)
961 return 1;
963 while ((dirent = readdir(dir)) != NULL) {
964 struct stat st;
965 char file[strlen(dirname) + 1 + strlen(dirent->d_name) + 1];
967 if (streq(dirent->d_name, ".") || streq(dirent->d_name, ".."))
968 continue;
970 sprintf(file, "%s/%s", dirname, dirent->d_name);
971 if (lstat(file, &st) != 0)
972 goto ret_true;
974 if (smells_like_module(dirent->d_name)) {
975 if (st.st_mtime > mtime)
976 goto ret_true;
977 } else if (S_ISDIR(st.st_mode)) {
978 if (any_modules_newer(file, mtime))
979 goto ret_true;
982 closedir(dir);
983 return 0;
985 ret_true:
986 closedir(dir);
987 return 1;
990 static int depfile_out_of_date(const char *dirname)
992 struct stat st;
993 char depfile[strlen(dirname) + 1 + strlen(depfiles[0].name) + 1];
995 sprintf(depfile, "%s/%s", dirname, depfiles[0].name);
997 if (stat(depfile, &st) != 0)
998 return 1;
1000 return any_modules_newer(dirname, st.st_mtime);
1003 static char *getline_wrapped(FILE *file, unsigned int *linenum)
1005 int size = 256;
1006 int i = 0;
1007 char *buf = NOFAIL(malloc(size));
1008 for(;;) {
1009 int ch = getc_unlocked(file);
1011 switch(ch) {
1012 case EOF:
1013 if (i == 0) {
1014 free(buf);
1015 return NULL;
1017 /* else fall through */
1019 case '\n':
1020 if (linenum)
1021 (*linenum)++;
1022 if (i == size)
1023 buf = NOFAIL(realloc(buf, size + 1));
1024 buf[i] = '\0';
1025 return buf;
1027 case '\\':
1028 ch = getc_unlocked(file);
1030 if (ch == '\n') {
1031 if (linenum)
1032 (*linenum)++;
1033 continue;
1035 /* else fall through */
1037 default:
1038 buf[i++] = ch;
1040 if (i == size) {
1041 size *= 2;
1042 buf = NOFAIL(realloc(buf, size));
1049 static char *strsep_skipspace(char **string, char *delim)
1051 if (!*string)
1052 return NULL;
1053 *string += strspn(*string, delim);
1054 return strsep(string, delim);
1057 static struct module_search *add_search(const char *search_path,
1058 size_t len,
1059 struct module_search *search)
1062 struct module_search *new;
1064 new = NOFAIL(malloc(sizeof(*new)));
1065 new->search_path = NOFAIL(strdup(search_path));
1066 new->len = len;
1067 new->next = search;
1069 return new;
1073 static struct module_overrides *add_override(const char *modfile,
1074 struct module_overrides *overrides)
1077 struct module_overrides *new;
1079 new = NOFAIL(malloc(sizeof(*new)));
1080 new->modfile = NOFAIL(strdup(modfile));
1081 new->next = overrides;
1083 return new;
1087 /* Recursion */
1088 static int read_config(const char *filename,
1089 const char *basedir,
1090 const char *kernelversion,
1091 struct module_search **search,
1092 struct module_overrides **overrides);
1094 static int read_config_file(const char *filename,
1095 const char *basedir,
1096 const char *kernelversion,
1097 struct module_search **search,
1098 struct module_overrides **overrides)
1100 char *line;
1101 unsigned int linenum = 0;
1102 FILE *cfile;
1104 cfile = fopen(filename, "r");
1105 if (!cfile) {
1106 if (errno != ENOENT)
1107 fatal("could not open '%s', reason: %s\n", filename,
1108 strerror(errno));
1109 return 0;
1112 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
1113 char *ptr = line;
1114 char *cmd, *modname;
1116 cmd = strsep_skipspace(&ptr, "\t ");
1118 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
1119 free(line);
1120 continue;
1123 if (strcmp(cmd, "search") == 0) {
1124 char *search_path;
1126 while ((search_path = strsep_skipspace(&ptr, "\t "))) {
1127 char *dirname;
1128 size_t len;
1130 if (strcmp(search_path,
1131 MODULE_BUILTIN_KEY) == 0) {
1132 *search = add_search(MODULE_BUILTIN_KEY,
1133 0, *search);
1134 continue;
1136 len = strlen(basedir)
1137 + strlen(MODULE_DIR)
1138 + strlen(kernelversion)
1140 + strlen(search_path);
1141 dirname = NOFAIL(malloc(len + 1));
1142 sprintf(dirname, "%s%s%s/%s", basedir,
1143 MODULE_DIR, kernelversion, search_path);
1144 *search = add_search(dirname, len, *search);
1145 free(dirname);
1147 } else if (strcmp(cmd, "override") == 0) {
1148 char *pathname = NULL, *version, *subdir;
1149 modname = strsep_skipspace(&ptr, "\t ");
1150 version = strsep_skipspace(&ptr, "\t ");
1151 subdir = strsep_skipspace(&ptr, "\t ");
1153 if (strcmp(version, kernelversion) != 0 &&
1154 strcmp(version, "*") != 0)
1155 continue;
1157 pathname = NOFAIL(malloc(strlen(basedir)
1158 + strlen(MODULE_DIR)
1159 + strlen(kernelversion)
1160 + strlen(subdir)
1161 + strlen(modname)
1162 + strlen(".ko")
1163 + 3));
1164 sprintf(pathname, "%s%s%s/%s/%s.ko", basedir,
1165 MODULE_DIR, kernelversion, subdir, modname);
1167 *overrides = add_override(pathname, *overrides);
1168 free(pathname);
1169 } else if (strcmp(cmd, "include") == 0) {
1170 char *newfilename;
1172 newfilename = strsep_skipspace(&ptr, "\t ");
1173 if (!newfilename)
1174 grammar(cmd, filename, linenum);
1175 else {
1176 if (!read_config(newfilename, basedir,
1177 kernelversion,
1178 search, overrides))
1179 warn("Failed to open included"
1180 " config file %s: %s\n",
1181 newfilename, strerror(errno));
1184 } else if (strcmp(cmd, "make_map_files") == 0) {
1185 char *option;
1187 option = strsep_skipspace(&ptr, "\t ");
1188 if (!option)
1189 grammar(cmd, filename, linenum);
1190 else {
1191 if (0 == strncmp(option, "yes", 3))
1192 make_map_files = 1;
1193 else if (0 == strncmp(option, "no", 2))
1194 make_map_files = 0;
1195 else
1196 grammar(cmd, filename, linenum);
1198 } else
1199 grammar(cmd, filename, linenum);
1201 free(line);
1203 fclose(cfile);
1204 return 1;
1207 /* Simple format, ignore lines starting with #, one command per line.
1208 Returns true or false. */
1209 static int read_config(const char *filename,
1210 const char *basedir,
1211 const char *kernelversion,
1212 struct module_search **search,
1213 struct module_overrides **overrides)
1215 DIR *dir;
1216 int ret = 0;
1218 dir = opendir(filename);
1219 if (dir) {
1220 struct dirent *i;
1221 while ((i = readdir(dir)) != NULL) {
1222 if (!streq(i->d_name,".") && !streq(i->d_name,"..")
1223 && config_filter(i->d_name)) {
1224 char sub[strlen(filename) + 1
1225 + strlen(i->d_name) + 1];
1227 sprintf(sub, "%s/%s", filename, i->d_name);
1228 if (!read_config(sub, basedir, kernelversion,
1229 search, overrides))
1230 warn("Failed to open"
1231 " config file %s: %s\n",
1232 sub, strerror(errno));
1235 closedir(dir);
1236 ret = 1;
1237 } else {
1238 if (read_config_file(filename, basedir, kernelversion, search,
1239 overrides))
1240 ret = 1;
1243 return ret;
1246 static const char *default_configs[] =
1248 "/etc/depmod.conf",
1249 "/etc/depmod.d",
1252 static void read_toplevel_config(const char *filename,
1253 const char *basedir,
1254 const char *kernelversion,
1255 struct module_search **search,
1256 struct module_overrides **overrides)
1258 unsigned int i;
1260 if (filename) {
1261 if (!read_config(filename, basedir, kernelversion, search,
1262 overrides))
1263 fatal("Failed to open config file %s: %s\n",
1264 filename, strerror(errno));
1265 return;
1268 /* Try defaults. */
1269 for (i = 0; i < ARRAY_SIZE(default_configs); i++) {
1270 read_config(default_configs[i], basedir, kernelversion,
1271 search, overrides);
1275 /* Local to main, but not freed on exit. Keep valgrind quiet. */
1276 struct module *list = NULL;
1277 struct module_search *search = NULL;
1278 struct module_overrides *overrides = NULL;
1280 int main(int argc, char *argv[])
1282 int opt, all = 0, maybe_all = 0, doing_stdout = 0;
1283 char *basedir = "", *dirname, *version, *badopt = NULL,
1284 *system_map = NULL;
1285 int i;
1286 const char *config = NULL;
1288 /* Don't print out any errors just yet, we might want to exec
1289 backwards compat version. */
1290 opterr = 0;
1291 while ((opt = getopt_long(argc, argv, "ab:ArehnqruvVF:C:wm", options, NULL))
1292 != -1) {
1293 switch (opt) {
1294 case 'a':
1295 all = 1;
1296 break;
1297 case 'b':
1298 basedir = optarg;
1299 skipchars = strlen(basedir);
1300 break;
1301 case 'A':
1302 maybe_all = 1;
1303 break;
1304 case 'F':
1305 system_map = optarg;
1306 break;
1307 case 'e':
1308 print_unknown = 1;
1309 break;
1310 case 'v':
1311 verbose = 1;
1312 break;
1313 case 'u':
1314 case 'q':
1315 case 'r':
1316 break;
1317 case 'C':
1318 config = optarg;
1319 break;
1320 case 'h':
1321 print_usage(argv[0]);
1322 exit(0);
1323 break;
1324 case 'n':
1325 doing_stdout = 1;
1326 break;
1327 case 'V':
1328 printf("%s %s\n", PACKAGE, VERSION);
1329 exit(0);
1330 case 'w':
1331 warn_dups = 1;
1332 break;
1333 case 'm':
1334 force_map_files = 1;
1335 break;
1336 default:
1337 badopt = argv[optind-1];
1341 /* We can't print unknowns without a System.map */
1342 if (!system_map)
1343 print_unknown = 0;
1344 else
1345 load_system_map(system_map);
1347 /* They can specify the version naked on the command line */
1348 if (optind < argc && is_version_number(argv[optind])) {
1349 version = NOFAIL(strdup(argv[optind]));
1350 optind++;
1351 } else {
1352 struct utsname buf;
1353 uname(&buf);
1354 version = NOFAIL(strdup(buf.release));
1357 /* Run old version if required. */
1358 if (old_module_version(version))
1359 exec_old_depmod(argv);
1361 if (badopt) {
1362 fprintf(stderr, "%s: malformed/unrecognized option '%s'\n",
1363 argv[0], badopt);
1364 print_usage(argv[0]);
1365 exit(1);
1368 /* Depmod -a by default if no names. */
1369 if (optind == argc)
1370 all = 1;
1372 dirname = NOFAIL(malloc(strlen(basedir)
1373 + strlen(MODULE_DIR)
1374 + strlen(version) + 1));
1375 sprintf(dirname, "%s%s%s", basedir, MODULE_DIR, version);
1377 if (maybe_all) {
1378 if (!doing_stdout && !depfile_out_of_date(dirname))
1379 exit(0);
1380 all = 1;
1383 read_toplevel_config(config, basedir, version, &search, &overrides);
1385 /* For backward compatibility add "updates" to the head of the search
1386 * list here. But only if there was no "search" option specified.
1389 if (!search)
1390 search = add_search("updates", strlen("updates"), search);
1392 if (!all) {
1393 /* Do command line args. */
1394 for (opt = optind; opt < argc; opt++) {
1395 struct module *new = grab_module(NULL, argv[opt]);
1396 if (!new) {
1397 /* cmd-line specified modules must exist */
1398 fatal("grab_module() failed for module %s\n", argv[opt]);
1400 new->next = list;
1401 list = new;
1403 } else {
1404 list = grab_basedir(dirname,search,overrides);
1406 list = sort_modules(dirname,list);
1407 list = parse_modules(list);
1409 for (i = 0; i < sizeof(depfiles)/sizeof(depfiles[0]); i++) {
1410 FILE *out;
1411 struct depfile *d = &depfiles[i];
1412 char depname[strlen(dirname) + 1 + strlen(d->name) + 1];
1413 char tmpname[strlen(dirname) + 1 + strlen(d->name) +
1414 strlen(".temp") + 1];
1416 if (d->map_file && !make_map_files && !force_map_files)
1417 continue;
1419 sprintf(depname, "%s/%s", dirname, d->name);
1420 sprintf(tmpname, "%s/%s.temp", dirname, d->name);
1421 if (!doing_stdout) {
1422 out = fopen(tmpname, "w");
1423 if (!out)
1424 fatal("Could not open %s for writing: %s\n",
1425 tmpname, strerror(errno));
1426 } else {
1427 out = stdout;
1428 if (ends_in(depname, ".bin"))
1429 continue;
1431 d->func(list, out, dirname);
1432 if (!doing_stdout) {
1433 fclose(out);
1434 if (rename(tmpname, depname) < 0)
1435 fatal("Could not rename %s into %s: %s\n",
1436 tmpname, depname, strerror(errno));
1440 free(dirname);
1441 free(version);
1443 return 0;