1  /* Hierarchical argument parsing, layered over getopt
       2     Copyright (C) 1995-2023 Free Software Foundation, Inc.
       3     This file is part of the GNU C Library.
       4     Written by Miles Bader <miles@gnu.ai.mit.edu>.
       5  
       6     This file is free software: you can redistribute it and/or modify
       7     it under the terms of the GNU Lesser General Public License as
       8     published by the Free Software Foundation, either version 3 of the
       9     License, or (at your option) any later version.
      10  
      11     This file is distributed in the hope that it will be useful,
      12     but WITHOUT ANY WARRANTY; without even the implied warranty of
      13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      14     GNU Lesser General Public License for more details.
      15  
      16     You should have received a copy of the GNU Lesser General Public License
      17     along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
      18  
      19  #ifdef HAVE_CONFIG_H
      20  # include <config.h>
      21  #endif
      22  
      23  #include <alloca.h>
      24  #include <stddef.h>
      25  #include <stdlib.h>
      26  #include <string.h>
      27  #include <unistd.h>
      28  #include <limits.h>
      29  #include <getopt.h>
      30  #include <getopt_int.h>
      31  
      32  #ifdef _LIBC
      33  # include <libintl.h>
      34  # undef dgettext
      35  # define dgettext(domain, msgid) \
      36     __dcgettext (domain, msgid, LC_MESSAGES)
      37  #else
      38  # include "gettext.h"
      39  #endif
      40  #define N_(msgid) msgid
      41  
      42  #ifdef _LIBC
      43  # define ARGP_TEXT_DOMAIN "libc"
      44  #else
      45  # ifdef DEFAULT_TEXT_DOMAIN
      46  #  define ARGP_TEXT_DOMAIN DEFAULT_TEXT_DOMAIN
      47  # else
      48  #  define ARGP_TEXT_DOMAIN NULL
      49  # endif
      50  #endif
      51  
      52  #include "argp.h"
      53  #include "argp-namefrob.h"
      54  
      55  #define alignto(n, d) ((((n) + (d) - 1) / (d)) * (d))
      56  
      57  /* Getopt return values.  */
      58  #define KEY_END (-1)            /* The end of the options.  */
      59  #define KEY_ARG 1               /* A non-option argument.  */
      60  #define KEY_ERR '?'             /* An error parsing the options.  */
      61  
      62  /* The meta-argument used to prevent any further arguments being interpreted
      63     as options.  */
      64  #define QUOTE "--"
      65  
      66  /* The number of bits we steal in a long-option value for our own use.  */
      67  #define GROUP_BITS CHAR_BIT
      68  
      69  /* The number of bits available for the user value.  */
      70  #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
      71  #define USER_MASK ((1 << USER_BITS) - 1)
      72  
      73  /* EZ alias for ARGP_ERR_UNKNOWN.  */
      74  #define EBADKEY ARGP_ERR_UNKNOWN
      75  
      76  /* Default options.  */
      77  
      78  /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
      79     for one second intervals, decrementing _ARGP_HANG until it's zero.  Thus
      80     you can force the program to continue by attaching a debugger and setting
      81     it to 0 yourself.  */
      82  static volatile int _argp_hang;
      83  
      84  #define OPT_PROGNAME    -2
      85  #define OPT_USAGE       -3
      86  #define OPT_HANG        -4
      87  
      88  static const struct argp_option argp_default_options[] =
      89  {
      90    {"help",        '?',          0, 0,  N_("give this help list"), -1},
      91    {"usage",       OPT_USAGE,    0, 0,  N_("give a short usage message"), 0},
      92    {"program-name",OPT_PROGNAME, N_("NAME"), OPTION_HIDDEN,
      93     N_("set the program name"), 0},
      94    {"HANG",        OPT_HANG,    N_("SECS"), OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
      95     N_("hang for SECS seconds (default 3600)"), 0},
      96    {NULL, 0, 0, 0, NULL, 0}
      97  };
      98  
      99  static error_t
     100  argp_default_parser (int key, char *arg, struct argp_state *state)
     101  {
     102    switch (key)
     103      {
     104      case '?':
     105        __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
     106        break;
     107      case OPT_USAGE:
     108        __argp_state_help (state, state->out_stream,
     109                           ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
     110        break;
     111  
     112      case OPT_PROGNAME:          /* Set the program name.  */
     113  #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME
     114        program_invocation_name = arg;
     115  #endif
     116        /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
     117           __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
     118           to be that, so we have to be a bit careful here.]  */
     119  
     120        /* Update what we use for messages.  */
     121        state->name = __argp_base_name (arg);
     122  
     123  #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
     124        program_invocation_short_name = state->name;
     125  #endif
     126  
     127        if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
     128            == ARGP_PARSE_ARGV0)
     129          /* Update what getopt uses too.  */
     130          state->argv[0] = arg;
     131  
     132        break;
     133  
     134      case OPT_HANG:
     135        _argp_hang = atoi (arg ? arg : "3600");
     136        while (_argp_hang-- > 0)
     137          __sleep (1);
     138        break;
     139  
     140      default:
     141        return EBADKEY;
     142      }
     143    return 0;
     144  }
     145  
     146  static const struct argp argp_default_argp =
     147    {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL,
     148     ARGP_TEXT_DOMAIN};
     149  
     150  
     151  static const struct argp_option argp_version_options[] =
     152  {
     153    {"version",     'V',          0, 0,  N_("print program version"), -1},
     154    {NULL, 0, 0, 0, NULL, 0}
     155  };
     156  
     157  static error_t
     158  argp_version_parser (int key, char *arg, struct argp_state *state)
     159  {
     160    switch (key)
     161      {
     162      case 'V':
     163        if (argp_program_version_hook)
     164          (*argp_program_version_hook) (state->out_stream, state);
     165        else if (argp_program_version)
     166          fprintf (state->out_stream, "%s\n", argp_program_version);
     167        else
     168          __argp_error (state, "%s",
     169                        dgettext (ARGP_TEXT_DOMAIN,
     170                                  "(PROGRAM ERROR) No version known!?"));
     171        if (! (state->flags & ARGP_NO_EXIT))
     172          exit (0);
     173        break;
     174      default:
     175        return EBADKEY;
     176      }
     177    return 0;
     178  }
     179  
     180  static const struct argp argp_version_argp =
     181    {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL,
     182     ARGP_TEXT_DOMAIN};
     183  
     184  /* Returns the offset into the getopt long options array LONG_OPTIONS of a
     185     long option with called NAME, or -1 if none is found.  Passing NULL as
     186     NAME will return the number of options.  */
     187  static int
     188  find_long_option (struct option *long_options, const char *name)
     189  {
     190    struct option *l = long_options;
     191    while (l->name != NULL)
     192      if (name != NULL && strcmp (l->name, name) == 0)
     193        return l - long_options;
     194      else
     195        l++;
     196    if (name == NULL)
     197      return l - long_options;
     198    else
     199      return -1;
     200  }
     201  
     202  
     203  /* The state of a "group" during parsing.  Each group corresponds to a
     204     particular argp structure from the tree of such descending from the top
     205     level argp passed to argp_parse.  */
     206  struct group
     207  {
     208    /* This group's parsing function.  */
     209    argp_parser_t parser;
     210  
     211    /* Which argp this group is from.  */
     212    const struct argp *argp;
     213  
     214    /* Points to the point in SHORT_OPTS corresponding to the end of the short
     215       options for this group.  We use it to determine from which group a
     216       particular short options is from.  */
     217    char *short_end;
     218  
     219    /* The number of non-option args successfully handled by this parser.  */
     220    unsigned args_processed;
     221  
     222    /* This group's parser's parent's group.  */
     223    struct group *parent;
     224    unsigned parent_index;        /* And the our position in the parent.   */
     225  
     226    /* These fields are swapped into and out of the state structure when
     227       calling this group's parser.  */
     228    void *input, **child_inputs;
     229    void *hook;
     230  };
     231  
     232  /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
     233     from STATE before calling, and back into state afterwards.  If GROUP has
     234     no parser, EBADKEY is returned.  */
     235  static error_t
     236  group_parse (struct group *group, struct argp_state *state, int key, char *arg)
     237  {
     238    if (group->parser)
     239      {
     240        error_t err;
     241        state->hook = group->hook;
     242        state->input = group->input;
     243        state->child_inputs = group->child_inputs;
     244        state->arg_num = group->args_processed;
     245        err = (*group->parser)(key, arg, state);
     246        group->hook = state->hook;
     247        return err;
     248      }
     249    else
     250      return EBADKEY;
     251  }
     252  
     253  struct parser
     254  {
     255    const struct argp *argp;
     256  
     257    /* SHORT_OPTS is the getopt short options string for the union of all the
     258       groups of options.  */
     259    char *short_opts;
     260    /* LONG_OPTS is the array of getop long option structures for the union of
     261       all the groups of options.  */
     262    struct option *long_opts;
     263    /* OPT_DATA is the getopt data used for the reentrant getopt.  */
     264    struct _getopt_data opt_data;
     265  
     266    /* States of the various parsing groups.  */
     267    struct group *groups;
     268    /* The end of the GROUPS array.  */
     269    struct group *egroup;
     270    /* A vector containing storage for the CHILD_INPUTS field in all groups.  */
     271    void **child_inputs;
     272  
     273    /* True if we think using getopt is still useful; if false, then
     274       remaining arguments are just passed verbatim with ARGP_KEY_ARG.  This is
     275       cleared whenever getopt returns KEY_END, but may be set again if the user
     276       moves the next argument pointer backwards.  */
     277    int try_getopt;
     278  
     279    /* State block supplied to parsing routines.  */
     280    struct argp_state state;
     281  
     282    /* Memory used by this parser.  */
     283    void *storage;
     284  };
     285  
     286  /* The next usable entries in the various parser tables being filled in by
     287     convert_options.  */
     288  struct parser_convert_state
     289  {
     290    struct parser *parser;
     291    char *short_end;
     292    struct option *long_end;
     293    void **child_inputs_end;
     294  };
     295  
     296  /* Converts all options in ARGP (which is put in GROUP) and ancestors
     297     into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
     298     CVT->LONG_END are the points at which new options are added.  Returns the
     299     next unused group entry.  CVT holds state used during the conversion.  */
     300  static struct group *
     301  convert_options (const struct argp *argp,
     302                   struct group *parent, unsigned parent_index,
     303                   struct group *group, struct parser_convert_state *cvt)
     304  {
     305    /* REAL is the most recent non-alias value of OPT.  */
     306    const struct argp_option *real = argp->options;
     307    const struct argp_child *children = argp->children;
     308  
     309    if (real || argp->parser)
     310      {
     311        const struct argp_option *opt;
     312  
     313        if (real)
     314          for (opt = real; !__option_is_end (opt); opt++)
     315            {
     316              if (! (opt->flags & OPTION_ALIAS))
     317                /* OPT isn't an alias, so we can use values from it.  */
     318                real = opt;
     319  
     320              if (! (real->flags & OPTION_DOC))
     321                /* A real option (not just documentation).  */
     322                {
     323                  if (__option_is_short (opt))
     324                    /* OPT can be used as a short option.  */
     325                    {
     326                      *cvt->short_end++ = opt->key;
     327                      if (real->arg)
     328                        {
     329                          *cvt->short_end++ = ':';
     330                          if (real->flags & OPTION_ARG_OPTIONAL)
     331                            *cvt->short_end++ = ':';
     332                        }
     333                      *cvt->short_end = '\0'; /* keep 0 terminated */
     334                    }
     335  
     336                  if (opt->name
     337                      && find_long_option (cvt->parser->long_opts, opt->name) < 0)
     338                    /* OPT can be used as a long option.  */
     339                    {
     340                      cvt->long_end->name = opt->name;
     341                      cvt->long_end->has_arg =
     342                        (real->arg
     343                         ? (real->flags & OPTION_ARG_OPTIONAL
     344                            ? optional_argument
     345                            : required_argument)
     346                         : no_argument);
     347                      cvt->long_end->flag = 0;
     348                      /* we add a disambiguating code to all the user's
     349                         values (which is removed before we actually call
     350                         the function to parse the value); this means that
     351                         the user loses use of the high 8 bits in all his
     352                         values (the sign of the lower bits is preserved
     353                         however)...  */
     354                      cvt->long_end->val =
     355                        ((opt->key ? opt->key : real->key) & USER_MASK)
     356                        + (((group - cvt->parser->groups) + 1) << USER_BITS);
     357  
     358                      /* Keep the LONG_OPTS list terminated.  */
     359                      (++cvt->long_end)->name = NULL;
     360                    }
     361                }
     362              }
     363  
     364        group->parser = argp->parser;
     365        group->argp = argp;
     366        group->short_end = cvt->short_end;
     367        group->args_processed = 0;
     368        group->parent = parent;
     369        group->parent_index = parent_index;
     370        group->input = 0;
     371        group->hook = 0;
     372        group->child_inputs = 0;
     373  
     374        if (children)
     375          /* Assign GROUP's CHILD_INPUTS field some space from
     376             CVT->child_inputs_end.*/
     377          {
     378            unsigned num_children = 0;
     379            while (children[num_children].argp)
     380              num_children++;
     381            group->child_inputs = cvt->child_inputs_end;
     382            cvt->child_inputs_end += num_children;
     383          }
     384  
     385        parent = group++;
     386      }
     387    else
     388      parent = 0;
     389  
     390    if (children)
     391      {
     392        unsigned index = 0;
     393        while (children->argp)
     394          group =
     395            convert_options (children++->argp, parent, index++, group, cvt);
     396      }
     397  
     398    return group;
     399  }
     400  
     401  /* Find the merged set of getopt options, with keys appropriately prefixed. */
     402  static void
     403  parser_convert (struct parser *parser, const struct argp *argp, int flags)
     404  {
     405    struct parser_convert_state cvt;
     406  
     407    cvt.parser = parser;
     408    cvt.short_end = parser->short_opts;
     409    cvt.long_end = parser->long_opts;
     410    cvt.child_inputs_end = parser->child_inputs;
     411  
     412    if (flags & ARGP_IN_ORDER)
     413      *cvt.short_end++ = '-';
     414    else if (flags & ARGP_NO_ARGS)
     415      *cvt.short_end++ = '+';
     416    *cvt.short_end = '\0';
     417  
     418    cvt.long_end->name = NULL;
     419  
     420    parser->argp = argp;
     421  
     422    if (argp)
     423      parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
     424    else
     425      parser->egroup = parser->groups; /* No parsers at all! */
     426  }
     427  
     428  /* Lengths of various parser fields which we will allocated.  */
     429  struct parser_sizes
     430  {
     431    size_t short_len;             /* Getopt short options string.  */
     432    size_t long_len;              /* Getopt long options vector.  */
     433    size_t num_groups;            /* Group structures we allocate.  */
     434    size_t num_child_inputs;      /* Child input slots.  */
     435  };
     436  
     437  /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
     438   argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
     439   the maximum lengths of the resulting merged getopt short options string and
     440   long-options array, respectively.  */
     441  static void
     442  calc_sizes (const struct argp *argp,  struct parser_sizes *szs)
     443  {
     444    const struct argp_child *child = argp->children;
     445    const struct argp_option *opt = argp->options;
     446  
     447    if (opt || argp->parser)
     448      {
     449        szs->num_groups++;
     450        if (opt)
     451          {
     452            int num_opts = 0;
     453            while (!__option_is_end (opt++))
     454              num_opts++;
     455            szs->short_len += num_opts * 3; /* opt + up to 2 ':'s */
     456            szs->long_len += num_opts;
     457          }
     458      }
     459  
     460    if (child)
     461      while (child->argp)
     462        {
     463          calc_sizes ((child++)->argp, szs);
     464          szs->num_child_inputs++;
     465        }
     466  }
     467  
     468  /* Initializes PARSER to parse ARGP in a manner described by FLAGS.  */
     469  static error_t
     470  parser_init (struct parser *parser, const struct argp *argp,
     471               int argc, char **argv, int flags, void *input)
     472  {
     473    error_t err = 0;
     474    struct group *group;
     475    struct parser_sizes szs;
     476    struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
     477    char *storage;
     478    size_t glen, gsum;
     479    size_t clen, csum;
     480    size_t llen, lsum;
     481    size_t slen, ssum;
     482  
     483    szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
     484    szs.long_len = 0;
     485    szs.num_groups = 0;
     486    szs.num_child_inputs = 0;
     487  
     488    if (argp)
     489      calc_sizes (argp, &szs);
     490  
     491    /* Lengths of the various bits of storage used by PARSER.  */
     492    glen = (szs.num_groups + 1) * sizeof (struct group);
     493    clen = szs.num_child_inputs * sizeof (void *);
     494    llen = (szs.long_len + 1) * sizeof (struct option);
     495    slen = szs.short_len + 1;
     496  
     497    /* Sums of previous lengths, properly aligned.  There's no need to
     498       align gsum, since struct group is aligned at least as strictly as
     499       void * (since it contains a void * member).  And there's no need
     500       to align lsum, since struct option is aligned at least as
     501       strictly as char.  */
     502    gsum = glen;
     503    csum = alignto (gsum + clen, alignof (struct option));
     504    lsum = csum + llen;
     505    ssum = lsum + slen;
     506  
     507    parser->storage = malloc (ssum);
     508    if (! parser->storage)
     509      return ENOMEM;
     510  
     511    storage = parser->storage;
     512    parser->groups = parser->storage;
     513    parser->child_inputs = (void **) (storage + gsum);
     514    parser->long_opts = (struct option *) (storage + csum);
     515    parser->short_opts = storage + lsum;
     516    parser->opt_data = opt_data;
     517  
     518    memset (parser->child_inputs, 0, clen);
     519    parser_convert (parser, argp, flags);
     520  
     521    memset (&parser->state, 0, sizeof (struct argp_state));
     522    parser->state.root_argp = parser->argp;
     523    parser->state.argc = argc;
     524    parser->state.argv = argv;
     525    parser->state.flags = flags;
     526    parser->state.err_stream = stderr;
     527    parser->state.out_stream = stdout;
     528    parser->state.next = 0;       /* Tell getopt to initialize.  */
     529    parser->state.pstate = parser;
     530  
     531    parser->try_getopt = 1;
     532  
     533    /* Call each parser for the first time, giving it a chance to propagate
     534       values to child parsers.  */
     535    if (parser->groups < parser->egroup)
     536      parser->groups->input = input;
     537    for (group = parser->groups;
     538         group < parser->egroup && (!err || err == EBADKEY);
     539         group++)
     540      {
     541        if (group->parent)
     542          /* If a child parser, get the initial input value from the parent. */
     543          group->input = group->parent->child_inputs[group->parent_index];
     544  
     545        if (!group->parser
     546            && group->argp->children && group->argp->children->argp)
     547          /* For the special case where no parsing function is supplied for an
     548             argp, propagate its input to its first child, if any (this just
     549             makes very simple wrapper argps more convenient).  */
     550          group->child_inputs[0] = group->input;
     551  
     552        err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
     553      }
     554    if (err == EBADKEY)
     555      err = 0;                    /* Some parser didn't understand.  */
     556  
     557    if (err)
     558      return err;
     559  
     560    if (parser->state.flags & ARGP_NO_ERRS)
     561      {
     562        parser->opt_data.opterr = 0;
     563        if (parser->state.flags & ARGP_PARSE_ARGV0)
     564          /* getopt always skips ARGV[0], so we have to fake it out.  As long
     565             as OPTERR is 0, then it shouldn't actually try to access it.  */
     566          parser->state.argv--, parser->state.argc++;
     567      }
     568    else
     569      parser->opt_data.opterr = 1;        /* Print error messages.  */
     570  
     571    if (parser->state.argv == argv && argv[0])
     572      /* There's an argv[0]; use it for messages.  */
     573      parser->state.name = __argp_base_name (argv[0]);
     574    else
     575      parser->state.name = __argp_short_program_name ();
     576  
     577    return 0;
     578  }
     579  
     580  /* Free any storage consumed by PARSER (but not PARSER itself).  */
     581  static error_t
     582  parser_finalize (struct parser *parser,
     583                   error_t err, int arg_ebadkey, int *end_index)
     584  {
     585    struct group *group;
     586  
     587    if (err == EBADKEY && arg_ebadkey)
     588      /* Suppress errors generated by unparsed arguments.  */
     589      err = 0;
     590  
     591    if (! err)
     592      {
     593        if (parser->state.next == parser->state.argc)
     594          /* We successfully parsed all arguments!  Call all the parsers again,
     595             just a few more times... */
     596          {
     597            for (group = parser->groups;
     598                 group < parser->egroup && (!err || err==EBADKEY);
     599                 group++)
     600              if (group->args_processed == 0)
     601                err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
     602            for (group = parser->egroup - 1;
     603                 group >= parser->groups && (!err || err==EBADKEY);
     604                 group--)
     605              err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
     606  
     607            if (err == EBADKEY)
     608              err = 0;            /* Some parser didn't understand.  */
     609  
     610            /* Tell the user that all arguments are parsed.  */
     611            if (end_index)
     612              *end_index = parser->state.next;
     613          }
     614        else if (end_index)
     615          /* Return any remaining arguments to the user.  */
     616          *end_index = parser->state.next;
     617        else
     618          /* No way to return the remaining arguments, they must be bogus. */
     619          {
     620            if (!(parser->state.flags & ARGP_NO_ERRS)
     621                && parser->state.err_stream)
     622              fprintf (parser->state.err_stream,
     623                       dgettext (ARGP_TEXT_DOMAIN, "%s: Too many arguments\n"),
     624                       parser->state.name);
     625            err = EBADKEY;
     626          }
     627      }
     628  
     629    /* Okay, we're all done, with either an error or success; call the parsers
     630       to indicate which one.  */
     631  
     632    if (err)
     633      {
     634        /* Maybe print an error message.  */
     635        if (err == EBADKEY)
     636          /* An appropriate message describing what the error was should have
     637             been printed earlier.  */
     638          __argp_state_help (&parser->state, parser->state.err_stream,
     639                             ARGP_HELP_STD_ERR);
     640  
     641        /* Since we didn't exit, give each parser an error indication.  */
     642        for (group = parser->groups; group < parser->egroup; group++)
     643          group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
     644      }
     645    else
     646      /* Notify parsers of success, and propagate back values from parsers.  */
     647      {
     648        /* We pass over the groups in reverse order so that child groups are
     649           given a chance to do there processing before passing back a value to
     650           the parent.  */
     651        for (group = parser->egroup - 1
     652             ; group >= parser->groups && (!err || err == EBADKEY)
     653             ; group--)
     654          err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
     655        if (err == EBADKEY)
     656          err = 0;                /* Some parser didn't understand.  */
     657      }
     658  
     659    /* Call parsers once more, to do any final cleanup.  Errors are ignored.  */
     660    for (group = parser->egroup - 1; group >= parser->groups; group--)
     661      group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
     662  
     663    if (err == EBADKEY)
     664      err = EINVAL;
     665  
     666    free (parser->storage);
     667  
     668    return err;
     669  }
     670  
     671  /* Call the user parsers to parse the non-option argument VAL, at the current
     672     position, returning any error.  The state NEXT pointer is assumed to have
     673     been adjusted (by getopt) to point after this argument; this function will
     674     adjust it correctly to reflect however many args actually end up being
     675     consumed.  */
     676  static error_t
     677  parser_parse_arg (struct parser *parser, char *val)
     678  {
     679    /* Save the starting value of NEXT, first adjusting it so that the arg
     680       we're parsing is again the front of the arg vector.  */
     681    int index = --parser->state.next;
     682    error_t err = EBADKEY;
     683    struct group *group;
     684    int key = 0;                  /* Which of ARGP_KEY_ARG[S] we used.  */
     685  
     686    /* Try to parse the argument in each parser.  */
     687    for (group = parser->groups
     688         ; group < parser->egroup && err == EBADKEY
     689         ; group++)
     690      {
     691        parser->state.next++;     /* For ARGP_KEY_ARG, consume the arg.  */
     692        key = ARGP_KEY_ARG;
     693        err = group_parse (group, &parser->state, key, val);
     694  
     695        if (err == EBADKEY)
     696          /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
     697          {
     698            parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg.  */
     699            key = ARGP_KEY_ARGS;
     700            err = group_parse (group, &parser->state, key, 0);
     701          }
     702      }
     703  
     704    if (! err)
     705      {
     706        if (key == ARGP_KEY_ARGS)
     707          /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
     708             changed by the user, *all* arguments should be considered
     709             consumed.  */
     710          parser->state.next = parser->state.argc;
     711  
     712        if (parser->state.next > index)
     713          /* Remember that we successfully processed a non-option
     714             argument -- but only if the user hasn't gotten tricky and set
     715             the clock back.  */
     716          (--group)->args_processed += (parser->state.next - index);
     717        else
     718          /* The user wants to reparse some args, give getopt another try.  */
     719          parser->try_getopt = 1;
     720      }
     721  
     722    return err;
     723  }
     724  
     725  /* Call the user parsers to parse the option OPT, with argument VAL, at the
     726     current position, returning any error.  */
     727  static error_t
     728  parser_parse_opt (struct parser *parser, int opt, char *val)
     729  {
     730    /* The group key encoded in the high bits; 0 for short opts or
     731       group_number + 1 for long opts.  */
     732    int group_key = opt >> USER_BITS;
     733    error_t err = EBADKEY;
     734  
     735    if (group_key == 0)
     736      /* A short option.  By comparing OPT's position in SHORT_OPTS to the
     737         various starting positions in each group's SHORT_END field, we can
     738         determine which group OPT came from.  */
     739      {
     740        struct group *group;
     741        char *short_index = strchr (parser->short_opts, opt);
     742  
     743        if (short_index)
     744          for (group = parser->groups; group < parser->egroup; group++)
     745            if (group->short_end > short_index)
     746              {
     747                err = group_parse (group, &parser->state, opt,
     748                                   parser->opt_data.optarg);
     749                break;
     750              }
     751      }
     752    else
     753      /* A long option.  Preserve the sign in the user key, without
     754         invoking undefined behavior.  Assume two's complement.  */
     755      {
     756        int user_key =
     757          ((opt & (1 << (USER_BITS - 1))) ? ~USER_MASK : 0) | (opt & USER_MASK);
     758        err =
     759          group_parse (&parser->groups[group_key - 1], &parser->state,
     760                       user_key, parser->opt_data.optarg);
     761      }
     762  
     763    if (err == EBADKEY)
     764      /* At least currently, an option not recognized is an error in the
     765         parser, because we pre-compute which parser is supposed to deal
     766         with each option.  */
     767      {
     768        static const char bad_key_err[] =
     769          N_("(PROGRAM ERROR) Option should have been recognized!?");
     770        if (group_key == 0)
     771          __argp_error (&parser->state, "-%c: %s", opt,
     772                        dgettext (ARGP_TEXT_DOMAIN, bad_key_err));
     773        else
     774          {
     775            struct option *long_opt = parser->long_opts;
     776            while (long_opt->val != opt && long_opt->name)
     777              long_opt++;
     778            __argp_error (&parser->state, "--%s: %s",
     779                          long_opt->name ? long_opt->name : "???",
     780                          dgettext (ARGP_TEXT_DOMAIN, bad_key_err));
     781          }
     782      }
     783  
     784    return err;
     785  }
     786  
     787  /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
     788     Any error from the parsers is returned, and *ARGP_EBADKEY indicates
     789     whether a value of EBADKEY is due to an unrecognized argument (which is
     790     generally not fatal).  */
     791  static error_t
     792  parser_parse_next (struct parser *parser, int *arg_ebadkey)
     793  {
     794    int opt;
     795    error_t err = 0;
     796  
     797    if (parser->state.quoted && parser->state.next < parser->state.quoted)
     798      /* The next argument pointer has been moved to before the quoted
     799         region, so pretend we never saw the quoting "--", and give getopt
     800         another chance.  If the user hasn't removed it, getopt will just
     801         process it again.  */
     802      parser->state.quoted = 0;
     803  
     804    if (parser->try_getopt && !parser->state.quoted)
     805      /* Give getopt a chance to parse this.  */
     806      {
     807        /* Put it back in OPTIND for getopt.  */
     808        parser->opt_data.optind = parser->state.next;
     809        /* Distinguish KEY_ERR from a real option.  */
     810        parser->opt_data.optopt = KEY_END;
     811        if (parser->state.flags & ARGP_LONG_ONLY)
     812          opt = _getopt_long_only_r (parser->state.argc, parser->state.argv,
     813                                     parser->short_opts, parser->long_opts, 0,
     814                                     &parser->opt_data);
     815        else
     816          opt = _getopt_long_r (parser->state.argc, parser->state.argv,
     817                                parser->short_opts, parser->long_opts, 0,
     818                                &parser->opt_data);
     819        /* And see what getopt did.  */
     820        parser->state.next = parser->opt_data.optind;
     821  
     822        if (opt == KEY_END)
     823          /* Getopt says there are no more options, so stop using
     824             getopt; we'll continue if necessary on our own.  */
     825          {
     826            parser->try_getopt = 0;
     827            if (parser->state.next > 1
     828                && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
     829                     == 0)
     830              /* Not only is this the end of the options, but it's a
     831                 "quoted" region, which may have args that *look* like
     832                 options, so we definitely shouldn't try to use getopt past
     833                 here, whatever happens.  */
     834              parser->state.quoted = parser->state.next;
     835          }
     836        else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END)
     837          /* KEY_ERR can have the same value as a valid user short
     838             option, but in the case of a real error, getopt sets OPTOPT
     839             to the offending character, which can never be KEY_END.  */
     840          {
     841            *arg_ebadkey = 0;
     842            return EBADKEY;
     843          }
     844      }
     845    else
     846      opt = KEY_END;
     847  
     848    if (opt == KEY_END)
     849      {
     850        /* We're past what getopt considers the options.  */
     851        if (parser->state.next >= parser->state.argc
     852            || (parser->state.flags & ARGP_NO_ARGS))
     853          /* Indicate that we're done.  */
     854          {
     855            *arg_ebadkey = 1;
     856            return EBADKEY;
     857          }
     858        else
     859          /* A non-option arg; simulate what getopt might have done.  */
     860          {
     861            opt = KEY_ARG;
     862            parser->opt_data.optarg = parser->state.argv[parser->state.next++];
     863          }
     864      }
     865  
     866    if (opt == KEY_ARG)
     867      /* A non-option argument; try each parser in turn.  */
     868      err = parser_parse_arg (parser, parser->opt_data.optarg);
     869    else
     870      err = parser_parse_opt (parser, opt, parser->opt_data.optarg);
     871  
     872    if (err == EBADKEY)
     873      *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
     874  
     875    return err;
     876  }
     877  
     878  /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
     879     FLAGS is one of the ARGP_ flags above.  If END_INDEX is non-NULL, the
     880     index in ARGV of the first unparsed option is returned in it.  If an
     881     unknown option is present, EINVAL is returned; if some parser routine
     882     returned a non-zero value, it is returned; otherwise 0 is returned.  */
     883  error_t
     884  __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
     885                int *end_index, void *input)
     886  {
     887    error_t err;
     888    struct parser parser;
     889  
     890    /* If true, then err == EBADKEY is a result of a non-option argument failing
     891       to be parsed (which in some cases isn't actually an error).  */
     892    int arg_ebadkey = 0;
     893  
     894  #ifndef _LIBC
     895    if (!(flags & ARGP_PARSE_ARGV0))
     896      {
     897  #if HAVE_DECL_PROGRAM_INVOCATION_NAME
     898        if (!program_invocation_name)
     899          program_invocation_name = argv[0];
     900  #endif
     901  #if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
     902        if (!program_invocation_short_name)
     903          program_invocation_short_name = __argp_base_name (argv[0]);
     904  #endif
     905      }
     906  #endif
     907  
     908    if (! (flags & ARGP_NO_HELP))
     909      /* Add our own options.  */
     910      {
     911        struct argp_child *child = alloca (4 * sizeof (struct argp_child));
     912        struct argp *top_argp = alloca (sizeof (struct argp));
     913  
     914        /* TOP_ARGP has no options, it just serves to group the user & default
     915           argps.  */
     916        memset (top_argp, 0, sizeof (*top_argp));
     917        top_argp->children = child;
     918  
     919        memset (child, 0, 4 * sizeof (struct argp_child));
     920  
     921        if (argp)
     922          (child++)->argp = argp;
     923        (child++)->argp = &argp_default_argp;
     924        if (argp_program_version || argp_program_version_hook)
     925          (child++)->argp = &argp_version_argp;
     926        child->argp = 0;
     927  
     928        argp = top_argp;
     929      }
     930  
     931    /* Construct a parser for these arguments.  */
     932    err = parser_init (&parser, argp, argc, argv, flags, input);
     933  
     934    if (! err)
     935      /* Parse! */
     936      {
     937        while (! err)
     938          err = parser_parse_next (&parser, &arg_ebadkey);
     939        err = parser_finalize (&parser, err, arg_ebadkey, end_index);
     940      }
     941  
     942    return err;
     943  }
     944  #ifdef weak_alias
     945  weak_alias (__argp_parse, argp_parse)
     946  #endif
     947  
     948  /* Return the input field for ARGP in the parser corresponding to STATE; used
     949     by the help routines.  */
     950  void *
     951  __argp_input (const struct argp *argp, const struct argp_state *state)
     952  {
     953    if (state)
     954      {
     955        struct group *group;
     956        struct parser *parser = state->pstate;
     957  
     958        for (group = parser->groups; group < parser->egroup; group++)
     959          if (group->argp == argp)
     960            return group->input;
     961      }
     962  
     963    return 0;
     964  }
     965  #ifdef weak_alias
     966  weak_alias (__argp_input, _argp_input)
     967  #endif