modprobe-small.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * simplified modprobe
  4. *
  5. * Copyright (c) 2008 Vladimir Dronnikov
  6. * Copyright (c) 2008 Bernhard Reutner-Fischer (initial depmod code)
  7. *
  8. * Licensed under GPLv2, see file LICENSE in this source tree.
  9. */
  10. //applet:IF_MODPROBE_SMALL(APPLET(modprobe, BB_DIR_SBIN, BB_SUID_DROP))
  11. //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(depmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, depmod))
  12. //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(insmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, insmod))
  13. //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(lsmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, lsmod))
  14. //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(rmmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, rmmod))
  15. #include "libbb.h"
  16. /* After libbb.h, since it needs sys/types.h on some systems */
  17. #include <sys/utsname.h> /* uname() */
  18. #include <fnmatch.h>
  19. extern int init_module(void *module, unsigned long len, const char *options);
  20. extern int delete_module(const char *module, unsigned flags);
  21. extern int query_module(const char *name, int which, void *buf, size_t bufsize, size_t *ret);
  22. /* linux/include/linux/module.h has limit of 64 chars on module names */
  23. #undef MODULE_NAME_LEN
  24. #define MODULE_NAME_LEN 64
  25. #if 1
  26. # define dbg1_error_msg(...) ((void)0)
  27. # define dbg2_error_msg(...) ((void)0)
  28. #else
  29. # define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
  30. # define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
  31. #endif
  32. #define DEPFILE_BB CONFIG_DEFAULT_DEPMOD_FILE".bb"
  33. enum {
  34. OPT_q = (1 << 0), /* be quiet */
  35. OPT_r = (1 << 1), /* module removal instead of loading */
  36. };
  37. typedef struct module_info {
  38. char *pathname;
  39. char *aliases;
  40. char *deps;
  41. } module_info;
  42. /*
  43. * GLOBALS
  44. */
  45. struct globals {
  46. module_info *modinfo;
  47. char *module_load_options;
  48. smallint dep_bb_seen;
  49. smallint wrote_dep_bb_ok;
  50. unsigned module_count;
  51. int module_found_idx;
  52. unsigned stringbuf_idx;
  53. unsigned stringbuf_size;
  54. char *stringbuf; /* some modules have lots of stuff */
  55. /* for example, drivers/media/video/saa7134/saa7134.ko */
  56. /* therefore having a fixed biggish buffer is not wise */
  57. };
  58. #define G (*ptr_to_globals)
  59. #define modinfo (G.modinfo )
  60. #define dep_bb_seen (G.dep_bb_seen )
  61. #define wrote_dep_bb_ok (G.wrote_dep_bb_ok )
  62. #define module_count (G.module_count )
  63. #define module_found_idx (G.module_found_idx )
  64. #define module_load_options (G.module_load_options)
  65. #define stringbuf_idx (G.stringbuf_idx )
  66. #define stringbuf_size (G.stringbuf_size )
  67. #define stringbuf (G.stringbuf )
  68. #define INIT_G() do { \
  69. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  70. } while (0)
  71. static void append(const char *s)
  72. {
  73. unsigned len = strlen(s);
  74. if (stringbuf_idx + len + 15 > stringbuf_size) {
  75. stringbuf_size = stringbuf_idx + len + 127;
  76. dbg2_error_msg("grow stringbuf to %u", stringbuf_size);
  77. stringbuf = xrealloc(stringbuf, stringbuf_size);
  78. }
  79. memcpy(stringbuf + stringbuf_idx, s, len);
  80. stringbuf_idx += len;
  81. }
  82. static void appendc(char c)
  83. {
  84. /* We appendc() only after append(), + 15 trick in append()
  85. * makes it unnecessary to check for overflow here */
  86. stringbuf[stringbuf_idx++] = c;
  87. }
  88. static void bksp(void)
  89. {
  90. if (stringbuf_idx)
  91. stringbuf_idx--;
  92. }
  93. static void reset_stringbuf(void)
  94. {
  95. stringbuf_idx = 0;
  96. }
  97. static char* copy_stringbuf(void)
  98. {
  99. char *copy = xzalloc(stringbuf_idx + 1); /* terminating NUL */
  100. return memcpy(copy, stringbuf, stringbuf_idx);
  101. }
  102. static char* find_keyword(char *ptr, size_t len, const char *word)
  103. {
  104. int wlen;
  105. if (!ptr) /* happens if xmalloc_open_zipped_read_close cannot read it */
  106. return NULL;
  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. static void replace(char *s, char what, char with)
  123. {
  124. while (*s) {
  125. if (what == *s)
  126. *s = with;
  127. ++s;
  128. }
  129. }
  130. static char *filename2modname(const char *filename, char *modname)
  131. {
  132. int i;
  133. const char *from;
  134. // Disabled since otherwise "modprobe dir/name" would work
  135. // as if it is "modprobe name". It is unclear why
  136. // 'basenamization' was here in the first place.
  137. //from = bb_get_last_path_component_nostrip(filename);
  138. from = filename;
  139. for (i = 0; i < (MODULE_NAME_LEN-1) && from[i] != '\0' && from[i] != '.'; i++)
  140. modname[i] = (from[i] == '-') ? '_' : from[i];
  141. modname[i] = '\0';
  142. return modname;
  143. }
  144. /* Take "word word", return malloced "word",NUL,"word",NUL,NUL */
  145. static char* str_2_list(const char *str)
  146. {
  147. int len = strlen(str) + 1;
  148. char *dst = xmalloc(len + 1);
  149. dst[len] = '\0';
  150. memcpy(dst, str, len);
  151. //TODO: protect against 2+ spaces: "word word"
  152. replace(dst, ' ', '\0');
  153. return dst;
  154. }
  155. /* We use error numbers in a loose translation... */
  156. static const char *moderror(int err)
  157. {
  158. switch (err) {
  159. case ENOEXEC:
  160. return "invalid module format";
  161. case ENOENT:
  162. return "unknown symbol in module or invalid parameter";
  163. case ESRCH:
  164. return "module has wrong symbol version";
  165. case EINVAL: /* "invalid parameter" */
  166. return "unknown symbol in module or invalid parameter"
  167. + sizeof("unknown symbol in module or");
  168. default:
  169. return strerror(err);
  170. }
  171. }
  172. static int load_module(const char *fname, const char *options)
  173. {
  174. #if 1
  175. int r;
  176. size_t len = MAXINT(ssize_t);
  177. char *module_image;
  178. dbg1_error_msg("load_module('%s','%s')", fname, options);
  179. module_image = xmalloc_open_zipped_read_close(fname, &len);
  180. r = (!module_image || init_module(module_image, len, options ? options : "") != 0);
  181. free(module_image);
  182. dbg1_error_msg("load_module:%d", r);
  183. return r; /* 0 = success */
  184. #else
  185. /* For testing */
  186. dbg1_error_msg("load_module('%s','%s')", fname, options);
  187. return 1;
  188. #endif
  189. }
  190. static void parse_module(module_info *info, const char *pathname)
  191. {
  192. char *module_image;
  193. char *ptr;
  194. size_t len;
  195. size_t pos;
  196. dbg1_error_msg("parse_module('%s')", pathname);
  197. /* Read (possibly compressed) module */
  198. len = 64 * 1024 * 1024; /* 64 Mb at most */
  199. module_image = xmalloc_open_zipped_read_close(pathname, &len);
  200. /* module_image == NULL is ok here, find_keyword handles it */
  201. //TODO: optimize redundant module body reads
  202. /* "alias1 symbol:sym1 alias2 symbol:sym2" */
  203. reset_stringbuf();
  204. pos = 0;
  205. while (1) {
  206. unsigned start = stringbuf_idx;
  207. ptr = find_keyword(module_image + pos, len - pos, "alias=");
  208. if (!ptr) {
  209. ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
  210. if (!ptr)
  211. break;
  212. /* DOCME: __ksymtab_gpl and __ksymtab_strings occur
  213. * in many modules. What do they mean? */
  214. if (strcmp(ptr, "gpl") == 0 || strcmp(ptr, "strings") == 0)
  215. goto skip;
  216. dbg2_error_msg("alias:'symbol:%s'", ptr);
  217. append("symbol:");
  218. } else {
  219. dbg2_error_msg("alias:'%s'", ptr);
  220. }
  221. append(ptr);
  222. appendc(' ');
  223. /*
  224. * Don't add redundant aliases, such as:
  225. * libcrc32c.ko symbol:crc32c symbol:crc32c
  226. */
  227. if (start) { /* "if we aren't the first alias" */
  228. char *found, *last;
  229. stringbuf[stringbuf_idx] = '\0';
  230. last = stringbuf + start;
  231. /*
  232. * String at last-1 is " symbol:crc32c "
  233. * (with both leading and trailing spaces).
  234. */
  235. if (strncmp(stringbuf, last, stringbuf_idx - start) == 0)
  236. /* First alias matches us */
  237. found = stringbuf;
  238. else
  239. /* Does any other alias match? */
  240. found = strstr(stringbuf, last-1);
  241. if (found < last-1) {
  242. /* There is absolutely the same string before us */
  243. dbg2_error_msg("redundant:'%s'", last);
  244. stringbuf_idx = start;
  245. goto skip;
  246. }
  247. }
  248. skip:
  249. pos = (ptr - module_image);
  250. }
  251. bksp(); /* remove last ' ' */
  252. info->aliases = copy_stringbuf();
  253. replace(info->aliases, '-', '_');
  254. /* "dependency1 depandency2" */
  255. reset_stringbuf();
  256. ptr = find_keyword(module_image, len, "depends=");
  257. if (ptr && *ptr) {
  258. replace(ptr, ',', ' ');
  259. replace(ptr, '-', '_');
  260. dbg2_error_msg("dep:'%s'", ptr);
  261. append(ptr);
  262. }
  263. info->deps = copy_stringbuf();
  264. free(module_image);
  265. }
  266. static int pathname_matches_modname(const char *pathname, const char *modname)
  267. {
  268. int r;
  269. char name[MODULE_NAME_LEN];
  270. const char *fname = bb_get_last_path_component_nostrip(pathname);
  271. const char *suffix = strrstr(fname, ".ko");
  272. safe_strncpy(name, fname, suffix - fname + 1);
  273. replace(name, '-', '_');
  274. r = (strcmp(name, modname) == 0);
  275. return r;
  276. }
  277. static FAST_FUNC int fileAction(const char *pathname,
  278. struct stat *sb UNUSED_PARAM,
  279. void *modname_to_match,
  280. int depth UNUSED_PARAM)
  281. {
  282. int cur;
  283. const char *fname;
  284. pathname += 2; /* skip "./" */
  285. fname = bb_get_last_path_component_nostrip(pathname);
  286. if (!strrstr(fname, ".ko")) {
  287. dbg1_error_msg("'%s' is not a module", pathname);
  288. return TRUE; /* not a module, continue search */
  289. }
  290. cur = module_count++;
  291. modinfo = xrealloc_vector(modinfo, 12, cur);
  292. modinfo[cur].pathname = xstrdup(pathname);
  293. /*modinfo[cur].aliases = NULL; - xrealloc_vector did it */
  294. /*modinfo[cur+1].pathname = NULL;*/
  295. if (!pathname_matches_modname(fname, modname_to_match)) {
  296. dbg1_error_msg("'%s' module name doesn't match", pathname);
  297. return TRUE; /* module name doesn't match, continue search */
  298. }
  299. dbg1_error_msg("'%s' module name matches", pathname);
  300. module_found_idx = cur;
  301. parse_module(&modinfo[cur], pathname);
  302. if (!(option_mask32 & OPT_r)) {
  303. if (load_module(pathname, module_load_options) == 0) {
  304. /* Load was successful, there is nothing else to do.
  305. * This can happen ONLY for "top-level" module load,
  306. * not a dep, because deps dont do dirscan. */
  307. exit(EXIT_SUCCESS);
  308. }
  309. }
  310. return TRUE;
  311. }
  312. static int load_dep_bb(void)
  313. {
  314. char *line;
  315. FILE *fp = fopen_for_read(DEPFILE_BB);
  316. if (!fp)
  317. return 0;
  318. dep_bb_seen = 1;
  319. dbg1_error_msg("loading "DEPFILE_BB);
  320. /* Why? There is a rare scenario: we did not find modprobe.dep.bb,
  321. * we scanned the dir and found no module by name, then we search
  322. * for alias (full scan), and we decided to generate modprobe.dep.bb.
  323. * But we see modprobe.dep.bb.new! Other modprobe is at work!
  324. * We wait and other modprobe renames it to modprobe.dep.bb.
  325. * Now we can use it.
  326. * But we already have modinfo[] filled, and "module_count = 0"
  327. * makes us start anew. Yes, we leak modinfo[].xxx pointers -
  328. * there is not much of data there anyway. */
  329. module_count = 0;
  330. memset(&modinfo[0], 0, sizeof(modinfo[0]));
  331. while ((line = xmalloc_fgetline(fp)) != NULL) {
  332. char* space;
  333. char* linebuf;
  334. int cur;
  335. if (!line[0]) {
  336. free(line);
  337. continue;
  338. }
  339. space = strchrnul(line, ' ');
  340. cur = module_count++;
  341. modinfo = xrealloc_vector(modinfo, 12, cur);
  342. /*modinfo[cur+1].pathname = NULL; - xrealloc_vector did it */
  343. modinfo[cur].pathname = line; /* we take ownership of malloced block here */
  344. if (*space)
  345. *space++ = '\0';
  346. modinfo[cur].aliases = space;
  347. linebuf = xmalloc_fgetline(fp);
  348. modinfo[cur].deps = linebuf ? linebuf : xzalloc(1);
  349. if (modinfo[cur].deps[0]) {
  350. /* deps are not "", so next line must be empty */
  351. line = xmalloc_fgetline(fp);
  352. /* Refuse to work with damaged config file */
  353. if (line && line[0])
  354. bb_error_msg_and_die("error in %s at '%s'", DEPFILE_BB, line);
  355. free(line);
  356. }
  357. }
  358. return 1;
  359. }
  360. static int start_dep_bb_writeout(void)
  361. {
  362. int fd;
  363. /* depmod -n: write result to stdout */
  364. if (applet_name[0] == 'd' && (option_mask32 & 1))
  365. return STDOUT_FILENO;
  366. fd = open(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
  367. if (fd < 0) {
  368. if (errno == EEXIST) {
  369. int count = 5 * 20;
  370. dbg1_error_msg(DEPFILE_BB".new exists, waiting for "DEPFILE_BB);
  371. while (1) {
  372. usleep(1000*1000 / 20);
  373. if (load_dep_bb()) {
  374. dbg1_error_msg(DEPFILE_BB" appeared");
  375. return -2; /* magic number */
  376. }
  377. if (!--count)
  378. break;
  379. }
  380. bb_error_msg("deleting stale %s", DEPFILE_BB".new");
  381. fd = open_or_warn(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC);
  382. }
  383. }
  384. dbg1_error_msg("opened "DEPFILE_BB".new:%d", fd);
  385. return fd;
  386. }
  387. static void write_out_dep_bb(int fd)
  388. {
  389. int i;
  390. FILE *fp;
  391. /* We want good error reporting. fdprintf is not good enough. */
  392. fp = xfdopen_for_write(fd);
  393. i = 0;
  394. while (modinfo[i].pathname) {
  395. fprintf(fp, "%s%s%s\n" "%s%s\n",
  396. modinfo[i].pathname, modinfo[i].aliases[0] ? " " : "", modinfo[i].aliases,
  397. modinfo[i].deps, modinfo[i].deps[0] ? "\n" : "");
  398. i++;
  399. }
  400. /* Badly formatted depfile is a no-no. Be paranoid. */
  401. errno = 0;
  402. if (ferror(fp) | fclose(fp)) /* | instead of || is intended */
  403. goto err;
  404. if (fd == STDOUT_FILENO) /* it was depmod -n */
  405. goto ok;
  406. if (rename(DEPFILE_BB".new", DEPFILE_BB) != 0) {
  407. err:
  408. bb_perror_msg("can't create '%s'", DEPFILE_BB);
  409. unlink(DEPFILE_BB".new");
  410. } else {
  411. ok:
  412. wrote_dep_bb_ok = 1;
  413. dbg1_error_msg("created "DEPFILE_BB);
  414. }
  415. }
  416. static module_info** find_alias(const char *alias)
  417. {
  418. int i;
  419. int dep_bb_fd;
  420. int infoidx;
  421. module_info **infovec;
  422. dbg1_error_msg("find_alias('%s')", alias);
  423. try_again:
  424. /* First try to find by name (cheaper) */
  425. i = 0;
  426. while (modinfo[i].pathname) {
  427. if (pathname_matches_modname(modinfo[i].pathname, alias)) {
  428. dbg1_error_msg("found '%s' in module '%s'",
  429. alias, modinfo[i].pathname);
  430. if (!modinfo[i].aliases) {
  431. parse_module(&modinfo[i], modinfo[i].pathname);
  432. }
  433. infovec = xzalloc(2 * sizeof(infovec[0]));
  434. infovec[0] = &modinfo[i];
  435. return infovec;
  436. }
  437. i++;
  438. }
  439. /* Ok, we definitely have to scan module bodies. This is a good
  440. * moment to generate modprobe.dep.bb, if it does not exist yet */
  441. dep_bb_fd = dep_bb_seen ? -1 : start_dep_bb_writeout();
  442. if (dep_bb_fd == -2) /* modprobe.dep.bb appeared? */
  443. goto try_again;
  444. /* Scan all module bodies, extract modinfo (it contains aliases) */
  445. i = 0;
  446. infoidx = 0;
  447. infovec = NULL;
  448. while (modinfo[i].pathname) {
  449. char *desc, *s;
  450. if (!modinfo[i].aliases) {
  451. parse_module(&modinfo[i], modinfo[i].pathname);
  452. }
  453. /* "alias1 symbol:sym1 alias2 symbol:sym2" */
  454. desc = str_2_list(modinfo[i].aliases);
  455. /* Does matching substring exist? */
  456. for (s = desc; *s; s += strlen(s) + 1) {
  457. /* Aliases in module bodies can be defined with
  458. * shell patterns. Example:
  459. * "pci:v000010DEd000000D9sv*sd*bc*sc*i*".
  460. * Plain strcmp() won't catch that */
  461. if (fnmatch(s, alias, 0) == 0) {
  462. dbg1_error_msg("found alias '%s' in module '%s'",
  463. alias, modinfo[i].pathname);
  464. infovec = xrealloc_vector(infovec, 1, infoidx);
  465. infovec[infoidx++] = &modinfo[i];
  466. break;
  467. }
  468. }
  469. free(desc);
  470. i++;
  471. }
  472. /* Create module.dep.bb if needed */
  473. if (dep_bb_fd >= 0) {
  474. write_out_dep_bb(dep_bb_fd);
  475. }
  476. dbg1_error_msg("find_alias '%s' returns %d results", alias, infoidx);
  477. return infovec;
  478. }
  479. #if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
  480. // TODO: open only once, invent config_rewind()
  481. static int already_loaded(const char *name)
  482. {
  483. int ret = 0;
  484. char *s;
  485. parser_t *parser = config_open2("/proc/modules", xfopen_for_read);
  486. while (config_read(parser, &s, 1, 1, "# \t", PARSE_NORMAL & ~PARSE_GREEDY)) {
  487. if (strcmp(s, name) == 0) {
  488. ret = 1;
  489. break;
  490. }
  491. }
  492. config_close(parser);
  493. return ret;
  494. }
  495. #else
  496. #define already_loaded(name) 0
  497. #endif
  498. static int rmmod(const char *filename)
  499. {
  500. int r;
  501. char modname[MODULE_NAME_LEN];
  502. filename2modname(filename, modname);
  503. r = delete_module(modname, O_NONBLOCK | O_EXCL);
  504. dbg1_error_msg("delete_module('%s', O_NONBLOCK | O_EXCL):%d", modname, r);
  505. if (r != 0 && !(option_mask32 & OPT_q)) {
  506. bb_perror_msg("remove '%s'", modname);
  507. }
  508. return r;
  509. }
  510. /*
  511. * Given modules definition and module name (or alias, or symbol)
  512. * load/remove the module respecting dependencies.
  513. * NB: also called by depmod with bogus name "/",
  514. * just in order to force modprobe.dep.bb creation.
  515. */
  516. #if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
  517. #define process_module(a,b) process_module(a)
  518. #define cmdline_options ""
  519. #endif
  520. static void process_module(char *name, const char *cmdline_options)
  521. {
  522. char *s, *deps, *options;
  523. module_info **infovec;
  524. module_info *info;
  525. int infoidx;
  526. int is_remove = (option_mask32 & OPT_r) != 0;
  527. dbg1_error_msg("process_module('%s','%s')", name, cmdline_options);
  528. replace(name, '-', '_');
  529. dbg1_error_msg("already_loaded:%d is_remove:%d", already_loaded(name), is_remove);
  530. if (applet_name[0] == 'r') {
  531. /* rmmod.
  532. * Does not remove dependencies, no need to scan, just remove.
  533. * (compat note: this allows and strips .ko suffix)
  534. */
  535. rmmod(name);
  536. return;
  537. }
  538. /*
  539. * We used to have "is_remove != already_loaded(name)" check here, but
  540. * modprobe -r pci:v00008086d00007010sv00000000sd00000000bc01sc01i80
  541. * won't unload modules (there are more than one)
  542. * which have this alias.
  543. */
  544. if (!is_remove && already_loaded(name)) {
  545. dbg1_error_msg("nothing to do for '%s'", name);
  546. return;
  547. }
  548. options = NULL;
  549. if (!is_remove) {
  550. char *opt_filename = xasprintf("/etc/modules/%s", name);
  551. options = xmalloc_open_read_close(opt_filename, NULL);
  552. if (options)
  553. replace(options, '\n', ' ');
  554. #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
  555. if (cmdline_options) {
  556. /* NB: cmdline_options always have one leading ' '
  557. * (see main()), we remove it here */
  558. char *op = xasprintf(options ? "%s %s" : "%s %s" + 3,
  559. cmdline_options + 1, options);
  560. free(options);
  561. options = op;
  562. }
  563. #endif
  564. free(opt_filename);
  565. module_load_options = options;
  566. dbg1_error_msg("process_module('%s'): options:'%s'", name, options);
  567. }
  568. if (!module_count) {
  569. /* Scan module directory. This is done only once.
  570. * It will attempt module load, and will exit(EXIT_SUCCESS)
  571. * on success.
  572. */
  573. module_found_idx = -1;
  574. recursive_action(".",
  575. ACTION_RECURSE, /* flags */
  576. fileAction, /* file action */
  577. NULL, /* dir action */
  578. name, /* user data */
  579. 0 /* depth */
  580. );
  581. dbg1_error_msg("dirscan complete");
  582. /* Module was not found, or load failed, or is_remove */
  583. if (module_found_idx >= 0) { /* module was found */
  584. infovec = xzalloc(2 * sizeof(infovec[0]));
  585. infovec[0] = &modinfo[module_found_idx];
  586. } else { /* search for alias, not a plain module name */
  587. infovec = find_alias(name);
  588. }
  589. } else {
  590. infovec = find_alias(name);
  591. }
  592. if (!infovec) {
  593. /* both dirscan and find_alias found nothing */
  594. if (!is_remove && applet_name[0] != 'd') /* it wasn't rmmod or depmod */
  595. bb_error_msg("module '%s' not found", name);
  596. //TODO: _and_die()? or should we continue (un)loading modules listed on cmdline?
  597. goto ret;
  598. }
  599. /* There can be more than one module for the given alias. For example,
  600. * "pci:v00008086d00007010sv00000000sd00000000bc01sc01i80" matches
  601. * ata_piix because it has alias "pci:v00008086d00007010sv*sd*bc*sc*i*"
  602. * and ata_generic, it has alias "pci:v*d*sv*sd*bc01sc01i*"
  603. * Standard modprobe loads them both. We achieve it by returning
  604. * a *list* of modinfo pointers from find_alias().
  605. */
  606. /* modprobe -r? unload module(s) */
  607. if (is_remove) {
  608. infoidx = 0;
  609. while ((info = infovec[infoidx++]) != NULL) {
  610. int r = rmmod(bb_get_last_path_component_nostrip(info->pathname));
  611. if (r != 0) {
  612. goto ret; /* error */
  613. }
  614. }
  615. /* modprobe -r: we do not stop here -
  616. * continue to unload modules on which the module depends:
  617. * "-r --remove: option causes modprobe to remove a module.
  618. * If the modules it depends on are also unused, modprobe
  619. * will try to remove them, too."
  620. */
  621. }
  622. infoidx = 0;
  623. while ((info = infovec[infoidx++]) != NULL) {
  624. /* Iterate thru dependencies, trying to (un)load them */
  625. deps = str_2_list(info->deps);
  626. for (s = deps; *s; s += strlen(s) + 1) {
  627. //if (strcmp(name, s) != 0) // N.B. do loops exist?
  628. dbg1_error_msg("recurse on dep '%s'", s);
  629. process_module(s, NULL);
  630. dbg1_error_msg("recurse on dep '%s' done", s);
  631. }
  632. free(deps);
  633. if (is_remove)
  634. continue;
  635. /* We are modprobe: load it */
  636. if (options && strstr(options, "blacklist")) {
  637. dbg1_error_msg("'%s': blacklisted", info->pathname);
  638. continue;
  639. }
  640. errno = 0;
  641. if (load_module(info->pathname, options) != 0) {
  642. if (EEXIST != errno) {
  643. bb_error_msg("'%s': %s",
  644. info->pathname,
  645. moderror(errno));
  646. } else {
  647. dbg1_error_msg("'%s': %s",
  648. info->pathname,
  649. moderror(errno));
  650. }
  651. }
  652. }
  653. ret:
  654. free(infovec);
  655. free(options);
  656. //TODO: return load attempt result from process_module.
  657. //If dep didn't load ok, continuing makes little sense.
  658. }
  659. #undef cmdline_options
  660. /* For reference, module-init-tools v3.4 options:
  661. # insmod
  662. Usage: insmod filename [args]
  663. # rmmod --help
  664. Usage: rmmod [-fhswvV] modulename ...
  665. -f (or --force) forces a module unload, and may crash your
  666. machine. This requires the Forced Module Removal option
  667. when the kernel was compiled.
  668. -h (or --help) prints this help text
  669. -s (or --syslog) says use syslog, not stderr
  670. -v (or --verbose) enables more messages
  671. -V (or --version) prints the version code
  672. -w (or --wait) begins module removal even if it is used
  673. and will stop new users from accessing the module (so it
  674. should eventually fall to zero).
  675. # modprobe
  676. Usage: modprobe [-v] [-V] [-C config-file] [-n] [-i] [-q] [-b]
  677. [-o <modname>] [ --dump-modversions ] <modname> [parameters...]
  678. modprobe -r [-n] [-i] [-v] <modulename> ...
  679. modprobe -l -t <dirname> [ -a <modulename> ...]
  680. # depmod --help
  681. depmod 3.4 -- part of module-init-tools
  682. depmod -[aA] [-n -e -v -q -V -r -u]
  683. [-b basedirectory] [forced_version]
  684. depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.ko module2.ko ...
  685. If no arguments (except options) are given, "depmod -a" is assumed.
  686. depmod will output a dependency list suitable for the modprobe utility.
  687. Options:
  688. -a, --all Probe all modules
  689. -A, --quick Only does the work if there's a new module
  690. -n, --show Write the dependency file on stdout only
  691. -e, --errsyms Report not supplied symbols
  692. -V, --version Print the release version
  693. -v, --verbose Enable verbose mode
  694. -h, --help Print this usage message
  695. The following options are useful for people managing distributions:
  696. -b basedirectory
  697. --basedir basedirectory
  698. Use an image of a module tree
  699. -F kernelsyms
  700. --filesyms kernelsyms
  701. Use the file instead of the current kernel symbols
  702. */
  703. //usage:#if ENABLE_MODPROBE_SMALL
  704. //usage:#define depmod_trivial_usage NOUSAGE_STR
  705. //usage:#define depmod_full_usage ""
  706. //usage:#define lsmod_trivial_usage
  707. //usage: ""
  708. //usage:#define lsmod_full_usage "\n\n"
  709. //usage: "List the currently loaded kernel modules"
  710. //usage:#define insmod_trivial_usage
  711. //usage: IF_FEATURE_2_4_MODULES("[OPTIONS] MODULE ")
  712. //usage: IF_NOT_FEATURE_2_4_MODULES("FILE ")
  713. //usage: "[SYMBOL=VALUE]..."
  714. //usage:#define insmod_full_usage "\n\n"
  715. //usage: "Load kernel module"
  716. //usage: IF_FEATURE_2_4_MODULES( "\n"
  717. //usage: "\n -f Force module to load into the wrong kernel version"
  718. //usage: "\n -k Make module autoclean-able"
  719. //usage: "\n -v Verbose"
  720. //usage: "\n -q Quiet"
  721. //usage: "\n -L Lock: prevent simultaneous loads"
  722. //usage: IF_FEATURE_INSMOD_LOAD_MAP(
  723. //usage: "\n -m Output load map to stdout"
  724. //usage: )
  725. //usage: "\n -x Don't export externs"
  726. //usage: )
  727. //usage:#define rmmod_trivial_usage
  728. //usage: "[-wfa] [MODULE]..."
  729. //usage:#define rmmod_full_usage "\n\n"
  730. //usage: "Unload kernel modules\n"
  731. //usage: "\n -w Wait until the module is no longer used"
  732. //usage: "\n -f Force unload"
  733. //usage: "\n -a Remove all unused modules (recursively)"
  734. //usage:
  735. //usage:#define rmmod_example_usage
  736. //usage: "$ rmmod tulip\n"
  737. //usage:#define modprobe_trivial_usage
  738. //usage: "[-qfwrsv] MODULE [SYMBOL=VALUE]..."
  739. //usage:#define modprobe_full_usage "\n\n"
  740. //usage: " -r Remove MODULE (stacks) or do autoclean"
  741. //usage: "\n -q Quiet"
  742. //usage: "\n -v Verbose"
  743. //usage: "\n -f Force"
  744. //usage: "\n -w Wait for unload"
  745. //usage: "\n -s Report via syslog instead of stderr"
  746. //usage:#endif
  747. int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  748. int modprobe_main(int argc UNUSED_PARAM, char **argv)
  749. {
  750. struct utsname uts;
  751. char applet0 = applet_name[0];
  752. IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
  753. /* are we lsmod? -> just dump /proc/modules */
  754. if ('l' == applet0) {
  755. xprint_and_close_file(xfopen_for_read("/proc/modules"));
  756. return EXIT_SUCCESS;
  757. }
  758. INIT_G();
  759. /* Prevent ugly corner cases with no modules at all */
  760. modinfo = xzalloc(sizeof(modinfo[0]));
  761. if ('i' != applet0) { /* not insmod */
  762. /* Goto modules directory */
  763. xchdir(CONFIG_DEFAULT_MODULES_DIR);
  764. }
  765. uname(&uts); /* never fails */
  766. /* depmod? */
  767. if ('d' == applet0) {
  768. /* Supported:
  769. * -n: print result to stdout
  770. * -a: process all modules (default)
  771. * optional VERSION parameter
  772. * Ignored:
  773. * -A: do work only if a module is newer than depfile
  774. * -e: report any symbols which a module needs
  775. * which are not supplied by other modules or the kernel
  776. * -F FILE: System.map (symbols for -e)
  777. * -q, -r, -u: noop?
  778. * Not supported:
  779. * -b BASEDIR: (TODO!) modules are in
  780. * $BASEDIR/lib/modules/$VERSION
  781. * -v: human readable deps to stdout
  782. * -V: version (don't want to support it - people may depend
  783. * on it as an indicator of "standard" depmod)
  784. * -h: help (well duh)
  785. * module1.o module2.o parameters (just ignored for now)
  786. */
  787. getopt32(argv, "na" "AeF:qru" /* "b:vV", NULL */, NULL);
  788. argv += optind;
  789. /* if (argv[0] && argv[1]) bb_show_usage(); */
  790. /* Goto $VERSION directory */
  791. xchdir(argv[0] ? argv[0] : uts.release);
  792. /* Force full module scan by asking to find a bogus module.
  793. * This will generate modules.dep.bb as a side effect. */
  794. process_module((char*)"/", NULL);
  795. return !wrote_dep_bb_ok;
  796. }
  797. /* insmod, modprobe, rmmod require at least one argument */
  798. opt_complementary = "-1";
  799. /* only -q (quiet) and -r (rmmod),
  800. * the rest are accepted and ignored (compat) */
  801. getopt32(argv, "qrfsvwb");
  802. argv += optind;
  803. /* are we rmmod? -> simulate modprobe -r */
  804. if ('r' == applet0) {
  805. option_mask32 |= OPT_r;
  806. }
  807. if ('i' != applet0) { /* not insmod */
  808. /* Goto $VERSION directory */
  809. xchdir(uts.release);
  810. }
  811. #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
  812. /* If not rmmod/-r, parse possible module options given on command line.
  813. * insmod/modprobe takes one module name, the rest are parameters. */
  814. options = NULL;
  815. if (!(option_mask32 & OPT_r)) {
  816. char **arg = argv;
  817. while (*++arg) {
  818. /* Enclose options in quotes */
  819. char *s = options;
  820. options = xasprintf("%s \"%s\"", s ? s : "", *arg);
  821. free(s);
  822. *arg = NULL;
  823. }
  824. }
  825. #else
  826. if (!(option_mask32 & OPT_r))
  827. argv[1] = NULL;
  828. #endif
  829. if ('i' == applet0) { /* insmod */
  830. size_t len;
  831. void *map;
  832. len = MAXINT(ssize_t);
  833. map = xmalloc_open_zipped_read_close(*argv, &len);
  834. if (!map)
  835. bb_perror_msg_and_die("can't read '%s'", *argv);
  836. if (init_module(map, len,
  837. IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(options ? options : "")
  838. IF_NOT_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE("")
  839. ) != 0
  840. ) {
  841. bb_error_msg_and_die("can't insert '%s': %s",
  842. *argv, moderror(errno));
  843. }
  844. return 0;
  845. }
  846. /* Try to load modprobe.dep.bb */
  847. if ('r' != applet0) /* not rmmod */
  848. load_dep_bb();
  849. /* Load/remove modules.
  850. * Only rmmod/modprobe -r loops here, insmod/modprobe has only argv[0] */
  851. do {
  852. process_module(*argv, options);
  853. } while (*++argv);
  854. if (ENABLE_FEATURE_CLEAN_UP) {
  855. IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
  856. }
  857. return EXIT_SUCCESS;
  858. }