argp-parse.c 31 KB

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