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