args.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /* args.c - Command line argument parsing.
  2. *
  3. * Copyright 2006 Rob Landley <rob@landley.net>
  4. */
  5. // NOTE: If option parsing segfaults, switch on TOYBOX_DEBUG in menuconfig to
  6. // add syntax checks to option string parsing which aren't needed in the final
  7. // code (since get_opt string is hardwired and should be correct when you ship)
  8. #include "toys.h"
  9. // Design goals:
  10. // Don't use getopt() out of libc.
  11. // Don't permute original arguments (screwing up ps/top output).
  12. // Integrated --long options "(noshort)a(along)b(blong1)(blong2)"
  13. /* This uses a getopt-like option string, but not getopt() itself. We call
  14. * it the get_opt string.
  15. *
  16. * Each option in the get_opt string corresponds to a bit position in the
  17. * return value. The rightmost argument is (1<<0), the next to last is (1<<1)
  18. * and so on. If the option isn't seen in argv[], its bit remains 0.
  19. *
  20. * Options which have an argument fill in the corresponding slot in the global
  21. * union "this" (see generated/globals.h), which it treats as an array of longs
  22. * (note that sizeof(long)==sizeof(pointer) is guaranteed by LP64).
  23. *
  24. * You don't have to free the option strings, which point into the environment
  25. * space. List objects should be freed by main() when command_main() returns.
  26. *
  27. * Example:
  28. * Calling get_optflags() when toys.which->options="ab:c:d" and
  29. * argv = ["command", "-b", "fruit", "-d", "walrus"] results in:
  30. *
  31. * Changes to struct toys:
  32. * toys.optflags = 5 (I.E. 0101 so -b = 4 | -d = 1)
  33. * toys.optargs[0] = "walrus" (leftover argument)
  34. * toys.optargs[1] = NULL (end of list)
  35. * toys.optc = 1 (there was 1 leftover argument)
  36. *
  37. * Changes to union this:
  38. * this[0]=NULL (because -c didn't get an argument this time)
  39. * this[1]="fruit" (argument to -b)
  40. */
  41. // What you can put in a get_opt string:
  42. // Any otherwise unused character (all letters, unprefixed numbers) specify
  43. // an option that sets a flag. The bit value is the same as the binary digit
  44. // if you string the option characters together in order.
  45. // So in "abcdefgh" a = 128, h = 1
  46. //
  47. // Suffixes specify that this option takes an argument (stored in GLOBALS):
  48. // Note that pointer and long are always the same size, even on 64 bit.
  49. // : string argument, keep most recent if more than one
  50. // * string argument, appended to a struct arg_list linked list.
  51. // # signed long argument
  52. // <LOW - die if less than LOW
  53. // >HIGH - die if greater than HIGH
  54. // =DEFAULT - value if not specified
  55. // - signed long argument defaulting to negative (say + for positive)
  56. // . double precision floating point argument (with CFG_TOYBOX_FLOAT)
  57. // Chop this option out with USE_TOYBOX_FLOAT() in option string
  58. // Same <LOW>HIGH=DEFAULT as #
  59. // @ occurrence counter (which is a long)
  60. // % time offset in milliseconds with optional s/m/h/d suffix
  61. // (longopt)
  62. // | this is required. If more than one marked, only one required.
  63. // ; Option's argument is optional, and must be collated: -aARG or --a=ARG
  64. // ^ Stop parsing after encountering this argument
  65. // " " (space char) the "plus an argument" must be separate
  66. // I.E. "-j 3" not "-j3". So "kill -stop" != "kill -s top"
  67. //
  68. // At the beginning of the get_opt string (before any options):
  69. // <0 die if less than # leftover arguments (default 0)
  70. // >9 die if > # leftover arguments (default MAX_INT)
  71. // 0 Include argv[0] in optargs
  72. // ^ stop at first nonoption argument (implied when no flags)
  73. // ? Pass unknown arguments through to command (implied when no flags).
  74. // & first arg has imaginary dash (ala tar/ps/ar) which sets FLAGS_NODASH
  75. // ~ Collate following bare longopts (as if under short opt, repeatable)
  76. //
  77. // At the end: [groups] of previously seen options
  78. // - Only one in group (switch off) [-abc] means -ab=-b, -ba=-a, -abc=-c
  79. // + Synonyms (switch on all) [+abc] means -ab=-abc, -c=-abc
  80. // ! More than one in group is error [!abc] means -ab calls error_exit()
  81. // primarily useful if you can switch things back off again.
  82. //
  83. // You may use octal escapes with the high bit (127) set to use a control
  84. // character as an option flag. For example, \300 would be the option -@
  85. // Notes from getopt man page
  86. // - and -- cannot be arguments.
  87. // -- force end of arguments
  88. // - is a synonym for stdin in file arguments
  89. // -abcd means -a -b -c -d (but if -b takes an argument, then it's -a -b cd)
  90. // Linked list of all known options (option string parsed into this).
  91. // Hangs off getoptflagstate, freed at end of option parsing.
  92. struct opts {
  93. struct opts *next;
  94. long *arg; // Pointer into union "this" to store arguments at.
  95. int c; // Argument character to match
  96. int flags; // |=1, ^=2, " "=4, ;=8
  97. unsigned long long dex[3]; // bits to disable/enable/exclude in toys.optflags
  98. char type; // Type of arguments to store union "this"
  99. union {
  100. long l;
  101. FLOAT f;
  102. } val[3]; // low, high, default - range of allowed values
  103. };
  104. // linked list of long options. (Hangs off getoptflagstate, free at end of
  105. // option parsing, details about flag to set and global slot to fill out
  106. // stored in related short option struct, but if opt->c = -1 the long option
  107. // is "bare" (has no corresponding short option).
  108. struct longopts {
  109. struct longopts *next;
  110. struct opts *opt;
  111. char *str;
  112. int len;
  113. };
  114. // State during argument parsing.
  115. struct getoptflagstate
  116. {
  117. int argc, minargs, maxargs;
  118. char *arg;
  119. struct opts *opts;
  120. struct longopts *longopts;
  121. int noerror, nodash_now, stopearly;
  122. unsigned excludes, requires;
  123. };
  124. static void forget_arg(struct opts *opt)
  125. {
  126. if (opt->arg) {
  127. if (opt->type=='*') llist_traverse((void *)*opt->arg, free);
  128. *opt->arg = 0;
  129. }
  130. }
  131. // Use getoptflagstate to parse one command line option from argv
  132. // Sets flags, saves/clears opt->arg, advances gof->arg/gof->argc as necessary
  133. static void gotflag(struct getoptflagstate *gof, struct opts *opt, int longopt)
  134. {
  135. unsigned long long i;
  136. struct opts *and;
  137. char *arg;
  138. int type;
  139. // Did we recognize this option?
  140. if (!opt) help_exit("Unknown option '%s'", gof->arg);
  141. // Might enabling this switch off something else?
  142. if (toys.optflags & opt->dex[0]) {
  143. // Forget saved argument for flag we switch back off
  144. for (and = gof->opts, i = 1; and; and = and->next, i<<=1)
  145. if (i & toys.optflags & opt->dex[0]) forget_arg(and);
  146. toys.optflags &= ~opt->dex[0];
  147. }
  148. // Set flags
  149. toys.optflags |= opt->dex[1];
  150. gof->excludes |= opt->dex[2];
  151. if (opt->flags&2) gof->stopearly=2;
  152. if (toys.optflags & gof->excludes) {
  153. for (and = gof->opts, i = 1; and; and = and->next, i<<=1) {
  154. if (opt == and || !(i & toys.optflags)) continue;
  155. if (toys.optflags & and->dex[2]) break;
  156. }
  157. if (and) help_exit("No '%c' with '%c'", opt->c, and->c);
  158. }
  159. // Are we NOT saving an argument? (Type 0, '@', unattached ';', short ' ')
  160. if (*(arg = gof->arg)) gof->arg++;
  161. if ((type = opt->type) == '@') {
  162. ++*opt->arg;
  163. return;
  164. }
  165. if (!longopt && *gof->arg && (opt->flags & 4)) return forget_arg(opt);
  166. if (!type || (!arg[!longopt] && (opt->flags & 8))) return forget_arg(opt);
  167. // Handle "-xblah" and "-x blah", but also a third case: "abxc blah"
  168. // to make "tar xCjfv blah1 blah2 thingy" work like
  169. // "tar -x -C blah1 -j -f blah2 -v thingy"
  170. if (longopt && *arg) arg++;
  171. else arg = (gof->nodash_now||!*gof->arg) ? toys.argv[++gof->argc] : gof->arg;
  172. if (!gof->nodash_now) gof->arg = "";
  173. if (!arg) {
  174. struct longopts *lo;
  175. arg = "Missing argument to ";
  176. if (opt->c != -1) help_exit("%s-%c", arg, opt->c);
  177. for (lo = gof->longopts; lo->opt != opt; lo = lo->next);
  178. help_exit("%s--%.*s", arg, lo->len, lo->str);
  179. }
  180. // Parse argument by type
  181. if (type == ':') *(opt->arg) = (long)arg;
  182. else if (type == '*') {
  183. struct arg_list **list;
  184. list = (struct arg_list **)opt->arg;
  185. while (*list) list=&((*list)->next);
  186. *list = xzalloc(sizeof(struct arg_list));
  187. (*list)->arg = arg;
  188. } else if (type == '#' || type == '-') {
  189. long l = atolx(arg);
  190. if (type == '-' && !ispunct(*arg)) l*=-1;
  191. if (l < opt->val[0].l) help_exit("-%c < %ld", opt->c, opt->val[0].l);
  192. if (l > opt->val[1].l) help_exit("-%c > %ld", opt->c, opt->val[1].l);
  193. *(opt->arg) = l;
  194. } else if (CFG_TOYBOX_FLOAT && type == '.') {
  195. FLOAT *f = (FLOAT *)(opt->arg);
  196. *f = strtod(arg, &arg);
  197. if (opt->val[0].l != LONG_MIN && *f < opt->val[0].f)
  198. help_exit("-%c < %lf", opt->c, (double)opt->val[0].f);
  199. if (opt->val[1].l != LONG_MAX && *f > opt->val[1].f)
  200. help_exit("-%c > %lf", opt->c, (double)opt->val[1].f);
  201. } else if (type=='%') *(opt->arg) = xparsemillitime(arg);
  202. }
  203. // Parse this command's options string into struct getoptflagstate, which
  204. // includes a struct opts linked list in reverse order (I.E. right-to-left)
  205. static int parse_optflaglist(struct getoptflagstate *gof)
  206. {
  207. char *options = toys.which->options;
  208. long *nextarg = (long *)&this;
  209. struct opts *new = 0;
  210. int idx, rc = 0;
  211. // Parse option format string
  212. memset(gof, 0, sizeof(struct getoptflagstate));
  213. gof->maxargs = INT_MAX;
  214. if (!options) return 0;
  215. // Parse leading special behavior indicators
  216. for (;;) {
  217. if (*options == '^') gof->stopearly++;
  218. else if (*options == '<') gof->minargs=*(++options)-'0';
  219. else if (*options == '>') gof->maxargs=*(++options)-'0';
  220. else if (*options == '?') gof->noerror++;
  221. else if (*options == '&') gof->nodash_now = 1;
  222. else if (*options == '0') rc = 1;
  223. else break;
  224. options++;
  225. }
  226. // Parse option string into a linked list of options with attributes.
  227. if (!*options) gof->stopearly++, gof->noerror++;
  228. while (*options) {
  229. char *temp;
  230. // Option groups come after all options are defined
  231. if (*options == '[') break;
  232. // Allocate a new list entry when necessary
  233. if (!new) {
  234. new = xzalloc(sizeof(struct opts));
  235. new->next = gof->opts;
  236. gof->opts = new;
  237. new->val[0].l = LONG_MIN;
  238. new->val[1].l = LONG_MAX;
  239. }
  240. // Each option must start with "(" or an option character. (Bare
  241. // longopts only come at the start of the string.)
  242. if (*options == '(' && new->c != -1) {
  243. char *end;
  244. struct longopts *lo;
  245. // Find the end of the longopt
  246. for (end = ++options; *end && *end != ')'; end++);
  247. if (CFG_TOYBOX_DEBUG && !*end) error_exit("(longopt) didn't end");
  248. // init a new struct longopts
  249. lo = xmalloc(sizeof(struct longopts));
  250. lo->next = gof->longopts;
  251. lo->opt = new;
  252. lo->str = options;
  253. lo->len = end-options;
  254. gof->longopts = lo;
  255. options = ++end;
  256. // Mark this struct opt as used, even when no short opt.
  257. if (!new->c) new->c = -1;
  258. continue;
  259. // If this is the start of a new option that wasn't a longopt,
  260. } else if (strchr(":*#@.-%", *options)) {
  261. if (CFG_TOYBOX_DEBUG && new->type)
  262. error_exit("multiple types %c:%c%c", new->c, new->type, *options);
  263. new->type = *options;
  264. } else if (-1 != (idx = stridx("|^ ;", *options))) new->flags |= 1<<idx;
  265. // bounds checking
  266. else if (-1 != (idx = stridx("<>=", *options))) {
  267. if (new->type == '#' || new->type == '%') {
  268. long l = strtol(++options, &temp, 10);
  269. if (temp != options) new->val[idx].l = l;
  270. } else if (CFG_TOYBOX_FLOAT && new->type == '.') {
  271. FLOAT f = strtod(++options, &temp);
  272. if (temp != options) new->val[idx].f = f;
  273. } else error_exit("<>= only after .#%%");
  274. options = --temp;
  275. // At this point, we've hit the end of the previous option. The
  276. // current character is the start of a new option. If we've already
  277. // assigned an option to this struct, loop to allocate a new one.
  278. // (It'll get back here afterwards and fall through to next else.)
  279. } else if (new->c) {
  280. new = 0;
  281. continue;
  282. // Claim this option, loop to see what's after it.
  283. } else new->c = 127&*options;
  284. options++;
  285. }
  286. // Initialize enable/disable/exclude masks and pointers to store arguments.
  287. // (This goes right to left so we need the whole list before we can start.)
  288. idx = 0;
  289. for (new = gof->opts; new; new = new->next) {
  290. unsigned long long u = 1LL<<idx++;
  291. if (new->c == 1 || new->c=='~') new->c = 0;
  292. new->dex[1] = u;
  293. if (new->flags & 1) gof->requires |= u;
  294. if (new->type) {
  295. new->arg = (void *)nextarg;
  296. *(nextarg++) = new->val[2].l;
  297. }
  298. }
  299. // Parse trailing group indicators
  300. while (*options) {
  301. unsigned long long bits = 0;
  302. if (CFG_TOYBOX_DEBUG && *options != '[') error_exit("trailing %s", options);
  303. idx = stridx("-+!", *++options);
  304. if (CFG_TOYBOX_DEBUG && idx == -1) error_exit("[ needs +-!");
  305. if (CFG_TOYBOX_DEBUG && (options[1] == ']' || !options[1]))
  306. error_exit("empty []");
  307. // Don't advance past ] but do process it once in loop.
  308. while (*options++ != ']') {
  309. struct opts *opt;
  310. long long ll;
  311. if (CFG_TOYBOX_DEBUG && !*options) error_exit("[ without ]");
  312. // Find this option flag (in previously parsed struct opt)
  313. for (ll = 1, opt = gof->opts; ; ll <<= 1, opt = opt->next) {
  314. if (*options == ']') {
  315. if (!opt) break;
  316. if (bits&ll) opt->dex[idx] |= bits&~ll;
  317. } else {
  318. if (*options==1) break;
  319. if (CFG_TOYBOX_DEBUG && !opt)
  320. error_exit("[] unknown target %c", *options);
  321. if (opt->c == *options) {
  322. bits |= ll;
  323. break;
  324. }
  325. }
  326. }
  327. }
  328. }
  329. return rc;
  330. }
  331. // Fill out toys.optflags, toys.optargs, and this[] from toys.argv
  332. void get_optflags(void)
  333. {
  334. struct getoptflagstate gof;
  335. struct opts *catch;
  336. unsigned long long saveflags;
  337. char *letters[]={"s",""}, *ss;
  338. // Option parsing is a two stage process: parse the option string into
  339. // a struct opts list, then use that list to process argv[];
  340. toys.exitval = toys.which->flags >> 24;
  341. // Allocate memory for optargs
  342. saveflags = toys.optc = parse_optflaglist(&gof);
  343. while (toys.argv[saveflags++]);
  344. toys.optargs = xzalloc(sizeof(char *)*saveflags);
  345. if (toys.optc) *toys.optargs = *toys.argv;
  346. if (toys.argv[1] && toys.argv[1][0] == '-') gof.nodash_now = 0;
  347. // Iterate through command line arguments, skipping argv[0]
  348. for (gof.argc=1; toys.argv[gof.argc]; gof.argc++) {
  349. gof.arg = toys.argv[gof.argc];
  350. catch = 0;
  351. // Parse this argument
  352. if (gof.stopearly>1) goto notflag;
  353. if (gof.argc>1 || *gof.arg=='-') gof.nodash_now = 0;
  354. // Various things with dashes
  355. if (*gof.arg == '-') {
  356. // Handle -
  357. if (!gof.arg[1]) goto notflag;
  358. gof.arg++;
  359. if (*gof.arg=='-') {
  360. struct longopts *lo;
  361. struct arg_list *al = 0, *al2;
  362. int ii;
  363. gof.arg++;
  364. // Handle --
  365. if (!*gof.arg) {
  366. gof.stopearly += 2;
  367. continue;
  368. }
  369. // unambiguously match the start of a known --longopt?
  370. check_help(toys.argv+gof.argc);
  371. for (lo = gof.longopts; lo; lo = lo->next) {
  372. for (ii = 0; ii<lo->len; ii++) if (gof.arg[ii] != lo->str[ii]) break;
  373. // = only terminates when we can take an argument, not type 0 or '@'
  374. if (!gof.arg[ii] || (gof.arg[ii]=='=' && !strchr("@", lo->opt->type)))
  375. {
  376. al2 = xmalloc(sizeof(struct arg_list));
  377. al2->next = al;
  378. al2->arg = (void *)lo;
  379. al = al2;
  380. // Exact match is unambigous even when longer options available
  381. if (ii==lo->len) {
  382. llist_traverse(al, free);
  383. al = 0;
  384. break;
  385. }
  386. }
  387. }
  388. // How many matches?
  389. if (al) {
  390. *libbuf = 0;
  391. if (al->next) for (ss = libbuf, al2 = al; al2; al2 = al2->next) {
  392. lo = (void *)al2->arg;
  393. ss += sprintf(ss, " %.*s"+(al2==al), lo->len, lo->str);
  394. } else lo = (void *)al->arg;
  395. llist_traverse(al, free);
  396. if (*libbuf) error_exit("bad --%s (%s)", gof.arg, libbuf);
  397. }
  398. // One unambiguous match?
  399. if (lo) {
  400. catch = lo->opt;
  401. while (!strchr("=", *gof.arg)) gof.arg++;
  402. // Should we handle this --longopt as a non-option argument?
  403. } else if (gof.noerror) {
  404. gof.arg -= 2;
  405. goto notflag;
  406. }
  407. // Long option parsed, handle option.
  408. gotflag(&gof, catch, 1);
  409. continue;
  410. }
  411. // Handle things that don't start with a dash.
  412. } else {
  413. if (gof.nodash_now) toys.optflags |= FLAGS_NODASH;
  414. else goto notflag;
  415. }
  416. // At this point, we have the args part of -args. Loop through
  417. // each entry (could be -abc meaning -a -b -c)
  418. saveflags = toys.optflags;
  419. while (gof.arg && *gof.arg) {
  420. // Identify next option char.
  421. for (catch = gof.opts; catch; catch = catch->next)
  422. if (*gof.arg == catch->c)
  423. if (!gof.arg[1] || (catch->flags&(4|8))!=4) break;
  424. if (!catch && gof.noerror) {
  425. toys.optflags = saveflags;
  426. gof.arg = toys.argv[gof.argc];
  427. goto notflag;
  428. }
  429. // Handle option char (advancing past what was used)
  430. gotflag(&gof, catch, 0);
  431. }
  432. continue;
  433. // Not a flag, save value in toys.optargs[]
  434. notflag:
  435. if (gof.stopearly) gof.stopearly++;
  436. toys.optargs[toys.optc++] = toys.argv[gof.argc];
  437. }
  438. // Sanity check
  439. if (toys.optc<gof.minargs)
  440. help_exit("Need%s %d argument%s", letters[!!(gof.minargs-1)],
  441. gof.minargs, letters[!(gof.minargs-1)]);
  442. if (toys.optc>gof.maxargs)
  443. help_exit("Max %d argument%s", gof.maxargs, letters[!(gof.maxargs-1)]);
  444. if (gof.requires && !(gof.requires & toys.optflags)) {
  445. struct opts *req;
  446. char needs[32], *s = needs;
  447. for (req = gof.opts; req; req = req->next)
  448. if (req->flags & 1) *(s++) = req->c;
  449. *s = 0;
  450. help_exit("Needs %s-%s", s[1] ? "one of " : "", needs);
  451. }
  452. toys.exitval = 0;
  453. if (CFG_TOYBOX_FREE) {
  454. llist_traverse(gof.opts, free);
  455. llist_traverse(gof.longopts, free);
  456. }
  457. }