3
0

getopt32.c 19 KB

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