modprobe-small.c 27 KB

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