getopt.c 32 KB

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