argp-parse.c 30 KB

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