modprobe-small.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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. 0 /* depth */
  672. );
  673. dbg1_error_msg("dirscan complete");
  674. /* Module was not found, or load failed, or is_remove */
  675. if (module_found_idx >= 0) { /* module was found */
  676. infovec = xzalloc(2 * sizeof(infovec[0]));
  677. infovec[0] = &modinfo[module_found_idx];
  678. } else { /* search for alias, not a plain module name */
  679. infovec = find_alias(name);
  680. }
  681. } else {
  682. infovec = find_alias(name);
  683. }
  684. if (!infovec) {
  685. /* both dirscan and find_alias found nothing */
  686. if (!is_remove && !is_depmod) { /* it wasn't rmmod or depmod */
  687. bb_error_msg("module '%s' not found", name);
  688. //TODO: _and_die()? or should we continue (un)loading modules listed on cmdline?
  689. /* "modprobe non-existing-module; echo $?" must print 1 */
  690. exitcode = EXIT_FAILURE;
  691. }
  692. goto ret;
  693. }
  694. /* There can be more than one module for the given alias. For example,
  695. * "pci:v00008086d00007010sv00000000sd00000000bc01sc01i80" matches
  696. * ata_piix because it has alias "pci:v00008086d00007010sv*sd*bc*sc*i*"
  697. * and ata_generic, it has alias "pci:v*d*sv*sd*bc01sc01i*"
  698. * Standard modprobe loads them both. We achieve it by returning
  699. * a *list* of modinfo pointers from find_alias().
  700. */
  701. /* modprobe -r? unload module(s) */
  702. if (is_remove) {
  703. infoidx = 0;
  704. while ((info = infovec[infoidx++]) != NULL) {
  705. int r = rmmod(bb_get_last_path_component_nostrip(info->pathname));
  706. if (r != 0) {
  707. goto ret; /* error */
  708. }
  709. }
  710. /* modprobe -r: we do not stop here -
  711. * continue to unload modules on which the module depends:
  712. * "-r --remove: option causes modprobe to remove a module.
  713. * If the modules it depends on are also unused, modprobe
  714. * will try to remove them, too."
  715. */
  716. }
  717. infoidx = 0;
  718. while ((info = infovec[infoidx++]) != NULL) {
  719. /* Iterate thru dependencies, trying to (un)load them */
  720. deps = str_2_list(info->deps);
  721. for (s = deps; *s; s += strlen(s) + 1) {
  722. //if (strcmp(name, s) != 0) // N.B. do loops exist?
  723. dbg1_error_msg("recurse on dep '%s'", s);
  724. process_module(s, NULL);
  725. dbg1_error_msg("recurse on dep '%s' done", s);
  726. }
  727. free(deps);
  728. if (is_remove)
  729. continue;
  730. /* We are modprobe: load it */
  731. if (options && strstr(options, "blacklist")) {
  732. dbg1_error_msg("'%s': blacklisted", info->pathname);
  733. continue;
  734. }
  735. if (info->open_read_failed) {
  736. /* We already tried it, didn't work. Don't try load again */
  737. exitcode = EXIT_FAILURE;
  738. continue;
  739. }
  740. errno = 0;
  741. if (load_module(info->pathname, options) != 0) {
  742. if (EEXIST != errno) {
  743. bb_error_msg("'%s': %s",
  744. info->pathname,
  745. moderror(errno));
  746. } else {
  747. dbg1_error_msg("'%s': %s",
  748. info->pathname,
  749. moderror(errno));
  750. }
  751. exitcode = EXIT_FAILURE;
  752. }
  753. }
  754. ret:
  755. free(infovec);
  756. free(options);
  757. return exitcode;
  758. }
  759. #undef cmdline_options
  760. /* For reference, module-init-tools v3.4 options:
  761. # insmod
  762. Usage: insmod filename [args]
  763. # rmmod --help
  764. Usage: rmmod [-fhswvV] modulename ...
  765. -f (or --force) forces a module unload, and may crash your
  766. machine. This requires the Forced Module Removal option
  767. when the kernel was compiled.
  768. -h (or --help) prints this help text
  769. -s (or --syslog) says use syslog, not stderr
  770. -v (or --verbose) enables more messages
  771. -V (or --version) prints the version code
  772. -w (or --wait) begins module removal even if it is used
  773. and will stop new users from accessing the module (so it
  774. should eventually fall to zero).
  775. # modprobe
  776. Usage: modprobe [-v] [-V] [-C config-file] [-d <dirname> ] [-n] [-i] [-q]
  777. [-b] [-o <modname>] [ --dump-modversions ] <modname> [parameters...]
  778. modprobe -r [-n] [-i] [-v] <modulename> ...
  779. modprobe -l -t <dirname> [ -a <modulename> ...]
  780. # depmod --help
  781. depmod 3.13 -- part of module-init-tools
  782. depmod -[aA] [-n -e -v -q -V -r -u -w -m]
  783. [-b basedirectory] [forced_version]
  784. depmod [-n -e -v -q -r -u -w] [-F kernelsyms] module1.ko module2.ko ...
  785. If no arguments (except options) are given, "depmod -a" is assumed.
  786. depmod will output a dependency list suitable for the modprobe utility.
  787. Options:
  788. -a, --all Probe all modules
  789. -A, --quick Only does the work if there's a new module
  790. -e, --errsyms Report not supplied symbols
  791. -m, --map Create the legacy map files
  792. -n, --show Write the dependency file on stdout only
  793. -P, --symbol-prefix Architecture symbol prefix
  794. -V, --version Print the release version
  795. -v, --verbose Enable verbose mode
  796. -w, --warn Warn on duplicates
  797. -h, --help Print this usage message
  798. The following options are useful for people managing distributions:
  799. -b basedirectory
  800. --basedir basedirectory
  801. Use an image of a module tree
  802. -F kernelsyms
  803. --filesyms kernelsyms
  804. Use the file instead of the current kernel symbols
  805. -E Module.symvers
  806. --symvers Module.symvers
  807. Use Module.symvers file to check symbol versions
  808. */
  809. //usage:#if ENABLE_MODPROBE_SMALL
  810. //usage:#define depmod_trivial_usage "[-n]"
  811. //usage:#define depmod_full_usage "\n\n"
  812. //usage: "Generate modules.dep.bb"
  813. //usage: "\n"
  814. //usage: "\n -n Dry run: print file to stdout"
  815. //usage:#define insmod_trivial_usage
  816. //usage: "FILE" IF_FEATURE_CMDLINE_MODULE_OPTIONS(" [SYMBOL=VALUE]...")
  817. //usage:#define insmod_full_usage "\n\n"
  818. //usage: "Load kernel module"
  819. //usage:#define rmmod_trivial_usage
  820. //usage: "MODULE..."
  821. //usage:#define rmmod_full_usage "\n\n"
  822. //usage: "Unload kernel modules"
  823. //usage:#define modprobe_trivial_usage
  824. //usage: "[-rq] MODULE" IF_FEATURE_CMDLINE_MODULE_OPTIONS(" [SYMBOL=VALUE]...")
  825. //usage:#define modprobe_full_usage "\n\n"
  826. //usage: " -r Remove MODULE"
  827. //usage: "\n -q Quiet"
  828. //usage:#endif
  829. int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  830. int modprobe_main(int argc UNUSED_PARAM, char **argv)
  831. {
  832. #if ENABLE_MODPROBE || ENABLE_INSMOD || ENABLE_RMMOD
  833. int exitcode;
  834. #endif
  835. struct utsname uts;
  836. IF_FEATURE_CMDLINE_MODULE_OPTIONS(char *options = NULL;)
  837. INIT_G();
  838. /* Prevent ugly corner cases with no modules at all */
  839. modinfo = xzalloc(sizeof(modinfo[0]));
  840. if ((MOD_APPLET_CNT == 2 && ENABLE_DEPMOD && ENABLE_MODPROBE)
  841. || is_depmod || is_modprobe
  842. ) {
  843. /* Goto modules directory */
  844. xchdir(CONFIG_DEFAULT_MODULES_DIR);
  845. uname(&uts); /* never fails */
  846. }
  847. /* depmod? */
  848. if (is_depmod) {
  849. /* Supported:
  850. * -n: print result to stdout
  851. * -a: process all modules (default)
  852. * optional VERSION parameter
  853. * Ignored:
  854. * -A: do work only if a module is newer than depfile
  855. * -e: report any symbols which a module needs
  856. * which are not supplied by other modules or the kernel
  857. * -F FILE: System.map (symbols for -e)
  858. * -q, -r, -u: noop
  859. * Not supported:
  860. * -b BASEDIR: (TODO!) modules are in
  861. * $BASEDIR/lib/modules/$VERSION
  862. * -m: create legacy "modules.*map" files (deprecated; in
  863. * kmod's depmod, prints a warning message and continues)
  864. * -v: human readable deps to stdout
  865. * -V: version (don't want to support it - people may depend
  866. * on it as an indicator of "standard" depmod)
  867. * -h: help (well duh)
  868. * module1.o module2.o parameters (just ignored for now)
  869. */
  870. getopt32(argv, "na" "AeF:qru" /* "b:vV", NULL */, NULL);
  871. argv += optind;
  872. /* if (argv[0] && argv[1]) bb_show_usage(); */
  873. /* Goto $VERSION directory */
  874. xchdir(argv[0] ? argv[0] : uts.release);
  875. /* Force full module scan by asking to find a bogus module.
  876. * This will generate modules.dep.bb as a side effect. */
  877. process_module((char*)"/", NULL);
  878. return !wrote_dep_bb_ok;
  879. }
  880. #if ENABLE_MODPROBE || ENABLE_INSMOD || ENABLE_RMMOD
  881. /* modprobe, insmod, rmmod require at least one argument */
  882. /* only -q (quiet) and -r (rmmod),
  883. * the rest are accepted and ignored (compat) */
  884. getopt32(argv, "^" "qrfsvwb" "\0" "-1");
  885. argv += optind;
  886. if (is_modprobe) {
  887. /* Goto $VERSION directory */
  888. xchdir(uts.release);
  889. }
  890. /* are we rmmod? -> simulate modprobe -r, but don't bother the flag if
  891. * there're no other applets here */
  892. if (is_rmmod) {
  893. if (!ONLY_APPLET)
  894. option_mask32 |= OPT_r;
  895. } else if (!ENABLE_MODPROBE || !(option_mask32 & OPT_r)) {
  896. # if ENABLE_FEATURE_CMDLINE_MODULE_OPTIONS
  897. /* If not rmmod/-r, parse possible module options given on command line.
  898. * insmod/modprobe takes one module name, the rest are parameters. */
  899. char **arg = argv;
  900. while (*++arg) {
  901. /* Enclose options in quotes */
  902. char *s = options;
  903. options = xasprintf("%s \"%s\"", s ? s : "", *arg);
  904. free(s);
  905. *arg = NULL;
  906. }
  907. # else
  908. argv[1] = NULL;
  909. # endif
  910. }
  911. if (is_insmod) {
  912. size_t len;
  913. void *map;
  914. len = MAXINT(ssize_t);
  915. map = xmalloc_open_zipped_read_close(*argv, &len);
  916. if (!map)
  917. bb_perror_msg_and_die("can't read '%s'", *argv);
  918. if (init_module(map, len,
  919. (IF_FEATURE_CMDLINE_MODULE_OPTIONS(options ? options : ) "")
  920. ) != 0
  921. ) {
  922. bb_error_msg_and_die("can't insert '%s': %s",
  923. *argv, moderror(errno));
  924. }
  925. return EXIT_SUCCESS;
  926. }
  927. /* Try to load modprobe.dep.bb */
  928. if (!is_rmmod) {
  929. load_dep_bb();
  930. }
  931. /* Load/remove modules.
  932. * Only rmmod/modprobe -r loops here, insmod/modprobe has only argv[0] */
  933. exitcode = EXIT_SUCCESS;
  934. do {
  935. exitcode |= process_module(*argv, options);
  936. } while (*++argv);
  937. if (ENABLE_FEATURE_CLEAN_UP) {
  938. IF_FEATURE_CMDLINE_MODULE_OPTIONS(free(options);)
  939. }
  940. return exitcode;
  941. #endif /* MODPROBE || INSMOD || RMMOD */
  942. }
  943. #endif /* MOD_APPLET_CNT > 0 */