getopt32.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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(my_b->data); my_b = my_b->link; }
  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. enum {
  219. PARAM_STRING,
  220. PARAM_LIST,
  221. PARAM_INT,
  222. };
  223. typedef struct {
  224. unsigned char opt_char;
  225. smallint param_type;
  226. unsigned switch_on;
  227. unsigned switch_off;
  228. unsigned incongruously;
  229. unsigned requires;
  230. void **optarg; /* char**, llist_t** or int *. */
  231. int *counter;
  232. } t_complementary;
  233. /* You can set applet_long_options for parse called long options */
  234. #if ENABLE_GETOPT_LONG
  235. static const struct option bb_null_long_options[1] = {
  236. { 0, 0, 0, 0 }
  237. };
  238. const char *applet_long_options;
  239. #endif
  240. uint32_t option_mask32;
  241. uint32_t
  242. getopt32(char **argv, const char *applet_opts, ...)
  243. {
  244. int argc;
  245. unsigned flags = 0;
  246. unsigned requires = 0;
  247. t_complementary complementary[33];
  248. int c;
  249. const unsigned char *s;
  250. t_complementary *on_off;
  251. va_list p;
  252. #if ENABLE_GETOPT_LONG
  253. const struct option *l_o;
  254. struct option *long_options = (struct option *) &bb_null_long_options;
  255. #endif
  256. unsigned trigger;
  257. char **pargv = NULL;
  258. int min_arg = 0;
  259. int max_arg = -1;
  260. #define SHOW_USAGE_IF_ERROR 1
  261. #define ALL_ARGV_IS_OPTS 2
  262. #define FIRST_ARGV_IS_OPT 4
  263. #define FREE_FIRST_ARGV_IS_OPT 8
  264. int spec_flgs = 0;
  265. argc = 0;
  266. while (argv[argc])
  267. argc++;
  268. va_start(p, applet_opts);
  269. c = 0;
  270. on_off = complementary;
  271. memset(on_off, 0, sizeof(complementary));
  272. /* skip GNU extension */
  273. s = (const unsigned char *)applet_opts;
  274. if (*s == '+' || *s == '-')
  275. s++;
  276. while (*s) {
  277. if (c >= 32)
  278. break;
  279. on_off->opt_char = *s;
  280. on_off->switch_on = (1 << c);
  281. if (*++s == ':') {
  282. on_off->optarg = va_arg(p, void **);
  283. while (*++s == ':')
  284. continue;
  285. }
  286. on_off++;
  287. c++;
  288. }
  289. #if ENABLE_GETOPT_LONG
  290. if (applet_long_options) {
  291. const char *optstr;
  292. unsigned i, count;
  293. count = 1;
  294. optstr = applet_long_options;
  295. while (optstr[0]) {
  296. optstr += strlen(optstr) + 3; /* skip NUL, has_arg, val */
  297. count++;
  298. }
  299. /* count == no. of longopts + 1 */
  300. long_options = alloca(count * sizeof(*long_options));
  301. memset(long_options, 0, count * sizeof(*long_options));
  302. i = 0;
  303. optstr = applet_long_options;
  304. while (--count) {
  305. long_options[i].name = optstr;
  306. optstr += strlen(optstr) + 1;
  307. long_options[i].has_arg = (unsigned char)(*optstr++);
  308. /* long_options[i].flag = NULL; */
  309. long_options[i].val = (unsigned char)(*optstr++);
  310. i++;
  311. }
  312. for (l_o = long_options; l_o->name; l_o++) {
  313. if (l_o->flag)
  314. continue;
  315. for (on_off = complementary; on_off->opt_char; on_off++)
  316. if (on_off->opt_char == l_o->val)
  317. goto next_long;
  318. if (c >= 32)
  319. break;
  320. on_off->opt_char = l_o->val;
  321. on_off->switch_on = (1 << c);
  322. if (l_o->has_arg != no_argument)
  323. on_off->optarg = va_arg(p, void **);
  324. c++;
  325. next_long: ;
  326. }
  327. }
  328. #endif /* ENABLE_GETOPT_LONG */
  329. for (s = (const unsigned char *)opt_complementary; s && *s; s++) {
  330. t_complementary *pair;
  331. unsigned *pair_switch;
  332. if (*s == ':')
  333. continue;
  334. c = s[1];
  335. if (*s == '?') {
  336. if (c < '0' || c > '9') {
  337. spec_flgs |= SHOW_USAGE_IF_ERROR;
  338. } else {
  339. max_arg = c - '0';
  340. s++;
  341. }
  342. continue;
  343. }
  344. if (*s == '-') {
  345. if (c < '0' || c > '9') {
  346. if (c == '-') {
  347. spec_flgs |= FIRST_ARGV_IS_OPT;
  348. s++;
  349. } else
  350. spec_flgs |= ALL_ARGV_IS_OPTS;
  351. } else {
  352. min_arg = c - '0';
  353. s++;
  354. }
  355. continue;
  356. }
  357. if (*s == '=') {
  358. min_arg = max_arg = c - '0';
  359. s++;
  360. continue;
  361. }
  362. for (on_off = complementary; on_off->opt_char; on_off++)
  363. if (on_off->opt_char == *s)
  364. break;
  365. if (c == ':' && s[2] == ':') {
  366. on_off->param_type = PARAM_LIST;
  367. continue;
  368. }
  369. if (c == '+' && (s[2] == ':' || s[2] == '\0')) {
  370. on_off->param_type = PARAM_INT;
  371. continue;
  372. }
  373. if (c == ':' || c == '\0') {
  374. requires |= on_off->switch_on;
  375. continue;
  376. }
  377. if (c == '-' && (s[2] == ':' || s[2] == '\0')) {
  378. flags |= on_off->switch_on;
  379. on_off->incongruously |= on_off->switch_on;
  380. s++;
  381. continue;
  382. }
  383. if (c == *s) {
  384. on_off->counter = va_arg(p, int *);
  385. s++;
  386. }
  387. pair = on_off;
  388. pair_switch = &(pair->switch_on);
  389. for (s++; *s && *s != ':'; s++) {
  390. if (*s == '?') {
  391. pair_switch = &(pair->requires);
  392. } else if (*s == '-') {
  393. if (pair_switch == &(pair->switch_off))
  394. pair_switch = &(pair->incongruously);
  395. else
  396. pair_switch = &(pair->switch_off);
  397. } else {
  398. for (on_off = complementary; on_off->opt_char; on_off++)
  399. if (on_off->opt_char == *s) {
  400. *pair_switch |= on_off->switch_on;
  401. break;
  402. }
  403. }
  404. }
  405. s--;
  406. }
  407. va_end(p);
  408. if (spec_flgs & FIRST_ARGV_IS_OPT) {
  409. if (argv[1] && argv[1][0] != '-' && argv[1][0] != '\0') {
  410. argv[1] = xasprintf("-%s", argv[1]);
  411. if (ENABLE_FEATURE_CLEAN_UP)
  412. spec_flgs |= FREE_FIRST_ARGV_IS_OPT;
  413. }
  414. }
  415. /* In case getopt32 was already called:
  416. * reset the libc getopt() function, which keeps internal state.
  417. *
  418. * BSD-derived getopt() functions require that optind be set to 1 in
  419. * order to reset getopt() state. This used to be generally accepted
  420. * way of resetting getopt(). However, glibc's getopt()
  421. * has additional getopt() state beyond optind, and requires that
  422. * optind be set to zero to reset its state. So the unfortunate state of
  423. * affairs is that BSD-derived versions of getopt() misbehave if
  424. * optind is set to 0 in order to reset getopt(), and glibc's getopt()
  425. * will core dump if optind is set 1 in order to reset getopt().
  426. *
  427. * More modern versions of BSD require that optreset be set to 1 in
  428. * order to reset getopt(). Sigh. Standards, anyone?
  429. */
  430. #ifdef __GLIBC__
  431. optind = 0;
  432. #else /* BSD style */
  433. optind = 1;
  434. /* optreset = 1; */
  435. #endif
  436. /* optarg = NULL; opterr = 0; optopt = 0; - do we need this?? */
  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_GETOPT_LONG
  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. c &= 0xff; /* fight libc's sign extension */
  448. loop_arg_is_opt:
  449. for (on_off = complementary; on_off->opt_char != c; on_off++) {
  450. /* c==0 if long opt have non NULL flag */
  451. if (on_off->opt_char == '\0' && c != '\0')
  452. bb_show_usage();
  453. }
  454. if (flags & on_off->incongruously)
  455. bb_show_usage();
  456. trigger = on_off->switch_on & on_off->switch_off;
  457. flags &= ~(on_off->switch_off ^ trigger);
  458. flags |= on_off->switch_on ^ trigger;
  459. flags ^= trigger;
  460. if (on_off->counter)
  461. (*(on_off->counter))++;
  462. if (on_off->param_type == PARAM_LIST) {
  463. if (optarg)
  464. llist_add_to_end((llist_t **)(on_off->optarg), optarg);
  465. } else if (on_off->param_type == PARAM_INT) {
  466. if (optarg)
  467. *(unsigned*)(on_off->optarg) = xatoi_u(optarg);
  468. } else if (on_off->optarg) {
  469. if (optarg)
  470. *(char **)(on_off->optarg) = optarg;
  471. }
  472. if (pargv != NULL)
  473. break;
  474. }
  475. if (spec_flgs & ALL_ARGV_IS_OPTS) {
  476. /* process argv is option, for example "ps" applet */
  477. if (pargv == NULL)
  478. pargv = argv + optind;
  479. while (*pargv) {
  480. c = **pargv;
  481. if (c == '\0') {
  482. pargv++;
  483. } else {
  484. (*pargv)++;
  485. goto loop_arg_is_opt;
  486. }
  487. }
  488. }
  489. #if (ENABLE_AR || ENABLE_TAR) && ENABLE_FEATURE_CLEAN_UP
  490. if (spec_flgs & FREE_FIRST_ARGV_IS_OPT)
  491. free(argv[1]);
  492. #endif
  493. /* check depending requires for given options */
  494. for (on_off = complementary; on_off->opt_char; on_off++) {
  495. if (on_off->requires && (flags & on_off->switch_on) &&
  496. (flags & on_off->requires) == 0)
  497. bb_show_usage();
  498. }
  499. if (requires && (flags & requires) == 0)
  500. bb_show_usage();
  501. argc -= optind;
  502. if (argc < min_arg || (max_arg >= 0 && argc > max_arg))
  503. bb_show_usage();
  504. option_mask32 = flags;
  505. return flags;
  506. }