getopt32.c 19 KB

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