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