argp-parse.c 28 KB

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