getopt.c 30 KB

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