Back to index

glibc  2.9
argp-parse.c
Go to the documentation of this file.
00001 /* Hierarchial argument parsing, layered over getopt
00002    Copyright (C) 1995-2000, 2002, 2003, 2004 Free Software Foundation, Inc.
00003    This file is part of the GNU C Library.
00004    Written by Miles Bader <miles@gnu.ai.mit.edu>.
00005 
00006    The GNU C Library is free software; you can redistribute it and/or
00007    modify it under the terms of the GNU Lesser General Public
00008    License as published by the Free Software Foundation; either
00009    version 2.1 of the License, or (at your option) any later version.
00010 
00011    The GNU C Library is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014    Lesser General Public License for more details.
00015 
00016    You should have received a copy of the GNU Lesser General Public
00017    License along with the GNU C Library; if not, write to the Free
00018    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00019    02111-1307 USA.  */
00020 
00021 #ifdef HAVE_CONFIG_H
00022 #include <config.h>
00023 #endif
00024 
00025 /* AIX requires this to be the first thing in the file.  */
00026 #ifndef __GNUC__
00027 # if HAVE_ALLOCA_H || defined _LIBC
00028 #  include <alloca.h>
00029 # else
00030 #  ifdef _AIX
00031 #pragma alloca
00032 #  else
00033 #   ifndef alloca /* predefined by HP cc +Olibcalls */
00034 char *alloca ();
00035 #   endif
00036 #  endif
00037 # endif
00038 #endif
00039 
00040 #include <stdlib.h>
00041 #include <string.h>
00042 #include <unistd.h>
00043 #include <limits.h>
00044 #include <getopt.h>
00045 #include <getopt_int.h>
00046 
00047 #ifndef _
00048 /* This is for other GNU distributions with internationalized messages.
00049    When compiling libc, the _ macro is predefined.  */
00050 # if defined HAVE_LIBINTL_H || defined _LIBC
00051 #  include <libintl.h>
00052 #  ifdef _LIBC
00053 #   undef dgettext
00054 #   define dgettext(domain, msgid) \
00055   INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES)
00056 #  endif
00057 # else
00058 #  define dgettext(domain, msgid) (msgid)
00059 #  define gettext(msgid) (msgid)
00060 # endif
00061 #endif
00062 #ifndef N_
00063 # define N_(msgid) (msgid)
00064 #endif
00065 
00066 #include "argp.h"
00067 #include "argp-namefrob.h"
00068 
00069 /* Getopt return values.  */
00070 #define KEY_END (-1)        /* The end of the options.  */
00071 #define KEY_ARG 1           /* A non-option argument.  */
00072 #define KEY_ERR '?'         /* An error parsing the options.  */
00073 
00074 /* The meta-argument used to prevent any further arguments being interpreted
00075    as options.  */
00076 #define QUOTE "--"
00077 
00078 /* The number of bits we steal in a long-option value for our own use.  */
00079 #define GROUP_BITS CHAR_BIT
00080 
00081 /* The number of bits available for the user value.  */
00082 #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS)
00083 #define USER_MASK ((1 << USER_BITS) - 1)
00084 
00085 /* EZ alias for ARGP_ERR_UNKNOWN.  */
00086 #define EBADKEY ARGP_ERR_UNKNOWN
00087 
00088 /* Default options.  */
00089 
00090 /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep
00091    for one second intervals, decrementing _ARGP_HANG until it's zero.  Thus
00092    you can force the program to continue by attaching a debugger and setting
00093    it to 0 yourself.  */
00094 static volatile int _argp_hang;
00095 
00096 #define OPT_PROGNAME -2
00097 #define OPT_USAGE    -3
00098 #define OPT_HANG     -4
00099 
00100 static const struct argp_option argp_default_options[] =
00101 {
00102   {"help",      '?',        0, 0,  N_("Give this help list"), -1},
00103   {"usage",     OPT_USAGE,  0, 0,  N_("Give a short usage message")},
00104   {"program-name",OPT_PROGNAME,"NAME", OPTION_HIDDEN, N_("Set the program name")},
00105   {"HANG",      OPT_HANG,    "SECS", OPTION_ARG_OPTIONAL | OPTION_HIDDEN,
00106      N_("Hang for SECS seconds (default 3600)")},
00107   {0, 0}
00108 };
00109 
00110 static error_t
00111 argp_default_parser (int key, char *arg, struct argp_state *state)
00112 {
00113   switch (key)
00114     {
00115     case '?':
00116       __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP);
00117       break;
00118     case OPT_USAGE:
00119       __argp_state_help (state, state->out_stream,
00120                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
00121       break;
00122 
00123     case OPT_PROGNAME:             /* Set the program name.  */
00124 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME
00125       program_invocation_name = arg;
00126 #endif
00127       /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka
00128         __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined
00129         to be that, so we have to be a bit careful here.]  */
00130 
00131       /* Update what we use for messages.  */
00132       state->name = strrchr (arg, '/');
00133       if (state->name)
00134        state->name++;
00135       else
00136        state->name = arg;
00137 
00138 #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
00139       program_invocation_short_name = state->name;
00140 #endif
00141 
00142       if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS))
00143          == ARGP_PARSE_ARGV0)
00144        /* Update what getopt uses too.  */
00145        state->argv[0] = arg;
00146 
00147       break;
00148 
00149     case OPT_HANG:
00150       _argp_hang = atoi (arg ? arg : "3600");
00151       while (_argp_hang-- > 0)
00152        __sleep (1);
00153       break;
00154 
00155     default:
00156       return EBADKEY;
00157     }
00158   return 0;
00159 }
00160 
00161 static const struct argp argp_default_argp =
00162   {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"};
00163 
00164 
00165 static const struct argp_option argp_version_options[] =
00166 {
00167   {"version",   'V',        0, 0,  N_("Print program version"), -1},
00168   {0, 0}
00169 };
00170 
00171 static error_t
00172 argp_version_parser (int key, char *arg, struct argp_state *state)
00173 {
00174   switch (key)
00175     {
00176     case 'V':
00177       if (argp_program_version_hook)
00178        (*argp_program_version_hook) (state->out_stream, state);
00179       else if (argp_program_version)
00180        fprintf (state->out_stream, "%s\n", argp_program_version);
00181       else
00182        __argp_error (state, dgettext (state->root_argp->argp_domain,
00183                                    "(PROGRAM ERROR) No version known!?"));
00184       if (! (state->flags & ARGP_NO_EXIT))
00185        exit (0);
00186       break;
00187     default:
00188       return EBADKEY;
00189     }
00190   return 0;
00191 }
00192 
00193 static const struct argp argp_version_argp =
00194   {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"};
00195 
00196 /* Returns the offset into the getopt long options array LONG_OPTIONS of a
00197    long option with called NAME, or -1 if none is found.  Passing NULL as
00198    NAME will return the number of options.  */
00199 static int
00200 find_long_option (struct option *long_options, const char *name)
00201 {
00202   struct option *l = long_options;
00203   while (l->name != NULL)
00204     if (name != NULL && strcmp (l->name, name) == 0)
00205       return l - long_options;
00206     else
00207       l++;
00208   if (name == NULL)
00209     return l - long_options;
00210   else
00211     return -1;
00212 }
00213 
00214 
00215 /* The state of a `group' during parsing.  Each group corresponds to a
00216    particular argp structure from the tree of such descending from the top
00217    level argp passed to argp_parse.  */
00218 struct group
00219 {
00220   /* This group's parsing function.  */
00221   argp_parser_t parser;
00222 
00223   /* Which argp this group is from.  */
00224   const struct argp *argp;
00225 
00226   /* Points to the point in SHORT_OPTS corresponding to the end of the short
00227      options for this group.  We use it to determine from which group a
00228      particular short options is from.  */
00229   char *short_end;
00230 
00231   /* The number of non-option args sucessfully handled by this parser.  */
00232   unsigned args_processed;
00233 
00234   /* This group's parser's parent's group.  */
00235   struct group *parent;
00236   unsigned parent_index;    /* And the our position in the parent.   */
00237 
00238   /* These fields are swapped into and out of the state structure when
00239      calling this group's parser.  */
00240   void *input, **child_inputs;
00241   void *hook;
00242 };
00243 
00244 /* Call GROUP's parser with KEY and ARG, swapping any group-specific info
00245    from STATE before calling, and back into state afterwards.  If GROUP has
00246    no parser, EBADKEY is returned.  */
00247 static error_t
00248 group_parse (struct group *group, struct argp_state *state, int key, char *arg)
00249 {
00250   if (group->parser)
00251     {
00252       error_t err;
00253       state->hook = group->hook;
00254       state->input = group->input;
00255       state->child_inputs = group->child_inputs;
00256       state->arg_num = group->args_processed;
00257       err = (*group->parser)(key, arg, state);
00258       group->hook = state->hook;
00259       return err;
00260     }
00261   else
00262     return EBADKEY;
00263 }
00264 
00265 struct parser
00266 {
00267   const struct argp *argp;
00268 
00269   /* SHORT_OPTS is the getopt short options string for the union of all the
00270      groups of options.  */
00271   char *short_opts;
00272   /* LONG_OPTS is the array of getop long option structures for the union of
00273      all the groups of options.  */
00274   struct option *long_opts;
00275   /* OPT_DATA is the getopt data used for the re-entrant getopt.  */
00276   struct _getopt_data opt_data;
00277 
00278   /* States of the various parsing groups.  */
00279   struct group *groups;
00280   /* The end of the GROUPS array.  */
00281   struct group *egroup;
00282   /* An vector containing storage for the CHILD_INPUTS field in all groups.  */
00283   void **child_inputs;
00284 
00285   /* True if we think using getopt is still useful; if false, then
00286      remaining arguments are just passed verbatim with ARGP_KEY_ARG.  This is
00287      cleared whenever getopt returns KEY_END, but may be set again if the user
00288      moves the next argument pointer backwards.  */
00289   int try_getopt;
00290 
00291   /* State block supplied to parsing routines.  */
00292   struct argp_state state;
00293 
00294   /* Memory used by this parser.  */
00295   void *storage;
00296 };
00297 
00298 /* The next usable entries in the various parser tables being filled in by
00299    convert_options.  */
00300 struct parser_convert_state
00301 {
00302   struct parser *parser;
00303   char *short_end;
00304   struct option *long_end;
00305   void **child_inputs_end;
00306 };
00307 
00308 /* Converts all options in ARGP (which is put in GROUP) and ancestors
00309    into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and
00310    CVT->LONG_END are the points at which new options are added.  Returns the
00311    next unused group entry.  CVT holds state used during the conversion.  */
00312 static struct group *
00313 convert_options (const struct argp *argp,
00314                struct group *parent, unsigned parent_index,
00315                struct group *group, struct parser_convert_state *cvt)
00316 {
00317   /* REAL is the most recent non-alias value of OPT.  */
00318   const struct argp_option *real = argp->options;
00319   const struct argp_child *children = argp->children;
00320 
00321   if (real || argp->parser)
00322     {
00323       const struct argp_option *opt;
00324 
00325       if (real)
00326        for (opt = real; !__option_is_end (opt); opt++)
00327          {
00328            if (! (opt->flags & OPTION_ALIAS))
00329              /* OPT isn't an alias, so we can use values from it.  */
00330              real = opt;
00331 
00332            if (! (real->flags & OPTION_DOC))
00333              /* A real option (not just documentation).  */
00334              {
00335               if (__option_is_short (opt))
00336                 /* OPT can be used as a short option.  */
00337                 {
00338                   *cvt->short_end++ = opt->key;
00339                   if (real->arg)
00340                     {
00341                      *cvt->short_end++ = ':';
00342                      if (real->flags & OPTION_ARG_OPTIONAL)
00343                        *cvt->short_end++ = ':';
00344                     }
00345                   *cvt->short_end = '\0'; /* keep 0 terminated */
00346                 }
00347 
00348               if (opt->name
00349                   && find_long_option (cvt->parser->long_opts, opt->name) < 0)
00350                 /* OPT can be used as a long option.  */
00351                 {
00352                   cvt->long_end->name = opt->name;
00353                   cvt->long_end->has_arg =
00354                     (real->arg
00355                      ? (real->flags & OPTION_ARG_OPTIONAL
00356                        ? optional_argument
00357                        : required_argument)
00358                      : no_argument);
00359                   cvt->long_end->flag = 0;
00360                   /* we add a disambiguating code to all the user's
00361                      values (which is removed before we actually call
00362                      the function to parse the value); this means that
00363                      the user loses use of the high 8 bits in all his
00364                      values (the sign of the lower bits is preserved
00365                      however)...  */
00366                   cvt->long_end->val =
00367                     ((opt->key | real->key) & USER_MASK)
00368                     + (((group - cvt->parser->groups) + 1) << USER_BITS);
00369 
00370                   /* Keep the LONG_OPTS list terminated.  */
00371                   (++cvt->long_end)->name = NULL;
00372                 }
00373              }
00374            }
00375 
00376       group->parser = argp->parser;
00377       group->argp = argp;
00378       group->short_end = cvt->short_end;
00379       group->args_processed = 0;
00380       group->parent = parent;
00381       group->parent_index = parent_index;
00382       group->input = 0;
00383       group->hook = 0;
00384       group->child_inputs = 0;
00385 
00386       if (children)
00387        /* Assign GROUP's CHILD_INPUTS field some space from
00388            CVT->child_inputs_end.*/
00389        {
00390          unsigned num_children = 0;
00391          while (children[num_children].argp)
00392            num_children++;
00393          group->child_inputs = cvt->child_inputs_end;
00394          cvt->child_inputs_end += num_children;
00395        }
00396 
00397       parent = group++;
00398     }
00399   else
00400     parent = 0;
00401 
00402   if (children)
00403     {
00404       unsigned index = 0;
00405       while (children->argp)
00406        group =
00407          convert_options (children++->argp, parent, index++, group, cvt);
00408     }
00409 
00410   return group;
00411 }
00412 
00413 /* Find the merged set of getopt options, with keys appropiately prefixed. */
00414 static void
00415 parser_convert (struct parser *parser, const struct argp *argp, int flags)
00416 {
00417   struct parser_convert_state cvt;
00418 
00419   cvt.parser = parser;
00420   cvt.short_end = parser->short_opts;
00421   cvt.long_end = parser->long_opts;
00422   cvt.child_inputs_end = parser->child_inputs;
00423 
00424   if (flags & ARGP_IN_ORDER)
00425     *cvt.short_end++ = '-';
00426   else if (flags & ARGP_NO_ARGS)
00427     *cvt.short_end++ = '+';
00428   *cvt.short_end = '\0';
00429 
00430   cvt.long_end->name = NULL;
00431 
00432   parser->argp = argp;
00433 
00434   if (argp)
00435     parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt);
00436   else
00437     parser->egroup = parser->groups; /* No parsers at all! */
00438 }
00439 
00440 /* Lengths of various parser fields which we will allocated.  */
00441 struct parser_sizes
00442 {
00443   size_t short_len;         /* Getopt short options string.  */
00444   size_t long_len;          /* Getopt long options vector.  */
00445   size_t num_groups;        /* Group structures we allocate.  */
00446   size_t num_child_inputs;  /* Child input slots.  */
00447 };
00448 
00449 /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of
00450  argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by
00451  the maximum lengths of the resulting merged getopt short options string and
00452  long-options array, respectively.  */
00453 static void
00454 calc_sizes (const struct argp *argp,  struct parser_sizes *szs)
00455 {
00456   const struct argp_child *child = argp->children;
00457   const struct argp_option *opt = argp->options;
00458 
00459   if (opt || argp->parser)
00460     {
00461       szs->num_groups++;
00462       if (opt)
00463        {
00464          int num_opts = 0;
00465          while (!__option_is_end (opt++))
00466            num_opts++;
00467          szs->short_len += num_opts * 3; /* opt + up to 2 `:'s */
00468          szs->long_len += num_opts;
00469        }
00470     }
00471 
00472   if (child)
00473     while (child->argp)
00474       {
00475        calc_sizes ((child++)->argp, szs);
00476        szs->num_child_inputs++;
00477       }
00478 }
00479 
00480 /* Initializes PARSER to parse ARGP in a manner described by FLAGS.  */
00481 static error_t
00482 parser_init (struct parser *parser, const struct argp *argp,
00483             int argc, char **argv, int flags, void *input)
00484 {
00485   error_t err = 0;
00486   struct group *group;
00487   struct parser_sizes szs;
00488   struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER;
00489 
00490   szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1;
00491   szs.long_len = 0;
00492   szs.num_groups = 0;
00493   szs.num_child_inputs = 0;
00494 
00495   if (argp)
00496     calc_sizes (argp, &szs);
00497 
00498   /* Lengths of the various bits of storage used by PARSER.  */
00499 #define GLEN (szs.num_groups + 1) * sizeof (struct group)
00500 #define CLEN (szs.num_child_inputs * sizeof (void *))
00501 #define LLEN ((szs.long_len + 1) * sizeof (struct option))
00502 #define SLEN (szs.short_len + 1)
00503 
00504   parser->storage = malloc (GLEN + CLEN + LLEN + SLEN);
00505   if (! parser->storage)
00506     return ENOMEM;
00507 
00508   parser->groups = parser->storage;
00509   parser->child_inputs = parser->storage + GLEN;
00510   parser->long_opts = parser->storage + GLEN + CLEN;
00511   parser->short_opts = parser->storage + GLEN + CLEN + LLEN;
00512   parser->opt_data = opt_data;
00513 
00514   memset (parser->child_inputs, 0, szs.num_child_inputs * sizeof (void *));
00515   parser_convert (parser, argp, flags);
00516 
00517   memset (&parser->state, 0, sizeof (struct argp_state));
00518   parser->state.root_argp = parser->argp;
00519   parser->state.argc = argc;
00520   parser->state.argv = argv;
00521   parser->state.flags = flags;
00522   parser->state.err_stream = stderr;
00523   parser->state.out_stream = stdout;
00524   parser->state.next = 0;   /* Tell getopt to initialize.  */
00525   parser->state.pstate = parser;
00526 
00527   parser->try_getopt = 1;
00528 
00529   /* Call each parser for the first time, giving it a chance to propagate
00530      values to child parsers.  */
00531   if (parser->groups < parser->egroup)
00532     parser->groups->input = input;
00533   for (group = parser->groups;
00534        group < parser->egroup && (!err || err == EBADKEY);
00535        group++)
00536     {
00537       if (group->parent)
00538        /* If a child parser, get the initial input value from the parent. */
00539        group->input = group->parent->child_inputs[group->parent_index];
00540 
00541       if (!group->parser
00542          && group->argp->children && group->argp->children->argp)
00543        /* For the special case where no parsing function is supplied for an
00544           argp, propagate its input to its first child, if any (this just
00545           makes very simple wrapper argps more convenient).  */
00546        group->child_inputs[0] = group->input;
00547 
00548       err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0);
00549     }
00550   if (err == EBADKEY)
00551     err = 0;                /* Some parser didn't understand.  */
00552 
00553   if (err)
00554     return err;
00555 
00556   if (parser->state.flags & ARGP_NO_ERRS)
00557     {
00558       parser->opt_data.opterr = 0;
00559       if (parser->state.flags & ARGP_PARSE_ARGV0)
00560        /* getopt always skips ARGV[0], so we have to fake it out.  As long
00561           as OPTERR is 0, then it shouldn't actually try to access it.  */
00562        parser->state.argv--, parser->state.argc++;
00563     }
00564   else
00565     parser->opt_data.opterr = 1;   /* Print error messages.  */
00566 
00567   if (parser->state.argv == argv && argv[0])
00568     /* There's an argv[0]; use it for messages.  */
00569     {
00570       char *short_name = strrchr (argv[0], '/');
00571       parser->state.name = short_name ? short_name + 1 : argv[0];
00572     }
00573   else
00574     parser->state.name = __argp_short_program_name ();
00575 
00576   return 0;
00577 }
00578 
00579 /* Free any storage consumed by PARSER (but not PARSER itself).  */
00580 static error_t
00581 parser_finalize (struct parser *parser,
00582                error_t err, int arg_ebadkey, int *end_index)
00583 {
00584   struct group *group;
00585 
00586   if (err == EBADKEY && arg_ebadkey)
00587     /* Suppress errors generated by unparsed arguments.  */
00588     err = 0;
00589 
00590   if (! err)
00591     {
00592       if (parser->state.next == parser->state.argc)
00593        /* We successfully parsed all arguments!  Call all the parsers again,
00594           just a few more times... */
00595        {
00596          for (group = parser->groups;
00597               group < parser->egroup && (!err || err==EBADKEY);
00598               group++)
00599            if (group->args_processed == 0)
00600              err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0);
00601          for (group = parser->egroup - 1;
00602               group >= parser->groups && (!err || err==EBADKEY);
00603               group--)
00604            err = group_parse (group, &parser->state, ARGP_KEY_END, 0);
00605 
00606          if (err == EBADKEY)
00607            err = 0;         /* Some parser didn't understand.  */
00608 
00609          /* Tell the user that all arguments are parsed.  */
00610          if (end_index)
00611            *end_index = parser->state.next;
00612        }
00613       else if (end_index)
00614        /* Return any remaining arguments to the user.  */
00615        *end_index = parser->state.next;
00616       else
00617        /* No way to return the remaining arguments, they must be bogus. */
00618        {
00619          if (!(parser->state.flags & ARGP_NO_ERRS)
00620              && parser->state.err_stream)
00621            fprintf (parser->state.err_stream,
00622                    dgettext (parser->argp->argp_domain,
00623                             "%s: Too many arguments\n"),
00624                    parser->state.name);
00625          err = EBADKEY;
00626        }
00627     }
00628 
00629   /* Okay, we're all done, with either an error or success; call the parsers
00630      to indicate which one.  */
00631 
00632   if (err)
00633     {
00634       /* Maybe print an error message.  */
00635       if (err == EBADKEY)
00636        /* An appropriate message describing what the error was should have
00637           been printed earlier.  */
00638        __argp_state_help (&parser->state, parser->state.err_stream,
00639                         ARGP_HELP_STD_ERR);
00640 
00641       /* Since we didn't exit, give each parser an error indication.  */
00642       for (group = parser->groups; group < parser->egroup; group++)
00643        group_parse (group, &parser->state, ARGP_KEY_ERROR, 0);
00644     }
00645   else
00646     /* Notify parsers of success, and propagate back values from parsers.  */
00647     {
00648       /* We pass over the groups in reverse order so that child groups are
00649         given a chance to do there processing before passing back a value to
00650         the parent.  */
00651       for (group = parser->egroup - 1
00652           ; group >= parser->groups && (!err || err == EBADKEY)
00653           ; group--)
00654        err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0);
00655       if (err == EBADKEY)
00656        err = 0;             /* Some parser didn't understand.  */
00657     }
00658 
00659   /* Call parsers once more, to do any final cleanup.  Errors are ignored.  */
00660   for (group = parser->egroup - 1; group >= parser->groups; group--)
00661     group_parse (group, &parser->state, ARGP_KEY_FINI, 0);
00662 
00663   if (err == EBADKEY)
00664     err = EINVAL;
00665 
00666   free (parser->storage);
00667 
00668   return err;
00669 }
00670 
00671 /* Call the user parsers to parse the non-option argument VAL, at the current
00672    position, returning any error.  The state NEXT pointer is assumed to have
00673    been adjusted (by getopt) to point after this argument; this function will
00674    adjust it correctly to reflect however many args actually end up being
00675    consumed.  */
00676 static error_t
00677 parser_parse_arg (struct parser *parser, char *val)
00678 {
00679   /* Save the starting value of NEXT, first adjusting it so that the arg
00680      we're parsing is again the front of the arg vector.  */
00681   int index = --parser->state.next;
00682   error_t err = EBADKEY;
00683   struct group *group;
00684   int key = 0;                     /* Which of ARGP_KEY_ARG[S] we used.  */
00685 
00686   /* Try to parse the argument in each parser.  */
00687   for (group = parser->groups
00688        ; group < parser->egroup && err == EBADKEY
00689        ; group++)
00690     {
00691       parser->state.next++; /* For ARGP_KEY_ARG, consume the arg.  */
00692       key = ARGP_KEY_ARG;
00693       err = group_parse (group, &parser->state, key, val);
00694 
00695       if (err == EBADKEY)
00696        /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */
00697        {
00698          parser->state.next--;     /* For ARGP_KEY_ARGS, put back the arg.  */
00699          key = ARGP_KEY_ARGS;
00700          err = group_parse (group, &parser->state, key, 0);
00701        }
00702     }
00703 
00704   if (! err)
00705     {
00706       if (key == ARGP_KEY_ARGS)
00707        /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't
00708           changed by the user, *all* arguments should be considered
00709           consumed.  */
00710        parser->state.next = parser->state.argc;
00711 
00712       if (parser->state.next > index)
00713        /* Remember that we successfully processed a non-option
00714           argument -- but only if the user hasn't gotten tricky and set
00715           the clock back.  */
00716        (--group)->args_processed += (parser->state.next - index);
00717       else
00718        /* The user wants to reparse some args, give getopt another try.  */
00719        parser->try_getopt = 1;
00720     }
00721 
00722   return err;
00723 }
00724 
00725 /* Call the user parsers to parse the option OPT, with argument VAL, at the
00726    current position, returning any error.  */
00727 static error_t
00728 parser_parse_opt (struct parser *parser, int opt, char *val)
00729 {
00730   /* The group key encoded in the high bits; 0 for short opts or
00731      group_number + 1 for long opts.  */
00732   int group_key = opt >> USER_BITS;
00733   error_t err = EBADKEY;
00734 
00735   if (group_key == 0)
00736     /* A short option.  By comparing OPT's position in SHORT_OPTS to the
00737        various starting positions in each group's SHORT_END field, we can
00738        determine which group OPT came from.  */
00739     {
00740       struct group *group;
00741       char *short_index = strchr (parser->short_opts, opt);
00742 
00743       if (short_index)
00744        for (group = parser->groups; group < parser->egroup; group++)
00745          if (group->short_end > short_index)
00746            {
00747              err = group_parse (group, &parser->state, opt,
00748                              parser->opt_data.optarg);
00749              break;
00750            }
00751     }
00752   else
00753     /* A long option.  We use shifts instead of masking for extracting
00754        the user value in order to preserve the sign.  */
00755     err =
00756       group_parse (&parser->groups[group_key - 1], &parser->state,
00757                  (opt << GROUP_BITS) >> GROUP_BITS,
00758                  parser->opt_data.optarg);
00759 
00760   if (err == EBADKEY)
00761     /* At least currently, an option not recognized is an error in the
00762        parser, because we pre-compute which parser is supposed to deal
00763        with each option.  */
00764     {
00765       static const char bad_key_err[] =
00766        N_("(PROGRAM ERROR) Option should have been recognized!?");
00767       if (group_key == 0)
00768        __argp_error (&parser->state, "-%c: %s", opt,
00769                     dgettext (parser->argp->argp_domain, bad_key_err));
00770       else
00771        {
00772          struct option *long_opt = parser->long_opts;
00773          while (long_opt->val != opt && long_opt->name)
00774            long_opt++;
00775          __argp_error (&parser->state, "--%s: %s",
00776                      long_opt->name ? long_opt->name : "???",
00777                      dgettext (parser->argp->argp_domain, bad_key_err));
00778        }
00779     }
00780 
00781   return err;
00782 }
00783 
00784 /* Parse the next argument in PARSER (as indicated by PARSER->state.next).
00785    Any error from the parsers is returned, and *ARGP_EBADKEY indicates
00786    whether a value of EBADKEY is due to an unrecognized argument (which is
00787    generally not fatal).  */
00788 static error_t
00789 parser_parse_next (struct parser *parser, int *arg_ebadkey)
00790 {
00791   int opt;
00792   error_t err = 0;
00793 
00794   if (parser->state.quoted && parser->state.next < parser->state.quoted)
00795     /* The next argument pointer has been moved to before the quoted
00796        region, so pretend we never saw the quoting `--', and give getopt
00797        another chance.  If the user hasn't removed it, getopt will just
00798        process it again.  */
00799     parser->state.quoted = 0;
00800 
00801   if (parser->try_getopt && !parser->state.quoted)
00802     /* Give getopt a chance to parse this.  */
00803     {
00804       /* Put it back in OPTIND for getopt.  */
00805       parser->opt_data.optind = parser->state.next;
00806       /* Distinguish KEY_ERR from a real option.  */
00807       parser->opt_data.optopt = KEY_END;
00808       if (parser->state.flags & ARGP_LONG_ONLY)
00809        opt = _getopt_long_only_r (parser->state.argc, parser->state.argv,
00810                                parser->short_opts, parser->long_opts, 0,
00811                                &parser->opt_data);
00812       else
00813        opt = _getopt_long_r (parser->state.argc, parser->state.argv,
00814                            parser->short_opts, parser->long_opts, 0,
00815                            &parser->opt_data);
00816       /* And see what getopt did.  */
00817       parser->state.next = parser->opt_data.optind;
00818 
00819       if (opt == KEY_END)
00820        /* Getopt says there are no more options, so stop using
00821           getopt; we'll continue if necessary on our own.  */
00822        {
00823          parser->try_getopt = 0;
00824          if (parser->state.next > 1
00825              && strcmp (parser->state.argv[parser->state.next - 1], QUOTE)
00826                   == 0)
00827            /* Not only is this the end of the options, but it's a
00828               `quoted' region, which may have args that *look* like
00829               options, so we definitely shouldn't try to use getopt past
00830               here, whatever happens.  */
00831            parser->state.quoted = parser->state.next;
00832        }
00833       else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END)
00834        /* KEY_ERR can have the same value as a valid user short
00835           option, but in the case of a real error, getopt sets OPTOPT
00836           to the offending character, which can never be KEY_END.  */
00837        {
00838          *arg_ebadkey = 0;
00839          return EBADKEY;
00840        }
00841     }
00842   else
00843     opt = KEY_END;
00844 
00845   if (opt == KEY_END)
00846     {
00847       /* We're past what getopt considers the options.  */
00848       if (parser->state.next >= parser->state.argc
00849          || (parser->state.flags & ARGP_NO_ARGS))
00850        /* Indicate that we're done.  */
00851        {
00852          *arg_ebadkey = 1;
00853          return EBADKEY;
00854        }
00855       else
00856        /* A non-option arg; simulate what getopt might have done.  */
00857        {
00858          opt = KEY_ARG;
00859          parser->opt_data.optarg = parser->state.argv[parser->state.next++];
00860        }
00861     }
00862 
00863   if (opt == KEY_ARG)
00864     /* A non-option argument; try each parser in turn.  */
00865     err = parser_parse_arg (parser, parser->opt_data.optarg);
00866   else
00867     err = parser_parse_opt (parser, opt, parser->opt_data.optarg);
00868 
00869   if (err == EBADKEY)
00870     *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG);
00871 
00872   return err;
00873 }
00874 
00875 /* Parse the options strings in ARGC & ARGV according to the argp in ARGP.
00876    FLAGS is one of the ARGP_ flags above.  If END_INDEX is non-NULL, the
00877    index in ARGV of the first unparsed option is returned in it.  If an
00878    unknown option is present, EINVAL is returned; if some parser routine
00879    returned a non-zero value, it is returned; otherwise 0 is returned.  */
00880 error_t
00881 __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags,
00882              int *end_index, void *input)
00883 {
00884   error_t err;
00885   struct parser parser;
00886 
00887   /* If true, then err == EBADKEY is a result of a non-option argument failing
00888      to be parsed (which in some cases isn't actually an error).  */
00889   int arg_ebadkey = 0;
00890 
00891   if (! (flags & ARGP_NO_HELP))
00892     /* Add our own options.  */
00893     {
00894       struct argp_child *child = alloca (4 * sizeof (struct argp_child));
00895       struct argp *top_argp = alloca (sizeof (struct argp));
00896 
00897       /* TOP_ARGP has no options, it just serves to group the user & default
00898         argps.  */
00899       memset (top_argp, 0, sizeof (*top_argp));
00900       top_argp->children = child;
00901 
00902       memset (child, 0, 4 * sizeof (struct argp_child));
00903 
00904       if (argp)
00905        (child++)->argp = argp;
00906       (child++)->argp = &argp_default_argp;
00907       if (argp_program_version || argp_program_version_hook)
00908        (child++)->argp = &argp_version_argp;
00909       child->argp = 0;
00910 
00911       argp = top_argp;
00912     }
00913 
00914   /* Construct a parser for these arguments.  */
00915   err = parser_init (&parser, argp, argc, argv, flags, input);
00916 
00917   if (! err)
00918     /* Parse! */
00919     {
00920       while (! err)
00921        err = parser_parse_next (&parser, &arg_ebadkey);
00922       err = parser_finalize (&parser, err, arg_ebadkey, end_index);
00923     }
00924 
00925   return err;
00926 }
00927 #ifdef weak_alias
00928 weak_alias (__argp_parse, argp_parse)
00929 #endif
00930 
00931 /* Return the input field for ARGP in the parser corresponding to STATE; used
00932    by the help routines.  */
00933 void *
00934 __argp_input (const struct argp *argp, const struct argp_state *state)
00935 {
00936   if (state)
00937     {
00938       struct group *group;
00939       struct parser *parser = state->pstate;
00940 
00941       for (group = parser->groups; group < parser->egroup; group++)
00942        if (group->argp == argp)
00943          return group->input;
00944     }
00945 
00946   return 0;
00947 }
00948 #ifdef weak_alias
00949 weak_alias (__argp_input, _argp_input)
00950 #endif