getopt32.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. NB: getopt32() will leak a small amount of memory if you use
  122. this option! Do not use it if there is a possibility of recursive
  123. getopt32() calls.
  124. "--" A double dash at the beginning of opt_complementary means the
  125. argv[1] string should always be treated as options, even if it isn't
  126. prefixed with a "-". This is useful for special syntax in applets
  127. such as "ar" and "tar":
  128. tar xvf foo.tar
  129. NB: getopt32() will leak a small amount of memory if you use
  130. this option! Do not use it if there is a possibility of recursive
  131. getopt32() calls.
  132. "-N" A dash as the first char in a opt_complementary group followed
  133. by a single digit (0-9) means that at least N non-option
  134. arguments must be present on the command line
  135. "=N" An equal sign as the first char in a opt_complementary group followed
  136. by a single digit (0-9) means that exactly N non-option
  137. arguments must be present on the command line
  138. "?N" A "?" as the first char in a opt_complementary group followed
  139. by a single digit (0-9) means that at most N arguments must be present
  140. on the command line.
  141. "V-" An option with dash before colon or end-of-line results in
  142. bb_show_usage() being called if this option is encountered.
  143. This is typically used to implement "print verbose usage message
  144. and exit" option.
  145. "a-b" A dash between two options causes the second of the two
  146. to be unset (and ignored) if it is given on the command line.
  147. [FIXME: what if they are the same? like "x-x"? Is it ever useful?]
  148. For example:
  149. The du applet has the options "-s" and "-d depth". If
  150. getopt32 finds -s, then -d is unset or if it finds -d
  151. then -s is unset. (Note: busybox implements the GNU
  152. "--max-depth" option as "-d".) To obtain this behavior, you
  153. set opt_complementary = "s-d:d-s". Only one flag value is
  154. added to getopt32's return value depending on the
  155. position of the options on the command line. If one of the
  156. two options requires an argument pointer (":" in applet_opts
  157. as in "d:") optarg is set accordingly.
  158. char *smax_print_depth;
  159. opt_complementary = "s-d:d-s:x-x";
  160. opt = getopt32(argv, "sd: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 = "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. "a+" 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_u() - allowed range is 0..INT_MAX.
  181. int param; // "unsigned param;" will also work
  182. opt_complementary = "p+";
  183. getopt32(argv, "p:", &param);
  184. "a::" A double colon after a char in opt_complementary means that the
  185. option can occur multiple times. Each occurrence will be saved as
  186. a llist_t element instead of char*.
  187. For example:
  188. The grep applet can have one or more "-e pattern" arguments.
  189. In this case you should use getopt32() as follows:
  190. llist_t *patterns = NULL;
  191. (this pointer must be initializated to NULL if the list is empty
  192. as required by llist_add_to_end(llist_t **old_head, char *new_item).)
  193. opt_complementary = "e::";
  194. getopt32(argv, "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. "a?b" A "?" between an option and a group of options means that
  199. at least one of them is required to occur if the first option
  200. occurs in preceding command line arguments.
  201. For example from "id" applet:
  202. // Don't allow -n -r -rn -ug -rug -nug -rnug
  203. opt_complementary = "r?ug:n?ug:u--g:g--u";
  204. flags = getopt32(argv, "rnug");
  205. This example allowed only:
  206. $ id; id -u; id -g; id -ru; id -nu; id -rg; id -ng; id -rnu; id -rng
  207. "X" A opt_complementary group with just a single letter means
  208. that this option is required. If more than one such group exists,
  209. at least one option is required to occur (not all of them).
  210. For example from "start-stop-daemon" applet:
  211. // Don't allow -KS -SK, but -S or -K is required
  212. opt_complementary = "K:S:K--S:S--K";
  213. flags = getopt32(argv, "KS...);
  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. const char *opt_complementary;
  224. enum {
  225. PARAM_STRING,
  226. PARAM_LIST,
  227. PARAM_INT,
  228. };
  229. typedef struct {
  230. unsigned char opt_char;
  231. smallint param_type;
  232. unsigned switch_on;
  233. unsigned switch_off;
  234. unsigned incongruously;
  235. unsigned requires;
  236. void **optarg; /* char**, llist_t** or int *. */
  237. int *counter;
  238. } t_complementary;
  239. /* You can set applet_long_options for parse called long options */
  240. #if ENABLE_GETOPT_LONG
  241. static const struct option bb_null_long_options[1] = {
  242. { 0, 0, 0, 0 }
  243. };
  244. const char *applet_long_options;
  245. #endif
  246. uint32_t option_mask32;
  247. uint32_t FAST_FUNC
  248. getopt32(char **argv, const char *applet_opts, ...)
  249. {
  250. int argc;
  251. unsigned flags = 0;
  252. unsigned requires = 0;
  253. t_complementary complementary[33]; /* last stays zero-filled */
  254. int c;
  255. const unsigned char *s;
  256. t_complementary *on_off;
  257. va_list p;
  258. #if ENABLE_GETOPT_LONG
  259. const struct option *l_o;
  260. struct option *long_options = (struct option *) &bb_null_long_options;
  261. #endif
  262. unsigned trigger;
  263. char **pargv;
  264. int min_arg = 0;
  265. int max_arg = -1;
  266. #define SHOW_USAGE_IF_ERROR 1
  267. #define ALL_ARGV_IS_OPTS 2
  268. #define FIRST_ARGV_IS_OPT 4
  269. int spec_flgs = 0;
  270. /* skip 0: some applets cheat: they do not actually HAVE argv[0] */
  271. argc = 1;
  272. while (argv[argc])
  273. argc++;
  274. va_start(p, applet_opts);
  275. c = 0;
  276. on_off = complementary;
  277. memset(on_off, 0, sizeof(complementary));
  278. /* skip GNU extension */
  279. s = (const unsigned char *)applet_opts;
  280. if (*s == '+' || *s == '-')
  281. s++;
  282. while (*s) {
  283. if (c >= 32)
  284. break;
  285. on_off->opt_char = *s;
  286. on_off->switch_on = (1 << c);
  287. if (*++s == ':') {
  288. on_off->optarg = va_arg(p, void **);
  289. while (*++s == ':')
  290. continue;
  291. }
  292. on_off++;
  293. c++;
  294. }
  295. #if ENABLE_GETOPT_LONG
  296. if (applet_long_options) {
  297. const char *optstr;
  298. unsigned i, count;
  299. count = 1;
  300. optstr = applet_long_options;
  301. while (optstr[0]) {
  302. optstr += strlen(optstr) + 3; /* skip NUL, has_arg, val */
  303. count++;
  304. }
  305. /* count == no. of longopts + 1 */
  306. long_options = alloca(count * sizeof(*long_options));
  307. memset(long_options, 0, count * sizeof(*long_options));
  308. i = 0;
  309. optstr = applet_long_options;
  310. while (--count) {
  311. long_options[i].name = optstr;
  312. optstr += strlen(optstr) + 1;
  313. long_options[i].has_arg = (unsigned char)(*optstr++);
  314. /* long_options[i].flag = NULL; */
  315. long_options[i].val = (unsigned char)(*optstr++);
  316. i++;
  317. }
  318. for (l_o = long_options; l_o->name; l_o++) {
  319. if (l_o->flag)
  320. continue;
  321. for (on_off = complementary; on_off->opt_char; on_off++)
  322. if (on_off->opt_char == l_o->val)
  323. goto next_long;
  324. if (c >= 32)
  325. break;
  326. on_off->opt_char = l_o->val;
  327. on_off->switch_on = (1 << c);
  328. if (l_o->has_arg != no_argument)
  329. on_off->optarg = va_arg(p, void **);
  330. c++;
  331. next_long: ;
  332. }
  333. }
  334. #endif /* ENABLE_GETOPT_LONG */
  335. for (s = (const unsigned char *)opt_complementary; s && *s; s++) {
  336. t_complementary *pair;
  337. unsigned *pair_switch;
  338. if (*s == ':')
  339. continue;
  340. c = s[1];
  341. if (*s == '?') {
  342. if (c < '0' || c > '9') {
  343. spec_flgs |= SHOW_USAGE_IF_ERROR;
  344. } else {
  345. max_arg = c - '0';
  346. s++;
  347. }
  348. continue;
  349. }
  350. if (*s == '-') {
  351. if (c < '0' || c > '9') {
  352. if (c == '-') {
  353. spec_flgs |= FIRST_ARGV_IS_OPT;
  354. s++;
  355. } else
  356. spec_flgs |= ALL_ARGV_IS_OPTS;
  357. } else {
  358. min_arg = c - '0';
  359. s++;
  360. }
  361. continue;
  362. }
  363. if (*s == '=') {
  364. min_arg = max_arg = c - '0';
  365. s++;
  366. continue;
  367. }
  368. for (on_off = complementary; on_off->opt_char; on_off++)
  369. if (on_off->opt_char == *s)
  370. break;
  371. if (c == ':' && s[2] == ':') {
  372. on_off->param_type = PARAM_LIST;
  373. continue;
  374. }
  375. if (c == '+' && (s[2] == ':' || s[2] == '\0')) {
  376. on_off->param_type = PARAM_INT;
  377. continue;
  378. }
  379. if (c == ':' || c == '\0') {
  380. requires |= on_off->switch_on;
  381. continue;
  382. }
  383. if (c == '-' && (s[2] == ':' || s[2] == '\0')) {
  384. flags |= on_off->switch_on;
  385. on_off->incongruously |= on_off->switch_on;
  386. s++;
  387. continue;
  388. }
  389. if (c == *s) {
  390. on_off->counter = va_arg(p, int *);
  391. s++;
  392. }
  393. pair = on_off;
  394. pair_switch = &(pair->switch_on);
  395. for (s++; *s && *s != ':'; s++) {
  396. if (*s == '?') {
  397. pair_switch = &(pair->requires);
  398. } else if (*s == '-') {
  399. if (pair_switch == &(pair->switch_off))
  400. pair_switch = &(pair->incongruously);
  401. else
  402. pair_switch = &(pair->switch_off);
  403. } else {
  404. for (on_off = complementary; on_off->opt_char; on_off++)
  405. if (on_off->opt_char == *s) {
  406. *pair_switch |= on_off->switch_on;
  407. break;
  408. }
  409. }
  410. }
  411. s--;
  412. }
  413. va_end(p);
  414. if (spec_flgs & (FIRST_ARGV_IS_OPT | ALL_ARGV_IS_OPTS)) {
  415. pargv = argv + 1;
  416. while (*pargv) {
  417. if (pargv[0][0] != '-' && pargv[0][0] != '\0') {
  418. /* Can't use alloca: opts with params will
  419. * return pointers to stack!
  420. * NB: we leak these allocations... */
  421. char *pp = xmalloc(strlen(*pargv) + 2);
  422. *pp = '-';
  423. strcpy(pp + 1, *pargv);
  424. *pargv = pp;
  425. }
  426. if (!(spec_flgs & ALL_ARGV_IS_OPTS))
  427. break;
  428. pargv++;
  429. }
  430. }
  431. /* In case getopt32 was already called:
  432. * reset the libc getopt() function, which keeps internal state.
  433. * run_nofork_applet_prime() does this, but we might end up here
  434. * also via gunzip_main() -> gzip_main(). Play safe.
  435. */
  436. #ifdef __GLIBC__
  437. optind = 0;
  438. #else /* BSD style */
  439. optind = 1;
  440. /* optreset = 1; */
  441. #endif
  442. /* optarg = NULL; opterr = 0; optopt = 0; - do we need this?? */
  443. pargv = NULL;
  444. /* Note: just "getopt() <= 0" will not work well for
  445. * "fake" short options, like this one:
  446. * wget $'-\203' "Test: test" http://kernel.org/
  447. * (supposed to act as --header, but doesn't) */
  448. #if ENABLE_GETOPT_LONG
  449. while ((c = getopt_long(argc, argv, applet_opts,
  450. long_options, NULL)) != -1) {
  451. #else
  452. while ((c = getopt(argc, argv, applet_opts)) != -1) {
  453. #endif
  454. /* getopt prints "option requires an argument -- X"
  455. * and returns '?' if an option has no arg, but one is reqd */
  456. c &= 0xff; /* fight libc's sign extension */
  457. for (on_off = complementary; on_off->opt_char != c; on_off++) {
  458. /* c can be NUL if long opt has non-NULL ->flag,
  459. * but we construct long opts so that flag
  460. * is always NULL (see above) */
  461. if (on_off->opt_char == '\0' /* && c != '\0' */) {
  462. /* c is probably '?' - "bad option" */
  463. bb_show_usage();
  464. }
  465. }
  466. if (flags & on_off->incongruously)
  467. bb_show_usage();
  468. trigger = on_off->switch_on & on_off->switch_off;
  469. flags &= ~(on_off->switch_off ^ trigger);
  470. flags |= on_off->switch_on ^ trigger;
  471. flags ^= trigger;
  472. if (on_off->counter)
  473. (*(on_off->counter))++;
  474. if (on_off->param_type == PARAM_LIST) {
  475. if (optarg)
  476. llist_add_to_end((llist_t **)(on_off->optarg), optarg);
  477. } else if (on_off->param_type == PARAM_INT) {
  478. if (optarg)
  479. //TODO: xatoi_u indirectly pulls in printf machinery
  480. *(unsigned*)(on_off->optarg) = xatoi_u(optarg);
  481. } else if (on_off->optarg) {
  482. if (optarg)
  483. *(char **)(on_off->optarg) = optarg;
  484. }
  485. if (pargv != NULL)
  486. break;
  487. }
  488. /* check depending requires for given options */
  489. for (on_off = complementary; on_off->opt_char; on_off++) {
  490. if (on_off->requires && (flags & on_off->switch_on) &&
  491. (flags & on_off->requires) == 0)
  492. bb_show_usage();
  493. }
  494. if (requires && (flags & requires) == 0)
  495. bb_show_usage();
  496. argc -= optind;
  497. if (argc < min_arg || (max_arg >= 0 && argc > max_arg))
  498. bb_show_usage();
  499. option_mask32 = flags;
  500. return flags;
  501. }