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