3
0

modprobe-small.c 28 KB

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