getopt32.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * universal getopt32 implementation for busybox
  4. *
  5. * Copyright (C) 2003-2005 Vladimir Oleynik <dzo@simtreas.ru>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG
  10. # include <getopt.h>
  11. #endif
  12. #include "libbb.h"
  13. /* Documentation
  14. uint32_t
  15. getopt32(char **argv, const char *applet_opts, ...)
  16. The command line options must be declared in const char
  17. *applet_opts as a string of chars, for example:
  18. flags = getopt32(argv, "rnug");
  19. If one of the given options is found, a flag value is added to
  20. the return value (an unsigned long).
  21. The flag value is determined by the position of the char in
  22. applet_opts string. For example, in the above case:
  23. flags = getopt32(argv, "rnug");
  24. "r" will add 1 (bit 0)
  25. "n" will add 2 (bit 1)
  26. "u" will add 4 (bit 2)
  27. "g" will add 8 (bit 3)
  28. and so on. You can also look at the return value as a bit
  29. field and each option sets one bit.
  30. On exit, global variable optind is set so that if you
  31. will do argc -= optind; argv += optind; then
  32. argc will be equal to number of remaining non-option
  33. arguments, first one would be in argv[0], next in argv[1] and so on
  34. (options and their parameters will be moved into argv[]
  35. positions prior to argv[optind]).
  36. ":" If one of the options requires an argument, then add a ":"
  37. after the char in applet_opts and provide a pointer to store
  38. the argument. For example:
  39. char *pointer_to_arg_for_a;
  40. char *pointer_to_arg_for_b;
  41. char *pointer_to_arg_for_c;
  42. char *pointer_to_arg_for_d;
  43. flags = getopt32(argv, "a:b:c:d:",
  44. &pointer_to_arg_for_a, &pointer_to_arg_for_b,
  45. &pointer_to_arg_for_c, &pointer_to_arg_for_d);
  46. The type of the pointer (char* or llist_t*) may be controlled
  47. by the "::" special separator that is set in the external string
  48. opt_complementary (see below for more info).
  49. "::" If option can have an *optional* argument, then add a "::"
  50. after its char in applet_opts and provide a pointer to store
  51. the argument. Note that optional arguments _must_
  52. immediately follow the option: -oparam, not -o param.
  53. "+" If the first character in the applet_opts string is a plus,
  54. then option processing will stop as soon as a non-option is
  55. encountered in the argv array. Useful for applets like env
  56. which should not process arguments to subprograms:
  57. env -i ls -d /
  58. Here we want env to process just the '-i', not the '-d'.
  59. "!" Report bad option, missing required options,
  60. inconsistent options with all-ones return value (instead of abort).
  61. const char *applet_long_options
  62. This struct allows you to define long options:
  63. static const char applet_longopts[] ALIGN1 =
  64. //"name\0" has_arg val
  65. "verbose\0" No_argument "v"
  66. ;
  67. applet_long_options = applet_longopts;
  68. The last member of struct option (val) typically is set to
  69. matching short option from applet_opts. If there is no matching
  70. char in applet_opts, then:
  71. - return bit have next position after short options
  72. - if has_arg is not "No_argument", use ptr for arg also
  73. - opt_complementary affects it too
  74. Note: a good applet will make long options configurable via the
  75. config process and not a required feature. The current standard
  76. is to name the config option CONFIG_FEATURE_<applet>_LONG_OPTIONS.
  77. const char *opt_complementary
  78. ":" The colon (":") is used to separate groups of two or more chars
  79. and/or groups of chars and special characters (stating some
  80. conditions to be checked).
  81. "abc" If groups of two or more chars are specified, the first char
  82. is the main option and the other chars are secondary options.
  83. Their flags will be turned on if the main option is found even
  84. if they are not specifed on the command line. For example:
  85. opt_complementary = "abc";
  86. flags = getopt32(argv, "abcd")
  87. If getopt() finds "-a" on the command line, then
  88. getopt32's return value will be as if "-a -b -c" were
  89. found.
  90. "ww" Adjacent double options have a counter associated which indicates
  91. the number of occurrences of the option.
  92. For example the ps applet needs:
  93. if w is given once, GNU ps sets the width to 132,
  94. if w is given more than once, it is "unlimited"
  95. int w_counter = 0; // must be initialized!
  96. opt_complementary = "ww";
  97. getopt32(argv, "w", &w_counter);
  98. if (w_counter)
  99. width = (w_counter == 1) ? 132 : INT_MAX;
  100. else
  101. get_terminal_width(...&width...);
  102. w_counter is a pointer to an integer. It has to be passed to
  103. getopt32() after all other option argument sinks.
  104. For example: accept multiple -v to indicate the level of verbosity
  105. and for each -b optarg, add optarg to my_b. Finally, if b is given,
  106. turn off c and vice versa:
  107. llist_t *my_b = NULL;
  108. int verbose_level = 0;
  109. opt_complementary = "vv:b::b-c:c-b";
  110. f = getopt32(argv, "vb:c", &my_b, &verbose_level);
  111. if (f & 2) // -c after -b unsets -b flag
  112. while (my_b) dosomething_with(llist_pop(&my_b));
  113. if (my_b) // but llist is stored if -b is specified
  114. free_llist(my_b);
  115. if (verbose_level) printf("verbose level is %d\n", verbose_level);
  116. Special characters:
  117. "-" A group consisting of just a dash forces all arguments
  118. to be treated as options, even if they have no leading dashes.
  119. Next char in this case can't be a digit (0-9), use ':' or end of line.
  120. Example:
  121. opt_complementary = "-:w-x:x-w"; // "-w-x:x-w" would also work,
  122. getopt32(argv, "wx"); // but is less readable
  123. This makes it possible to use options without a dash (./program w x)
  124. as well as with a dash (./program -x).
  125. NB: getopt32() will leak a small amount of memory if you use
  126. this option! Do not use it if there is a possibility of recursive
  127. getopt32() calls.
  128. "--" A double dash at the beginning of opt_complementary means the
  129. argv[1] string should always be treated as options, even if it isn't
  130. prefixed with a "-". This is useful for special syntax in applets
  131. such as "ar" and "tar":
  132. tar xvf foo.tar
  133. NB: getopt32() will leak a small amount of memory if you use
  134. this option! Do not use it if there is a possibility of recursive
  135. getopt32() calls.
  136. "-N" A dash as the first char in a opt_complementary group followed
  137. by a single digit (0-9) means that at least N non-option
  138. arguments must be present on the command line
  139. "=N" An equal sign as the first char in a opt_complementary group followed
  140. by a single digit (0-9) means that exactly N non-option
  141. arguments must be present on the command line
  142. "?N" A "?" as the first char in a opt_complementary group followed
  143. by a single digit (0-9) means that at most N arguments must be present
  144. on the command line.
  145. "V-" An option with dash before colon or end-of-line results in
  146. bb_show_usage() being called if this option is encountered.
  147. This is typically used to implement "print verbose usage message
  148. and exit" option.
  149. "a-b" A dash between two options causes the second of the two
  150. to be unset (and ignored) if it is given on the command line.
  151. [FIXME: what if they are the same? like "x-x"? Is it ever useful?]
  152. For example:
  153. The du applet has the options "-s" and "-d depth". If
  154. getopt32 finds -s, then -d is unset or if it finds -d
  155. then -s is unset. (Note: busybox implements the GNU
  156. "--max-depth" option as "-d".) To obtain this behavior, you
  157. set opt_complementary = "s-d:d-s". Only one flag value is
  158. added to getopt32's return value depending on the
  159. position of the options on the command line. If one of the
  160. two options requires an argument pointer (":" in applet_opts
  161. as in "d:") optarg is set accordingly.
  162. char *smax_print_depth;
  163. opt_complementary = "s-d:d-s:x-x";
  164. opt = getopt32(argv, "sd:x", &smax_print_depth);
  165. if (opt & 2)
  166. max_print_depth = atoi(smax_print_depth);
  167. if (opt & 4)
  168. printf("Detected odd -x usage\n");
  169. "a--b" A double dash between two options, or between an option and a group
  170. of options, means that they are mutually exclusive. Unlike
  171. the "-" case above, an error will be forced if the options
  172. are used together.
  173. For example:
  174. The cut applet must have only one type of list specified, so
  175. -b, -c and -f are mutually exclusive and should raise an error
  176. if specified together. In this case you must set
  177. opt_complementary = "b--cf:c--bf:f--bc". If two of the
  178. mutually exclusive options are found, getopt32 will call
  179. bb_show_usage() and die.
  180. "x--x" Variation of the above, it means that -x option should occur
  181. at most once.
  182. "a+" A plus after a char in opt_complementary means that the parameter
  183. for this option is a nonnegative integer. It will be processed
  184. with xatoi_positive() - allowed range is 0..INT_MAX.
  185. int param; // "unsigned param;" will also work
  186. opt_complementary = "p+";
  187. getopt32(argv, "p:", &param);
  188. "a::" A double colon after a char in opt_complementary means that the
  189. option can occur multiple times. Each occurrence will be saved as
  190. a llist_t element instead of char*.
  191. For example:
  192. The grep applet can have one or more "-e pattern" arguments.
  193. In this case you should use getopt32() as follows:
  194. llist_t *patterns = NULL;
  195. (this pointer must be initializated to NULL if the list is empty
  196. as required by llist_add_to_end(llist_t **old_head, char *new_item).)
  197. opt_complementary = "e::";
  198. getopt32(argv, "e:", &patterns);
  199. $ grep -e user -e root /etc/passwd
  200. root:x:0:0:root:/root:/bin/bash
  201. user:x:500:500::/home/user:/bin/bash
  202. "a?b" A "?" between an option and a group of options means that
  203. at least one of them is required to occur if the first option
  204. occurs in preceding command line arguments.
  205. For example from "id" applet:
  206. // Don't allow -n -r -rn -ug -rug -nug -rnug
  207. opt_complementary = "r?ug:n?ug:u--g:g--u";
  208. flags = getopt32(argv, "rnug");
  209. This example allowed only:
  210. $ id; id -u; id -g; id -ru; id -nu; id -rg; id -ng; id -rnu; id -rng
  211. "X" A opt_complementary group with just a single letter means
  212. that this option is required. If more than one such group exists,
  213. at least one option is required to occur (not all of them).
  214. For example from "start-stop-daemon" applet:
  215. // Don't allow -KS -SK, but -S or -K is required
  216. opt_complementary = "K:S:K--S:S--K";
  217. flags = getopt32(argv, "KS...);
  218. Don't forget to use ':'. For example, "?322-22-23X-x-a"
  219. is interpreted as "?3:22:-2:2-2:2-3Xa:2--x" -
  220. max 3 args; count uses of '-2'; min 2 args; if there is
  221. a '-2' option then unset '-3', '-X' and '-a'; if there is
  222. a '-2' and after it a '-x' then error out.
  223. But it's far too obfuscated. Use ':' to separate groups.
  224. */
  225. /* Code here assumes that 'unsigned' is at least 32 bits wide */
  226. const char *const bb_argv_dash[] = { "-", NULL };
  227. const char *opt_complementary;
  228. enum {
  229. PARAM_STRING,
  230. PARAM_LIST,
  231. PARAM_INT,
  232. };
  233. typedef struct {
  234. unsigned char opt_char;
  235. smallint param_type;
  236. unsigned switch_on;
  237. unsigned switch_off;
  238. unsigned incongruously;
  239. unsigned requires;
  240. void **optarg; /* char**, llist_t** or int *. */
  241. int *counter;
  242. } t_complementary;
  243. /* You can set applet_long_options for parse called long options */
  244. #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG
  245. static const struct option bb_null_long_options[1] = {
  246. { 0, 0, 0, 0 }
  247. };
  248. const char *applet_long_options;
  249. #endif
  250. uint32_t option_mask32;
  251. uint32_t FAST_FUNC
  252. getopt32(char **argv, const char *applet_opts, ...)
  253. {
  254. int argc;
  255. unsigned flags = 0;
  256. unsigned requires = 0;
  257. t_complementary complementary[33]; /* last stays zero-filled */
  258. char first_char;
  259. int c;
  260. const unsigned char *s;
  261. t_complementary *on_off;
  262. va_list p;
  263. #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG
  264. const struct option *l_o;
  265. struct option *long_options = (struct option *) &bb_null_long_options;
  266. #endif
  267. unsigned trigger;
  268. char **pargv;
  269. int min_arg = 0;
  270. int max_arg = -1;
  271. #define SHOW_USAGE_IF_ERROR 1
  272. #define ALL_ARGV_IS_OPTS 2
  273. #define FIRST_ARGV_IS_OPT 4
  274. int spec_flgs = 0;
  275. /* skip 0: some applets cheat: they do not actually HAVE argv[0] */
  276. argc = 1;
  277. while (argv[argc])
  278. argc++;
  279. va_start(p, applet_opts);
  280. c = 0;
  281. on_off = complementary;
  282. memset(on_off, 0, sizeof(complementary));
  283. /* skip bbox extension */
  284. first_char = applet_opts[0];
  285. if (first_char == '!')
  286. applet_opts++;
  287. /* skip GNU extension */
  288. s = (const unsigned char *)applet_opts;
  289. if (*s == '+' || *s == '-')
  290. s++;
  291. while (*s) {
  292. if (c >= 32)
  293. break;
  294. on_off->opt_char = *s;
  295. on_off->switch_on = (1 << c);
  296. if (*++s == ':') {
  297. on_off->optarg = va_arg(p, void **);
  298. while (*++s == ':')
  299. continue;
  300. }
  301. on_off++;
  302. c++;
  303. }
  304. #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG
  305. if (applet_long_options) {
  306. const char *optstr;
  307. unsigned i, count;
  308. count = 1;
  309. optstr = applet_long_options;
  310. while (optstr[0]) {
  311. optstr += strlen(optstr) + 3; /* skip NUL, has_arg, val */
  312. count++;
  313. }
  314. /* count == no. of longopts + 1 */
  315. long_options = alloca(count * sizeof(*long_options));
  316. memset(long_options, 0, count * sizeof(*long_options));
  317. i = 0;
  318. optstr = applet_long_options;
  319. while (--count) {
  320. long_options[i].name = optstr;
  321. optstr += strlen(optstr) + 1;
  322. long_options[i].has_arg = (unsigned char)(*optstr++);
  323. /* long_options[i].flag = NULL; */
  324. long_options[i].val = (unsigned char)(*optstr++);
  325. i++;
  326. }
  327. for (l_o = long_options; l_o->name; l_o++) {
  328. if (l_o->flag)
  329. continue;
  330. for (on_off = complementary; on_off->opt_char; on_off++)
  331. if (on_off->opt_char == l_o->val)
  332. goto next_long;
  333. if (c >= 32)
  334. break;
  335. on_off->opt_char = l_o->val;
  336. on_off->switch_on = (1 << c);
  337. if (l_o->has_arg != no_argument)
  338. on_off->optarg = va_arg(p, void **);
  339. c++;
  340. next_long: ;
  341. }
  342. /* Make it unnecessary to clear applet_long_options
  343. * by hand after each call to getopt32
  344. */
  345. applet_long_options = NULL;
  346. }
  347. #endif /* ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG */
  348. for (s = (const unsigned char *)opt_complementary; s && *s; s++) {
  349. t_complementary *pair;
  350. unsigned *pair_switch;
  351. if (*s == ':')
  352. continue;
  353. c = s[1];
  354. if (*s == '?') {
  355. if (c < '0' || c > '9') {
  356. spec_flgs |= SHOW_USAGE_IF_ERROR;
  357. } else {
  358. max_arg = c - '0';
  359. s++;
  360. }
  361. continue;
  362. }
  363. if (*s == '-') {
  364. if (c < '0' || c > '9') {
  365. if (c == '-') {
  366. spec_flgs |= FIRST_ARGV_IS_OPT;
  367. s++;
  368. } else
  369. spec_flgs |= ALL_ARGV_IS_OPTS;
  370. } else {
  371. min_arg = c - '0';
  372. s++;
  373. }
  374. continue;
  375. }
  376. if (*s == '=') {
  377. min_arg = max_arg = c - '0';
  378. s++;
  379. continue;
  380. }
  381. for (on_off = complementary; on_off->opt_char; on_off++)
  382. if (on_off->opt_char == *s)
  383. goto found_opt;
  384. /* Without this, diagnostic of such bugs is not easy */
  385. bb_error_msg_and_die("NO OPT %c!", *s);
  386. found_opt:
  387. if (c == ':' && s[2] == ':') {
  388. on_off->param_type = PARAM_LIST;
  389. continue;
  390. }
  391. if (c == '+' && (s[2] == ':' || s[2] == '\0')) {
  392. on_off->param_type = PARAM_INT;
  393. s++;
  394. continue;
  395. }
  396. if (c == ':' || c == '\0') {
  397. requires |= on_off->switch_on;
  398. continue;
  399. }
  400. if (c == '-' && (s[2] == ':' || s[2] == '\0')) {
  401. flags |= on_off->switch_on;
  402. on_off->incongruously |= on_off->switch_on;
  403. s++;
  404. continue;
  405. }
  406. if (c == *s) {
  407. on_off->counter = va_arg(p, int *);
  408. s++;
  409. }
  410. pair = on_off;
  411. pair_switch = &pair->switch_on;
  412. for (s++; *s && *s != ':'; s++) {
  413. if (*s == '?') {
  414. pair_switch = &pair->requires;
  415. } else if (*s == '-') {
  416. if (pair_switch == &pair->switch_off)
  417. pair_switch = &pair->incongruously;
  418. else
  419. pair_switch = &pair->switch_off;
  420. } else {
  421. for (on_off = complementary; on_off->opt_char; on_off++)
  422. if (on_off->opt_char == *s) {
  423. *pair_switch |= on_off->switch_on;
  424. break;
  425. }
  426. }
  427. }
  428. s--;
  429. }
  430. opt_complementary = NULL;
  431. va_end(p);
  432. if (spec_flgs & (FIRST_ARGV_IS_OPT | ALL_ARGV_IS_OPTS)) {
  433. pargv = argv + 1;
  434. while (*pargv) {
  435. if (pargv[0][0] != '-' && pargv[0][0] != '\0') {
  436. /* Can't use alloca: opts with params will
  437. * return pointers to stack!
  438. * NB: we leak these allocations... */
  439. char *pp = xmalloc(strlen(*pargv) + 2);
  440. *pp = '-';
  441. strcpy(pp + 1, *pargv);
  442. *pargv = pp;
  443. }
  444. if (!(spec_flgs & ALL_ARGV_IS_OPTS))
  445. break;
  446. pargv++;
  447. }
  448. }
  449. /* In case getopt32 was already called:
  450. * reset the libc getopt() function, which keeps internal state.
  451. * run_nofork_applet() does this, but we might end up here
  452. * also via gunzip_main() -> gzip_main(). Play safe.
  453. */
  454. #ifdef __GLIBC__
  455. optind = 0;
  456. #else /* BSD style */
  457. optind = 1;
  458. /* optreset = 1; */
  459. #endif
  460. /* optarg = NULL; opterr = 0; optopt = 0; - do we need this?? */
  461. /* Note: just "getopt() <= 0" will not work well for
  462. * "fake" short options, like this one:
  463. * wget $'-\203' "Test: test" http://kernel.org/
  464. * (supposed to act as --header, but doesn't) */
  465. #if ENABLE_LONG_OPTS || ENABLE_FEATURE_GETOPT_LONG
  466. while ((c = getopt_long(argc, argv, applet_opts,
  467. long_options, NULL)) != -1) {
  468. #else
  469. while ((c = getopt(argc, argv, applet_opts)) != -1) {
  470. #endif
  471. /* getopt prints "option requires an argument -- X"
  472. * and returns '?' if an option has no arg, but one is reqd */
  473. c &= 0xff; /* fight libc's sign extension */
  474. for (on_off = complementary; on_off->opt_char != c; on_off++) {
  475. /* c can be NUL if long opt has non-NULL ->flag,
  476. * but we construct long opts so that flag
  477. * is always NULL (see above) */
  478. if (on_off->opt_char == '\0' /* && c != '\0' */) {
  479. /* c is probably '?' - "bad option" */
  480. goto error;
  481. }
  482. }
  483. if (flags & on_off->incongruously)
  484. goto error;
  485. trigger = on_off->switch_on & on_off->switch_off;
  486. flags &= ~(on_off->switch_off ^ trigger);
  487. flags |= on_off->switch_on ^ trigger;
  488. flags ^= trigger;
  489. if (on_off->counter)
  490. (*(on_off->counter))++;
  491. if (optarg) {
  492. if (on_off->param_type == PARAM_LIST) {
  493. llist_add_to_end((llist_t **)(on_off->optarg), optarg);
  494. } else if (on_off->param_type == PARAM_INT) {
  495. //TODO: xatoi_positive indirectly pulls in printf machinery
  496. *(unsigned*)(on_off->optarg) = xatoi_positive(optarg);
  497. } else if (on_off->optarg) {
  498. *(char **)(on_off->optarg) = optarg;
  499. }
  500. }
  501. }
  502. /* check depending requires for given options */
  503. for (on_off = complementary; on_off->opt_char; on_off++) {
  504. if (on_off->requires
  505. && (flags & on_off->switch_on)
  506. && (flags & on_off->requires) == 0
  507. ) {
  508. goto error;
  509. }
  510. }
  511. if (requires && (flags & requires) == 0)
  512. goto error;
  513. argc -= optind;
  514. if (argc < min_arg || (max_arg >= 0 && argc > max_arg))
  515. goto error;
  516. option_mask32 = flags;
  517. return flags;
  518. error:
  519. if (first_char != '!')
  520. bb_show_usage();
  521. return (int32_t)-1;
  522. }