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