1 /* vi: set sw=4 ts=4: */
5 * Copyright (c) 2008 Vladimir Dronnikov
6 * Copyright (c) 2008 Bernhard Fischer (initial depmod code)
8 * Licensed under GPLv2, see file LICENSE in this tarball for details.
12 #include "unarchive.h"
14 #include <sys/utsname.h> /* uname() */
17 extern int init_module(void *module, unsigned long len, const char *options);
18 extern int delete_module(const char *module, unsigned flags);
19 extern int query_module(const char *name, int which, void *buf, size_t bufsize, size_t *ret);
22 #define dbg1_error_msg(...) ((void)0)
23 #define dbg2_error_msg(...) ((void)0)
24 //#define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
25 //#define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
27 #define DEPFILE_BB CONFIG_DEFAULT_DEPMOD_FILE".bb"
30 OPT_q = (1 << 0), /* be quiet */
31 OPT_r = (1 << 1), /* module removal instead of loading */
34 typedef struct module_info {
45 char *module_load_options;
47 smallint wrote_dep_bb_ok;
51 char stringbuf[32 * 1024]; /* some modules have lots of stuff */
52 /* for example, drivers/media/video/saa7134/saa7134.ko */
54 #define G (*ptr_to_globals)
55 #define modinfo (G.modinfo )
56 #define dep_bb_seen (G.dep_bb_seen )
57 #define wrote_dep_bb_ok (G.wrote_dep_bb_ok )
58 #define module_count (G.module_count )
59 #define module_found_idx (G.module_found_idx )
60 #define module_load_options (G.module_load_options)
61 #define stringbuf_idx (G.stringbuf_idx )
62 #define stringbuf (G.stringbuf )
63 #define INIT_G() do { \
64 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
68 static void appendc(char c)
70 if (stringbuf_idx < sizeof(stringbuf))
71 stringbuf[stringbuf_idx++] = c;
74 static void bksp(void)
80 static void append(const char *s)
82 size_t len = strlen(s);
83 if (stringbuf_idx + len < sizeof(stringbuf)) {
84 memcpy(stringbuf + stringbuf_idx, s, len);
89 static void reset_stringbuf(void)
94 static char* copy_stringbuf(void)
96 char *copy = xmalloc(stringbuf_idx);
97 return memcpy(copy, stringbuf, stringbuf_idx);
100 static char* find_keyword(char *ptr, size_t len, const char *word)
104 if (!ptr) /* happens if read_module cannot read it */
109 while ((ssize_t)len > 0) {
111 /* search for the first char in word */
112 ptr = memchr(ptr, *word, len);
113 if (ptr == NULL) /* no occurance left, done */
115 if (strncmp(ptr, word, wlen) == 0)
116 return ptr + wlen; /* found, return ptr past it */
123 static void replace(char *s, char what, char with)
132 /* Take "word word", return malloced "word",NUL,"word",NUL,NUL */
133 static char* str_2_list(const char *str)
135 int len = strlen(str) + 1;
136 char *dst = xmalloc(len + 1);
139 memcpy(dst, str, len);
140 //TODO: protect against 2+ spaces: "word word"
141 replace(dst, ' ', '\0');
145 #if ENABLE_FEATURE_MODPROBE_SMALL_ZIPPED
146 static char *xmalloc_open_zipped_read_close(const char *fname, size_t *sizep)
152 int fd = open_or_warn(fname, O_RDONLY);
156 suffix = strrchr(fname, '.');
158 if (strcmp(suffix, ".gz") == 0)
159 fd = open_transformer(fd, unpack_gz_stream, "gunzip");
160 else if (strcmp(suffix, ".bz2") == 0)
161 fd = open_transformer(fd, unpack_bz2_stream, "bunzip2");
164 len = (sizep) ? *sizep : 64 * 1024 * 1024;
165 image = xmalloc_read(fd, &len);
167 bb_perror_msg("read error from '%s'", fname);
174 # define read_module xmalloc_open_zipped_read_close
176 # define read_module xmalloc_open_read_close
179 /* We use error numbers in a loose translation... */
180 static const char *moderror(int err)
184 return "invalid module format";
186 return "unknown symbol in module or invalid parameter";
188 return "module has wrong symbol version";
189 case EINVAL: /* "invalid parameter" */
190 return "unknown symbol in module or invalid parameter"
191 + sizeof("unknown symbol in module or");
193 return strerror(err);
197 static int load_module(const char *fname, const char *options)
201 size_t len = MAXINT(ssize_t);
203 dbg1_error_msg("load_module('%s','%s')", fname, options);
205 module_image = read_module(fname, &len);
206 r = (!module_image || init_module(module_image, len, options ? options : "") != 0);
208 dbg1_error_msg("load_module:%d", r);
209 return r; /* 0 = success */
212 dbg1_error_msg("load_module('%s','%s')", fname, options);
217 static void parse_module(module_info *info, const char *pathname)
223 dbg1_error_msg("parse_module('%s')", pathname);
225 /* Read (possibly compressed) module */
226 len = 64 * 1024 * 1024; /* 64 Mb at most */
227 module_image = read_module(pathname, &len);
228 //TODO: optimize redundant module body reads
230 /* "alias1 symbol:sym1 alias2 symbol:sym2" */
234 ptr = find_keyword(module_image + pos, len - pos, "alias=");
236 ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
239 /* DOCME: __ksymtab_gpl and __ksymtab_strings occur
240 * in many modules. What do they mean? */
241 if (strcmp(ptr, "gpl") == 0 || strcmp(ptr, "strings") == 0)
243 dbg2_error_msg("alias:'symbol:%s'", ptr);
246 dbg2_error_msg("alias:'%s'", ptr);
251 pos = (ptr - module_image);
253 bksp(); /* remove last ' ' */
255 info->aliases = copy_stringbuf();
257 /* "dependency1 depandency2" */
259 ptr = find_keyword(module_image, len, "depends=");
261 replace(ptr, ',', ' ');
262 replace(ptr, '-', '_');
263 dbg2_error_msg("dep:'%s'", ptr);
267 info->deps = copy_stringbuf();
272 static int pathname_matches_modname(const char *pathname, const char *modname)
274 const char *fname = bb_get_last_path_component_nostrip(pathname);
275 const char *suffix = strrstr(fname, ".ko");
276 //TODO: can do without malloc?
277 char *name = xstrndup(fname, suffix - fname);
279 replace(name, '-', '_');
280 r = (strcmp(name, modname) == 0);
285 static FAST_FUNC int fileAction(const char *pathname,
286 struct stat *sb UNUSED_PARAM,
287 void *modname_to_match,
288 int depth UNUSED_PARAM)
293 pathname += 2; /* skip "./" */
294 fname = bb_get_last_path_component_nostrip(pathname);
295 if (!strrstr(fname, ".ko")) {
296 dbg1_error_msg("'%s' is not a module", pathname);
297 return TRUE; /* not a module, continue search */
300 cur = module_count++;
301 modinfo = xrealloc_vector(modinfo, 12, cur);
302 //TODO: use zeroing version of xrealloc_vector?
303 modinfo[cur].pathname = xstrdup(pathname);
304 modinfo[cur].aliases = NULL;
305 modinfo[cur+1].pathname = NULL;
307 if (!pathname_matches_modname(fname, modname_to_match)) {
308 dbg1_error_msg("'%s' module name doesn't match", pathname);
309 return TRUE; /* module name doesn't match, continue search */
312 dbg1_error_msg("'%s' module name matches", pathname);
313 module_found_idx = cur;
314 parse_module(&modinfo[cur], pathname);
316 if (!(option_mask32 & OPT_r)) {
317 if (load_module(pathname, module_load_options) == 0) {
318 /* Load was successful, there is nothing else to do.
319 * This can happen ONLY for "top-level" module load,
320 * not a dep, because deps dont do dirscan. */
328 static int load_dep_bb(void)
331 FILE *fp = fopen(DEPFILE_BB, "r");
337 dbg1_error_msg("loading "DEPFILE_BB);
339 /* Why? There is a rare scenario: we did not find modprobe.dep.bb,
340 * we scanned the dir and found no module by name, then we search
341 * for alias (full scan), and we decided to generate modprobe.dep.bb.
342 * But we see modprobe.dep.bb.new! Other modprobe is at work!
343 * We wait and other modprobe renames it to modprobe.dep.bb.
345 * But we already have modinfo[] filled, and "module_count = 0"
346 * makes us start anew. Yes, we leak modinfo[].xxx pointers -
347 * there is not much of data there anyway. */
349 memset(&modinfo[0], 0, sizeof(modinfo[0]));
351 while ((line = xmalloc_fgetline(fp)) != NULL) {
359 space = strchrnul(line, ' ');
360 cur = module_count++;
361 modinfo = xrealloc_vector(modinfo, 12, cur);
362 //TODO: use zeroing version of xrealloc_vector?
363 modinfo[cur+1].pathname = NULL;
364 modinfo[cur].pathname = line; /* we take ownership of malloced block here */
367 modinfo[cur].aliases = space;
368 modinfo[cur].deps = xmalloc_fgetline(fp) ? : xzalloc(1);
369 if (modinfo[cur].deps[0]) {
370 /* deps are not "", so next line must be empty */
371 line = xmalloc_fgetline(fp);
372 /* Refuse to work with damaged config file */
374 bb_error_msg_and_die("error in %s at '%s'", DEPFILE_BB, line);
381 static int start_dep_bb_writeout(void)
385 /* depmod -n: write result to stdout */
386 if (applet_name[0] == 'd' && (option_mask32 & 1))
387 return STDOUT_FILENO;
389 fd = open(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
391 if (errno == EEXIST) {
393 dbg1_error_msg(DEPFILE_BB".new exists, waiting for "DEPFILE_BB);
395 usleep(1000*1000 / 20);
397 dbg1_error_msg(DEPFILE_BB" appeared");
398 return -2; /* magic number */
403 bb_error_msg("deleting stale %s", DEPFILE_BB".new");
404 fd = open_or_warn(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC);
407 dbg1_error_msg("opened "DEPFILE_BB".new:%d", fd);
411 static void write_out_dep_bb(int fd)
416 /* We want good error reporting. fdprintf is not good enough. */
417 fp = fdopen(fd, "w");
423 while (modinfo[i].pathname) {
424 fprintf(fp, "%s%s%s\n" "%s%s\n",
425 modinfo[i].pathname, modinfo[i].aliases[0] ? " " : "", modinfo[i].aliases,
426 modinfo[i].deps, modinfo[i].deps[0] ? "\n" : "");
429 /* Badly formatted depfile is a no-no. Be paranoid. */
431 if (ferror(fp) | fclose(fp)) /* | instead of || is intended */
434 if (fd == STDOUT_FILENO) /* it was depmod -n */
437 if (rename(DEPFILE_BB".new", DEPFILE_BB) != 0) {
439 bb_perror_msg("can't create %s", DEPFILE_BB);
440 unlink(DEPFILE_BB".new");
444 dbg1_error_msg("created "DEPFILE_BB);
448 static module_info* find_alias(const char *alias)
453 dbg1_error_msg("find_alias('%s')", alias);
456 /* First try to find by name (cheaper) */
458 while (modinfo[i].pathname) {
459 if (pathname_matches_modname(modinfo[i].pathname, alias)) {
460 dbg1_error_msg("found '%s' in module '%s'",
461 alias, modinfo[i].pathname);
462 if (!modinfo[i].aliases) {
463 parse_module(&modinfo[i], modinfo[i].pathname);
470 /* Ok, we definitely have to scan module bodies. This is a good
471 * moment to generate modprobe.dep.bb, if it does not exist yet */
472 dep_bb_fd = dep_bb_seen ? -1 : start_dep_bb_writeout();
473 if (dep_bb_fd == -2) /* modprobe.dep.bb appeared? */
476 /* Scan all module bodies, extract modinfo (it contains aliases) */
479 while (modinfo[i].pathname) {
481 if (!modinfo[i].aliases) {
482 parse_module(&modinfo[i], modinfo[i].pathname);
486 /* "alias1 symbol:sym1 alias2 symbol:sym2" */
487 desc = str_2_list(modinfo[i].aliases);
488 /* Does matching substring exist? */
489 for (s = desc; *s; s += strlen(s) + 1) {
490 /* Aliases in module bodies can be defined with
491 * shell patterns. Example:
492 * "pci:v000010DEd000000D9sv*sd*bc*sc*i*".
493 * Plain strcmp() won't catch that */
494 if (fnmatch(s, alias, 0) == 0) {
495 dbg1_error_msg("found alias '%s' in module '%s'",
496 alias, modinfo[i].pathname);
497 result = &modinfo[i];
502 if (result && dep_bb_fd < 0)
507 /* Create module.dep.bb if needed */
508 if (dep_bb_fd >= 0) {
509 write_out_dep_bb(dep_bb_fd);
512 dbg1_error_msg("find_alias '%s' returns %p", alias, result);
516 #if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
517 static int already_loaded(const char *name)
520 int len = strlen(name);
524 modules = xfopen("/proc/modules", "r");
525 while ((line = xmalloc_fgets(modules)) != NULL) {
526 if (strncmp(line, name, len) == 0 && line[len] == ' ') {
537 #define already_loaded(name) is_rmmod
541 * Given modules definition and module name (or alias, or symbol)
542 * load/remove the module respecting dependencies.
543 * NB: also called by depmod with bogus name "/",
544 * just in order to force modprobe.dep.bb creation.
546 #if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
547 #define process_module(a,b) process_module(a)
548 #define cmdline_options ""
550 static void process_module(char *name, const char *cmdline_options)
552 char *s, *deps, *options;
554 int is_rmmod = (option_mask32 & OPT_r) != 0;
555 dbg1_error_msg("process_module('%s','%s')", name, cmdline_options);
557 replace(name, '-', '_');
559 dbg1_error_msg("already_loaded:%d is_rmmod:%d", already_loaded(name), is_rmmod);
560 if (already_loaded(name) != is_rmmod) {
561 dbg1_error_msg("nothing to do for '%s'", name);
567 char *opt_filename = xasprintf("/etc/modules/%s", name);
568 options = xmalloc_open_read_close(opt_filename, NULL);
570 replace(options, '\n', ' ');
571 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
572 if (cmdline_options) {
573 /* NB: cmdline_options always have one leading ' '
574 * (see main()), we remove it here */
575 char *op = xasprintf(options ? "%s %s" : "%s %s" + 3,
576 cmdline_options + 1, options);
582 module_load_options = options;
583 dbg1_error_msg("process_module('%s'): options:'%s'", name, options);
587 /* Scan module directory. This is done only once.
588 * It will attempt module load, and will exit(EXIT_SUCCESS)
590 module_found_idx = -1;
591 recursive_action(".",
592 ACTION_RECURSE, /* flags */
593 fileAction, /* file action */
594 NULL, /* dir action */
595 name, /* user data */
597 dbg1_error_msg("dirscan complete");
598 /* Module was not found, or load failed, or is_rmmod */
599 if (module_found_idx >= 0) { /* module was found */
600 info = &modinfo[module_found_idx];
601 } else { /* search for alias, not a plain module name */
602 info = find_alias(name);
605 info = find_alias(name);
608 /* rmmod? unload it by name */
610 if (delete_module(name, O_NONBLOCK | O_EXCL) != 0
611 && !(option_mask32 & OPT_q)
613 bb_perror_msg("remove '%s'", name);
616 /* N.B. we do not stop here -
617 * continue to unload modules on which the module depends:
618 * "-r --remove: option causes modprobe to remove a module.
619 * If the modules it depends on are also unused, modprobe
620 * will try to remove them, too." */
624 /* both dirscan and find_alias found nothing */
625 if (applet_name[0] != 'd') /* it wasn't depmod */
626 bb_error_msg("module '%s' not found", name);
631 /* Iterate thru dependencies, trying to (un)load them */
632 deps = str_2_list(info->deps);
633 for (s = deps; *s; s += strlen(s) + 1) {
634 //if (strcmp(name, s) != 0) // N.B. do loops exist?
635 dbg1_error_msg("recurse on dep '%s'", s);
636 process_module(s, NULL);
637 dbg1_error_msg("recurse on dep '%s' done", s);
641 /* insmod -> load it */
644 if (load_module(info->pathname, options) != 0) {
645 if (EEXIST != errno) {
646 bb_error_msg("'%s': %s",
650 dbg1_error_msg("'%s': %s",
658 //TODO: return load attempt result from process_module.
659 //If dep didn't load ok, continuing makes little sense.
661 #undef cmdline_options
664 /* For reference, module-init-tools v3.4 options:
667 Usage: insmod filename [args]
670 Usage: rmmod [-fhswvV] modulename ...
671 -f (or --force) forces a module unload, and may crash your
672 machine. This requires the Forced Module Removal option
673 when the kernel was compiled.
674 -h (or --help) prints this help text
675 -s (or --syslog) says use syslog, not stderr
676 -v (or --verbose) enables more messages
677 -V (or --version) prints the version code
678 -w (or --wait) begins a module removal even if it is used
679 and will stop new users from accessing the module (so it
680 should eventually fall to zero).
683 Usage: modprobe [-v] [-V] [-C config-file] [-n] [-i] [-q] [-b]
684 [-o <modname>] [ --dump-modversions ] <modname> [parameters...]
685 modprobe -r [-n] [-i] [-v] <modulename> ...
686 modprobe -l -t <dirname> [ -a <modulename> ...]
689 depmod 3.4 -- part of module-init-tools
690 depmod -[aA] [-n -e -v -q -V -r -u]
691 [-b basedirectory] [forced_version]
692 depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.ko module2.ko ...
693 If no arguments (except options) are given, "depmod -a" is assumed.
694 depmod will output a dependancy list suitable for the modprobe utility.
696 -a, --all Probe all modules
697 -A, --quick Only does the work if there's a new module
698 -n, --show Write the dependency file on stdout only
699 -e, --errsyms Report not supplied symbols
700 -V, --version Print the release version
701 -v, --verbose Enable verbose mode
702 -h, --help Print this usage message
703 The following options are useful for people managing distributions:
705 --basedir basedirectory Use an image of a module tree.
707 --filesyms kernelsyms Use the file instead of the
708 current kernel symbols.
711 int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
712 int modprobe_main(int argc UNUSED_PARAM, char **argv)
715 char applet0 = applet_name[0];
716 USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
718 /* are we lsmod? -> just dump /proc/modules */
719 if ('l' == applet0) {
720 xprint_and_close_file(xfopen("/proc/modules", "r"));
726 /* Prevent ugly corner cases with no modules at all */
727 modinfo = xzalloc(sizeof(modinfo[0]));
729 /* Goto modules directory */
730 xchdir(CONFIG_DEFAULT_MODULES_DIR);
731 uname(&uts); /* never fails */
734 if ('d' == applet0) {
736 * -n: print result to stdout
737 * -a: process all modules (default)
738 * optional VERSION parameter
740 * -A: do work only if a module is newer than depfile
741 * -e: report any symbols which a module needs
742 * which are not supplied by other modules or the kernel
743 * -F FILE: System.map (symbols for -e)
746 * -b BASEDIR: (TODO!) modules are in
747 * $BASEDIR/lib/modules/$VERSION
748 * -v: human readable deps to stdout
749 * -V: version (don't want to support it - people may depend
750 * on it as an indicator of "standard" depmod)
751 * -h: help (well duh)
752 * module1.o module2.o parameters (just ignored for now)
754 getopt32(argv, "na" "AeF:qru" /* "b:vV", NULL */, NULL);
756 /* if (argv[0] && argv[1]) bb_show_usage(); */
757 /* Goto $VERSION directory */
758 xchdir(argv[0] ? argv[0] : uts.release);
759 /* Force full module scan by asking to find a bogus module.
760 * This will generate modules.dep.bb as a side effect. */
761 process_module((char*)"/", NULL);
762 return !wrote_dep_bb_ok;
765 /* insmod, modprobe, rmmod require at least one argument */
766 opt_complementary = "-1";
767 /* only -q (quiet) and -r (rmmod),
768 * the rest are accepted and ignored (compat) */
769 getopt32(argv, "qrfsvw");
772 /* are we rmmod? -> simulate modprobe -r */
773 if ('r' == applet0) {
774 option_mask32 |= OPT_r;
777 /* Goto $VERSION directory */
780 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
781 /* If not rmmod, parse possible module options given on command line.
782 * insmod/modprobe takes one module name, the rest are parameters. */
784 if ('r' != applet0) {
787 /* Enclose options in quotes */
789 options = xasprintf("%s \"%s\"", s ? s : "", *arg);
799 /* Try to load modprobe.dep.bb */
802 /* Load/remove modules.
803 * Only rmmod loops here, insmod/modprobe has only argv[0] */
805 process_module(*argv++, options);
808 if (ENABLE_FEATURE_CLEAN_UP) {
809 USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)