3
0

getopt32.c 19 KB

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