Merge ../remotes/kay-mit
[mit.git] / depmod.c
blob0281c79b253321429fce4b4a25e16c19045e9e3a
1 /* New simplified depmod without backwards compat stuff and not
2 requiring ksyms.
4 (C) 2002 Rusty Russell IBM Corporation
5 */
6 #include <stdarg.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <getopt.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <unistd.h>
13 #include <elf.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <fcntl.h>
17 #include <dirent.h>
18 #include <sys/utsname.h>
19 #include <sys/mman.h>
21 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
23 #include "zlibsupport.h"
24 #include "depmod.h"
25 #include "moduleops.h"
26 #include "tables.h"
28 #include "testing.h"
30 #ifndef MODULE_DIR
31 #define MODULE_DIR "/lib/modules/"
32 #endif
34 #ifndef MODULE_BUILTIN_KEY
35 #define MODULE_BUILTIN_KEY "built-in"
36 #endif
38 struct module_overrides
40 /* Next override */
41 struct module_overrides *next;
43 /* overridden module */
44 char *modfile;
47 struct module_search
49 /* Next search */
50 struct module_search *next;
52 /* search path */
53 char *search_path;
56 static int verbose;
57 static unsigned int skipchars;
59 void fatal(const char *fmt, ...)
61 va_list arglist;
63 fprintf(stderr, "FATAL: ");
65 va_start(arglist, fmt);
66 vfprintf(stderr, fmt, arglist);
67 va_end(arglist);
69 exit(1);
72 void warn(const char *fmt, ...)
74 va_list arglist;
76 fprintf(stderr, "WARNING: ");
78 va_start(arglist, fmt);
79 vfprintf(stderr, fmt, arglist);
80 va_end(arglist);
83 void *do_nofail(void *ptr, const char *file, int line, const char *expr)
85 if (!ptr) {
86 fatal("Memory allocation failure %s line %d: %s.\n",
87 file, line, expr);
89 return ptr;
92 #define SYMBOL_HASH_SIZE 1024
93 struct symbol
95 struct symbol *next;
96 struct module *owner;
97 char name[0];
100 static struct symbol *symbolhash[SYMBOL_HASH_SIZE];
102 /* This is based on the hash agorithm from gdbm, via tdb */
103 static inline unsigned int tdb_hash(const char *name)
105 unsigned value; /* Used to compute the hash value. */
106 unsigned i; /* Used to cycle through random values. */
108 /* Set the initial value from the key size. */
109 for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
110 value = (value + (((unsigned char *)name)[i] << (i*5 % 24)));
112 return (1103515243 * value + 12345);
115 void add_symbol(const char *name, struct module *owner)
117 unsigned int hash;
118 struct symbol *new = NOFAIL(malloc(sizeof *new + strlen(name) + 1));
120 new->owner = owner;
121 strcpy(new->name, name);
123 hash = tdb_hash(name) % SYMBOL_HASH_SIZE;
124 new->next = symbolhash[hash];
125 symbolhash[hash] = new;
128 static int print_unknown;
130 struct module *find_symbol(const char *name, const char *modname, int weak)
132 struct symbol *s;
134 /* For our purposes, .foo matches foo. PPC64 needs this. */
135 if (name[0] == '.')
136 name++;
138 for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s=s->next) {
139 if (streq(s->name, name))
140 return s->owner;
143 if (print_unknown && !weak)
144 warn("%s needs unknown symbol %s\n", modname, name);
146 return NULL;
149 void add_dep(struct module *mod, struct module *depends_on)
151 unsigned int i;
153 for (i = 0; i < mod->num_deps; i++)
154 if (mod->deps[i] == depends_on)
155 return;
157 mod->deps = NOFAIL(realloc(mod->deps, sizeof(mod->deps[0])*(mod->num_deps+1)));
158 mod->deps[mod->num_deps++] = depends_on;
161 static void load_system_map(const char *filename)
163 FILE *system_map;
164 char line[10240];
165 const char ksymstr[] = "__ksymtab_";
166 const int ksymstr_len = strlen(ksymstr);
168 system_map = fopen(filename, "r");
169 if (!system_map)
170 fatal("Could not open '%s': %s\n", filename, strerror(errno));
172 /* eg. c0294200 R __ksymtab_devfs_alloc_devnum */
173 while (fgets(line, sizeof(line)-1, system_map)) {
174 char *ptr;
176 /* Snip \n */
177 ptr = strchr(line, '\n');
178 if (ptr)
179 *ptr = '\0';
181 ptr = strchr(line, ' ');
182 if (!ptr || !(ptr = strchr(ptr + 1, ' ')))
183 continue;
185 /* Covers gpl-only and normal symbols. */
186 if (strncmp(ptr+1, ksymstr, ksymstr_len) == 0)
187 add_symbol(ptr+1+ksymstr_len, NULL);
190 fclose(system_map);
192 /* __this_module is magic inserted by kernel loader. */
193 add_symbol("__this_module", NULL);
194 /* On S390, this is faked up too */
195 add_symbol("_GLOBAL_OFFSET_TABLE_", NULL);
198 static struct option options[] = { { "all", 0, NULL, 'a' },
199 { "quick", 0, NULL, 'A' },
200 { "basedir", 1, NULL, 'b' },
201 { "errsyms", 0, NULL, 'e' },
202 { "filesyms", 1, NULL, 'F' },
203 { "help", 0, NULL, 'h' },
204 { "show", 0, NULL, 'n' },
205 { "dry-run", 0, NULL, 'n' },
206 { "quiet", 0, NULL, 'q' },
207 { "root", 0, NULL, 'r' },
208 { "unresolved-error", 0, NULL, 'u' },
209 { "verbose", 0, NULL, 'v' },
210 { "version", 0, NULL, 'V' },
211 { "config", 1, NULL, 'C' },
212 { NULL, 0, NULL, 0 } };
214 /* Version number or module name? Don't assume extension. */
215 static int is_version_number(const char *version)
217 unsigned int dummy;
219 return (sscanf(version, "%u.%u.%u", &dummy, &dummy, &dummy) == 3);
222 static int old_module_version(const char *version)
224 /* Expect three part version. */
225 unsigned int major, sub, minor;
227 sscanf(version, "%u.%u.%u", &major, &sub, &minor);
229 if (major > 2) return 0;
230 if (major < 2) return 1;
232 /* 2.x */
233 if (sub > 5) return 0;
234 if (sub < 5) return 1;
236 /* 2.5.x */
237 if (minor >= 48) return 0;
238 return 1;
241 static void exec_old_depmod(char *argv[])
243 char *sep;
244 char pathname[strlen(argv[0])+1];
245 char oldname[strlen("depmod") + strlen(argv[0]) + sizeof(".old")];
247 memset(pathname, 0, strlen(argv[0])+1);
248 sep = strrchr(argv[0], '/');
249 if (sep)
250 memcpy(pathname, argv[0], sep - argv[0]+1);
251 sprintf(oldname, "%s%s.old", pathname, "depmod");
253 /* Recursion detection: we need an env var since we can't
254 change argv[0] (as older modutils uses it to determine
255 behavior). */
256 if (getenv("MODULE_RECURSE"))
257 return;
258 setenv("MODULE_RECURSE", "y", 0);
260 execvp(oldname, argv);
261 fprintf(stderr,
262 "Version requires old depmod, but couldn't run %s: %s\n",
263 oldname, strerror(errno));
264 exit(2);
267 static void grammar(const char *cmd, const char *filename, unsigned int line)
269 warn("%s line %u: ignoring bad line starting with '%s'\n",
270 filename, line, cmd);
274 static void print_usage(const char *name)
276 fprintf(stderr,
277 "%s " VERSION " -- part of " PACKAGE "\n"
278 "%s -[aA] [-n -e -v -q -V -r -u]\n"
279 " [-b basedirectory] [forced_version]\n"
280 "depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.ko module2.ko ...\n"
281 "If no arguments (except options) are given, \"depmod -a\" is assumed\n"
282 "\n"
283 "depmod will output a dependancy list suitable for the modprobe utility.\n"
284 "\n"
285 "\n"
286 "Options:\n"
287 "\t-a, --all Probe all modules\n"
288 "\t-A, --quick Only does the work if there's a new module\n"
289 "\t-n, --show Write the dependency file on stdout only\n"
290 "\t-e, --errsyms Report not supplied symbols\n"
291 "\t-V, --version Print the release version\n"
292 "\t-v, --verbose Enable verbose mode\n"
293 "\t-h, --help Print this usage message\n"
294 "\n"
295 "The following options are useful for people managing distributions:\n"
296 "\t-b basedirectory\n"
297 "\t --basedir basedirectory Use an image of a module tree.\n"
298 "\t-F kernelsyms\n"
299 "\t --filesyms kernelsyms Use the file instead of the\n"
300 "\t current kernel symbols.\n",
301 "depmod", "depmod");
304 static int ends_in(const char *name, const char *ext)
306 unsigned int namelen, extlen;
308 /* Grab lengths */
309 namelen = strlen(name);
310 extlen = strlen(ext);
312 if (namelen < extlen) return 0;
314 if (streq(name + namelen - extlen, ext))
315 return 1;
316 return 0;
319 /* "\177ELF" <byte> where byte = 001 for 32-bit, 002 for 64 */
320 int needconv(const char *elfhdr)
322 union { short s; char c[2]; } endian_test;
324 endian_test.s = 1;
325 if (endian_test.c[1] == 1) return elfhdr[EI_DATA] != ELFDATA2MSB;
326 if (endian_test.c[0] == 1) return elfhdr[EI_DATA] != ELFDATA2LSB;
327 else
328 abort();
331 static struct module *grab_module(const char *dirname, const char *filename)
333 struct module *new;
335 new = NOFAIL(malloc(sizeof(*new)
336 + strlen(dirname?:"") + 1 + strlen(filename) + 1));
337 if (dirname)
338 sprintf(new->pathname, "%s/%s", dirname, filename);
339 else
340 strcpy(new->pathname, filename);
342 INIT_LIST_HEAD(&new->dep_list);
344 new->data = grab_file(new->pathname, &new->len);
345 if (!new->data) {
346 warn("Can't read module %s: %s\n",
347 new->pathname, strerror(errno));
348 goto fail_data;
351 /* "\177ELF" <byte> where byte = 001 for 32-bit, 002 for 64 */
352 if (memcmp(new->data, ELFMAG, SELFMAG) != 0) {
353 warn("Module %s is not an elf object\n", new->pathname);
354 goto fail;
357 switch (((char *)new->data)[EI_CLASS]) {
358 case ELFCLASS32:
359 new->ops = &mod_ops32;
360 break;
361 case ELFCLASS64:
362 new->ops = &mod_ops64;
363 break;
364 default:
365 warn("Module %s has elf unknown identifier %i\n",
366 new->pathname, ((char *)new->data)[EI_CLASS]);
367 goto fail;
369 new->conv = needconv(new->data);
370 return new;
372 fail:
373 release_file(new->data, new->len);
374 fail_data:
375 free(new);
376 return NULL;
379 struct module_traverse
381 struct module_traverse *prev;
382 struct module *mod;
385 static int in_loop(struct module *mod, const struct module_traverse *traverse)
387 const struct module_traverse *i;
389 for (i = traverse; i; i = i->prev) {
390 if (i->mod == mod)
391 return 1;
393 return 0;
396 static char *basename(const char *name)
398 const char *base = strrchr(name, '/');
399 if (base) return (char *)base + 1;
400 return (char *)name;
403 /* Assume we are doing all the modules, so only report each loop once. */
404 static void report_loop(const struct module *mod,
405 const struct module_traverse *traverse)
407 const struct module_traverse *i;
409 /* Check that start is least alphabetically. eg. a depends
410 on b depends on a will get reported for a, not b. */
411 for (i = traverse->prev; i->prev; i = i->prev) {
412 if (strcmp(mod->pathname, i->mod->pathname) > 0)
413 return;
416 /* Is start in the loop? If not, don't report now. eg. a
417 depends on b which depends on c which depends on b. Don't
418 report when generating depends for a. */
419 if (mod != i->mod)
420 return;
422 warn("Loop detected: %s ", mod->pathname);
423 for (i = traverse->prev; i->prev; i = i->prev)
424 fprintf(stderr, "needs %s ", basename(i->mod->pathname));
425 fprintf(stderr, "which needs %s again!\n", basename(mod->pathname));
428 /* This is damn slow, but loops actually happen, and we don't want to
429 just exit() and leave the user without any modules. */
430 static int has_dep_loop(struct module *module, struct module_traverse *prev)
432 unsigned int i;
433 struct module_traverse traverse = { .prev = prev, .mod = module };
435 if (in_loop(module, prev)) {
436 report_loop(module, &traverse);
437 return 1;
440 for (i = 0; i < module->num_deps; i++)
441 if (has_dep_loop(module->deps[i], &traverse))
442 return 1;
443 return 0;
446 /* Uniquifies and orders a dependency list. */
447 static void order_dep_list(struct module *start, struct module *mod)
449 unsigned int i;
451 for (i = 0; i < mod->num_deps; i++) {
452 /* If it was previously depended on, move it to the
453 tail. ie. if a needs b and c, and c needs b, we
454 must order b after c. */
455 list_del(&mod->deps[i]->dep_list);
456 list_add_tail(&mod->deps[i]->dep_list, &start->dep_list);
457 order_dep_list(start, mod->deps[i]);
461 static void del_module(struct module **modules, struct module *delme)
463 struct module **i;
465 /* Find pointer to it. */
466 for (i = modules; *i != delme; i = &(*i)->next);
468 *i = delme->next;
471 static void output_deps(struct module *modules,
472 FILE *out)
474 struct module *i;
476 for (i = modules; i; i = i->next)
477 i->ops->calculate_deps(i, verbose);
479 /* Strip out loops. */
480 again:
481 for (i = modules; i; i = i->next) {
482 if (has_dep_loop(i, NULL)) {
483 warn("Module %s ignored, due to loop\n",
484 i->pathname + skipchars);
485 del_module(&modules, i);
486 goto again;
490 /* Now dump them out. */
491 for (i = modules; i; i = i->next) {
492 struct list_head *j, *tmp;
493 order_dep_list(i, i);
495 fprintf(out, "%s:", i->pathname + skipchars);
496 list_for_each_safe(j, tmp, &i->dep_list) {
497 struct module *dep
498 = list_entry(j, struct module, dep_list);
499 fprintf(out, " %s", dep->pathname + skipchars);
500 list_del_init(j);
502 fprintf(out, "\n");
506 static int smells_like_module(const char *name)
508 return ends_in(name,".ko") || ends_in(name, ".ko.gz");
511 typedef struct module *(*do_module_t)(const char *dirname,
512 const char *filename,
513 struct module *next,
514 struct module_search *search,
515 struct module_overrides *overrides);
517 static int is_higher_priority(const char *newpath, const char *oldpath,
518 struct module_search *search,
519 struct module_overrides *overrides)
521 char *p, *q, *s;
522 struct module_search *tmp;
523 struct module_overrides *ovtmp;
524 int i = 0;
525 int prio_builtin = -1;
526 int prio_new = -1;
527 int prio_old = -1;
529 /* The names already match, now we check for wildcard overrides and other
530 * high priority overrides we added to the config.
532 for (ovtmp=overrides;ovtmp!=NULL;ovtmp=ovtmp->next) {
534 p = strstr(ovtmp->modfile,newpath);
535 if (p)
536 return 1;
538 q = strstr(ovtmp->modfile,"*");
539 if (q) {
540 p = strstr(newpath, q+1);
541 if (p)
542 return 1;
544 p = strstr(oldpath, q+1);
545 if (p)
546 return 0;
549 p = strstr(ovtmp->modfile,oldpath);
550 if (p)
551 return 0;
554 for (i=0,tmp=search;tmp!=NULL;tmp=tmp->next,i++) {
556 s = NOFAIL(malloc(strlen(tmp->search_path)+2));
557 s[0] = '/';
558 strncpy(s+1,tmp->search_path, strlen(tmp->search_path)+1);
560 if (0 == strncmp(tmp->search_path,MODULE_BUILTIN_KEY,
561 strlen(MODULE_BUILTIN_KEY)))
562 prio_builtin = i;
564 p = strstr(newpath,s);
565 if ((p) && ((p[strlen(s)] == '/')
566 || (p[strlen(s)] == '\0')))
567 prio_new = i;
569 p = strstr(oldpath,s);
570 if ((p) && ((p[strlen(s)] == '/')
571 || (p[strlen(s)] == '\0')))
572 prio_old = i;
574 free(s);
578 if (prio_new < 0)
579 prio_new = prio_builtin;
581 if (prio_old < 0)
582 prio_old = prio_builtin;
584 return prio_new > prio_old;
589 static struct module *do_module(const char *dirname,
590 const char *filename,
591 struct module *list,
592 struct module_search *search,
593 struct module_overrides *overrides)
595 struct module *new, **i;
597 new = grab_module(dirname, filename);
598 if (!new)
599 return list;
601 /* Check if module is already in the list. */
602 for (i = &list; *i; i = &(*i)->next) {
604 if (streq(basename((*i)->pathname), filename)) {
605 char newpath[strlen(dirname) + strlen("/")
606 + strlen(filename) + 1];
608 sprintf(newpath, "%s/%s", dirname, filename);
610 if (is_higher_priority(newpath, (*i)->pathname,search,
611 overrides)) {
612 new->next = (*i)->next;
614 release_file((*i)->data, (*i)->len);
615 free(*i);
617 *i = new;
618 } else
619 free(new);
621 return list;
625 /* Not in the list already. Just prepend. */
626 new->next = list;
627 return new;
630 static struct module *grab_dir(const char *dirname,
631 DIR *dir,
632 struct module *next,
633 do_module_t do_mod,
634 struct module_search *search,
635 struct module_overrides *overrides)
637 struct dirent *dirent;
639 while ((dirent = readdir(dir)) != NULL) {
640 if (smells_like_module(dirent->d_name))
641 next = do_mod(dirname, dirent->d_name, next,
642 search, overrides);
643 else if (!streq(dirent->d_name, ".")
644 && !streq(dirent->d_name, "..")
645 && !streq(dirent->d_name, "source")
646 && !streq(dirent->d_name, "build")) {
648 DIR *sub;
649 char subdir[strlen(dirname) + 1
650 + strlen(dirent->d_name) + 1];
651 sprintf(subdir, "%s/%s", dirname, dirent->d_name);
652 sub = opendir(subdir);
653 if (sub) {
654 next = grab_dir(subdir, sub, next, do_mod,
655 search, overrides);
656 closedir(sub);
660 return next;
663 static struct module *grab_basedir(const char *dirname,
664 struct module_search *search,
665 struct module_overrides *overrides)
667 DIR *dir;
668 struct module *list;
670 dir = opendir(dirname);
671 if (!dir) {
672 warn("Couldn't open directory %s: %s\n",
673 dirname, strerror(errno));
674 return NULL;
676 list = grab_dir(dirname, dir, NULL, do_module, search, overrides);
677 closedir(dir);
679 return list;
682 static void parse_modules(struct module *list)
684 struct module *i;
686 for (i = list; i; i = i->next) {
687 i->ops->load_symbols(i);
688 i->ops->fetch_tables(i);
692 /* Convert filename to the module name. Works if filename == modname, too. */
693 static void filename2modname(char *modname, const char *filename)
695 const char *afterslash;
696 unsigned int i;
698 afterslash = strrchr(filename, '/');
699 if (!afterslash)
700 afterslash = filename;
701 else
702 afterslash++;
704 /* Convert to underscores, stop at first . */
705 for (i = 0; afterslash[i] && afterslash[i] != '.'; i++) {
706 if (afterslash[i] == '-')
707 modname[i] = '_';
708 else
709 modname[i] = afterslash[i];
711 modname[i] = '\0';
714 /* Simply dump hash table. */
715 static void output_symbols(struct module *unused, FILE *out)
717 unsigned int i;
719 fprintf(out, "# Aliases for symbols, used by symbol_request().\n");
720 for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
721 struct symbol *s;
723 for (s = symbolhash[i]; s; s = s->next) {
724 if (s->owner) {
725 char modname[strlen(s->owner->pathname)+1];
726 filename2modname(modname, s->owner->pathname);
727 fprintf(out, "alias symbol:%s %s\n",
728 s->name, modname);
734 static const char *next_string(const char *string, unsigned long *secsize)
736 /* Skip non-zero chars */
737 while (string[0]) {
738 string++;
739 if ((*secsize)-- <= 1)
740 return NULL;
743 /* Skip any zero padding. */
744 while (!string[0]) {
745 string++;
746 if ((*secsize)-- <= 1)
747 return NULL;
749 return string;
752 static void output_aliases(struct module *modules, FILE *out)
754 struct module *i;
755 const char *p;
756 unsigned long size;
758 fprintf(out, "# Aliases extracted from modules themselves.\n");
759 for (i = modules; i; i = i->next) {
760 char modname[strlen(i->pathname)+1];
762 filename2modname(modname, i->pathname);
764 /* Grab from old-style .modalias section. */
765 for (p = i->ops->get_aliases(i, &size);
767 p = next_string(p, &size))
768 fprintf(out, "alias %s %s\n", p, modname);
770 /* Grab form new-style .modinfo section. */
771 for (p = i->ops->get_modinfo(i, &size);
773 p = next_string(p, &size)) {
774 if (strncmp(p, "alias=", strlen("alias=")) == 0)
775 fprintf(out, "alias %s %s\n",
776 p + strlen("alias="), modname);
781 struct depfile {
782 char *name;
783 void (*func)(struct module *, FILE *);
786 static struct depfile depfiles[] = {
787 { "modules.dep", output_deps }, /* This is what we check for '-A'. */
788 { "modules.pcimap", output_pci_table },
789 { "modules.usbmap", output_usb_table },
790 { "modules.ccwmap", output_ccw_table },
791 { "modules.ieee1394map", output_ieee1394_table },
792 { "modules.isapnpmap", output_isapnp_table },
793 { "modules.inputmap", output_input_table },
794 { "modules.ofmap", output_of_table },
795 { "modules.seriomap", output_serio_table },
796 { "modules.alias", output_aliases },
797 { "modules.symbols", output_symbols },
800 /* If we can't figure it out, it's safe to say "true". */
801 static int any_modules_newer(const char *dirname, time_t mtime)
803 DIR *dir;
804 struct dirent *dirent;
806 dir = opendir(dirname);
807 if (!dir)
808 return 1;
810 while ((dirent = readdir(dir)) != NULL) {
811 struct stat st;
812 char file[strlen(dirname) + 1 + strlen(dirent->d_name) + 1];
814 if (streq(dirent->d_name, ".") || streq(dirent->d_name, ".."))
815 continue;
817 sprintf(file, "%s/%s", dirname, dirent->d_name);
818 if (lstat(file, &st) != 0)
819 return 1;
821 if (smells_like_module(dirent->d_name)) {
822 if (st.st_mtime > mtime)
823 return 1;
824 } else if (S_ISDIR(st.st_mode)) {
825 if (any_modules_newer(file, mtime))
826 return 1;
829 closedir(dir);
830 return 0;
833 static int depfile_out_of_date(const char *dirname)
835 struct stat st;
836 char depfile[strlen(dirname) + 1 + strlen(depfiles[0].name) + 1];
838 sprintf(depfile, "%s/%s", dirname, depfiles[0].name);
840 if (stat(depfile, &st) != 0)
841 return 1;
843 return any_modules_newer(dirname, st.st_mtime);
846 static int fgetc_wrapped(FILE *file, unsigned int *linenum)
848 for (;;) {
849 int ch = fgetc(file);
850 if (ch != '\\')
851 return ch;
852 ch = fgetc(file);
853 if (ch != '\n')
854 return ch;
855 if (linenum)
856 (*linenum)++;
860 static char *getline_wrapped(FILE *file, unsigned int *linenum)
862 int size = 1024;
863 int i = 0;
864 char *buf = NOFAIL(malloc(size));
865 for(;;) {
866 int ch = fgetc_wrapped(file, linenum);
867 if (i == size) {
868 size *= 2;
869 buf = NOFAIL(realloc(buf, size));
871 if (ch < 0 && i == 0) {
872 free(buf);
873 return NULL;
875 if (ch < 0 || ch == '\n') {
876 if (linenum)
877 (*linenum)++;
878 buf[i] = '\0';
879 return NOFAIL(realloc(buf, i+1));
881 buf[i++] = ch;
886 static char *strsep_skipspace(char **string, char *delim)
888 if (!*string)
889 return NULL;
890 *string += strspn(*string, delim);
891 return strsep(string, delim);
894 static struct module_search *add_search(const char *search_path,
895 struct module_search *search)
898 struct module_search *new;
900 new = NOFAIL(malloc(sizeof(*new)));
901 new->search_path = NOFAIL(strdup(search_path));
902 new->next = search;
904 return new;
908 static struct module_overrides *add_override(const char *modfile,
909 struct module_overrides *overrides)
912 struct module_overrides *new;
914 new = NOFAIL(malloc(sizeof(*new)));
915 new->modfile = NOFAIL(strdup(modfile));
916 new->next = overrides;
918 return new;
922 /* Recursion */
923 static int read_config(const char *filename,
924 const char *basedir,
925 struct module_search **search,
926 struct module_overrides **overrides);
928 static int read_config_file(const char *filename,
929 const char *basedir,
930 struct module_search **search,
931 struct module_overrides **overrides)
933 char *line;
934 unsigned int linenum = 0;
935 FILE *cfile;
937 cfile = fopen(filename, "r");
938 if (!cfile) {
939 if (errno != ENOENT)
940 fatal("could not open '%s', reason: %s\n", filename,
941 strerror(errno));
942 return 0;
945 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
946 char *ptr = line;
947 char *cmd, *modname;
949 cmd = strsep_skipspace(&ptr, "\t ");
951 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0')
952 continue;
954 if (strcmp(cmd, "search") == 0) {
955 char *search_path;
957 while ((search_path = strsep_skipspace(&ptr, "\t ")))
958 *search = add_search(search_path, *search);
959 } else if (strcmp(cmd, "override") == 0) {
960 char *pathname = NULL, *version, *subdir;
961 modname = strsep_skipspace(&ptr, "\t ");
962 version = strsep_skipspace(&ptr, "\t ");
963 subdir = strsep_skipspace(&ptr, "\t ");
965 pathname = NOFAIL(malloc(strlen(basedir)
966 + strlen(MODULE_DIR)
967 + strlen(version)
968 + strlen(subdir)
969 + strlen(modname)
970 + strlen(".ko")
971 + 3));
972 sprintf(pathname, "%s%s%s/%s/%s.ko", basedir,
973 MODULE_DIR, version, subdir, modname);
975 *overrides = add_override(pathname, *overrides);
976 } else if (strcmp(cmd, "include") == 0) {
977 char *newfilename;
979 newfilename = strsep_skipspace(&ptr, "\t ");
980 if (!newfilename)
981 grammar(cmd, filename, linenum);
982 else {
983 if (!read_config(newfilename, basedir,
984 search, overrides))
985 warn("Failed to open included"
986 " config file %s: %s\n",
987 newfilename, strerror(errno));
989 } else
990 grammar(cmd, filename, linenum);
992 free(line);
994 fclose(cfile);
995 return 1;
998 /* Simple format, ignore lines starting with #, one command per line.
999 Returns true or false. */
1000 static int read_config(const char *filename,
1001 const char *basedir,
1002 struct module_search **search,
1003 struct module_overrides **overrides)
1005 DIR *dir;
1006 int ret = 0;
1008 dir = opendir(filename);
1009 if (dir) {
1010 struct dirent *i;
1011 while ((i = readdir(dir)) != NULL) {
1012 if (!streq(i->d_name,".") && !streq(i->d_name,"..")) {
1013 char sub[strlen(filename) + 1
1014 + strlen(i->d_name) + 1];
1016 sprintf(sub, "%s/%s", filename, i->d_name);
1017 if (!read_config(sub, basedir, search,
1018 overrides))
1019 warn("Failed to open"
1020 " config file %s: %s\n",
1021 sub, strerror(errno));
1024 closedir(dir);
1025 ret = 1;
1026 } else {
1027 if (read_config_file(filename, basedir, search, overrides))
1028 ret = 1;
1031 return ret;
1034 static const char *default_configs[] =
1036 "/etc/depmod.conf",
1037 "/etc/depmod.d",
1040 static void read_toplevel_config(const char *filename,
1041 const char *basedir,
1042 struct module_search **search,
1043 struct module_overrides **overrides)
1045 unsigned int i;
1047 if (filename) {
1048 if (!read_config(filename, basedir, search, overrides))
1049 fatal("Failed to open config file %s: %s\n",
1050 filename, strerror(errno));
1051 return;
1054 /* Try defaults. */
1055 for (i = 0; i < ARRAY_SIZE(default_configs); i++) {
1056 if (read_config(default_configs[i], basedir, search, overrides))
1057 return;
1062 int main(int argc, char *argv[])
1064 int opt, all = 0, maybe_all = 0, doing_stdout = 0;
1065 char *basedir = "", *dirname, *version, *badopt = NULL,
1066 *system_map = NULL;
1067 struct module *list = NULL;
1068 int i;
1069 const char *config = NULL;
1070 struct module_search *search = NULL;
1071 struct module_overrides *overrides = NULL;
1073 /* Don't print out any errors just yet, we might want to exec
1074 backwards compat version. */
1075 opterr = 0;
1076 while ((opt = getopt_long(argc, argv, "ab:ArehnqruvVF:C:", options, NULL))
1077 != -1) {
1078 switch (opt) {
1079 case 'a':
1080 all = 1;
1081 break;
1082 case 'b':
1083 basedir = optarg;
1084 skipchars = strlen(basedir);
1085 break;
1086 case 'A':
1087 maybe_all = 1;
1088 break;
1089 case 'F':
1090 system_map = optarg;
1091 break;
1092 case 'e':
1093 print_unknown = 1;
1094 break;
1095 case 'v':
1096 verbose = 1;
1097 break;
1098 case 'u':
1099 case 'q':
1100 case 'r':
1101 break;
1102 case 'C':
1103 config = optarg;
1104 break;
1105 case 'h':
1106 print_usage(argv[0]);
1107 exit(0);
1108 break;
1109 case 'n':
1110 doing_stdout = 1;
1111 break;
1112 case 'V':
1113 printf("%s %s\n", PACKAGE, VERSION);
1114 exit(0);
1115 default:
1116 badopt = argv[optind-1];
1120 /* We can't print unknowns without a System.map */
1121 if (!system_map)
1122 print_unknown = 0;
1123 else
1124 load_system_map(system_map);
1126 /* They can specify the version naked on the command line */
1127 if (optind < argc && is_version_number(argv[optind])) {
1128 version = NOFAIL(strdup(argv[optind]));
1129 optind++;
1130 } else {
1131 struct utsname buf;
1132 uname(&buf);
1133 version = NOFAIL(strdup(buf.release));
1136 /* Run old version if required. */
1137 if (old_module_version(version))
1138 exec_old_depmod(argv);
1140 if (badopt) {
1141 fprintf(stderr, "%s: malformed/unrecognized option '%s'\n",
1142 argv[0], badopt);
1143 print_usage(argv[0]);
1144 exit(1);
1147 /* Depmod -a by default if no names. */
1148 if (optind == argc)
1149 all = 1;
1151 dirname = NOFAIL(malloc(strlen(basedir)
1152 + strlen(MODULE_DIR)
1153 + strlen(version) + 1));
1154 sprintf(dirname, "%s%s%s", basedir, MODULE_DIR, version);
1156 if (maybe_all) {
1157 if (!doing_stdout && !depfile_out_of_date(dirname))
1158 exit(0);
1159 all = 1;
1162 read_toplevel_config(config, basedir, &search, &overrides);
1164 /* For backward compatibility add "updates" to the head of the search
1165 * list here. But only if there was no "search" option specified.
1168 if (!search)
1169 search = add_search("updates",search);
1171 if (!all) {
1172 /* Do command line args. */
1173 for (opt = optind; opt < argc; opt++) {
1174 struct module *new = grab_module(NULL, argv[opt]);
1175 if (new) {
1176 new->next = list;
1177 list = new;
1180 } else {
1181 list = grab_basedir(dirname,search,overrides);
1183 parse_modules(list);
1185 for (i = 0; i < sizeof(depfiles)/sizeof(depfiles[0]); i++) {
1186 FILE *out;
1187 struct depfile *d = &depfiles[i];
1188 char depname[strlen(dirname) + 1 + strlen(d->name) + 1];
1189 char tmpname[strlen(dirname) + 1 + strlen(d->name) +
1190 strlen(".temp") + 1];
1192 sprintf(depname, "%s/%s", dirname, d->name);
1193 sprintf(tmpname, "%s/%s.temp", dirname, d->name);
1194 if (!doing_stdout) {
1195 out = fopen(tmpname, "w");
1196 if (!out)
1197 fatal("Could not open %s for writing: %s\n",
1198 tmpname, strerror(errno));
1199 } else
1200 out = stdout;
1201 d->func(list, out);
1202 if (!doing_stdout) {
1203 fclose(out);
1204 if (rename(tmpname, depname) < 0)
1205 fatal("Could not rename %s into %s: %s\n",
1206 tmpname, depname, strerror(errno));
1210 free(dirname);
1211 free(version);
1213 return 0;