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