argp-parse.c 30 KB

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