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