depmod: minimise basename() overhead
[mit.git] / depmod.c
blob22c0def79570919b7d7cfbc0bb8229fcef75658d
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 char *basename(const char *name)
333 const char *base = strrchr(name, '/');
334 if (base) return (char *)base + 1;
335 return (char *)name;
338 static struct module *grab_module(const char *dirname, const char *filename)
340 struct module *new;
342 new = NOFAIL(malloc(sizeof(*new)
343 + strlen(dirname?:"") + 1 + strlen(filename) + 1));
344 if (dirname)
345 sprintf(new->pathname, "%s/%s", dirname, filename);
346 else
347 strcpy(new->pathname, filename);
348 new->basename = basename(new->pathname);
350 INIT_LIST_HEAD(&new->dep_list);
352 new->data = grab_file(new->pathname, &new->len);
353 if (!new->data) {
354 warn("Can't read module %s: %s\n",
355 new->pathname, strerror(errno));
356 goto fail_data;
359 /* "\177ELF" <byte> where byte = 001 for 32-bit, 002 for 64 */
360 if (memcmp(new->data, ELFMAG, SELFMAG) != 0) {
361 warn("Module %s is not an elf object\n", new->pathname);
362 goto fail;
365 switch (((char *)new->data)[EI_CLASS]) {
366 case ELFCLASS32:
367 new->ops = &mod_ops32;
368 break;
369 case ELFCLASS64:
370 new->ops = &mod_ops64;
371 break;
372 default:
373 warn("Module %s has elf unknown identifier %i\n",
374 new->pathname, ((char *)new->data)[EI_CLASS]);
375 goto fail;
377 new->conv = needconv(new->data);
378 return new;
380 fail:
381 release_file(new->data, new->len);
382 fail_data:
383 free(new);
384 return NULL;
387 struct module_traverse
389 struct module_traverse *prev;
390 struct module *mod;
393 static int in_loop(struct module *mod, const struct module_traverse *traverse)
395 const struct module_traverse *i;
397 for (i = traverse; i; i = i->prev) {
398 if (i->mod == mod)
399 return 1;
401 return 0;
404 /* Assume we are doing all the modules, so only report each loop once. */
405 static void report_loop(const struct module *mod,
406 const struct module_traverse *traverse)
408 const struct module_traverse *i;
410 /* Check that start is least alphabetically. eg. a depends
411 on b depends on a will get reported for a, not b. */
412 for (i = traverse->prev; i->prev; i = i->prev) {
413 if (strcmp(mod->pathname, i->mod->pathname) > 0)
414 return;
417 /* Is start in the loop? If not, don't report now. eg. a
418 depends on b which depends on c which depends on b. Don't
419 report when generating depends for a. */
420 if (mod != i->mod)
421 return;
423 warn("Loop detected: %s ", mod->pathname);
424 for (i = traverse->prev; i->prev; i = i->prev)
425 fprintf(stderr, "needs %s ", i->mod->basename);
426 fprintf(stderr, "which needs %s again!\n", i->mod->basename);
429 /* This is damn slow, but loops actually happen, and we don't want to
430 just exit() and leave the user without any modules. */
431 static int has_dep_loop(struct module *module, struct module_traverse *prev)
433 unsigned int i;
434 struct module_traverse traverse = { .prev = prev, .mod = module };
436 if (in_loop(module, prev)) {
437 report_loop(module, &traverse);
438 return 1;
441 for (i = 0; i < module->num_deps; i++)
442 if (has_dep_loop(module->deps[i], &traverse))
443 return 1;
444 return 0;
447 /* Uniquifies and orders a dependency list. */
448 static void order_dep_list(struct module *start, struct module *mod)
450 unsigned int i;
452 for (i = 0; i < mod->num_deps; i++) {
453 /* If it was previously depended on, move it to the
454 tail. ie. if a needs b and c, and c needs b, we
455 must order b after c. */
456 list_del(&mod->deps[i]->dep_list);
457 list_add_tail(&mod->deps[i]->dep_list, &start->dep_list);
458 order_dep_list(start, mod->deps[i]);
462 static struct module *deleted = NULL;
464 static void del_module(struct module **modules, struct module *delme)
466 struct module **i;
468 /* Find pointer to it. */
469 if (modules) {
470 for (i = modules; *i != delme; i = &(*i)->next);
472 *i = delme->next;
475 /* Save on a list to quiet valgrind.
476 Can't free - other modules may depend on them */
477 delme->next = deleted;
478 deleted = delme;
481 static void output_deps(struct module *modules,
482 FILE *out)
484 struct module *i;
486 for (i = modules; i; i = i->next)
487 i->ops->calculate_deps(i, verbose);
489 /* Strip out loops. */
490 again:
491 for (i = modules; i; i = i->next) {
492 if (has_dep_loop(i, NULL)) {
493 warn("Module %s ignored, due to loop\n",
494 i->pathname + skipchars);
495 del_module(&modules, i);
496 goto again;
500 /* Now dump them out. */
501 for (i = modules; i; i = i->next) {
502 struct list_head *j, *tmp;
503 order_dep_list(i, i);
505 fprintf(out, "%s:", i->pathname + skipchars);
506 list_for_each_safe(j, tmp, &i->dep_list) {
507 struct module *dep
508 = list_entry(j, struct module, dep_list);
509 fprintf(out, " %s", dep->pathname + skipchars);
510 list_del_init(j);
512 fprintf(out, "\n");
516 static int smells_like_module(const char *name)
518 return ends_in(name,".ko") || ends_in(name, ".ko.gz");
521 typedef struct module *(*do_module_t)(const char *dirname,
522 const char *filename,
523 struct module *next,
524 struct module_search *search,
525 struct module_overrides *overrides);
527 static int is_higher_priority(const char *newpath, const char *oldpath,
528 struct module_search *search,
529 struct module_overrides *overrides)
531 char *p, *q, *s;
532 struct module_search *tmp;
533 struct module_overrides *ovtmp;
534 int i = 0;
535 int prio_builtin = -1;
536 int prio_new = -1;
537 int prio_old = -1;
539 /* The names already match, now we check for wildcard overrides and other
540 * high priority overrides we added to the config.
542 for (ovtmp=overrides;ovtmp!=NULL;ovtmp=ovtmp->next) {
544 p = strstr(ovtmp->modfile,newpath);
545 if (p)
546 return 1;
548 q = strstr(ovtmp->modfile,"*");
549 if (q) {
550 p = strstr(newpath, q+1);
551 if (p)
552 return 1;
554 p = strstr(oldpath, q+1);
555 if (p)
556 return 0;
559 p = strstr(ovtmp->modfile,oldpath);
560 if (p)
561 return 0;
564 for (i=0,tmp=search;tmp!=NULL;tmp=tmp->next,i++) {
566 s = NOFAIL(malloc(strlen(tmp->search_path)+2));
567 s[0] = '/';
568 strncpy(s+1,tmp->search_path, strlen(tmp->search_path)+1);
570 if (0 == strncmp(tmp->search_path,MODULE_BUILTIN_KEY,
571 strlen(MODULE_BUILTIN_KEY)))
572 prio_builtin = i;
574 p = strstr(newpath,s);
575 if ((p) && ((p[strlen(s)] == '/')
576 || (p[strlen(s)] == '\0')))
577 prio_new = i;
579 p = strstr(oldpath,s);
580 if ((p) && ((p[strlen(s)] == '/')
581 || (p[strlen(s)] == '\0')))
582 prio_old = i;
584 free(s);
588 if (prio_new < 0)
589 prio_new = prio_builtin;
591 if (prio_old < 0)
592 prio_old = prio_builtin;
594 return prio_new > prio_old;
599 static struct module *do_module(const char *dirname,
600 const char *filename,
601 struct module *list,
602 struct module_search *search,
603 struct module_overrides *overrides)
605 struct module *new, **i;
607 new = grab_module(dirname, filename);
608 if (!new)
609 return list;
611 /* Check if module is already in the list. */
612 for (i = &list; *i; i = &(*i)->next) {
614 if (streq((*i)->basename, filename)) {
615 char newpath[strlen(dirname) + strlen("/")
616 + strlen(filename) + 1];
618 sprintf(newpath, "%s/%s", dirname, filename);
620 if (is_higher_priority(newpath, (*i)->pathname,search,
621 overrides)) {
622 del_module(i, *i);
624 new->next = *i;
625 *i = new;
626 } else
627 del_module(NULL, new);
629 return list;
633 /* Not in the list already. Just prepend. */
634 new->next = list;
635 return new;
638 static struct module *grab_dir(const char *dirname,
639 DIR *dir,
640 struct module *next,
641 do_module_t do_mod,
642 struct module_search *search,
643 struct module_overrides *overrides)
645 struct dirent *dirent;
647 while ((dirent = readdir(dir)) != NULL) {
648 if (smells_like_module(dirent->d_name))
649 next = do_mod(dirname, dirent->d_name, next,
650 search, overrides);
651 else if (!streq(dirent->d_name, ".")
652 && !streq(dirent->d_name, "..")
653 && !streq(dirent->d_name, "source")
654 && !streq(dirent->d_name, "build")) {
656 DIR *sub;
657 char subdir[strlen(dirname) + 1
658 + strlen(dirent->d_name) + 1];
659 sprintf(subdir, "%s/%s", dirname, dirent->d_name);
660 sub = opendir(subdir);
661 if (sub) {
662 next = grab_dir(subdir, sub, next, do_mod,
663 search, overrides);
664 closedir(sub);
668 return next;
671 static struct module *grab_basedir(const char *dirname,
672 struct module_search *search,
673 struct module_overrides *overrides)
675 DIR *dir;
676 struct module *list;
678 dir = opendir(dirname);
679 if (!dir) {
680 warn("Couldn't open directory %s: %s\n",
681 dirname, strerror(errno));
682 return NULL;
684 list = grab_dir(dirname, dir, NULL, do_module, search, overrides);
685 closedir(dir);
687 return list;
690 static void parse_modules(struct module *list)
692 struct module *i;
694 for (i = list; i; i = i->next) {
695 i->ops->load_symbols(i);
696 i->ops->fetch_tables(i);
700 /* Convert filename to the module name. Works if filename == modname, too. */
701 static void filename2modname(char *modname, const char *filename)
703 const char *afterslash;
704 unsigned int i;
706 afterslash = strrchr(filename, '/');
707 if (!afterslash)
708 afterslash = filename;
709 else
710 afterslash++;
712 /* Convert to underscores, stop at first . */
713 for (i = 0; afterslash[i] && afterslash[i] != '.'; i++) {
714 if (afterslash[i] == '-')
715 modname[i] = '_';
716 else
717 modname[i] = afterslash[i];
719 modname[i] = '\0';
722 /* Simply dump hash table. */
723 static void output_symbols(struct module *unused, FILE *out)
725 unsigned int i;
727 fprintf(out, "# Aliases for symbols, used by symbol_request().\n");
728 for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
729 struct symbol *s;
731 for (s = symbolhash[i]; s; s = s->next) {
732 if (s->owner) {
733 char modname[strlen(s->owner->pathname)+1];
734 filename2modname(modname, s->owner->pathname);
735 fprintf(out, "alias symbol:%s %s\n",
736 s->name, modname);
742 static const char *next_string(const char *string, unsigned long *secsize)
744 /* Skip non-zero chars */
745 while (string[0]) {
746 string++;
747 if ((*secsize)-- <= 1)
748 return NULL;
751 /* Skip any zero padding. */
752 while (!string[0]) {
753 string++;
754 if ((*secsize)-- <= 1)
755 return NULL;
757 return string;
760 static void output_aliases(struct module *modules, FILE *out)
762 struct module *i;
763 const char *p;
764 unsigned long size;
766 fprintf(out, "# Aliases extracted from modules themselves.\n");
767 for (i = modules; i; i = i->next) {
768 char modname[strlen(i->pathname)+1];
770 filename2modname(modname, i->pathname);
772 /* Grab from old-style .modalias section. */
773 for (p = i->ops->get_aliases(i, &size);
775 p = next_string(p, &size))
776 fprintf(out, "alias %s %s\n", p, modname);
778 /* Grab form new-style .modinfo section. */
779 for (p = i->ops->get_modinfo(i, &size);
781 p = next_string(p, &size)) {
782 if (strncmp(p, "alias=", strlen("alias=")) == 0)
783 fprintf(out, "alias %s %s\n",
784 p + strlen("alias="), modname);
789 struct depfile {
790 char *name;
791 void (*func)(struct module *, FILE *);
794 static struct depfile depfiles[] = {
795 { "modules.dep", output_deps }, /* This is what we check for '-A'. */
796 { "modules.pcimap", output_pci_table },
797 { "modules.usbmap", output_usb_table },
798 { "modules.ccwmap", output_ccw_table },
799 { "modules.ieee1394map", output_ieee1394_table },
800 { "modules.isapnpmap", output_isapnp_table },
801 { "modules.inputmap", output_input_table },
802 { "modules.ofmap", output_of_table },
803 { "modules.seriomap", output_serio_table },
804 { "modules.alias", output_aliases },
805 { "modules.symbols", output_symbols },
808 /* If we can't figure it out, it's safe to say "true". */
809 static int any_modules_newer(const char *dirname, time_t mtime)
811 DIR *dir;
812 struct dirent *dirent;
814 dir = opendir(dirname);
815 if (!dir)
816 return 1;
818 while ((dirent = readdir(dir)) != NULL) {
819 struct stat st;
820 char file[strlen(dirname) + 1 + strlen(dirent->d_name) + 1];
822 if (streq(dirent->d_name, ".") || streq(dirent->d_name, ".."))
823 continue;
825 sprintf(file, "%s/%s", dirname, dirent->d_name);
826 if (lstat(file, &st) != 0)
827 goto ret_true;
829 if (smells_like_module(dirent->d_name)) {
830 if (st.st_mtime > mtime)
831 goto ret_true;
832 } else if (S_ISDIR(st.st_mode)) {
833 if (any_modules_newer(file, mtime))
834 goto ret_true;
837 closedir(dir);
838 return 0;
840 ret_true:
841 closedir(dir);
842 return 1;
845 static int depfile_out_of_date(const char *dirname)
847 struct stat st;
848 char depfile[strlen(dirname) + 1 + strlen(depfiles[0].name) + 1];
850 sprintf(depfile, "%s/%s", dirname, depfiles[0].name);
852 if (stat(depfile, &st) != 0)
853 return 1;
855 return any_modules_newer(dirname, st.st_mtime);
858 static char *getline_wrapped(FILE *file, unsigned int *linenum)
860 int size = 256;
861 int i = 0;
862 char *buf = NOFAIL(malloc(size));
863 for(;;) {
864 int ch = getc_unlocked(file);
866 switch(ch) {
867 case EOF:
868 if (i == 0) {
869 free(buf);
870 return NULL;
872 /* else fall through */
874 case '\n':
875 if (linenum)
876 (*linenum)++;
877 if (i == size)
878 buf = NOFAIL(realloc(buf, size + 1));
879 buf[i] = '\0';
880 return buf;
882 case '\\':
883 ch = getc_unlocked(file);
885 if (ch == '\n') {
886 if (linenum)
887 (*linenum)++;
888 continue;
890 /* else fall through */
892 default:
893 buf[i++] = ch;
895 if (i == size) {
896 size *= 2;
897 buf = NOFAIL(realloc(buf, size));
904 static char *strsep_skipspace(char **string, char *delim)
906 if (!*string)
907 return NULL;
908 *string += strspn(*string, delim);
909 return strsep(string, delim);
912 static struct module_search *add_search(const char *search_path,
913 struct module_search *search)
916 struct module_search *new;
918 new = NOFAIL(malloc(sizeof(*new)));
919 new->search_path = NOFAIL(strdup(search_path));
920 new->next = search;
922 return new;
926 static struct module_overrides *add_override(const char *modfile,
927 struct module_overrides *overrides)
930 struct module_overrides *new;
932 new = NOFAIL(malloc(sizeof(*new)));
933 new->modfile = NOFAIL(strdup(modfile));
934 new->next = overrides;
936 return new;
940 /* Recursion */
941 static int read_config(const char *filename,
942 const char *basedir,
943 struct module_search **search,
944 struct module_overrides **overrides);
946 static int read_config_file(const char *filename,
947 const char *basedir,
948 struct module_search **search,
949 struct module_overrides **overrides)
951 char *line;
952 unsigned int linenum = 0;
953 FILE *cfile;
955 cfile = fopen(filename, "r");
956 if (!cfile) {
957 if (errno != ENOENT)
958 fatal("could not open '%s', reason: %s\n", filename,
959 strerror(errno));
960 return 0;
963 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
964 char *ptr = line;
965 char *cmd, *modname;
967 cmd = strsep_skipspace(&ptr, "\t ");
969 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
970 free(line);
971 continue;
974 if (strcmp(cmd, "search") == 0) {
975 char *search_path;
977 while ((search_path = strsep_skipspace(&ptr, "\t ")))
978 *search = add_search(search_path, *search);
979 } else if (strcmp(cmd, "override") == 0) {
980 char *pathname = NULL, *version, *subdir;
981 modname = strsep_skipspace(&ptr, "\t ");
982 version = strsep_skipspace(&ptr, "\t ");
983 subdir = strsep_skipspace(&ptr, "\t ");
985 pathname = NOFAIL(malloc(strlen(basedir)
986 + strlen(MODULE_DIR)
987 + strlen(version)
988 + strlen(subdir)
989 + strlen(modname)
990 + strlen(".ko")
991 + 3));
992 sprintf(pathname, "%s%s%s/%s/%s.ko", basedir,
993 MODULE_DIR, version, subdir, modname);
995 *overrides = add_override(pathname, *overrides);
996 } else if (strcmp(cmd, "include") == 0) {
997 char *newfilename;
999 newfilename = strsep_skipspace(&ptr, "\t ");
1000 if (!newfilename)
1001 grammar(cmd, filename, linenum);
1002 else {
1003 if (!read_config(newfilename, basedir,
1004 search, overrides))
1005 warn("Failed to open included"
1006 " config file %s: %s\n",
1007 newfilename, strerror(errno));
1009 } else
1010 grammar(cmd, filename, linenum);
1012 free(line);
1014 fclose(cfile);
1015 return 1;
1018 /* Simple format, ignore lines starting with #, one command per line.
1019 Returns true or false. */
1020 static int read_config(const char *filename,
1021 const char *basedir,
1022 struct module_search **search,
1023 struct module_overrides **overrides)
1025 DIR *dir;
1026 int ret = 0;
1028 dir = opendir(filename);
1029 if (dir) {
1030 struct dirent *i;
1031 while ((i = readdir(dir)) != NULL) {
1032 if (!streq(i->d_name,".") && !streq(i->d_name,"..")) {
1033 char sub[strlen(filename) + 1
1034 + strlen(i->d_name) + 1];
1036 sprintf(sub, "%s/%s", filename, i->d_name);
1037 if (!read_config(sub, basedir, search,
1038 overrides))
1039 warn("Failed to open"
1040 " config file %s: %s\n",
1041 sub, strerror(errno));
1044 closedir(dir);
1045 ret = 1;
1046 } else {
1047 if (read_config_file(filename, basedir, search, overrides))
1048 ret = 1;
1051 return ret;
1054 static const char *default_configs[] =
1056 "/etc/depmod.conf",
1057 "/etc/depmod.d",
1060 static void read_toplevel_config(const char *filename,
1061 const char *basedir,
1062 struct module_search **search,
1063 struct module_overrides **overrides)
1065 unsigned int i;
1067 if (filename) {
1068 if (!read_config(filename, basedir, search, overrides))
1069 fatal("Failed to open config file %s: %s\n",
1070 filename, strerror(errno));
1071 return;
1074 /* Try defaults. */
1075 for (i = 0; i < ARRAY_SIZE(default_configs); i++) {
1076 if (read_config(default_configs[i], basedir, search, overrides))
1077 return;
1081 /* Local to main, but not freed on exit. Keep valgrind quiet. */
1082 struct module *list = NULL;
1083 struct module_search *search = NULL;
1084 struct module_overrides *overrides = NULL;
1086 int main(int argc, char *argv[])
1088 int opt, all = 0, maybe_all = 0, doing_stdout = 0;
1089 char *basedir = "", *dirname, *version, *badopt = NULL,
1090 *system_map = NULL;
1091 int i;
1092 const char *config = NULL;
1094 /* Don't print out any errors just yet, we might want to exec
1095 backwards compat version. */
1096 opterr = 0;
1097 while ((opt = getopt_long(argc, argv, "ab:ArehnqruvVF:C:", options, NULL))
1098 != -1) {
1099 switch (opt) {
1100 case 'a':
1101 all = 1;
1102 break;
1103 case 'b':
1104 basedir = optarg;
1105 skipchars = strlen(basedir);
1106 break;
1107 case 'A':
1108 maybe_all = 1;
1109 break;
1110 case 'F':
1111 system_map = optarg;
1112 break;
1113 case 'e':
1114 print_unknown = 1;
1115 break;
1116 case 'v':
1117 verbose = 1;
1118 break;
1119 case 'u':
1120 case 'q':
1121 case 'r':
1122 break;
1123 case 'C':
1124 config = optarg;
1125 break;
1126 case 'h':
1127 print_usage(argv[0]);
1128 exit(0);
1129 break;
1130 case 'n':
1131 doing_stdout = 1;
1132 break;
1133 case 'V':
1134 printf("%s %s\n", PACKAGE, VERSION);
1135 exit(0);
1136 default:
1137 badopt = argv[optind-1];
1141 /* We can't print unknowns without a System.map */
1142 if (!system_map)
1143 print_unknown = 0;
1144 else
1145 load_system_map(system_map);
1147 /* They can specify the version naked on the command line */
1148 if (optind < argc && is_version_number(argv[optind])) {
1149 version = NOFAIL(strdup(argv[optind]));
1150 optind++;
1151 } else {
1152 struct utsname buf;
1153 uname(&buf);
1154 version = NOFAIL(strdup(buf.release));
1157 /* Run old version if required. */
1158 if (old_module_version(version))
1159 exec_old_depmod(argv);
1161 if (badopt) {
1162 fprintf(stderr, "%s: malformed/unrecognized option '%s'\n",
1163 argv[0], badopt);
1164 print_usage(argv[0]);
1165 exit(1);
1168 /* Depmod -a by default if no names. */
1169 if (optind == argc)
1170 all = 1;
1172 dirname = NOFAIL(malloc(strlen(basedir)
1173 + strlen(MODULE_DIR)
1174 + strlen(version) + 1));
1175 sprintf(dirname, "%s%s%s", basedir, MODULE_DIR, version);
1177 if (maybe_all) {
1178 if (!doing_stdout && !depfile_out_of_date(dirname))
1179 exit(0);
1180 all = 1;
1183 read_toplevel_config(config, basedir, &search, &overrides);
1185 /* For backward compatibility add "updates" to the head of the search
1186 * list here. But only if there was no "search" option specified.
1189 if (!search)
1190 search = add_search("updates",search);
1192 if (!all) {
1193 /* Do command line args. */
1194 for (opt = optind; opt < argc; opt++) {
1195 struct module *new = grab_module(NULL, argv[opt]);
1196 if (new) {
1197 new->next = list;
1198 list = new;
1201 } else {
1202 list = grab_basedir(dirname,search,overrides);
1204 parse_modules(list);
1206 for (i = 0; i < sizeof(depfiles)/sizeof(depfiles[0]); i++) {
1207 FILE *out;
1208 struct depfile *d = &depfiles[i];
1209 char depname[strlen(dirname) + 1 + strlen(d->name) + 1];
1210 char tmpname[strlen(dirname) + 1 + strlen(d->name) +
1211 strlen(".temp") + 1];
1213 sprintf(depname, "%s/%s", dirname, d->name);
1214 sprintf(tmpname, "%s/%s.temp", dirname, d->name);
1215 if (!doing_stdout) {
1216 out = fopen(tmpname, "w");
1217 if (!out)
1218 fatal("Could not open %s for writing: %s\n",
1219 tmpname, strerror(errno));
1220 } else
1221 out = stdout;
1222 d->func(list, out);
1223 if (!doing_stdout) {
1224 fclose(out);
1225 if (rename(tmpname, depname) < 0)
1226 fatal("Could not rename %s into %s: %s\n",
1227 tmpname, depname, strerror(errno));
1231 free(dirname);
1232 free(version);
1234 return 0;