modprobe-small.c 30 KB

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