Bump to version 1.22.1
[platform/upstream/busybox.git] / modutils / modprobe-small.c
index 3aa06d5..5b78363 100644 (file)
@@ -3,74 +3,37 @@
  * simplified modprobe
  *
  * Copyright (c) 2008 Vladimir Dronnikov
- * Copyright (c) 2008 Bernhard Fischer (initial depmod code)
+ * Copyright (c) 2008 Bernhard Reutner-Fischer (initial depmod code)
  *
- * Licensed under GPLv2, see file LICENSE in this tarball for details.
+ * Licensed under GPLv2, see file LICENSE in this source tree.
  */
 
-#include "libbb.h"
-#include "unarchive.h"
+//applet:IF_MODPROBE_SMALL(APPLET(modprobe, BB_DIR_SBIN, BB_SUID_DROP))
+//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(depmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, modprobe))
+//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(insmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, modprobe))
+//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(lsmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, modprobe))
+//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(rmmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, modprobe))
 
+#include "libbb.h"
+/* After libbb.h, since it needs sys/types.h on some systems */
 #include <sys/utsname.h> /* uname() */
 #include <fnmatch.h>
 
-/* libbb candidate */
-static void *xmalloc_read(int fd, size_t *sizep)
-{
-       char *buf;
-       size_t size, rd_size, total;
-       off_t to_read;
-       struct stat st;
-
-       to_read = sizep ? *sizep : INT_MAX; /* max to read */
-
-       /* Estimate file size */
-       st.st_size = 0; /* in case fstat fails, assume 0 */
-       fstat(fd, &st);
-       /* /proc/N/stat files report st_size 0 */
-       /* In order to make such files readable, we add small const */
-       size = (st.st_size | 0x3ff) + 1;
-
-       total = 0;
-       buf = NULL;
-       while (1) {
-               if (to_read < size)
-                       size = to_read;
-               buf = xrealloc(buf, total + size + 1);
-               rd_size = full_read(fd, buf + total, size);
-               if ((ssize_t)rd_size < 0) { /* error */
-                       free(buf);
-                       return NULL;
-               }
-               total += rd_size;
-               if (rd_size < size) /* EOF */
-                       break;
-               to_read -= rd_size;
-               if (to_read <= 0)
-                       break;
-               /* grow by 1/8, but in [1k..64k] bounds */
-               size = ((total / 8) | 0x3ff) + 1;
-               if (size > 64*1024)
-                       size = 64*1024;
-       }
-       xrealloc(buf, total + 1);
-       buf[total] = '\0';
-
-       if (sizep)
-               *sizep = total;
-       return buf;
-}
-
-
-#define dbg1_error_msg(...) ((void)0)
-#define dbg2_error_msg(...) ((void)0)
-//#define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
-//#define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
-
 extern int init_module(void *module, unsigned long len, const char *options);
 extern int delete_module(const char *module, unsigned flags);
 extern int query_module(const char *name, int which, void *buf, size_t bufsize, size_t *ret);
 
+
+#if 1
+# define dbg1_error_msg(...) ((void)0)
+# define dbg2_error_msg(...) ((void)0)
+#else
+# define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
+# define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
+#endif
+
+#define DEPFILE_BB CONFIG_DEFAULT_DEPMOD_FILE".bb"
+
 enum {
        OPT_q = (1 << 0), /* be quiet */
        OPT_r = (1 << 1), /* module removal instead of loading */
@@ -78,7 +41,8 @@ enum {
 
 typedef struct module_info {
        char *pathname;
-       char *desc;
+       char *aliases;
+       char *deps;
 } module_info;
 
 /*
@@ -87,37 +51,53 @@ typedef struct module_info {
 struct globals {
        module_info *modinfo;
        char *module_load_options;
-       int module_count;
+       smallint dep_bb_seen;
+       smallint wrote_dep_bb_ok;
+       unsigned module_count;
        int module_found_idx;
-       int stringbuf_idx;
-       char stringbuf[32 * 1024]; /* some modules have lots of stuff */
+       unsigned stringbuf_idx;
+       unsigned stringbuf_size;
+       char *stringbuf; /* some modules have lots of stuff */
        /* for example, drivers/media/video/saa7134/saa7134.ko */
+       /* therefore having a fixed biggish buffer is not wise */
 };
 #define G (*ptr_to_globals)
 #define modinfo             (G.modinfo            )
+#define dep_bb_seen         (G.dep_bb_seen        )
+#define wrote_dep_bb_ok     (G.wrote_dep_bb_ok    )
 #define module_count        (G.module_count       )
 #define module_found_idx    (G.module_found_idx   )
 #define module_load_options (G.module_load_options)
 #define stringbuf_idx       (G.stringbuf_idx      )
+#define stringbuf_size      (G.stringbuf_size     )
 #define stringbuf           (G.stringbuf          )
 #define INIT_G() do { \
        SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
 } while (0)
 
+static void append(const char *s)
+{
+       unsigned len = strlen(s);
+       if (stringbuf_idx + len + 15 > stringbuf_size) {
+               stringbuf_size = stringbuf_idx + len + 127;
+               dbg2_error_msg("grow stringbuf to %u", stringbuf_size);
+               stringbuf = xrealloc(stringbuf, stringbuf_size);
+       }
+       memcpy(stringbuf + stringbuf_idx, s, len);
+       stringbuf_idx += len;
+}
 
 static void appendc(char c)
 {
-       if (stringbuf_idx < sizeof(stringbuf))
-               stringbuf[stringbuf_idx++] = c;
+       /* We appendc() only after append(), + 15 trick in append()
+        * makes it unnecessary to check for overflow here */
+       stringbuf[stringbuf_idx++] = c;
 }
 
-static void append(const char *s)
+static void bksp(void)
 {
-       size_t len = strlen(s);
-       if (stringbuf_idx + len < sizeof(stringbuf)) {
-               memcpy(stringbuf + stringbuf_idx, s, len);
-               stringbuf_idx += len;
-       }
+       if (stringbuf_idx)
+               stringbuf_idx--;
 }
 
 static void reset_stringbuf(void)
@@ -127,7 +107,7 @@ static void reset_stringbuf(void)
 
 static char* copy_stringbuf(void)
 {
-       char *copy = xmalloc(stringbuf_idx);
+       char *copy = xzalloc(stringbuf_idx + 1); /* terminating NUL */
        return memcpy(copy, stringbuf, stringbuf_idx);
 }
 
@@ -135,7 +115,7 @@ static char* find_keyword(char *ptr, size_t len, const char *word)
 {
        int wlen;
 
-       if (!ptr) /* happens if read_module cannot read it */
+       if (!ptr) /* happens if xmalloc_open_zipped_read_close cannot read it */
                return NULL;
 
        wlen = strlen(word);
@@ -163,39 +143,18 @@ static void replace(char *s, char what, char with)
        }
 }
 
-#if ENABLE_FEATURE_MODPROBE_SMALL_ZIPPED
-static char *xmalloc_open_zipped_read_close(const char *fname, size_t *sizep)
+/* Take "word word", return malloced "word",NUL,"word",NUL,NUL */
+static char* str_2_list(const char *str)
 {
-       size_t len;
-       char *image;
-       char *suffix;
-
-       int fd = open_or_warn(fname, O_RDONLY);
-       if (fd < 0)
-               return NULL;
-
-       suffix = strrchr(fname, '.');
-       if (suffix) {
-               if (strcmp(suffix, ".gz") == 0)
-                       fd = open_transformer(fd, unpack_gz_stream, "gunzip");
-               else if (strcmp(suffix, ".bz2") == 0)
-                       fd = open_transformer(fd, unpack_bz2_stream, "bunzip2");
-       }
-
-       len = (sizep) ? *sizep : 64 * 1024 * 1024;
-       image = xmalloc_read(fd, &len);
-       if (!image)
-               bb_perror_msg("read error from '%s'", fname);
-       close(fd);
-
-       if (sizep)
-               *sizep = len;
-       return image;
+       int len = strlen(str) + 1;
+       char *dst = xmalloc(len + 1);
+
+       dst[len] = '\0';
+       memcpy(dst, str, len);
+//TODO: protect against 2+ spaces: "word  word"
+       replace(dst, ' ', '\0');
+       return dst;
 }
-# define read_module xmalloc_open_zipped_read_close
-#else
-# define read_module xmalloc_open_read_close
-#endif
 
 /* We use error numbers in a loose translation... */
 static const char *moderror(int err)
@@ -223,7 +182,7 @@ static int load_module(const char *fname, const char *options)
        char *module_image;
        dbg1_error_msg("load_module('%s','%s')", fname, options);
 
-       module_image = read_module(fname, &len);
+       module_image = xmalloc_open_zipped_read_close(fname, &len);
        r = (!module_image || init_module(module_image, len, options ? options : "") != 0);
        free(module_image);
        dbg1_error_msg("load_module:%d", r);
@@ -235,26 +194,22 @@ static int load_module(const char *fname, const char *options)
 #endif
 }
 
-static char* parse_module(const char *pathname, const char *name)
+static void parse_module(module_info *info, const char *pathname)
 {
        char *module_image;
        char *ptr;
        size_t len;
        size_t pos;
-       dbg1_error_msg("parse_module('%s','%s')", pathname, name);
+       dbg1_error_msg("parse_module('%s')", pathname);
 
        /* Read (possibly compressed) module */
        len = 64 * 1024 * 1024; /* 64 Mb at most */
-       module_image = read_module(pathname, &len);
+       module_image = xmalloc_open_zipped_read_close(pathname, &len);
+       /* module_image == NULL is ok here, find_keyword handles it */
+//TODO: optimize redundant module body reads
 
+       /* "alias1 symbol:sym1 alias2 symbol:sym2" */
        reset_stringbuf();
-
-       /* First desc line's format is
-        * "modname alias1 symbol:sym1 alias2 symbol:sym2 " (note trailing ' ')
-        */
-       append(name);
-       appendc(' ');
-       /* Aliases */
        pos = 0;
        while (1) {
                ptr = find_keyword(module_image + pos, len - pos, "alias=");
@@ -264,20 +219,24 @@ static char* parse_module(const char *pathname, const char *name)
                                break;
                        /* DOCME: __ksymtab_gpl and __ksymtab_strings occur
                         * in many modules. What do they mean? */
-                       if (strcmp(ptr, "gpl") != 0 && strcmp(ptr, "strings") != 0) {
-                               dbg2_error_msg("alias: 'symbol:%s'", ptr);
-                               append("symbol:");
-                       }
+                       if (strcmp(ptr, "gpl") == 0 || strcmp(ptr, "strings") == 0)
+                               goto skip;
+                       dbg2_error_msg("alias:'symbol:%s'", ptr);
+                       append("symbol:");
                } else {
-                       dbg2_error_msg("alias: '%s'", ptr);
+                       dbg2_error_msg("alias:'%s'", ptr);
                }
                append(ptr);
                appendc(' ');
+ skip:
                pos = (ptr - module_image);
        }
-       appendc('\0');
+       bksp(); /* remove last ' ' */
+       info->aliases = copy_stringbuf();
+       replace(info->aliases, '-', '_');
 
-       /* Second line: "dependency1 depandency2 " (note trailing ' ') */
+       /* "dependency1 depandency2" */
+       reset_stringbuf();
        ptr = find_keyword(module_image, len, "depends=");
        if (ptr && *ptr) {
                replace(ptr, ',', ' ');
@@ -285,28 +244,30 @@ static char* parse_module(const char *pathname, const char *name)
                dbg2_error_msg("dep:'%s'", ptr);
                append(ptr);
        }
-       appendc(' '); appendc('\0');
+       info->deps = copy_stringbuf();
 
        free(module_image);
-       return copy_stringbuf();
 }
 
-static char* pathname_2_modname(const char *pathname)
+static int pathname_matches_modname(const char *pathname, const char *modname)
 {
        const char *fname = bb_get_last_path_component_nostrip(pathname);
        const char *suffix = strrstr(fname, ".ko");
+//TODO: can do without malloc?
        char *name = xstrndup(fname, suffix - fname);
+       int r;
        replace(name, '-', '_');
-       return name;
+       r = (strcmp(name, modname) == 0);
+       free(name);
+       return r;
 }
 
 static FAST_FUNC int fileAction(const char *pathname,
                struct stat *sb UNUSED_PARAM,
-               void *data,
+               void *modname_to_match,
                int depth UNUSED_PARAM)
 {
        int cur;
-       char *name;
        const char *fname;
 
        pathname += 2; /* skip "./" */
@@ -317,24 +278,19 @@ static FAST_FUNC int fileAction(const char *pathname,
        }
 
        cur = module_count++;
-       if (!(cur & 0xfff)) {
-               modinfo = xrealloc(modinfo, sizeof(modinfo[0]) * (cur + 0x1001));
-       }
+       modinfo = xrealloc_vector(modinfo, 12, cur);
        modinfo[cur].pathname = xstrdup(pathname);
-       modinfo[cur].desc = NULL;
-       modinfo[cur+1].pathname = NULL;
-       modinfo[cur+1].desc = NULL;
+       /*modinfo[cur].aliases = NULL; - xrealloc_vector did it */
+       /*modinfo[cur+1].pathname = NULL;*/
 
-       name = pathname_2_modname(fname);
-       if (strcmp(name, data) != 0) {
-               free(name);
+       if (!pathname_matches_modname(fname, modname_to_match)) {
                dbg1_error_msg("'%s' module name doesn't match", pathname);
                return TRUE; /* module name doesn't match, continue search */
        }
 
        dbg1_error_msg("'%s' module name matches", pathname);
        module_found_idx = cur;
-       modinfo[cur].desc = parse_module(pathname, name);
+       parse_module(&modinfo[cur], pathname);
 
        if (!(option_mask32 & OPT_r)) {
                if (load_module(pathname, module_load_options) == 0) {
@@ -342,81 +298,213 @@ static FAST_FUNC int fileAction(const char *pathname,
                         * This can happen ONLY for "top-level" module load,
                         * not a dep, because deps dont do dirscan. */
                        exit(EXIT_SUCCESS);
-                       /*free(name);return RECURSE_RESULT_ABORT;*/
                }
        }
 
-       free(name);
        return TRUE;
 }
 
+static int load_dep_bb(void)
+{
+       char *line;
+       FILE *fp = fopen_for_read(DEPFILE_BB);
+
+       if (!fp)
+               return 0;
+
+       dep_bb_seen = 1;
+       dbg1_error_msg("loading "DEPFILE_BB);
+
+       /* Why? There is a rare scenario: we did not find modprobe.dep.bb,
+        * we scanned the dir and found no module by name, then we search
+        * for alias (full scan), and we decided to generate modprobe.dep.bb.
+        * But we see modprobe.dep.bb.new! Other modprobe is at work!
+        * We wait and other modprobe renames it to modprobe.dep.bb.
+        * Now we can use it.
+        * But we already have modinfo[] filled, and "module_count = 0"
+        * makes us start anew. Yes, we leak modinfo[].xxx pointers -
+        * there is not much of data there anyway. */
+       module_count = 0;
+       memset(&modinfo[0], 0, sizeof(modinfo[0]));
+
+       while ((line = xmalloc_fgetline(fp)) != NULL) {
+               char* space;
+               char* linebuf;
+               int cur;
+
+               if (!line[0]) {
+                       free(line);
+                       continue;
+               }
+               space = strchrnul(line, ' ');
+               cur = module_count++;
+               modinfo = xrealloc_vector(modinfo, 12, cur);
+               /*modinfo[cur+1].pathname = NULL; - xrealloc_vector did it */
+               modinfo[cur].pathname = line; /* we take ownership of malloced block here */
+               if (*space)
+                       *space++ = '\0';
+               modinfo[cur].aliases = space;
+               linebuf = xmalloc_fgetline(fp);
+               modinfo[cur].deps = linebuf ? linebuf : xzalloc(1);
+               if (modinfo[cur].deps[0]) {
+                       /* deps are not "", so next line must be empty */
+                       line = xmalloc_fgetline(fp);
+                       /* Refuse to work with damaged config file */
+                       if (line && line[0])
+                               bb_error_msg_and_die("error in %s at '%s'", DEPFILE_BB, line);
+                       free(line);
+               }
+       }
+       return 1;
+}
+
+static int start_dep_bb_writeout(void)
+{
+       int fd;
+
+       /* depmod -n: write result to stdout */
+       if (applet_name[0] == 'd' && (option_mask32 & 1))
+               return STDOUT_FILENO;
+
+       fd = open(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
+       if (fd < 0) {
+               if (errno == EEXIST) {
+                       int count = 5 * 20;
+                       dbg1_error_msg(DEPFILE_BB".new exists, waiting for "DEPFILE_BB);
+                       while (1) {
+                               usleep(1000*1000 / 20);
+                               if (load_dep_bb()) {
+                                       dbg1_error_msg(DEPFILE_BB" appeared");
+                                       return -2; /* magic number */
+                               }
+                               if (!--count)
+                                       break;
+                       }
+                       bb_error_msg("deleting stale %s", DEPFILE_BB".new");
+                       fd = open_or_warn(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC);
+               }
+       }
+       dbg1_error_msg("opened "DEPFILE_BB".new:%d", fd);
+       return fd;
+}
+
+static void write_out_dep_bb(int fd)
+{
+       int i;
+       FILE *fp;
+
+       /* We want good error reporting. fdprintf is not good enough. */
+       fp = xfdopen_for_write(fd);
+       i = 0;
+       while (modinfo[i].pathname) {
+               fprintf(fp, "%s%s%s\n" "%s%s\n",
+                       modinfo[i].pathname, modinfo[i].aliases[0] ? " " : "", modinfo[i].aliases,
+                       modinfo[i].deps, modinfo[i].deps[0] ? "\n" : "");
+               i++;
+       }
+       /* Badly formatted depfile is a no-no. Be paranoid. */
+       errno = 0;
+       if (ferror(fp) | fclose(fp)) /* | instead of || is intended */
+               goto err;
+
+       if (fd == STDOUT_FILENO) /* it was depmod -n */
+               goto ok;
+
+       if (rename(DEPFILE_BB".new", DEPFILE_BB) != 0) {
+ err:
+               bb_perror_msg("can't create '%s'", DEPFILE_BB);
+               unlink(DEPFILE_BB".new");
+       } else {
+ ok:
+               wrote_dep_bb_ok = 1;
+               dbg1_error_msg("created "DEPFILE_BB);
+       }
+}
+
 static module_info* find_alias(const char *alias)
 {
        int i;
+       int dep_bb_fd;
+       module_info *result;
        dbg1_error_msg("find_alias('%s')", alias);
 
+ try_again:
        /* First try to find by name (cheaper) */
        i = 0;
        while (modinfo[i].pathname) {
-               char *name = pathname_2_modname(modinfo[i].pathname);
-               if (strcmp(name, alias) == 0) {
+               if (pathname_matches_modname(modinfo[i].pathname, alias)) {
                        dbg1_error_msg("found '%s' in module '%s'",
                                        alias, modinfo[i].pathname);
-                       if (!modinfo[i].desc)
-                               modinfo[i].desc = parse_module(modinfo[i].pathname, name);
-                       free(name);
+                       if (!modinfo[i].aliases) {
+                               parse_module(&modinfo[i], modinfo[i].pathname);
+                       }
                        return &modinfo[i];
                }
-               free(name);
                i++;
        }
 
+       /* Ok, we definitely have to scan module bodies. This is a good
+        * moment to generate modprobe.dep.bb, if it does not exist yet */
+       dep_bb_fd = dep_bb_seen ? -1 : start_dep_bb_writeout();
+       if (dep_bb_fd == -2) /* modprobe.dep.bb appeared? */
+               goto try_again;
+
        /* Scan all module bodies, extract modinfo (it contains aliases) */
        i = 0;
+       result = NULL;
        while (modinfo[i].pathname) {
                char *desc, *s;
-               if (!modinfo[i].desc) {
-                       char *name = pathname_2_modname(modinfo[i].pathname);
-                       modinfo[i].desc = parse_module(modinfo[i].pathname, name);
-                       free(name);
+               if (!modinfo[i].aliases) {
+                       parse_module(&modinfo[i], modinfo[i].pathname);
                }
-               /* "modname alias1 symbol:sym1 alias2 symbol:sym2 " */
-               desc = xstrdup(modinfo[i].desc);
+               if (result) {
+                       i++;
+                       continue;
+               }
+               /* "alias1 symbol:sym1 alias2 symbol:sym2" */
+               desc = str_2_list(modinfo[i].aliases);
                /* Does matching substring exist? */
-               replace(desc, ' ', '\0');
                for (s = desc; *s; s += strlen(s) + 1) {
-                       if (strcmp(s, alias) == 0) {
-                               free(desc);
+                       /* Aliases in module bodies can be defined with
+                        * shell patterns. Example:
+                        * "pci:v000010DEd000000D9sv*sd*bc*sc*i*".
+                        * Plain strcmp() won't catch that */
+                       if (fnmatch(s, alias, 0) == 0) {
                                dbg1_error_msg("found alias '%s' in module '%s'",
                                                alias, modinfo[i].pathname);
-                               return &modinfo[i];
+                               result = &modinfo[i];
+                               break;
                        }
                }
                free(desc);
+               if (result && dep_bb_fd < 0)
+                       return result;
                i++;
        }
-       dbg1_error_msg("find_alias '%s' returns NULL", alias);
-       return NULL;
+
+       /* Create module.dep.bb if needed */
+       if (dep_bb_fd >= 0) {
+               write_out_dep_bb(dep_bb_fd);
+       }
+
+       dbg1_error_msg("find_alias '%s' returns %p", alias, result);
+       return result;
 }
 
 #if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
+// TODO: open only once, invent config_rewind()
 static int already_loaded(const char *name)
 {
        int ret = 0;
-       int len = strlen(name);
-       char *line;
-       FILE* modules;
-
-       modules = xfopen("/proc/modules", "r");
-       while ((line = xmalloc_fgets(modules)) != NULL) {
-               if (strncmp(line, name, len) == 0 && line[len] == ' ') {
-                       free(line);
+       char *s;
+       parser_t *parser = config_open2("/proc/modules", xfopen_for_read);
+       while (config_read(parser, &s, 1, 1, "# \t", PARSE_NORMAL & ~PARSE_GREEDY)) {
+               if (strcmp(s, name) == 0) {
                        ret = 1;
                        break;
                }
-               free(line);
        }
-       fclose(modules);
+       config_close(parser);
        return ret;
 }
 #else
@@ -424,8 +512,10 @@ static int already_loaded(const char *name)
 #endif
 
 /*
- Given modules definition and module name (or alias, or symbol)
- load/remove the module respecting dependencies
+ * Given modules definition and module name (or alias, or symbol)
+ * load/remove the module respecting dependencies.
+ * NB: also called by depmod with bogus name "/",
+ * just in order to force modprobe.dep.bb creation.
 */
 #if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
 #define process_module(a,b) process_module(a)
@@ -489,31 +579,45 @@ static void process_module(char *name, const char *cmdline_options)
                info = find_alias(name);
        }
 
+// Problem here: there can be more than one module
+// for the given alias. For example,
+// "pci:v00008086d00007010sv00000000sd00000000bc01sc01i80" matches
+// ata_piix because it has an alias "pci:v00008086d00007010sv*sd*bc*sc*i*"
+// and ata_generic, it has an alias "alias=pci:v*d*sv*sd*bc01sc01i*"
+// Standard modprobe would load them both.
+// In this code, find_alias() returns only the first matching module.
+
        /* rmmod? unload it by name */
        if (is_rmmod) {
-               if (delete_module(name, O_NONBLOCK|O_EXCL) != 0
-                && !(option_mask32 & OPT_q)
-               ) {
-                       bb_perror_msg("remove '%s'", name);
+               if (delete_module(name, O_NONBLOCK | O_EXCL) != 0) {
+                       if (!(option_mask32 & OPT_q))
+                               bb_perror_msg("remove '%s'", name);
                        goto ret;
                }
-               /* N.B. we do not stop here -
+
+               if (applet_name[0] == 'r') {
+                       /* rmmod: do not remove dependencies, exit */
+                       goto ret;
+               }
+
+               /* modprobe -r: we do not stop here -
                 * continue to unload modules on which the module depends:
                 * "-r --remove: option causes modprobe to remove a module.
                 * If the modules it depends on are also unused, modprobe
-                * will try to remove them, too." */
+                * will try to remove them, too."
+                */
        }
 
-       if (!info) { /* both dirscan and find_alias found nothing */
+       if (!info) {
+               /* both dirscan and find_alias found nothing */
+               if (!is_rmmod && applet_name[0] != 'd') /* it wasn't rmmod or depmod */
+                       bb_error_msg("module '%s' not found", name);
+//TODO: _and_die()? or should we continue (un)loading modules listed on cmdline?
                goto ret;
        }
 
-       /* Second line of desc contains dependencies */
-       deps = xstrdup(info->desc + strlen(info->desc) + 1);
-
-       /* Transform deps to string list */
-       replace(deps, ' ', '\0');
        /* Iterate thru dependencies, trying to (un)load them */
+       deps = str_2_list(info->deps);
        for (s = deps; *s; s += strlen(s) + 1) {
                //if (strcmp(name, s) != 0) // N.B. do loops exist?
                dbg1_error_msg("recurse on dep '%s'", s);
@@ -522,19 +626,23 @@ static void process_module(char *name, const char *cmdline_options)
        }
        free(deps);
 
-       /* insmod -> load it */
+       /* modprobe -> load it */
        if (!is_rmmod) {
-               errno = 0;
-               if (load_module(info->pathname, options) != 0) {
-                       if (EEXIST != errno) {
-                               bb_error_msg("insert '%s' %s: %s",
-                                               info->pathname, options,
+               if (!options || strstr(options, "blacklist") == NULL) {
+                       errno = 0;
+                       if (load_module(info->pathname, options) != 0) {
+                               if (EEXIST != errno) {
+                                       bb_error_msg("'%s': %s",
+                                               info->pathname,
                                                moderror(errno));
-                       } else {
-                               dbg1_error_msg("insert '%s' %s: %s",
-                                               info->pathname, options,
+                               } else {
+                                       dbg1_error_msg("'%s': %s",
+                                               info->pathname,
                                                moderror(errno));
+                               }
                        }
+               } else {
+                       dbg1_error_msg("'%s': blacklisted", info->pathname);
                }
        }
  ret:
@@ -545,65 +653,170 @@ static void process_module(char *name, const char *cmdline_options)
 #undef cmdline_options
 
 
-/* For reference, module-init-tools-0.9.15-pre2 options:
+/* For reference, module-init-tools v3.4 options:
 
 # insmod
 Usage: insmod filename [args]
 
 # rmmod --help
 Usage: rmmod [-fhswvV] modulename ...
- -f (or --force) forces a module unload, and may crash your machine.
+ -f (or --force) forces a module unload, and may crash your
+    machine. This requires the Forced Module Removal option
+    when the kernel was compiled.
+ -h (or --help) prints this help text
  -s (or --syslog) says use syslog, not stderr
  -v (or --verbose) enables more messages
- -w (or --wait) begins a module removal even if it is used
+ -V (or --version) prints the version code
+ -w (or --wait) begins module removal even if it is used
     and will stop new users from accessing the module (so it
     should eventually fall to zero).
 
 # modprobe
-Usage: modprobe [--verbose|--version|--config|--remove] filename [options]
+Usage: modprobe [-v] [-V] [-C config-file] [-n] [-i] [-q] [-b]
+    [-o <modname>] [ --dump-modversions ] <modname> [parameters...]
+modprobe -r [-n] [-i] [-v] <modulename> ...
+modprobe -l -t <dirname> [ -a <modulename> ...]
 
 # depmod --help
-depmod 0.9.15-pre2 -- part of module-init-tools
-depmod -[aA] [-n -e -v -q -V -r -u] [-b basedirectory] [forced_version]
-depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.o module2.o ...
-If no arguments (except options) are given, "depmod -a" is assumed
-
-depmod will output a dependancy list suitable for the modprobe utility.
-
+depmod 3.4 -- part of module-init-tools
+depmod -[aA] [-n -e -v -q -V -r -u]
+      [-b basedirectory] [forced_version]
+depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.ko module2.ko ...
+If no arguments (except options) are given, "depmod -a" is assumed.
+depmod will output a dependency list suitable for the modprobe utility.
 Options:
-        -a, --all               Probe all modules
-        -n, --show              Write the dependency file on stdout only
-        -b basedirectory
-        --basedir basedirectory Use an image of a module tree.
-        -F kernelsyms
-        --filesyms kernelsyms   Use the file instead of the
-                                current kernel symbols.
+    -a, --all           Probe all modules
+    -A, --quick         Only does the work if there's a new module
+    -n, --show          Write the dependency file on stdout only
+    -e, --errsyms       Report not supplied symbols
+    -V, --version       Print the release version
+    -v, --verbose       Enable verbose mode
+    -h, --help          Print this usage message
+The following options are useful for people managing distributions:
+    -b basedirectory
+    --basedir basedirectory
+                        Use an image of a module tree
+    -F kernelsyms
+    --filesyms kernelsyms
+                        Use the file instead of the current kernel symbols
 */
 
+//usage:#if ENABLE_MODPROBE_SMALL
+
+//// Note: currently, help system shows modprobe --help text for all aliased cmds
+//// (see APPLET_ODDNAME macro definition).
+//// All other help texts defined below are not used. FIXME?
+
+//usage:#define depmod_trivial_usage NOUSAGE_STR
+//usage:#define depmod_full_usage ""
+
+//usage:#define lsmod_trivial_usage
+//usage:       ""
+//usage:#define lsmod_full_usage "\n\n"
+//usage:       "List the currently loaded kernel modules"
+
+//usage:#define insmod_trivial_usage
+//usage:       IF_FEATURE_2_4_MODULES("[OPTIONS] MODULE ")
+//usage:       IF_NOT_FEATURE_2_4_MODULES("FILE ")
+//usage:       "[SYMBOL=VALUE]..."
+//usage:#define insmod_full_usage "\n\n"
+//usage:       "Load the specified kernel modules into the kernel"
+//usage:       IF_FEATURE_2_4_MODULES( "\n"
+//usage:     "\n       -f      Force module to load into the wrong kernel version"
+//usage:     "\n       -k      Make module autoclean-able"
+//usage:     "\n       -v      Verbose"
+//usage:     "\n       -q      Quiet"
+//usage:     "\n       -L      Lock: prevent simultaneous loads"
+//usage:       IF_FEATURE_INSMOD_LOAD_MAP(
+//usage:     "\n       -m      Output load map to stdout"
+//usage:       )
+//usage:     "\n       -x      Don't export externs"
+//usage:       )
+
+//usage:#define rmmod_trivial_usage
+//usage:       "[-wfa] [MODULE]..."
+//usage:#define rmmod_full_usage "\n\n"
+//usage:       "Unload kernel modules\n"
+//usage:     "\n       -w      Wait until the module is no longer used"
+//usage:     "\n       -f      Force unload"
+//usage:     "\n       -a      Remove all unused modules (recursively)"
+//usage:
+//usage:#define rmmod_example_usage
+//usage:       "$ rmmod tulip\n"
+
+//usage:#define modprobe_trivial_usage
+//usage:       "[-qfwrsv] MODULE [symbol=value]..."
+//usage:#define modprobe_full_usage "\n\n"
+//usage:       "       -r      Remove MODULE (stacks) or do autoclean"
+//usage:     "\n       -q      Quiet"
+//usage:     "\n       -v      Verbose"
+//usage:     "\n       -f      Force"
+//usage:     "\n       -w      Wait for unload"
+//usage:     "\n       -s      Report via syslog instead of stderr"
+
+//usage:#endif
+
 int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
 int modprobe_main(int argc UNUSED_PARAM, char **argv)
 {
        struct utsname uts;
        char applet0 = applet_name[0];
-       USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
-
-       /* depmod is a stub */
-       if ('d' == applet0)
-               return EXIT_SUCCESS;
+       IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
 
        /* are we lsmod? -> just dump /proc/modules */
        if ('l' == applet0) {
-               xprint_and_close_file(xfopen("/proc/modules", "r"));
+               xprint_and_close_file(xfopen_for_read("/proc/modules"));
                return EXIT_SUCCESS;
        }
 
        INIT_G();
 
+       /* Prevent ugly corner cases with no modules at all */
+       modinfo = xzalloc(sizeof(modinfo[0]));
+
+       if ('i' != applet0) { /* not insmod */
+               /* Goto modules directory */
+               xchdir(CONFIG_DEFAULT_MODULES_DIR);
+       }
+       uname(&uts); /* never fails */
+
+       /* depmod? */
+       if ('d' == applet0) {
+               /* Supported:
+                * -n: print result to stdout
+                * -a: process all modules (default)
+                * optional VERSION parameter
+                * Ignored:
+                * -A: do work only if a module is newer than depfile
+                * -e: report any symbols which a module needs
+                *  which are not supplied by other modules or the kernel
+                * -F FILE: System.map (symbols for -e)
+                * -q, -r, -u: noop?
+                * Not supported:
+                * -b BASEDIR: (TODO!) modules are in
+                *  $BASEDIR/lib/modules/$VERSION
+                * -v: human readable deps to stdout
+                * -V: version (don't want to support it - people may depend
+                *  on it as an indicator of "standard" depmod)
+                * -h: help (well duh)
+                * module1.o module2.o parameters (just ignored for now)
+                */
+               getopt32(argv, "na" "AeF:qru" /* "b:vV", NULL */, NULL);
+               argv += optind;
+               /* if (argv[0] && argv[1]) bb_show_usage(); */
+               /* Goto $VERSION directory */
+               xchdir(argv[0] ? argv[0] : uts.release);
+               /* Force full module scan by asking to find a bogus module.
+                * This will generate modules.dep.bb as a side effect. */
+               process_module((char*)"/", NULL);
+               return !wrote_dep_bb_ok;
+       }
+
        /* insmod, modprobe, rmmod require at least one argument */
        opt_complementary = "-1";
        /* only -q (quiet) and -r (rmmod),
         * the rest are accepted and ignored (compat) */
-       getopt32(argv, "qrfsvw");
+       getopt32(argv, "qrfsvwb");
        argv += optind;
 
        /* are we rmmod? -> simulate modprobe -r */
@@ -611,10 +824,10 @@ int modprobe_main(int argc UNUSED_PARAM, char **argv)
                option_mask32 |= OPT_r;
        }
 
-       /* goto modules directory */
-       xchdir(CONFIG_DEFAULT_MODULES_DIR);
-       uname(&uts); /* never fails */
-       xchdir(uts.release);
+       if ('i' != applet0) { /* not insmod */
+               /* Goto $VERSION directory */
+               xchdir(uts.release);
+       }
 
 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
        /* If not rmmod, parse possible module options given on command line.
@@ -635,14 +848,36 @@ int modprobe_main(int argc UNUSED_PARAM, char **argv)
                argv[1] = NULL;
 #endif
 
+       if ('i' == applet0) { /* insmod */
+               size_t len;
+               void *map;
+
+               len = MAXINT(ssize_t);
+               map = xmalloc_open_zipped_read_close(*argv, &len);
+               if (!map)
+                       bb_perror_msg_and_die("can't read '%s'", *argv);
+               if (init_module(map, len,
+                       IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(options ? options : "")
+                       IF_NOT_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE("")
+                       ) != 0
+               ) {
+                       bb_error_msg_and_die("can't insert '%s': %s",
+                                       *argv, moderror(errno));
+               }
+               return 0;
+       }
+
+       /* Try to load modprobe.dep.bb */
+       load_dep_bb();
+
        /* Load/remove modules.
-        * Only rmmod loops here, insmod/modprobe has only argv[0] */
+        * Only rmmod loops here, modprobe has only argv[0] */
        do {
-               process_module(*argv++, options);
-       } while (*argv);
+               process_module(*argv, options);
+       } while (*++argv);
 
        if (ENABLE_FEATURE_CLEAN_UP) {
-               USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
+               IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
        }
        return EXIT_SUCCESS;
 }