3
0

getopt32.c 17 KB

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