Reduce valgrind memory leak warnings in depmod and modprobe
[mit.git] / depmod.c
blob58d4c30630e2c85611a85b59ead669e967f8f602
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 struct module *deleted = NULL;
463 static void del_module(struct module **modules, struct module *delme)
465 struct module **i;
467 /* Find pointer to it. */
468 if (modules) {
469 for (i = modules; *i != delme; i = &(*i)->next);
471 *i = delme->next;
474 /* Save on a list to quiet valgrind.
475 Can't free - other modules may depend on them */
476 delme->next = deleted;
477 deleted = delme;
480 static void output_deps(struct module *modules,
481 FILE *out)
483 struct module *i;
485 for (i = modules; i; i = i->next)
486 i->ops->calculate_deps(i, verbose);
488 /* Strip out loops. */
489 again:
490 for (i = modules; i; i = i->next) {
491 if (has_dep_loop(i, NULL)) {
492 warn("Module %s ignored, due to loop\n",
493 i->pathname + skipchars);
494 del_module(&modules, i);
495 goto again;
499 /* Now dump them out. */
500 for (i = modules; i; i = i->next) {
501 struct list_head *j, *tmp;
502 order_dep_list(i, i);
504 fprintf(out, "%s:", i->pathname + skipchars);
505 list_for_each_safe(j, tmp, &i->dep_list) {
506 struct module *dep
507 = list_entry(j, struct module, dep_list);
508 fprintf(out, " %s", dep->pathname + skipchars);
509 list_del_init(j);
511 fprintf(out, "\n");
515 static int smells_like_module(const char *name)
517 return ends_in(name,".ko") || ends_in(name, ".ko.gz");
520 typedef struct module *(*do_module_t)(const char *dirname,
521 const char *filename,
522 struct module *next,
523 struct module_search *search,
524 struct module_overrides *overrides);
526 static int is_higher_priority(const char *newpath, const char *oldpath,
527 struct module_search *search,
528 struct module_overrides *overrides)
530 char *p, *q, *s;
531 struct module_search *tmp;
532 struct module_overrides *ovtmp;
533 int i = 0;
534 int prio_builtin = -1;
535 int prio_new = -1;
536 int prio_old = -1;
538 /* The names already match, now we check for wildcard overrides and other
539 * high priority overrides we added to the config.
541 for (ovtmp=overrides;ovtmp!=NULL;ovtmp=ovtmp->next) {
543 p = strstr(ovtmp->modfile,newpath);
544 if (p)
545 return 1;
547 q = strstr(ovtmp->modfile,"*");
548 if (q) {
549 p = strstr(newpath, q+1);
550 if (p)
551 return 1;
553 p = strstr(oldpath, q+1);
554 if (p)
555 return 0;
558 p = strstr(ovtmp->modfile,oldpath);
559 if (p)
560 return 0;
563 for (i=0,tmp=search;tmp!=NULL;tmp=tmp->next,i++) {
565 s = NOFAIL(malloc(strlen(tmp->search_path)+2));
566 s[0] = '/';
567 strncpy(s+1,tmp->search_path, strlen(tmp->search_path)+1);
569 if (0 == strncmp(tmp->search_path,MODULE_BUILTIN_KEY,
570 strlen(MODULE_BUILTIN_KEY)))
571 prio_builtin = i;
573 p = strstr(newpath,s);
574 if ((p) && ((p[strlen(s)] == '/')
575 || (p[strlen(s)] == '\0')))
576 prio_new = i;
578 p = strstr(oldpath,s);
579 if ((p) && ((p[strlen(s)] == '/')
580 || (p[strlen(s)] == '\0')))
581 prio_old = i;
583 free(s);
587 if (prio_new < 0)
588 prio_new = prio_builtin;
590 if (prio_old < 0)
591 prio_old = prio_builtin;
593 return prio_new > prio_old;
598 static struct module *do_module(const char *dirname,
599 const char *filename,
600 struct module *list,
601 struct module_search *search,
602 struct module_overrides *overrides)
604 struct module *new, **i;
606 new = grab_module(dirname, filename);
607 if (!new)
608 return list;
610 /* Check if module is already in the list. */
611 for (i = &list; *i; i = &(*i)->next) {
613 if (streq(basename((*i)->pathname), filename)) {
614 char newpath[strlen(dirname) + strlen("/")
615 + strlen(filename) + 1];
617 sprintf(newpath, "%s/%s", dirname, filename);
619 if (is_higher_priority(newpath, (*i)->pathname,search,
620 overrides)) {
621 del_module(i, *i);
623 new->next = *i;
624 *i = new;
625 } else
626 del_module(NULL, new);
628 return list;
632 /* Not in the list already. Just prepend. */
633 new->next = list;
634 return new;
637 static struct module *grab_dir(const char *dirname,
638 DIR *dir,
639 struct module *next,
640 do_module_t do_mod,
641 struct module_search *search,
642 struct module_overrides *overrides)
644 struct dirent *dirent;
646 while ((dirent = readdir(dir)) != NULL) {
647 if (smells_like_module(dirent->d_name))
648 next = do_mod(dirname, dirent->d_name, next,
649 search, overrides);
650 else if (!streq(dirent->d_name, ".")
651 && !streq(dirent->d_name, "..")
652 && !streq(dirent->d_name, "source")
653 && !streq(dirent->d_name, "build")) {
655 DIR *sub;
656 char subdir[strlen(dirname) + 1
657 + strlen(dirent->d_name) + 1];
658 sprintf(subdir, "%s/%s", dirname, dirent->d_name);
659 sub = opendir(subdir);
660 if (sub) {
661 next = grab_dir(subdir, sub, next, do_mod,
662 search, overrides);
663 closedir(sub);
667 return next;
670 static struct module *grab_basedir(const char *dirname,
671 struct module_search *search,
672 struct module_overrides *overrides)
674 DIR *dir;
675 struct module *list;
677 dir = opendir(dirname);
678 if (!dir) {
679 warn("Couldn't open directory %s: %s\n",
680 dirname, strerror(errno));
681 return NULL;
683 list = grab_dir(dirname, dir, NULL, do_module, search, overrides);
684 closedir(dir);
686 return list;
689 static void parse_modules(struct module *list)
691 struct module *i;
693 for (i = list; i; i = i->next) {
694 i->ops->load_symbols(i);
695 i->ops->fetch_tables(i);
699 /* Convert filename to the module name. Works if filename == modname, too. */
700 static void filename2modname(char *modname, const char *filename)
702 const char *afterslash;
703 unsigned int i;
705 afterslash = strrchr(filename, '/');
706 if (!afterslash)
707 afterslash = filename;
708 else
709 afterslash++;
711 /* Convert to underscores, stop at first . */
712 for (i = 0; afterslash[i] && afterslash[i] != '.'; i++) {
713 if (afterslash[i] == '-')
714 modname[i] = '_';
715 else
716 modname[i] = afterslash[i];
718 modname[i] = '\0';
721 /* Simply dump hash table. */
722 static void output_symbols(struct module *unused, FILE *out)
724 unsigned int i;
726 fprintf(out, "# Aliases for symbols, used by symbol_request().\n");
727 for (i = 0; i < SYMBOL_HASH_SIZE; i++) {
728 struct symbol *s;
730 for (s = symbolhash[i]; s; s = s->next) {
731 if (s->owner) {
732 char modname[strlen(s->owner->pathname)+1];
733 filename2modname(modname, s->owner->pathname);
734 fprintf(out, "alias symbol:%s %s\n",
735 s->name, modname);
741 static const char *next_string(const char *string, unsigned long *secsize)
743 /* Skip non-zero chars */
744 while (string[0]) {
745 string++;
746 if ((*secsize)-- <= 1)
747 return NULL;
750 /* Skip any zero padding. */
751 while (!string[0]) {
752 string++;
753 if ((*secsize)-- <= 1)
754 return NULL;
756 return string;
759 static void output_aliases(struct module *modules, FILE *out)
761 struct module *i;
762 const char *p;
763 unsigned long size;
765 fprintf(out, "# Aliases extracted from modules themselves.\n");
766 for (i = modules; i; i = i->next) {
767 char modname[strlen(i->pathname)+1];
769 filename2modname(modname, i->pathname);
771 /* Grab from old-style .modalias section. */
772 for (p = i->ops->get_aliases(i, &size);
774 p = next_string(p, &size))
775 fprintf(out, "alias %s %s\n", p, modname);
777 /* Grab form new-style .modinfo section. */
778 for (p = i->ops->get_modinfo(i, &size);
780 p = next_string(p, &size)) {
781 if (strncmp(p, "alias=", strlen("alias=")) == 0)
782 fprintf(out, "alias %s %s\n",
783 p + strlen("alias="), modname);
788 struct depfile {
789 char *name;
790 void (*func)(struct module *, FILE *);
793 static struct depfile depfiles[] = {
794 { "modules.dep", output_deps }, /* This is what we check for '-A'. */
795 { "modules.pcimap", output_pci_table },
796 { "modules.usbmap", output_usb_table },
797 { "modules.ccwmap", output_ccw_table },
798 { "modules.ieee1394map", output_ieee1394_table },
799 { "modules.isapnpmap", output_isapnp_table },
800 { "modules.inputmap", output_input_table },
801 { "modules.ofmap", output_of_table },
802 { "modules.seriomap", output_serio_table },
803 { "modules.alias", output_aliases },
804 { "modules.symbols", output_symbols },
807 /* If we can't figure it out, it's safe to say "true". */
808 static int any_modules_newer(const char *dirname, time_t mtime)
810 DIR *dir;
811 struct dirent *dirent;
813 dir = opendir(dirname);
814 if (!dir)
815 return 1;
817 while ((dirent = readdir(dir)) != NULL) {
818 struct stat st;
819 char file[strlen(dirname) + 1 + strlen(dirent->d_name) + 1];
821 if (streq(dirent->d_name, ".") || streq(dirent->d_name, ".."))
822 continue;
824 sprintf(file, "%s/%s", dirname, dirent->d_name);
825 if (lstat(file, &st) != 0)
826 goto ret_true;
828 if (smells_like_module(dirent->d_name)) {
829 if (st.st_mtime > mtime)
830 goto ret_true;
831 } else if (S_ISDIR(st.st_mode)) {
832 if (any_modules_newer(file, mtime))
833 goto ret_true;
836 closedir(dir);
837 return 0;
839 ret_true:
840 closedir(dir);
841 return 1;
844 static int depfile_out_of_date(const char *dirname)
846 struct stat st;
847 char depfile[strlen(dirname) + 1 + strlen(depfiles[0].name) + 1];
849 sprintf(depfile, "%s/%s", dirname, depfiles[0].name);
851 if (stat(depfile, &st) != 0)
852 return 1;
854 return any_modules_newer(dirname, st.st_mtime);
857 static int fgetc_wrapped(FILE *file, unsigned int *linenum)
859 for (;;) {
860 int ch = fgetc(file);
861 if (ch != '\\')
862 return ch;
863 ch = fgetc(file);
864 if (ch != '\n')
865 return ch;
866 if (linenum)
867 (*linenum)++;
871 static char *getline_wrapped(FILE *file, unsigned int *linenum)
873 int size = 1024;
874 int i = 0;
875 char *buf = NOFAIL(malloc(size));
876 for(;;) {
877 int ch = fgetc_wrapped(file, linenum);
878 if (i == size) {
879 size *= 2;
880 buf = NOFAIL(realloc(buf, size));
882 if (ch < 0 && i == 0) {
883 free(buf);
884 return NULL;
886 if (ch < 0 || ch == '\n') {
887 if (linenum)
888 (*linenum)++;
889 buf[i] = '\0';
890 return NOFAIL(realloc(buf, i+1));
892 buf[i++] = ch;
897 static char *strsep_skipspace(char **string, char *delim)
899 if (!*string)
900 return NULL;
901 *string += strspn(*string, delim);
902 return strsep(string, delim);
905 static struct module_search *add_search(const char *search_path,
906 struct module_search *search)
909 struct module_search *new;
911 new = NOFAIL(malloc(sizeof(*new)));
912 new->search_path = NOFAIL(strdup(search_path));
913 new->next = search;
915 return new;
919 static struct module_overrides *add_override(const char *modfile,
920 struct module_overrides *overrides)
923 struct module_overrides *new;
925 new = NOFAIL(malloc(sizeof(*new)));
926 new->modfile = NOFAIL(strdup(modfile));
927 new->next = overrides;
929 return new;
933 /* Recursion */
934 static int read_config(const char *filename,
935 const char *basedir,
936 struct module_search **search,
937 struct module_overrides **overrides);
939 static int read_config_file(const char *filename,
940 const char *basedir,
941 struct module_search **search,
942 struct module_overrides **overrides)
944 char *line;
945 unsigned int linenum = 0;
946 FILE *cfile;
948 cfile = fopen(filename, "r");
949 if (!cfile) {
950 if (errno != ENOENT)
951 fatal("could not open '%s', reason: %s\n", filename,
952 strerror(errno));
953 return 0;
956 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
957 char *ptr = line;
958 char *cmd, *modname;
960 cmd = strsep_skipspace(&ptr, "\t ");
962 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
963 free(line);
964 continue;
967 if (strcmp(cmd, "search") == 0) {
968 char *search_path;
970 while ((search_path = strsep_skipspace(&ptr, "\t ")))
971 *search = add_search(search_path, *search);
972 } else if (strcmp(cmd, "override") == 0) {
973 char *pathname = NULL, *version, *subdir;
974 modname = strsep_skipspace(&ptr, "\t ");
975 version = strsep_skipspace(&ptr, "\t ");
976 subdir = strsep_skipspace(&ptr, "\t ");
978 pathname = NOFAIL(malloc(strlen(basedir)
979 + strlen(MODULE_DIR)
980 + strlen(version)
981 + strlen(subdir)
982 + strlen(modname)
983 + strlen(".ko")
984 + 3));
985 sprintf(pathname, "%s%s%s/%s/%s.ko", basedir,
986 MODULE_DIR, version, subdir, modname);
988 *overrides = add_override(pathname, *overrides);
989 } else if (strcmp(cmd, "include") == 0) {
990 char *newfilename;
992 newfilename = strsep_skipspace(&ptr, "\t ");
993 if (!newfilename)
994 grammar(cmd, filename, linenum);
995 else {
996 if (!read_config(newfilename, basedir,
997 search, overrides))
998 warn("Failed to open included"
999 " config file %s: %s\n",
1000 newfilename, strerror(errno));
1002 } else
1003 grammar(cmd, filename, linenum);
1005 free(line);
1007 fclose(cfile);
1008 return 1;
1011 /* Simple format, ignore lines starting with #, one command per line.
1012 Returns true or false. */
1013 static int read_config(const char *filename,
1014 const char *basedir,
1015 struct module_search **search,
1016 struct module_overrides **overrides)
1018 DIR *dir;
1019 int ret = 0;
1021 dir = opendir(filename);
1022 if (dir) {
1023 struct dirent *i;
1024 while ((i = readdir(dir)) != NULL) {
1025 if (!streq(i->d_name,".") && !streq(i->d_name,"..")) {
1026 char sub[strlen(filename) + 1
1027 + strlen(i->d_name) + 1];
1029 sprintf(sub, "%s/%s", filename, i->d_name);
1030 if (!read_config(sub, basedir, search,
1031 overrides))
1032 warn("Failed to open"
1033 " config file %s: %s\n",
1034 sub, strerror(errno));
1037 closedir(dir);
1038 ret = 1;
1039 } else {
1040 if (read_config_file(filename, basedir, search, overrides))
1041 ret = 1;
1044 return ret;
1047 static const char *default_configs[] =
1049 "/etc/depmod.conf",
1050 "/etc/depmod.d",
1053 static void read_toplevel_config(const char *filename,
1054 const char *basedir,
1055 struct module_search **search,
1056 struct module_overrides **overrides)
1058 unsigned int i;
1060 if (filename) {
1061 if (!read_config(filename, basedir, search, overrides))
1062 fatal("Failed to open config file %s: %s\n",
1063 filename, strerror(errno));
1064 return;
1067 /* Try defaults. */
1068 for (i = 0; i < ARRAY_SIZE(default_configs); i++) {
1069 if (read_config(default_configs[i], basedir, search, overrides))
1070 return;
1074 /* Local to main, but not freed on exit. Keep valgrind quiet. */
1075 struct module *list = NULL;
1076 struct module_search *search = NULL;
1077 struct module_overrides *overrides = NULL;
1079 int main(int argc, char *argv[])
1081 int opt, all = 0, maybe_all = 0, doing_stdout = 0;
1082 char *basedir = "", *dirname, *version, *badopt = NULL,
1083 *system_map = NULL;
1084 int i;
1085 const char *config = NULL;
1087 /* Don't print out any errors just yet, we might want to exec
1088 backwards compat version. */
1089 opterr = 0;
1090 while ((opt = getopt_long(argc, argv, "ab:ArehnqruvVF:C:", options, NULL))
1091 != -1) {
1092 switch (opt) {
1093 case 'a':
1094 all = 1;
1095 break;
1096 case 'b':
1097 basedir = optarg;
1098 skipchars = strlen(basedir);
1099 break;
1100 case 'A':
1101 maybe_all = 1;
1102 break;
1103 case 'F':
1104 system_map = optarg;
1105 break;
1106 case 'e':
1107 print_unknown = 1;
1108 break;
1109 case 'v':
1110 verbose = 1;
1111 break;
1112 case 'u':
1113 case 'q':
1114 case 'r':
1115 break;
1116 case 'C':
1117 config = optarg;
1118 break;
1119 case 'h':
1120 print_usage(argv[0]);
1121 exit(0);
1122 break;
1123 case 'n':
1124 doing_stdout = 1;
1125 break;
1126 case 'V':
1127 printf("%s %s\n", PACKAGE, VERSION);
1128 exit(0);
1129 default:
1130 badopt = argv[optind-1];
1134 /* We can't print unknowns without a System.map */
1135 if (!system_map)
1136 print_unknown = 0;
1137 else
1138 load_system_map(system_map);
1140 /* They can specify the version naked on the command line */
1141 if (optind < argc && is_version_number(argv[optind])) {
1142 version = NOFAIL(strdup(argv[optind]));
1143 optind++;
1144 } else {
1145 struct utsname buf;
1146 uname(&buf);
1147 version = NOFAIL(strdup(buf.release));
1150 /* Run old version if required. */
1151 if (old_module_version(version))
1152 exec_old_depmod(argv);
1154 if (badopt) {
1155 fprintf(stderr, "%s: malformed/unrecognized option '%s'\n",
1156 argv[0], badopt);
1157 print_usage(argv[0]);
1158 exit(1);
1161 /* Depmod -a by default if no names. */
1162 if (optind == argc)
1163 all = 1;
1165 dirname = NOFAIL(malloc(strlen(basedir)
1166 + strlen(MODULE_DIR)
1167 + strlen(version) + 1));
1168 sprintf(dirname, "%s%s%s", basedir, MODULE_DIR, version);
1170 if (maybe_all) {
1171 if (!doing_stdout && !depfile_out_of_date(dirname))
1172 exit(0);
1173 all = 1;
1176 read_toplevel_config(config, basedir, &search, &overrides);
1178 /* For backward compatibility add "updates" to the head of the search
1179 * list here. But only if there was no "search" option specified.
1182 if (!search)
1183 search = add_search("updates",search);
1185 if (!all) {
1186 /* Do command line args. */
1187 for (opt = optind; opt < argc; opt++) {
1188 struct module *new = grab_module(NULL, argv[opt]);
1189 if (new) {
1190 new->next = list;
1191 list = new;
1194 } else {
1195 list = grab_basedir(dirname,search,overrides);
1197 parse_modules(list);
1199 for (i = 0; i < sizeof(depfiles)/sizeof(depfiles[0]); i++) {
1200 FILE *out;
1201 struct depfile *d = &depfiles[i];
1202 char depname[strlen(dirname) + 1 + strlen(d->name) + 1];
1203 char tmpname[strlen(dirname) + 1 + strlen(d->name) +
1204 strlen(".temp") + 1];
1206 sprintf(depname, "%s/%s", dirname, d->name);
1207 sprintf(tmpname, "%s/%s.temp", dirname, d->name);
1208 if (!doing_stdout) {
1209 out = fopen(tmpname, "w");
1210 if (!out)
1211 fatal("Could not open %s for writing: %s\n",
1212 tmpname, strerror(errno));
1213 } else
1214 out = stdout;
1215 d->func(list, out);
1216 if (!doing_stdout) {
1217 fclose(out);
1218 if (rename(tmpname, depname) < 0)
1219 fatal("Could not rename %s into %s: %s\n",
1220 tmpname, depname, strerror(errno));
1224 free(dirname);
1225 free(version);
1227 return 0;