getopt32.c 19 KB

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