getopt.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. /* Getopt for GNU.
  2. NOTE: getopt is now part of the C library, so if you don't know what
  3. "Keep this file name-space clean" means, talk to drepper@gnu.org
  4. before changing it!
  5. Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
  6. 1996, 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation,
  7. Inc.
  8. This file is part of the GNU C Library.
  9. This program is free software; you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation; either version 2, or (at your option)
  12. any later version.
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. GNU General Public License for more details.
  17. You should have received a copy of the GNU General Public License along
  18. with this program; if not, write to the Free Software Foundation,
  19. Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  20. /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
  21. Ditto for AIX 3.2 and <stdlib.h>. */
  22. #ifndef _NO_PROTO
  23. # define _NO_PROTO
  24. #endif
  25. #ifdef HAVE_CONFIG_H
  26. # include <config.h>
  27. #endif
  28. #include <stdio.h>
  29. /* Comment out all this code if we are using the GNU C Library, and are not
  30. actually compiling the library itself. This code is part of the GNU C
  31. Library, but also included in many other GNU distributions. Compiling
  32. and linking in this code is a waste when using the GNU C library
  33. (especially if it is a shared library). Rather than having every GNU
  34. program understand `configure --with-gnu-libc' and omit the object files,
  35. it is simpler to just do this in the source for each such file. */
  36. #define GETOPT_INTERFACE_VERSION 2
  37. #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
  38. # include <gnu-versions.h>
  39. # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
  40. # define ELIDE_CODE
  41. # endif
  42. #endif
  43. #ifndef ELIDE_CODE
  44. /* This needs to come after some library #include
  45. to get __GNU_LIBRARY__ defined. */
  46. #ifdef __GNU_LIBRARY__
  47. /* Don't include stdlib.h for non-GNU C libraries because some of them
  48. contain conflicting prototypes for getopt. */
  49. # include <stdlib.h>
  50. # include <unistd.h>
  51. #endif /* GNU C library. */
  52. #include <string.h>
  53. #ifdef VMS
  54. # include <unixlib.h>
  55. #endif
  56. #ifdef _LIBC
  57. # include <libintl.h>
  58. #else
  59. /* This is for other GNU distributions with internationalized messages. */
  60. # include "gettext.h"
  61. #endif
  62. #define _(msgid) gettext (msgid)
  63. #if defined _LIBC && defined USE_IN_LIBIO
  64. # include <wchar.h>
  65. #endif
  66. #ifndef attribute_hidden
  67. # define attribute_hidden
  68. #endif
  69. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  70. but it behaves differently for the user, since it allows the user
  71. to intersperse the options with the other arguments.
  72. As `getopt' works, it permutes the elements of ARGV so that,
  73. when it is done, all the options precede everything else. Thus
  74. all application programs are extended to handle flexible argument order.
  75. Setting the environment variable POSIXLY_CORRECT disables permutation.
  76. Then the behavior is completely standard.
  77. GNU application programs can use a third alternative mode in which
  78. they can distinguish the relative order of options and other arguments. */
  79. #include "getopt.h"
  80. /* For communication from `getopt' to the caller.
  81. When `getopt' finds an option that takes an argument,
  82. the argument value is returned here.
  83. Also, when `ordering' is RETURN_IN_ORDER,
  84. each non-option ARGV-element is returned here. */
  85. char *optarg;
  86. /* Index in ARGV of the next element to be scanned.
  87. This is used for communication to and from the caller
  88. and for communication between successive calls to `getopt'.
  89. On entry to `getopt', zero means this is the first call; initialize.
  90. When `getopt' returns -1, this is the index of the first of the
  91. non-option elements that the caller should itself scan.
  92. Otherwise, `optind' communicates from one call to the next
  93. how much of ARGV has been scanned so far. */
  94. /* 1003.2 says this must be 1 before any call. */
  95. int optind = 1;
  96. /* Formerly, initialization of getopt depended on optind==0, which
  97. causes problems with re-calling getopt as programs generally don't
  98. know that. */
  99. int __getopt_initialized attribute_hidden;
  100. /* The next char to be scanned in the option-element
  101. in which the last option character we returned was found.
  102. This allows us to pick up the scan where we left off.
  103. If this is zero, or a null string, it means resume the scan
  104. by advancing to the next ARGV-element. */
  105. static char *nextchar;
  106. /* Callers store zero here to inhibit the error message
  107. for unrecognized options. */
  108. int opterr = 1;
  109. /* Set to an option character which was unrecognized.
  110. This must be initialized on some systems to avoid linking in the
  111. system's own getopt implementation. */
  112. int optopt = '?';
  113. /* Describe how to deal with options that follow non-option ARGV-elements.
  114. If the caller did not specify anything,
  115. the default is REQUIRE_ORDER if the environment variable
  116. POSIXLY_CORRECT is defined, PERMUTE otherwise.
  117. REQUIRE_ORDER means don't recognize them as options;
  118. stop option processing when the first non-option is seen.
  119. This is what Unix does.
  120. This mode of operation is selected by either setting the environment
  121. variable POSIXLY_CORRECT, or using `+' as the first character
  122. of the list of option characters.
  123. PERMUTE is the default. We permute the contents of ARGV as we scan,
  124. so that eventually all the non-options are at the end. This allows options
  125. to be given in any order, even with programs that were not written to
  126. expect this.
  127. RETURN_IN_ORDER is an option available to programs that were written
  128. to expect options and other ARGV-elements in any order and that care about
  129. the ordering of the two. We describe each non-option ARGV-element
  130. as if it were the argument of an option with character code 1.
  131. Using `-' as the first character of the list of option characters
  132. selects this mode of operation.
  133. The special argument `--' forces an end of option-scanning regardless
  134. of the value of `ordering'. In the case of RETURN_IN_ORDER, only
  135. `--' can cause `getopt' to return -1 with `optind' != ARGC. */
  136. static enum
  137. {
  138. REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  139. } ordering;
  140. /* Value of POSIXLY_CORRECT environment variable. */
  141. static char *posixly_correct;
  142. #ifndef __GNU_LIBRARY__
  143. /* Avoid depending on library functions or files
  144. whose names are inconsistent. */
  145. #ifndef getenv
  146. extern char *getenv ();
  147. #endif
  148. #endif /* not __GNU_LIBRARY__ */
  149. /* Handle permutation of arguments. */
  150. /* Describe the part of ARGV that contains non-options that have
  151. been skipped. `first_nonopt' is the index in ARGV of the first of them;
  152. `last_nonopt' is the index after the last of them. */
  153. static int first_nonopt;
  154. static int last_nonopt;
  155. #ifdef _LIBC
  156. /* Stored original parameters.
  157. XXX This is no good solution. We should rather copy the args so
  158. that we can compare them later. But we must not use malloc(3). */
  159. extern int __libc_argc;
  160. extern char **__libc_argv;
  161. /* Bash 2.0 gives us an environment variable containing flags
  162. indicating ARGV elements that should not be considered arguments. */
  163. # ifdef USE_NONOPTION_FLAGS
  164. /* Defined in getopt_init.c */
  165. extern char *__getopt_nonoption_flags;
  166. static int nonoption_flags_max_len;
  167. static int nonoption_flags_len;
  168. # endif
  169. # ifdef USE_NONOPTION_FLAGS
  170. # define SWAP_FLAGS(ch1, ch2) \
  171. if (nonoption_flags_len > 0) \
  172. { \
  173. char __tmp = __getopt_nonoption_flags[ch1]; \
  174. __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
  175. __getopt_nonoption_flags[ch2] = __tmp; \
  176. }
  177. # else
  178. # define SWAP_FLAGS(ch1, ch2)
  179. # endif
  180. #else /* !_LIBC */
  181. # define SWAP_FLAGS(ch1, ch2)
  182. #endif /* _LIBC */
  183. /* Exchange two adjacent subsequences of ARGV.
  184. One subsequence is elements [first_nonopt,last_nonopt)
  185. which contains all the non-options that have been skipped so far.
  186. The other is elements [last_nonopt,optind), which contains all
  187. the options processed since those non-options were skipped.
  188. `first_nonopt' and `last_nonopt' are relocated so that they describe
  189. the new indices of the non-options in ARGV after they are moved. */
  190. static void
  191. exchange (char **argv)
  192. {
  193. int bottom = first_nonopt;
  194. int middle = last_nonopt;
  195. int top = optind;
  196. char *tem;
  197. /* Exchange the shorter segment with the far end of the longer segment.
  198. That puts the shorter segment into the right place.
  199. It leaves the longer segment in the right place overall,
  200. but it consists of two parts that need to be swapped next. */
  201. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  202. /* First make sure the handling of the `__getopt_nonoption_flags'
  203. string can work normally. Our top argument must be in the range
  204. of the string. */
  205. if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
  206. {
  207. /* We must extend the array. The user plays games with us and
  208. presents new arguments. */
  209. char *new_str = malloc (top + 1);
  210. if (new_str == NULL)
  211. nonoption_flags_len = nonoption_flags_max_len = 0;
  212. else
  213. {
  214. memset (__mempcpy (new_str, __getopt_nonoption_flags,
  215. nonoption_flags_max_len),
  216. '\0', top + 1 - nonoption_flags_max_len);
  217. nonoption_flags_max_len = top + 1;
  218. __getopt_nonoption_flags = new_str;
  219. }
  220. }
  221. #endif
  222. while (top > middle && middle > bottom)
  223. {
  224. if (top - middle > middle - bottom)
  225. {
  226. /* Bottom segment is the short one. */
  227. int len = middle - bottom;
  228. register int i;
  229. /* Swap it with the top part of the top segment. */
  230. for (i = 0; i < len; i++)
  231. {
  232. tem = argv[bottom + i];
  233. argv[bottom + i] = argv[top - (middle - bottom) + i];
  234. argv[top - (middle - bottom) + i] = tem;
  235. SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  236. }
  237. /* Exclude the moved bottom segment from further swapping. */
  238. top -= len;
  239. }
  240. else
  241. {
  242. /* Top segment is the short one. */
  243. int len = top - middle;
  244. register int i;
  245. /* Swap it with the bottom part of the bottom segment. */
  246. for (i = 0; i < len; i++)
  247. {
  248. tem = argv[bottom + i];
  249. argv[bottom + i] = argv[middle + i];
  250. argv[middle + i] = tem;
  251. SWAP_FLAGS (bottom + i, middle + i);
  252. }
  253. /* Exclude the moved top segment from further swapping. */
  254. bottom += len;
  255. }
  256. }
  257. /* Update records for the slots the non-options now occupy. */
  258. first_nonopt += (optind - last_nonopt);
  259. last_nonopt = optind;
  260. }
  261. /* Initialize the internal data when the first call is made. */
  262. static const char *
  263. _getopt_initialize (int argc, char *const *argv, const char *optstring)
  264. {
  265. /* Start processing options with ARGV-element 1 (since ARGV-element 0
  266. is the program name); the sequence of previously skipped
  267. non-option ARGV-elements is empty. */
  268. first_nonopt = last_nonopt = optind;
  269. nextchar = NULL;
  270. posixly_correct = getenv ("POSIXLY_CORRECT");
  271. /* Determine how to handle the ordering of options and nonoptions. */
  272. if (optstring[0] == '-')
  273. {
  274. ordering = RETURN_IN_ORDER;
  275. ++optstring;
  276. }
  277. else if (optstring[0] == '+')
  278. {
  279. ordering = REQUIRE_ORDER;
  280. ++optstring;
  281. }
  282. else if (posixly_correct != NULL)
  283. ordering = REQUIRE_ORDER;
  284. else
  285. ordering = PERMUTE;
  286. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  287. if (posixly_correct == NULL
  288. && argc == __libc_argc && argv == __libc_argv)
  289. {
  290. if (nonoption_flags_max_len == 0)
  291. {
  292. if (__getopt_nonoption_flags == NULL
  293. || __getopt_nonoption_flags[0] == '\0')
  294. nonoption_flags_max_len = -1;
  295. else
  296. {
  297. const char *orig_str = __getopt_nonoption_flags;
  298. int len = nonoption_flags_max_len = strlen (orig_str);
  299. if (nonoption_flags_max_len < argc)
  300. nonoption_flags_max_len = argc;
  301. __getopt_nonoption_flags =
  302. (char *) malloc (nonoption_flags_max_len);
  303. if (__getopt_nonoption_flags == NULL)
  304. nonoption_flags_max_len = -1;
  305. else
  306. memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
  307. '\0', nonoption_flags_max_len - len);
  308. }
  309. }
  310. nonoption_flags_len = nonoption_flags_max_len;
  311. }
  312. else
  313. nonoption_flags_len = 0;
  314. #endif
  315. return optstring;
  316. }
  317. /* Scan elements of ARGV (whose length is ARGC) for option characters
  318. given in OPTSTRING.
  319. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  320. then it is an option element. The characters of this element
  321. (aside from the initial '-') are option characters. If `getopt'
  322. is called repeatedly, it returns successively each of the option characters
  323. from each of the option elements.
  324. If `getopt' finds another option character, it returns that character,
  325. updating `optind' and `nextchar' so that the next call to `getopt' can
  326. resume the scan with the following option character or ARGV-element.
  327. If there are no more option characters, `getopt' returns -1.
  328. Then `optind' is the index in ARGV of the first ARGV-element
  329. that is not an option. (The ARGV-elements have been permuted
  330. so that those that are not options now come last.)
  331. OPTSTRING is a string containing the legitimate option characters.
  332. If an option character is seen that is not listed in OPTSTRING,
  333. return '?' after printing an error message. If you set `opterr' to
  334. zero, the error message is suppressed but we still return '?'.
  335. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  336. so the following text in the same ARGV-element, or the text of the following
  337. ARGV-element, is returned in `optarg'. Two colons mean an option that
  338. wants an optional arg; if there is text in the current ARGV-element,
  339. it is returned in `optarg', otherwise `optarg' is set to zero.
  340. If OPTSTRING starts with `-' or `+', it requests different methods of
  341. handling the non-option ARGV-elements.
  342. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  343. Long-named options begin with `--' instead of `-'.
  344. Their names may be abbreviated as long as the abbreviation is unique
  345. or is an exact match for some defined option. If they have an
  346. argument, it follows the option name in the same ARGV-element, separated
  347. from the option name by a `=', or else the in next ARGV-element.
  348. When `getopt' finds a long-named option, it returns 0 if that option's
  349. `flag' field is nonzero, the value of the option's `val' field
  350. if the `flag' field is zero.
  351. The elements of ARGV aren't really const, because we permute them.
  352. But we pretend they're const in the prototype to be compatible
  353. with other systems.
  354. LONGOPTS is a vector of `struct option' terminated by an
  355. element containing a name which is zero.
  356. LONGIND returns the index in LONGOPT of the long-named option found.
  357. It is only valid when a long-named option has been found by the most
  358. recent call.
  359. If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  360. long-named options. */
  361. int
  362. _getopt_internal (int argc, char *const *argv,
  363. const char *optstring, const struct option *longopts,
  364. int *longind, int long_only)
  365. {
  366. int print_errors = opterr;
  367. if (optstring[0] == ':')
  368. print_errors = 0;
  369. if (argc < 1)
  370. return -1;
  371. optarg = NULL;
  372. if (optind == 0 || !__getopt_initialized)
  373. {
  374. if (optind == 0)
  375. optind = 1; /* Don't scan ARGV[0], the program name. */
  376. optstring = _getopt_initialize (argc, argv, optstring);
  377. __getopt_initialized = 1;
  378. }
  379. /* Test whether ARGV[optind] points to a non-option argument.
  380. Either it does not have option syntax, or there is an environment flag
  381. from the shell indicating it is not an option. The later information
  382. is only used when the used in the GNU libc. */
  383. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  384. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
  385. || (optind < nonoption_flags_len \
  386. && __getopt_nonoption_flags[optind] == '1'))
  387. #else
  388. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
  389. #endif
  390. if (nextchar == NULL || *nextchar == '\0')
  391. {
  392. /* Advance to the next ARGV-element. */
  393. /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  394. moved back by the user (who may also have changed the arguments). */
  395. if (last_nonopt > optind)
  396. last_nonopt = optind;
  397. if (first_nonopt > optind)
  398. first_nonopt = optind;
  399. if (ordering == PERMUTE)
  400. {
  401. /* If we have just processed some options following some non-options,
  402. exchange them so that the options come first. */
  403. if (first_nonopt != last_nonopt && last_nonopt != optind)
  404. exchange ((char **) argv);
  405. else if (last_nonopt != optind)
  406. first_nonopt = optind;
  407. /* Skip any additional non-options
  408. and extend the range of non-options previously skipped. */
  409. while (optind < argc && NONOPTION_P)
  410. optind++;
  411. last_nonopt = optind;
  412. }
  413. /* The special ARGV-element `--' means premature end of options.
  414. Skip it like a null option,
  415. then exchange with previous non-options as if it were an option,
  416. then skip everything else like a non-option. */
  417. if (optind != argc && !strcmp (argv[optind], "--"))
  418. {
  419. optind++;
  420. if (first_nonopt != last_nonopt && last_nonopt != optind)
  421. exchange ((char **) argv);
  422. else if (first_nonopt == last_nonopt)
  423. first_nonopt = optind;
  424. last_nonopt = argc;
  425. optind = argc;
  426. }
  427. /* If we have done all the ARGV-elements, stop the scan
  428. and back over any non-options that we skipped and permuted. */
  429. if (optind == argc)
  430. {
  431. /* Set the next-arg-index to point at the non-options
  432. that we previously skipped, so the caller will digest them. */
  433. if (first_nonopt != last_nonopt)
  434. optind = first_nonopt;
  435. return -1;
  436. }
  437. /* If we have come to a non-option and did not permute it,
  438. either stop the scan or describe it to the caller and pass it by. */
  439. if (NONOPTION_P)
  440. {
  441. if (ordering == REQUIRE_ORDER)
  442. return -1;
  443. optarg = argv[optind++];
  444. return 1;
  445. }
  446. /* We have found another option-ARGV-element.
  447. Skip the initial punctuation. */
  448. nextchar = (argv[optind] + 1
  449. + (longopts != NULL && argv[optind][1] == '-'));
  450. }
  451. /* Decode the current option-ARGV-element. */
  452. /* Check whether the ARGV-element is a long option.
  453. If long_only and the ARGV-element has the form "-f", where f is
  454. a valid short option, don't consider it an abbreviated form of
  455. a long option that starts with f. Otherwise there would be no
  456. way to give the -f short option.
  457. On the other hand, if there's a long option "fubar" and
  458. the ARGV-element is "-fu", do consider that an abbreviation of
  459. the long option, just like "--fu", and not "-f" with arg "u".
  460. This distinction seems to be the most useful approach. */
  461. if (longopts != NULL
  462. && (argv[optind][1] == '-'
  463. || (long_only
  464. && (argv[optind][2] || !strchr (optstring, argv[optind][1])))))
  465. {
  466. char *nameend;
  467. const struct option *p;
  468. const struct option *pfound = NULL;
  469. int exact = 0;
  470. int ambig = 0;
  471. int indfound = -1;
  472. int option_index;
  473. for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
  474. /* Do nothing. */ ;
  475. /* Test all long options for either exact match
  476. or abbreviated matches. */
  477. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  478. if (!strncmp (p->name, nextchar, nameend - nextchar))
  479. {
  480. if ((unsigned int) (nameend - nextchar)
  481. == (unsigned int) strlen (p->name))
  482. {
  483. /* Exact match found. */
  484. pfound = p;
  485. indfound = option_index;
  486. exact = 1;
  487. break;
  488. }
  489. else if (pfound == NULL)
  490. {
  491. /* First nonexact match found. */
  492. pfound = p;
  493. indfound = option_index;
  494. }
  495. else if (long_only
  496. || pfound->has_arg != p->has_arg
  497. || pfound->flag != p->flag
  498. || pfound->val != p->val)
  499. /* Second or later nonexact match found. */
  500. ambig = 1;
  501. }
  502. if (ambig && !exact)
  503. {
  504. if (print_errors)
  505. {
  506. #if defined _LIBC && defined USE_IN_LIBIO
  507. char *buf;
  508. if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
  509. argv[0], argv[optind]) >= 0)
  510. {
  511. if (_IO_fwide (stderr, 0) > 0)
  512. __fwprintf (stderr, L"%s", buf);
  513. else
  514. fputs (buf, stderr);
  515. free (buf);
  516. }
  517. #else
  518. fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
  519. argv[0], argv[optind]);
  520. #endif
  521. }
  522. nextchar += strlen (nextchar);
  523. optind++;
  524. optopt = 0;
  525. return '?';
  526. }
  527. if (pfound != NULL)
  528. {
  529. option_index = indfound;
  530. optind++;
  531. if (*nameend)
  532. {
  533. /* Don't test has_arg with >, because some C compilers don't
  534. allow it to be used on enums. */
  535. if (pfound->has_arg)
  536. optarg = nameend + 1;
  537. else
  538. {
  539. if (print_errors)
  540. {
  541. #if defined _LIBC && defined USE_IN_LIBIO
  542. char *buf;
  543. int n;
  544. #endif
  545. if (argv[optind - 1][1] == '-')
  546. {
  547. /* --option */
  548. #if defined _LIBC && defined USE_IN_LIBIO
  549. n = __asprintf (&buf, _("\
  550. %s: option `--%s' doesn't allow an argument\n"),
  551. argv[0], pfound->name);
  552. #else
  553. fprintf (stderr, _("\
  554. %s: option `--%s' doesn't allow an argument\n"),
  555. argv[0], pfound->name);
  556. #endif
  557. }
  558. else
  559. {
  560. /* +option or -option */
  561. #if defined _LIBC && defined USE_IN_LIBIO
  562. n = __asprintf (&buf, _("\
  563. %s: option `%c%s' doesn't allow an argument\n"),
  564. argv[0], argv[optind - 1][0],
  565. pfound->name);
  566. #else
  567. fprintf (stderr, _("\
  568. %s: option `%c%s' doesn't allow an argument\n"),
  569. argv[0], argv[optind - 1][0], pfound->name);
  570. #endif
  571. }
  572. #if defined _LIBC && defined USE_IN_LIBIO
  573. if (n >= 0)
  574. {
  575. if (_IO_fwide (stderr, 0) > 0)
  576. __fwprintf (stderr, L"%s", buf);
  577. else
  578. fputs (buf, stderr);
  579. free (buf);
  580. }
  581. #endif
  582. }
  583. nextchar += strlen (nextchar);
  584. optopt = pfound->val;
  585. return '?';
  586. }
  587. }
  588. else if (pfound->has_arg == 1)
  589. {
  590. if (optind < argc)
  591. optarg = argv[optind++];
  592. else
  593. {
  594. if (print_errors)
  595. {
  596. #if defined _LIBC && defined USE_IN_LIBIO
  597. char *buf;
  598. if (__asprintf (&buf, _("\
  599. %s: option `%s' requires an argument\n"),
  600. argv[0], argv[optind - 1]) >= 0)
  601. {
  602. if (_IO_fwide (stderr, 0) > 0)
  603. __fwprintf (stderr, L"%s", buf);
  604. else
  605. fputs (buf, stderr);
  606. free (buf);
  607. }
  608. #else
  609. fprintf (stderr,
  610. _("%s: option `%s' requires an argument\n"),
  611. argv[0], argv[optind - 1]);
  612. #endif
  613. }
  614. nextchar += strlen (nextchar);
  615. optopt = pfound->val;
  616. return optstring[0] == ':' ? ':' : '?';
  617. }
  618. }
  619. nextchar += strlen (nextchar);
  620. if (longind != NULL)
  621. *longind = option_index;
  622. if (pfound->flag)
  623. {
  624. *(pfound->flag) = pfound->val;
  625. return 0;
  626. }
  627. return pfound->val;
  628. }
  629. /* Can't find it as a long option. If this is not getopt_long_only,
  630. or the option starts with '--' or is not a valid short
  631. option, then it's an error.
  632. Otherwise interpret it as a short option. */
  633. if (!long_only || argv[optind][1] == '-'
  634. || strchr (optstring, *nextchar) == NULL)
  635. {
  636. if (print_errors)
  637. {
  638. #if defined _LIBC && defined USE_IN_LIBIO
  639. char *buf;
  640. int n;
  641. #endif
  642. if (argv[optind][1] == '-')
  643. {
  644. /* --option */
  645. #if defined _LIBC && defined USE_IN_LIBIO
  646. n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
  647. argv[0], nextchar);
  648. #else
  649. fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
  650. argv[0], nextchar);
  651. #endif
  652. }
  653. else
  654. {
  655. /* +option or -option */
  656. #if defined _LIBC && defined USE_IN_LIBIO
  657. n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
  658. argv[0], argv[optind][0], nextchar);
  659. #else
  660. fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
  661. argv[0], argv[optind][0], nextchar);
  662. #endif
  663. }
  664. #if defined _LIBC && defined USE_IN_LIBIO
  665. if (n >= 0)
  666. {
  667. if (_IO_fwide (stderr, 0) > 0)
  668. __fwprintf (stderr, L"%s", buf);
  669. else
  670. fputs (buf, stderr);
  671. free (buf);
  672. }
  673. #endif
  674. }
  675. nextchar = (char *) "";
  676. optind++;
  677. optopt = 0;
  678. return '?';
  679. }
  680. }
  681. /* Look at and handle the next short option-character. */
  682. {
  683. char c = *nextchar++;
  684. char *temp = strchr (optstring, c);
  685. /* Increment `optind' when we start to process its last character. */
  686. if (*nextchar == '\0')
  687. ++optind;
  688. if (temp == NULL || c == ':')
  689. {
  690. if (print_errors)
  691. {
  692. #if defined _LIBC && defined USE_IN_LIBIO
  693. char *buf;
  694. int n;
  695. #endif
  696. if (posixly_correct)
  697. {
  698. /* 1003.2 specifies the format of this message. */
  699. #if defined _LIBC && defined USE_IN_LIBIO
  700. n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
  701. argv[0], c);
  702. #else
  703. fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
  704. #endif
  705. }
  706. else
  707. {
  708. #if defined _LIBC && defined USE_IN_LIBIO
  709. n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
  710. argv[0], c);
  711. #else
  712. fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
  713. #endif
  714. }
  715. #if defined _LIBC && defined USE_IN_LIBIO
  716. if (n >= 0)
  717. {
  718. if (_IO_fwide (stderr, 0) > 0)
  719. __fwprintf (stderr, L"%s", buf);
  720. else
  721. fputs (buf, stderr);
  722. free (buf);
  723. }
  724. #endif
  725. }
  726. optopt = c;
  727. return '?';
  728. }
  729. /* Convenience. Treat POSIX -W foo same as long option --foo */
  730. if (temp[0] == 'W' && temp[1] == ';')
  731. {
  732. char *nameend;
  733. const struct option *p;
  734. const struct option *pfound = NULL;
  735. int exact = 0;
  736. int ambig = 0;
  737. int indfound = 0;
  738. int option_index;
  739. /* This is an option that requires an argument. */
  740. if (*nextchar != '\0')
  741. {
  742. optarg = nextchar;
  743. /* If we end this ARGV-element by taking the rest as an arg,
  744. we must advance to the next element now. */
  745. optind++;
  746. }
  747. else if (optind == argc)
  748. {
  749. if (print_errors)
  750. {
  751. /* 1003.2 specifies the format of this message. */
  752. #if defined _LIBC && defined USE_IN_LIBIO
  753. char *buf;
  754. if (__asprintf (&buf,
  755. _("%s: option requires an argument -- %c\n"),
  756. argv[0], c) >= 0)
  757. {
  758. if (_IO_fwide (stderr, 0) > 0)
  759. __fwprintf (stderr, L"%s", buf);
  760. else
  761. fputs (buf, stderr);
  762. free (buf);
  763. }
  764. #else
  765. fprintf (stderr, _("%s: option requires an argument -- %c\n"),
  766. argv[0], c);
  767. #endif
  768. }
  769. optopt = c;
  770. if (optstring[0] == ':')
  771. c = ':';
  772. else
  773. c = '?';
  774. return c;
  775. }
  776. else
  777. /* We already incremented `optind' once;
  778. increment it again when taking next ARGV-elt as argument. */
  779. optarg = argv[optind++];
  780. /* optarg is now the argument, see if it's in the
  781. table of longopts. */
  782. for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
  783. /* Do nothing. */ ;
  784. /* Test all long options for either exact match
  785. or abbreviated matches. */
  786. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  787. if (!strncmp (p->name, nextchar, nameend - nextchar))
  788. {
  789. if ((unsigned int) (nameend - nextchar) == strlen (p->name))
  790. {
  791. /* Exact match found. */
  792. pfound = p;
  793. indfound = option_index;
  794. exact = 1;
  795. break;
  796. }
  797. else if (pfound == NULL)
  798. {
  799. /* First nonexact match found. */
  800. pfound = p;
  801. indfound = option_index;
  802. }
  803. else
  804. /* Second or later nonexact match found. */
  805. ambig = 1;
  806. }
  807. if (ambig && !exact)
  808. {
  809. if (print_errors)
  810. {
  811. #if defined _LIBC && defined USE_IN_LIBIO
  812. char *buf;
  813. if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
  814. argv[0], argv[optind]) >= 0)
  815. {
  816. if (_IO_fwide (stderr, 0) > 0)
  817. __fwprintf (stderr, L"%s", buf);
  818. else
  819. fputs (buf, stderr);
  820. free (buf);
  821. }
  822. #else
  823. fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
  824. argv[0], argv[optind]);
  825. #endif
  826. }
  827. nextchar += strlen (nextchar);
  828. optind++;
  829. return '?';
  830. }
  831. if (pfound != NULL)
  832. {
  833. option_index = indfound;
  834. if (*nameend)
  835. {
  836. /* Don't test has_arg with >, because some C compilers don't
  837. allow it to be used on enums. */
  838. if (pfound->has_arg)
  839. optarg = nameend + 1;
  840. else
  841. {
  842. if (print_errors)
  843. {
  844. #if defined _LIBC && defined USE_IN_LIBIO
  845. char *buf;
  846. if (__asprintf (&buf, _("\
  847. %s: option `-W %s' doesn't allow an argument\n"),
  848. argv[0], pfound->name) >= 0)
  849. {
  850. if (_IO_fwide (stderr, 0) > 0)
  851. __fwprintf (stderr, L"%s", buf);
  852. else
  853. fputs (buf, stderr);
  854. free (buf);
  855. }
  856. #else
  857. fprintf (stderr, _("\
  858. %s: option `-W %s' doesn't allow an argument\n"),
  859. argv[0], pfound->name);
  860. #endif
  861. }
  862. nextchar += strlen (nextchar);
  863. return '?';
  864. }
  865. }
  866. else if (pfound->has_arg == 1)
  867. {
  868. if (optind < argc)
  869. optarg = argv[optind++];
  870. else
  871. {
  872. if (print_errors)
  873. {
  874. #if defined _LIBC && defined USE_IN_LIBIO
  875. char *buf;
  876. if (__asprintf (&buf, _("\
  877. %s: option `%s' requires an argument\n"),
  878. argv[0], argv[optind - 1]) >= 0)
  879. {
  880. if (_IO_fwide (stderr, 0) > 0)
  881. __fwprintf (stderr, L"%s", buf);
  882. else
  883. fputs (buf, stderr);
  884. free (buf);
  885. }
  886. #else
  887. fprintf (stderr,
  888. _("%s: option `%s' requires an argument\n"),
  889. argv[0], argv[optind - 1]);
  890. #endif
  891. }
  892. nextchar += strlen (nextchar);
  893. return optstring[0] == ':' ? ':' : '?';
  894. }
  895. }
  896. nextchar += strlen (nextchar);
  897. if (longind != NULL)
  898. *longind = option_index;
  899. if (pfound->flag)
  900. {
  901. *(pfound->flag) = pfound->val;
  902. return 0;
  903. }
  904. return pfound->val;
  905. }
  906. nextchar = NULL;
  907. return 'W'; /* Let the application handle it. */
  908. }
  909. if (temp[1] == ':')
  910. {
  911. if (temp[2] == ':')
  912. {
  913. /* This is an option that accepts an argument optionally. */
  914. if (*nextchar != '\0')
  915. {
  916. optarg = nextchar;
  917. optind++;
  918. }
  919. else
  920. optarg = NULL;
  921. nextchar = NULL;
  922. }
  923. else
  924. {
  925. /* This is an option that requires an argument. */
  926. if (*nextchar != '\0')
  927. {
  928. optarg = nextchar;
  929. /* If we end this ARGV-element by taking the rest as an arg,
  930. we must advance to the next element now. */
  931. optind++;
  932. }
  933. else if (optind == argc)
  934. {
  935. if (print_errors)
  936. {
  937. /* 1003.2 specifies the format of this message. */
  938. #if defined _LIBC && defined USE_IN_LIBIO
  939. char *buf;
  940. if (__asprintf (&buf, _("\
  941. %s: option requires an argument -- %c\n"),
  942. argv[0], c) >= 0)
  943. {
  944. if (_IO_fwide (stderr, 0) > 0)
  945. __fwprintf (stderr, L"%s", buf);
  946. else
  947. fputs (buf, stderr);
  948. free (buf);
  949. }
  950. #else
  951. fprintf (stderr,
  952. _("%s: option requires an argument -- %c\n"),
  953. argv[0], c);
  954. #endif
  955. }
  956. optopt = c;
  957. if (optstring[0] == ':')
  958. c = ':';
  959. else
  960. c = '?';
  961. }
  962. else
  963. /* We already incremented `optind' once;
  964. increment it again when taking next ARGV-elt as argument. */
  965. optarg = argv[optind++];
  966. nextchar = NULL;
  967. }
  968. }
  969. return c;
  970. }
  971. }
  972. int
  973. getopt (int argc, char *const *argv, const char *optstring)
  974. {
  975. return _getopt_internal (argc, argv, optstring,
  976. (const struct option *) 0,
  977. (int *) 0,
  978. 0);
  979. }
  980. #endif /* Not ELIDE_CODE. */
  981. #ifdef TEST
  982. /* Compile with -DTEST to make an executable for use in testing
  983. the above definition of `getopt'. */
  984. int
  985. main (int argc, char **argv)
  986. {
  987. int c;
  988. int digit_optind = 0;
  989. while (1)
  990. {
  991. int this_option_optind = optind ? optind : 1;
  992. c = getopt (argc, argv, "abc:d:0123456789");
  993. if (c == -1)
  994. break;
  995. switch (c)
  996. {
  997. case '0':
  998. case '1':
  999. case '2':
  1000. case '3':
  1001. case '4':
  1002. case '5':
  1003. case '6':
  1004. case '7':
  1005. case '8':
  1006. case '9':
  1007. if (digit_optind != 0 && digit_optind != this_option_optind)
  1008. printf ("digits occur in two different argv-elements.\n");
  1009. digit_optind = this_option_optind;
  1010. printf ("option %c\n", c);
  1011. break;
  1012. case 'a':
  1013. printf ("option a\n");
  1014. break;
  1015. case 'b':
  1016. printf ("option b\n");
  1017. break;
  1018. case 'c':
  1019. printf ("option c with value `%s'\n", optarg);
  1020. break;
  1021. case '?':
  1022. break;
  1023. default:
  1024. printf ("?? getopt returned character code 0%o ??\n", c);
  1025. }
  1026. }
  1027. if (optind < argc)
  1028. {
  1029. printf ("non-option ARGV-elements: ");
  1030. while (optind < argc)
  1031. printf ("%s ", argv[optind++]);
  1032. printf ("\n");
  1033. }
  1034. exit (0);
  1035. }
  1036. #endif /* TEST */