modprobe-small.c 30 KB

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