argp-parse.c 28 KB

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