f28c42558f4c8002bdf47a1dcc7f1e313029dcfe
[oweals/busybox.git] / modutils / modprobe-small.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * simplified modprobe
4  *
5  * Copyright (c) 2008 Vladimir Dronnikov
6  * Copyright (c) 2008 Bernhard Fischer (initial depmod code)
7  *
8  * Licensed under GPLv2, see file LICENSE in this tarball for details.
9  */
10
11 #include "libbb.h"
12 #include "unarchive.h"
13
14 #include <sys/utsname.h> /* uname() */
15 #include <fnmatch.h>
16
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);
20
21
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__)
26
27 #define DEPFILE_BB CONFIG_DEFAULT_DEPMOD_FILE".bb"
28
29 enum {
30         OPT_q = (1 << 0), /* be quiet */
31         OPT_r = (1 << 1), /* module removal instead of loading */
32 };
33
34 typedef struct module_info {
35         char *pathname;
36         char *aliases;
37         char *deps;
38 } module_info;
39
40 /*
41  * GLOBALS
42  */
43 struct globals {
44         module_info *modinfo;
45         char *module_load_options;
46         smallint dep_bb_seen;
47         smallint wrote_dep_bb_ok;
48         int module_count;
49         int module_found_idx;
50         int stringbuf_idx;
51         char stringbuf[32 * 1024]; /* some modules have lots of stuff */
52         /* for example, drivers/media/video/saa7134/saa7134.ko */
53 };
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))); \
65 } while (0)
66
67
68 static void appendc(char c)
69 {
70         if (stringbuf_idx < sizeof(stringbuf))
71                 stringbuf[stringbuf_idx++] = c;
72 }
73
74 static void bksp(void)
75 {
76         if (stringbuf_idx)
77                 stringbuf_idx--;
78 }
79
80 static void append(const char *s)
81 {
82         size_t len = strlen(s);
83         if (stringbuf_idx + len < sizeof(stringbuf)) {
84                 memcpy(stringbuf + stringbuf_idx, s, len);
85                 stringbuf_idx += len;
86         }
87 }
88
89 static void reset_stringbuf(void)
90 {
91         stringbuf_idx = 0;
92 }
93
94 static char* copy_stringbuf(void)
95 {
96         char *copy = xmalloc(stringbuf_idx);
97         return memcpy(copy, stringbuf, stringbuf_idx);
98 }
99
100 static char* find_keyword(char *ptr, size_t len, const char *word)
101 {
102         int wlen;
103
104         if (!ptr) /* happens if read_module cannot read it */
105                 return NULL;
106
107         wlen = strlen(word);
108         len -= wlen - 1;
109         while ((ssize_t)len > 0) {
110                 char *old = ptr;
111                 /* search for the first char in word */
112                 ptr = memchr(ptr, *word, len);
113                 if (ptr == NULL) /* no occurance left, done */
114                         break;
115                 if (strncmp(ptr, word, wlen) == 0)
116                         return ptr + wlen; /* found, return ptr past it */
117                 ++ptr;
118                 len -= (ptr - old);
119         }
120         return NULL;
121 }
122
123 static void replace(char *s, char what, char with)
124 {
125         while (*s) {
126                 if (what == *s)
127                         *s = with;
128                 ++s;
129         }
130 }
131
132 /* Take "word word", return malloced "word",NUL,"word",NUL,NUL */
133 static char* str_2_list(const char *str)
134 {
135         int len = strlen(str) + 1;
136         char *dst = xmalloc(len + 1);
137
138         dst[len] = '\0';
139         memcpy(dst, str, len);
140 //TODO: protect against 2+ spaces: "word  word"
141         replace(dst, ' ', '\0');
142         return dst;
143 }
144
145 #if ENABLE_FEATURE_MODPROBE_SMALL_ZIPPED
146 static char *xmalloc_open_zipped_read_close(const char *fname, size_t *sizep)
147 {
148         size_t len;
149         char *image;
150         char *suffix;
151
152         int fd = open_or_warn(fname, O_RDONLY);
153         if (fd < 0)
154                 return NULL;
155
156         suffix = strrchr(fname, '.');
157         if (suffix) {
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");
162         }
163
164         len = (sizep) ? *sizep : 64 * 1024 * 1024;
165         image = xmalloc_read(fd, &len);
166         if (!image)
167                 bb_perror_msg("read error from '%s'", fname);
168         close(fd);
169
170         if (sizep)
171                 *sizep = len;
172         return image;
173 }
174 # define read_module xmalloc_open_zipped_read_close
175 #else
176 # define read_module xmalloc_open_read_close
177 #endif
178
179 /* We use error numbers in a loose translation... */
180 static const char *moderror(int err)
181 {
182         switch (err) {
183         case ENOEXEC:
184                 return "invalid module format";
185         case ENOENT:
186                 return "unknown symbol in module or invalid parameter";
187         case ESRCH:
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");
192         default:
193                 return strerror(err);
194         }
195 }
196
197 static int load_module(const char *fname, const char *options)
198 {
199 #if 1
200         int r;
201         size_t len = MAXINT(ssize_t);
202         char *module_image;
203         dbg1_error_msg("load_module('%s','%s')", fname, options);
204
205         module_image = read_module(fname, &len);
206         r = (!module_image || init_module(module_image, len, options ? options : "") != 0);
207         free(module_image);
208         dbg1_error_msg("load_module:%d", r);
209         return r; /* 0 = success */
210 #else
211         /* For testing */
212         dbg1_error_msg("load_module('%s','%s')", fname, options);
213         return 1;
214 #endif
215 }
216
217 static void parse_module(module_info *info, const char *pathname)
218 {
219         char *module_image;
220         char *ptr;
221         size_t len;
222         size_t pos;
223         dbg1_error_msg("parse_module('%s')", pathname);
224
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
229
230         /* "alias1 symbol:sym1 alias2 symbol:sym2" */
231         reset_stringbuf();
232         pos = 0;
233         while (1) {
234                 ptr = find_keyword(module_image + pos, len - pos, "alias=");
235                 if (!ptr) {
236                         ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
237                         if (!ptr)
238                                 break;
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)
242                                 goto skip;
243                         dbg2_error_msg("alias:'symbol:%s'", ptr);
244                         append("symbol:");
245                 } else {
246                         dbg2_error_msg("alias:'%s'", ptr);
247                 }
248                 append(ptr);
249                 appendc(' ');
250  skip:
251                 pos = (ptr - module_image);
252         }
253         bksp(); /* remove last ' ' */
254         appendc('\0');
255         info->aliases = copy_stringbuf();
256
257         /* "dependency1 depandency2" */
258         reset_stringbuf();
259         ptr = find_keyword(module_image, len, "depends=");
260         if (ptr && *ptr) {
261                 replace(ptr, ',', ' ');
262                 replace(ptr, '-', '_');
263                 dbg2_error_msg("dep:'%s'", ptr);
264                 append(ptr);
265         }
266         appendc('\0');
267         info->deps = copy_stringbuf();
268
269         free(module_image);
270 }
271
272 static int pathname_matches_modname(const char *pathname, const char *modname)
273 {
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);
278         int r;
279         replace(name, '-', '_');
280         r = (strcmp(name, modname) == 0);
281         free(name);
282         return r;
283 }
284
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)
289 {
290         int cur;
291         const char *fname;
292
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 */
298         }
299
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;
306
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 */
310         }
311
312         dbg1_error_msg("'%s' module name matches", pathname);
313         module_found_idx = cur;
314         parse_module(&modinfo[cur], pathname);
315
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. */
321                         exit(EXIT_SUCCESS);
322                 }
323         }
324
325         return TRUE;
326 }
327
328 static int load_dep_bb(void)
329 {
330         char *line;
331         FILE *fp = fopen(DEPFILE_BB, "r");
332
333         if (!fp)
334                 return 0;
335
336         dep_bb_seen = 1;
337         dbg1_error_msg("loading "DEPFILE_BB);
338
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.
344          * Now we can use it.
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. */
348         module_count = 0;
349         memset(&modinfo[0], 0, sizeof(modinfo[0]));
350
351         while ((line = xmalloc_fgetline(fp)) != NULL) {
352                 char* space;
353                 int cur;
354
355                 if (!line[0]) {
356                         free(line);
357                         continue;
358                 }
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 */
365                 if (*space)
366                         *space++ = '\0';
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 */
373                         if (line && line[0])
374                                 bb_error_msg_and_die("error in %s at '%s'", DEPFILE_BB, line);
375                         free(line);
376                 }
377         }
378         return 1;
379 }
380
381 static int start_dep_bb_writeout(void)
382 {
383         int fd;
384
385         /* depmod -n: write result to stdout */
386         if (applet_name[0] == 'd' && (option_mask32 & 1))
387                 return STDOUT_FILENO;
388
389         fd = open(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
390         if (fd < 0) {
391                 if (errno == EEXIST) {
392                         int count = 5 * 20;
393                         dbg1_error_msg(DEPFILE_BB".new exists, waiting for "DEPFILE_BB);
394                         while (1) {
395                                 usleep(1000*1000 / 20);
396                                 if (load_dep_bb()) {
397                                         dbg1_error_msg(DEPFILE_BB" appeared");
398                                         return -2; /* magic number */
399                                 }
400                                 if (!--count)
401                                         break;
402                         }
403                         bb_error_msg("deleting stale %s", DEPFILE_BB".new");
404                         fd = open_or_warn(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC);
405                 }
406         }
407         dbg1_error_msg("opened "DEPFILE_BB".new:%d", fd);
408         return fd;
409 }
410
411 static void write_out_dep_bb(int fd)
412 {
413         int i;
414         FILE *fp;
415
416         /* We want good error reporting. fdprintf is not good enough. */
417         fp = fdopen(fd, "w");
418         if (!fp) {
419                 close(fd);
420                 goto err;
421         }
422         i = 0;
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" : "");
427                 i++;
428         }
429         /* Badly formatted depfile is a no-no. Be paranoid. */
430         errno = 0;
431         if (ferror(fp) | fclose(fp)) /* | instead of || is intended */
432                 goto err;
433
434         if (fd == STDOUT_FILENO) /* it was depmod -n */
435                 goto ok;
436
437         if (rename(DEPFILE_BB".new", DEPFILE_BB) != 0) {
438  err:
439                 bb_perror_msg("can't create %s", DEPFILE_BB);
440                 unlink(DEPFILE_BB".new");
441         } else {
442  ok:
443                 wrote_dep_bb_ok = 1;
444                 dbg1_error_msg("created "DEPFILE_BB);
445         }
446 }
447
448 static module_info* find_alias(const char *alias)
449 {
450         int i;
451         int dep_bb_fd;
452         module_info *result;
453         dbg1_error_msg("find_alias('%s')", alias);
454
455  try_again:
456         /* First try to find by name (cheaper) */
457         i = 0;
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);
464                         }
465                         return &modinfo[i];
466                 }
467                 i++;
468         }
469
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? */
474                 goto try_again;
475
476         /* Scan all module bodies, extract modinfo (it contains aliases) */
477         i = 0;
478         result = NULL;
479         while (modinfo[i].pathname) {
480                 char *desc, *s;
481                 if (!modinfo[i].aliases) {
482                         parse_module(&modinfo[i], modinfo[i].pathname);
483                 }
484                 if (result)
485                         continue;
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];
498                                 break;
499                         }
500                 }
501                 free(desc);
502                 if (result && dep_bb_fd < 0)
503                         return result;
504                 i++;
505         }
506
507         /* Create module.dep.bb if needed */
508         if (dep_bb_fd >= 0) {
509                 write_out_dep_bb(dep_bb_fd);
510         }
511
512         dbg1_error_msg("find_alias '%s' returns %p", alias, result);
513         return result;
514 }
515
516 #if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
517 static int already_loaded(const char *name)
518 {
519         int ret = 0;
520         int len = strlen(name);
521         char *line;
522         FILE* modules;
523
524         modules = xfopen("/proc/modules", "r");
525         while ((line = xmalloc_fgets(modules)) != NULL) {
526                 if (strncmp(line, name, len) == 0 && line[len] == ' ') {
527                         free(line);
528                         ret = 1;
529                         break;
530                 }
531                 free(line);
532         }
533         fclose(modules);
534         return ret;
535 }
536 #else
537 #define already_loaded(name) is_rmmod
538 #endif
539
540 /*
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.
545 */
546 #if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
547 #define process_module(a,b) process_module(a)
548 #define cmdline_options ""
549 #endif
550 static void process_module(char *name, const char *cmdline_options)
551 {
552         char *s, *deps, *options;
553         module_info *info;
554         int is_rmmod = (option_mask32 & OPT_r) != 0;
555         dbg1_error_msg("process_module('%s','%s')", name, cmdline_options);
556
557         replace(name, '-', '_');
558
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);
562                 return;
563         }
564
565         options = NULL;
566         if (!is_rmmod) {
567                 char *opt_filename = xasprintf("/etc/modules/%s", name);
568                 options = xmalloc_open_read_close(opt_filename, NULL);
569                 if (options)
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);
577                         free(options);
578                         options = op;
579                 }
580 #endif
581                 free(opt_filename);
582                 module_load_options = options;
583                 dbg1_error_msg("process_module('%s'): options:'%s'", name, options);
584         }
585
586         if (!module_count) {
587                 /* Scan module directory. This is done only once.
588                  * It will attempt module load, and will exit(EXIT_SUCCESS)
589                  * on 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 */
596                         0); /* depth */
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);
603                 }
604         } else {
605                 info = find_alias(name);
606         }
607
608         /* rmmod? unload it by name */
609         if (is_rmmod) {
610                 if (delete_module(name, O_NONBLOCK | O_EXCL) != 0
611                  && !(option_mask32 & OPT_q)
612                 ) {
613                         bb_perror_msg("remove '%s'", name);
614                         goto ret;
615                 }
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." */
621         }
622
623         if (!info) {
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);
627 //TODO: _and_die()?
628                 goto ret;
629         }
630
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);
638         }
639         free(deps);
640
641         /* insmod -> load it */
642         if (!is_rmmod) {
643                 errno = 0;
644                 if (load_module(info->pathname, options) != 0) {
645                         if (EEXIST != errno) {
646                                 bb_error_msg("'%s': %s",
647                                                 info->pathname,
648                                                 moderror(errno));
649                         } else {
650                                 dbg1_error_msg("'%s': %s",
651                                                 info->pathname,
652                                                 moderror(errno));
653                         }
654                 }
655         }
656  ret:
657         free(options);
658 //TODO: return load attempt result from process_module.
659 //If dep didn't load ok, continuing makes little sense.
660 }
661 #undef cmdline_options
662
663
664 /* For reference, module-init-tools v3.4 options:
665
666 # insmod
667 Usage: insmod filename [args]
668
669 # rmmod --help
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).
681
682 # modprobe
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> ...]
687
688 # depmod --help
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.
695 Options:
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:
704     -b basedirectory
705         --basedir basedirectory    Use an image of a module tree.
706     -F kernelsyms
707         --filesyms kernelsyms      Use the file instead of the
708                                    current kernel symbols.
709 */
710
711 int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
712 int modprobe_main(int argc UNUSED_PARAM, char **argv)
713 {
714         struct utsname uts;
715         char applet0 = applet_name[0];
716         USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
717
718         /* are we lsmod? -> just dump /proc/modules */
719         if ('l' == applet0) {
720                 xprint_and_close_file(xfopen("/proc/modules", "r"));
721                 return EXIT_SUCCESS;
722         }
723
724         INIT_G();
725
726         /* Prevent ugly corner cases with no modules at all */
727         modinfo = xzalloc(sizeof(modinfo[0]));
728
729         /* Goto modules directory */
730         xchdir(CONFIG_DEFAULT_MODULES_DIR);
731         uname(&uts); /* never fails */
732
733         /* depmod? */
734         if ('d' == applet0) {
735                 /* Supported:
736                  * -n: print result to stdout
737                  * -a: process all modules (default)
738                  * optional VERSION parameter
739                  * Ignored:
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)
744                  * -q, -r, -u: noop?
745                  * Not supported:
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)
753                  */
754                 getopt32(argv, "na" "AeF:qru" /* "b:vV", NULL */, NULL);
755                 argv += optind;
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;
763         }
764
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");
770         argv += optind;
771
772         /* are we rmmod? -> simulate modprobe -r */
773         if ('r' == applet0) {
774                 option_mask32 |= OPT_r;
775         }
776
777         /* Goto $VERSION directory */
778         xchdir(uts.release);
779
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. */
783         options = NULL;
784         if ('r' != applet0) {
785                 char **arg = argv;
786                 while (*++arg) {
787                         /* Enclose options in quotes */
788                         char *s = options;
789                         options = xasprintf("%s \"%s\"", s ? s : "", *arg);
790                         free(s);
791                         *arg = NULL;
792                 }
793         }
794 #else
795         if ('r' != applet0)
796                 argv[1] = NULL;
797 #endif
798
799         /* Try to load modprobe.dep.bb */
800         load_dep_bb();
801
802         /* Load/remove modules.
803          * Only rmmod loops here, insmod/modprobe has only argv[0] */
804         do {
805                 process_module(*argv++, options);
806         } while (*argv);
807
808         if (ENABLE_FEATURE_CLEAN_UP) {
809                 USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
810         }
811         return EXIT_SUCCESS;
812 }