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