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