getopt.c 30 KB

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