144a8b964ed1c08e5a5e64c418ef580af51bb407
[platform/upstream/nettle.git] / getopt.c
1 /* Getopt for GNU.
2    NOTE: getopt is 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-2014 Free Software Foundation, Inc.
6    This file is part of the GNU C Library.
7
8    The GNU C Library is free software; you can redistribute it and/or
9    modify it under the terms of the GNU Lesser General Public
10    License as published by the Free Software Foundation; either
11    version 2.1 of the License, or (at your option) any later version.
12
13    The GNU C Library is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    Lesser General Public License for more details.
17
18    You should have received a copy of the GNU Lesser General Public
19    License along with the GNU C Library; if not, see
20    <http://www.gnu.org/licenses/>.  */
21 \f
22 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
23    Ditto for AIX 3.2 and <stdlib.h>.  */
24 #ifndef _NO_PROTO
25 # define _NO_PROTO
26 #endif
27
28 #ifdef HAVE_CONFIG_H
29 # include <config.h>
30 #endif
31
32 #include <stdio.h>
33
34 /* Comment out all this code if we are using the GNU C Library, and are not
35    actually compiling the library itself.  This code is part of the GNU C
36    Library, but also included in many other GNU distributions.  Compiling
37    and linking in this code is a waste when using the GNU C library
38    (especially if it is a shared library).  Rather than having every GNU
39    program understand `configure --with-gnu-libc' and omit the object files,
40    it is simpler to just do this in the source for each such file.  */
41
42 #define GETOPT_INTERFACE_VERSION 2
43 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
44 # include <gnu-versions.h>
45 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
46 #  define ELIDE_CODE
47 # endif
48 #endif
49
50 #ifndef ELIDE_CODE
51
52
53 /* This needs to come after some library #include
54    to get __GNU_LIBRARY__ defined.  */
55 #ifdef  __GNU_LIBRARY__
56 /* Don't include stdlib.h for non-GNU C libraries because some of them
57    contain conflicting prototypes for getopt.  */
58 # include <stdlib.h>
59 # include <unistd.h>
60 #endif  /* GNU C library.  */
61
62 #include <string.h>
63
64 #ifdef VMS
65 # include <unixlib.h>
66 #endif
67
68 #ifdef _LIBC
69 # include <libintl.h>
70 #else
71 /* The glibc version includes "gettext.h" here, but Nettle currently doesn't
72    have that. */
73 # define _(msgid) msgid
74 #endif
75
76 #if defined _LIBC
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           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           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, int posixly_correct)
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 = 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, int posixly_correct)
395 {
396   int print_errors = d->opterr;
397
398   if (argc < 1)
399     return -1;
400
401   d->optarg = NULL;
402
403   if (d->optind == 0 || !d->__initialized)
404     {
405       if (d->optind == 0)
406         d->optind = 1;  /* Don't scan ARGV[0], the program name.  */
407       optstring = _getopt_initialize (argc, argv, optstring, d,
408                                       posixly_correct);
409       d->__initialized = 1;
410     }
411   else if (optstring[0] == '-' || optstring[0] == '+')
412     optstring++;
413   if (optstring[0] == ':')
414     print_errors = 0;
415
416   /* Test whether ARGV[optind] points to a non-option argument.
417      Either it does not have option syntax, or there is an environment flag
418      from the shell indicating it is not an option.  The later information
419      is only used when the used in the GNU libc.  */
420 #if defined _LIBC && defined USE_NONOPTION_FLAGS
421 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
422                       || (d->optind < d->__nonoption_flags_len                \
423                           && __getopt_nonoption_flags[d->optind] == '1'))
424 #else
425 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
426 #endif
427
428   if (d->__nextchar == NULL || *d->__nextchar == '\0')
429     {
430       /* Advance to the next ARGV-element.  */
431
432       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
433          moved back by the user (who may also have changed the arguments).  */
434       if (d->__last_nonopt > d->optind)
435         d->__last_nonopt = d->optind;
436       if (d->__first_nonopt > d->optind)
437         d->__first_nonopt = d->optind;
438
439       if (d->__ordering == PERMUTE)
440         {
441           /* If we have just processed some options following some non-options,
442              exchange them so that the options come first.  */
443
444           if (d->__first_nonopt != d->__last_nonopt
445               && d->__last_nonopt != d->optind)
446             exchange ((char **) argv, d);
447           else if (d->__last_nonopt != d->optind)
448             d->__first_nonopt = d->optind;
449
450           /* Skip any additional non-options
451              and extend the range of non-options previously skipped.  */
452
453           while (d->optind < argc && NONOPTION_P)
454             d->optind++;
455           d->__last_nonopt = d->optind;
456         }
457
458       /* The special ARGV-element `--' means premature end of options.
459          Skip it like a null option,
460          then exchange with previous non-options as if it were an option,
461          then skip everything else like a non-option.  */
462
463       if (d->optind != argc && !strcmp (argv[d->optind], "--"))
464         {
465           d->optind++;
466
467           if (d->__first_nonopt != d->__last_nonopt
468               && d->__last_nonopt != d->optind)
469             exchange ((char **) argv, d);
470           else if (d->__first_nonopt == d->__last_nonopt)
471             d->__first_nonopt = d->optind;
472           d->__last_nonopt = argc;
473
474           d->optind = argc;
475         }
476
477       /* If we have done all the ARGV-elements, stop the scan
478          and back over any non-options that we skipped and permuted.  */
479
480       if (d->optind == argc)
481         {
482           /* Set the next-arg-index to point at the non-options
483              that we previously skipped, so the caller will digest them.  */
484           if (d->__first_nonopt != d->__last_nonopt)
485             d->optind = d->__first_nonopt;
486           return -1;
487         }
488
489       /* If we have come to a non-option and did not permute it,
490          either stop the scan or describe it to the caller and pass it by.  */
491
492       if (NONOPTION_P)
493         {
494           if (d->__ordering == REQUIRE_ORDER)
495             return -1;
496           d->optarg = argv[d->optind++];
497           return 1;
498         }
499
500       /* We have found another option-ARGV-element.
501          Skip the initial punctuation.  */
502
503       d->__nextchar = (argv[d->optind] + 1
504                   + (longopts != NULL && argv[d->optind][1] == '-'));
505     }
506
507   /* Decode the current option-ARGV-element.  */
508
509   /* Check whether the ARGV-element is a long option.
510
511      If long_only and the ARGV-element has the form "-f", where f is
512      a valid short option, don't consider it an abbreviated form of
513      a long option that starts with f.  Otherwise there would be no
514      way to give the -f short option.
515
516      On the other hand, if there's a long option "fubar" and
517      the ARGV-element is "-fu", do consider that an abbreviation of
518      the long option, just like "--fu", and not "-f" with arg "u".
519
520      This distinction seems to be the most useful approach.  */
521
522   if (longopts != NULL
523       && (argv[d->optind][1] == '-'
524           || (long_only && (argv[d->optind][2]
525                             || !strchr (optstring, argv[d->optind][1])))))
526     {
527       char *nameend;
528       unsigned int namelen;
529       const struct option *p;
530       const struct option *pfound = NULL;
531       struct option_list
532       {
533         const struct option *p;
534         struct option_list *next;
535       } *ambig_list = NULL;
536       int exact = 0;
537       int indfound = -1;
538       int option_index;
539
540       for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
541         /* Do nothing.  */ ;
542       namelen = nameend - d->__nextchar;
543
544       /* Test all long options for either exact match
545          or abbreviated matches.  */
546       for (p = longopts, option_index = 0; p->name; p++, option_index++)
547         if (!strncmp (p->name, d->__nextchar, namelen))
548           {
549             if (namelen == (unsigned int) strlen (p->name))
550               {
551                 /* Exact match found.  */
552                 pfound = p;
553                 indfound = option_index;
554                 exact = 1;
555                 break;
556               }
557             else if (pfound == NULL)
558               {
559                 /* First nonexact match found.  */
560                 pfound = p;
561                 indfound = option_index;
562               }
563             else if (long_only
564                      || pfound->has_arg != p->has_arg
565                      || pfound->flag != p->flag
566                      || pfound->val != p->val)
567               {
568                 /* Second or later nonexact match found.  */
569                 struct option_list *newp = alloca (sizeof (*newp));
570                 newp->p = p;
571                 newp->next = ambig_list;
572                 ambig_list = newp;
573               }
574           }
575
576       if (ambig_list != NULL && !exact)
577         {
578           if (print_errors)
579             {
580               struct option_list first;
581               first.p = pfound;
582               first.next = ambig_list;
583               ambig_list = &first;
584
585 #if defined _LIBC
586               char *buf = NULL;
587               size_t buflen = 0;
588
589               FILE *fp = open_memstream (&buf, &buflen);
590               if (fp != NULL)
591                 {
592                   fprintf (fp,
593                            _("%s: option '%s' is ambiguous; possibilities:"),
594                            argv[0], argv[d->optind]);
595
596                   do
597                     {
598                       fprintf (fp, " '--%s'", ambig_list->p->name);
599                       ambig_list = ambig_list->next;
600                     }
601                   while (ambig_list != NULL);
602
603                   fputc_unlocked ('\n', fp);
604
605                   if (__builtin_expect (fclose (fp) != EOF, 1))
606                     {
607                       _IO_flockfile (stderr);
608
609                       int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
610                       ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
611
612                       __fxprintf (NULL, "%s", buf);
613
614                       ((_IO_FILE *) stderr)->_flags2 = old_flags2;
615                       _IO_funlockfile (stderr);
616
617                       free (buf);
618                     }
619                 }
620 #else
621               fprintf (stderr,
622                        _("%s: option '%s' is ambiguous; possibilities:"),
623                        argv[0], argv[d->optind]);
624               do
625                 {
626                   fprintf (stderr, " '--%s'", ambig_list->p->name);
627                   ambig_list = ambig_list->next;
628                 }
629               while (ambig_list != NULL);
630
631               fputc ('\n', stderr);
632 #endif
633             }
634           d->__nextchar += strlen (d->__nextchar);
635           d->optind++;
636           d->optopt = 0;
637           return '?';
638         }
639
640       if (pfound != NULL)
641         {
642           option_index = indfound;
643           d->optind++;
644           if (*nameend)
645             {
646               /* Don't test has_arg with >, because some C compilers don't
647                  allow it to be used on enums.  */
648               if (pfound->has_arg)
649                 d->optarg = nameend + 1;
650               else
651                 {
652                   if (print_errors)
653                     {
654 #if defined _LIBC
655                       char *buf;
656                       int n;
657 #endif
658
659                       if (argv[d->optind - 1][1] == '-')
660                         {
661                           /* --option */
662 #if defined _LIBC
663                           n = __asprintf (&buf, _("\
664 %s: option '--%s' doesn't allow an argument\n"),
665                                           argv[0], pfound->name);
666 #else
667                           fprintf (stderr, _("\
668 %s: option '--%s' doesn't allow an argument\n"),
669                                    argv[0], pfound->name);
670 #endif
671                         }
672                       else
673                         {
674                           /* +option or -option */
675 #if defined _LIBC
676                           n = __asprintf (&buf, _("\
677 %s: option '%c%s' doesn't allow an argument\n"),
678                                           argv[0], argv[d->optind - 1][0],
679                                           pfound->name);
680 #else
681                           fprintf (stderr, _("\
682 %s: option '%c%s' doesn't allow an argument\n"),
683                                    argv[0], argv[d->optind - 1][0],
684                                    pfound->name);
685 #endif
686                         }
687
688 #if defined _LIBC
689                       if (n >= 0)
690                         {
691                           _IO_flockfile (stderr);
692
693                           int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
694                           ((_IO_FILE *) stderr)->_flags2
695                             |= _IO_FLAGS2_NOTCANCEL;
696
697                           __fxprintf (NULL, "%s", buf);
698
699                           ((_IO_FILE *) stderr)->_flags2 = old_flags2;
700                           _IO_funlockfile (stderr);
701
702                           free (buf);
703                         }
704 #endif
705                     }
706
707                   d->__nextchar += strlen (d->__nextchar);
708
709                   d->optopt = pfound->val;
710                   return '?';
711                 }
712             }
713           else if (pfound->has_arg == 1)
714             {
715               if (d->optind < argc)
716                 d->optarg = argv[d->optind++];
717               else
718                 {
719                   if (print_errors)
720                     {
721 #if defined _LIBC
722                       char *buf;
723
724                       if (__asprintf (&buf, _("\
725 %s: option '--%s' requires an argument\n"),
726                                       argv[0], pfound->name) >= 0)
727                         {
728                           _IO_flockfile (stderr);
729
730                           int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
731                           ((_IO_FILE *) stderr)->_flags2
732                             |= _IO_FLAGS2_NOTCANCEL;
733
734                           __fxprintf (NULL, "%s", buf);
735
736                           ((_IO_FILE *) stderr)->_flags2 = old_flags2;
737                           _IO_funlockfile (stderr);
738
739                           free (buf);
740                         }
741 #else
742                       fprintf (stderr,
743                                _("%s: option '--%s' requires an argument\n"),
744                                argv[0], pfound->name);
745 #endif
746                     }
747                   d->__nextchar += strlen (d->__nextchar);
748                   d->optopt = pfound->val;
749                   return optstring[0] == ':' ? ':' : '?';
750                 }
751             }
752           d->__nextchar += strlen (d->__nextchar);
753           if (longind != NULL)
754             *longind = option_index;
755           if (pfound->flag)
756             {
757               *(pfound->flag) = pfound->val;
758               return 0;
759             }
760           return pfound->val;
761         }
762
763       /* Can't find it as a long option.  If this is not getopt_long_only,
764          or the option starts with '--' or is not a valid short
765          option, then it's an error.
766          Otherwise interpret it as a short option.  */
767       if (!long_only || argv[d->optind][1] == '-'
768           || strchr (optstring, *d->__nextchar) == NULL)
769         {
770           if (print_errors)
771             {
772 #if defined _LIBC
773               char *buf;
774               int n;
775 #endif
776
777               if (argv[d->optind][1] == '-')
778                 {
779                   /* --option */
780 #if defined _LIBC
781                   n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"),
782                                   argv[0], d->__nextchar);
783 #else
784                   fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
785                            argv[0], d->__nextchar);
786 #endif
787                 }
788               else
789                 {
790                   /* +option or -option */
791 #if defined _LIBC
792                   n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"),
793                                   argv[0], argv[d->optind][0], d->__nextchar);
794 #else
795                   fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
796                            argv[0], argv[d->optind][0], d->__nextchar);
797 #endif
798                 }
799
800 #if defined _LIBC
801               if (n >= 0)
802                 {
803                   _IO_flockfile (stderr);
804
805                   int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
806                   ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
807
808                   __fxprintf (NULL, "%s", buf);
809
810                   ((_IO_FILE *) stderr)->_flags2 = old_flags2;
811                   _IO_funlockfile (stderr);
812
813                   free (buf);
814                 }
815 #endif
816             }
817           d->__nextchar = (char *) "";
818           d->optind++;
819           d->optopt = 0;
820           return '?';
821         }
822     }
823
824   /* Look at and handle the next short option-character.  */
825
826   {
827     char c = *d->__nextchar++;
828     char *temp = strchr (optstring, c);
829
830     /* Increment `optind' when we start to process its last character.  */
831     if (*d->__nextchar == '\0')
832       ++d->optind;
833
834     if (temp == NULL || c == ':' || c == ';')
835       {
836         if (print_errors)
837           {
838 #if defined _LIBC
839             char *buf;
840             int n;
841 #endif
842
843 #if defined _LIBC
844             n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"),
845                             argv[0], c);
846 #else
847             fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
848 #endif
849
850 #if defined _LIBC
851             if (n >= 0)
852               {
853                 _IO_flockfile (stderr);
854
855                 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
856                 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
857
858                 __fxprintf (NULL, "%s", buf);
859
860                 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
861                 _IO_funlockfile (stderr);
862
863                 free (buf);
864               }
865 #endif
866           }
867         d->optopt = c;
868         return '?';
869       }
870     /* Convenience. Treat POSIX -W foo same as long option --foo */
871     if (temp[0] == 'W' && temp[1] == ';')
872       {
873         if (longopts == NULL)
874           goto no_longs;
875
876         char *nameend;
877         const struct option *p;
878         const struct option *pfound = NULL;
879         int exact = 0;
880         int ambig = 0;
881         int indfound = 0;
882         int option_index;
883
884         /* This is an option that requires an argument.  */
885         if (*d->__nextchar != '\0')
886           {
887             d->optarg = d->__nextchar;
888             /* If we end this ARGV-element by taking the rest as an arg,
889                we must advance to the next element now.  */
890             d->optind++;
891           }
892         else if (d->optind == argc)
893           {
894             if (print_errors)
895               {
896 #if defined _LIBC
897                 char *buf;
898
899                 if (__asprintf (&buf,
900                                 _("%s: option requires an argument -- '%c'\n"),
901                                 argv[0], c) >= 0)
902                   {
903                     _IO_flockfile (stderr);
904
905                     int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
906                     ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
907
908                     __fxprintf (NULL, "%s", buf);
909
910                     ((_IO_FILE *) stderr)->_flags2 = old_flags2;
911                     _IO_funlockfile (stderr);
912
913                     free (buf);
914                   }
915 #else
916                 fprintf (stderr,
917                          _("%s: option requires an argument -- '%c'\n"),
918                          argv[0], c);
919 #endif
920               }
921             d->optopt = c;
922             if (optstring[0] == ':')
923               c = ':';
924             else
925               c = '?';
926             return c;
927           }
928         else
929           /* We already incremented `d->optind' once;
930              increment it again when taking next ARGV-elt as argument.  */
931           d->optarg = argv[d->optind++];
932
933         /* optarg is now the argument, see if it's in the
934            table of longopts.  */
935
936         for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
937              nameend++)
938           /* Do nothing.  */ ;
939
940         /* Test all long options for either exact match
941            or abbreviated matches.  */
942         for (p = longopts, option_index = 0; p->name; p++, option_index++)
943           if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
944             {
945               if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
946                 {
947                   /* Exact match found.  */
948                   pfound = p;
949                   indfound = option_index;
950                   exact = 1;
951                   break;
952                 }
953               else if (pfound == NULL)
954                 {
955                   /* First nonexact match found.  */
956                   pfound = p;
957                   indfound = option_index;
958                 }
959               else if (long_only
960                        || pfound->has_arg != p->has_arg
961                        || pfound->flag != p->flag
962                        || pfound->val != p->val)
963                 /* Second or later nonexact match found.  */
964                 ambig = 1;
965             }
966         if (ambig && !exact)
967           {
968             if (print_errors)
969               {
970 #if defined _LIBC
971                 char *buf;
972
973                 if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"),
974                                 argv[0], d->optarg) >= 0)
975                   {
976                     _IO_flockfile (stderr);
977
978                     int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
979                     ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
980
981                     __fxprintf (NULL, "%s", buf);
982
983                     ((_IO_FILE *) stderr)->_flags2 = old_flags2;
984                     _IO_funlockfile (stderr);
985
986                     free (buf);
987                   }
988 #else
989                 fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
990                          argv[0], d->optarg);
991 #endif
992               }
993             d->__nextchar += strlen (d->__nextchar);
994             d->optind++;
995             return '?';
996           }
997         if (pfound != NULL)
998           {
999             option_index = indfound;
1000             if (*nameend)
1001               {
1002                 /* Don't test has_arg with >, because some C compilers don't
1003                    allow it to be used on enums.  */
1004                 if (pfound->has_arg)
1005                   d->optarg = nameend + 1;
1006                 else
1007                   {
1008                     if (print_errors)
1009                       {
1010 #if defined _LIBC
1011                         char *buf;
1012
1013                         if (__asprintf (&buf, _("\
1014 %s: option '-W %s' doesn't allow an argument\n"),
1015                                         argv[0], pfound->name) >= 0)
1016                           {
1017                             _IO_flockfile (stderr);
1018
1019                             int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1020                             ((_IO_FILE *) stderr)->_flags2
1021                               |= _IO_FLAGS2_NOTCANCEL;
1022
1023                             __fxprintf (NULL, "%s", buf);
1024
1025                             ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1026                             _IO_funlockfile (stderr);
1027
1028                             free (buf);
1029                           }
1030 #else
1031                         fprintf (stderr, _("\
1032 %s: option '-W %s' doesn't allow an argument\n"),
1033                                  argv[0], pfound->name);
1034 #endif
1035                       }
1036
1037                     d->__nextchar += strlen (d->__nextchar);
1038                     return '?';
1039                   }
1040               }
1041             else if (pfound->has_arg == 1)
1042               {
1043                 if (d->optind < argc)
1044                   d->optarg = argv[d->optind++];
1045                 else
1046                   {
1047                     if (print_errors)
1048                       {
1049 #if defined _LIBC
1050                         char *buf;
1051
1052                         if (__asprintf (&buf, _("\
1053 %s: option '-W %s' requires an argument\n"),
1054                                         argv[0], pfound->name) >= 0)
1055                           {
1056                             _IO_flockfile (stderr);
1057
1058                             int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1059                             ((_IO_FILE *) stderr)->_flags2
1060                               |= _IO_FLAGS2_NOTCANCEL;
1061
1062                             __fxprintf (NULL, "%s", buf);
1063
1064                             ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1065                             _IO_funlockfile (stderr);
1066
1067                             free (buf);
1068                           }
1069 #else
1070                         fprintf (stderr, _("\
1071 %s: option '-W %s' requires an argument\n"),
1072                                  argv[0], pfound->name);
1073 #endif
1074                       }
1075                     d->__nextchar += strlen (d->__nextchar);
1076                     return optstring[0] == ':' ? ':' : '?';
1077                   }
1078               }
1079             else
1080               d->optarg = NULL;
1081             d->__nextchar += strlen (d->__nextchar);
1082             if (longind != NULL)
1083               *longind = option_index;
1084             if (pfound->flag)
1085               {
1086                 *(pfound->flag) = pfound->val;
1087                 return 0;
1088               }
1089             return pfound->val;
1090           }
1091
1092       no_longs:
1093         d->__nextchar = NULL;
1094         return 'W';     /* Let the application handle it.   */
1095       }
1096     if (temp[1] == ':')
1097       {
1098         if (temp[2] == ':')
1099           {
1100             /* This is an option that accepts an argument optionally.  */
1101             if (*d->__nextchar != '\0')
1102               {
1103                 d->optarg = d->__nextchar;
1104                 d->optind++;
1105               }
1106             else
1107               d->optarg = NULL;
1108             d->__nextchar = NULL;
1109           }
1110         else
1111           {
1112             /* This is an option that requires an argument.  */
1113             if (*d->__nextchar != '\0')
1114               {
1115                 d->optarg = d->__nextchar;
1116                 /* If we end this ARGV-element by taking the rest as an arg,
1117                    we must advance to the next element now.  */
1118                 d->optind++;
1119               }
1120             else if (d->optind == argc)
1121               {
1122                 if (print_errors)
1123                   {
1124 #if defined _LIBC
1125                     char *buf;
1126
1127                     if (__asprintf (&buf, _("\
1128 %s: option requires an argument -- '%c'\n"),
1129                                     argv[0], c) >= 0)
1130                       {
1131                         _IO_flockfile (stderr);
1132
1133                         int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1134                         ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1135
1136                         __fxprintf (NULL, "%s", buf);
1137
1138                         ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1139                         _IO_funlockfile (stderr);
1140
1141                         free (buf);
1142                       }
1143 #else
1144                     fprintf (stderr,
1145                              _("%s: option requires an argument -- '%c'\n"),
1146                              argv[0], c);
1147 #endif
1148                   }
1149                 d->optopt = c;
1150                 if (optstring[0] == ':')
1151                   c = ':';
1152                 else
1153                   c = '?';
1154               }
1155             else
1156               /* We already incremented `optind' once;
1157                  increment it again when taking next ARGV-elt as argument.  */
1158               d->optarg = argv[d->optind++];
1159             d->__nextchar = NULL;
1160           }
1161       }
1162     return c;
1163   }
1164 }
1165
1166 int
1167 _getopt_internal (int argc, char *const *argv, const char *optstring,
1168                   const struct option *longopts, int *longind, int long_only,
1169                   int posixly_correct)
1170 {
1171   int result;
1172
1173   getopt_data.optind = optind;
1174   getopt_data.opterr = opterr;
1175
1176   result = _getopt_internal_r (argc, argv, optstring, longopts,
1177                                longind, long_only, &getopt_data,
1178                                posixly_correct);
1179
1180   optind = getopt_data.optind;
1181   optarg = getopt_data.optarg;
1182   optopt = getopt_data.optopt;
1183
1184   return result;
1185 }
1186
1187 int
1188 getopt (int argc, char *const *argv, const char *optstring)
1189 {
1190   return _getopt_internal (argc, argv, optstring,
1191                            (const struct option *) 0,
1192                            (int *) 0,
1193                            0, 0);
1194 }
1195
1196 #ifdef _LIBC
1197 int
1198 __posix_getopt (int argc, char *const *argv, const char *optstring)
1199 {
1200   return _getopt_internal (argc, argv, optstring,
1201                            (const struct option *) 0,
1202                            (int *) 0,
1203                            0, 1);
1204 }
1205 #endif
1206
1207 #endif  /* Not ELIDE_CODE.  */
1208 \f
1209 #ifdef TEST
1210
1211 /* Compile with -DTEST to make an executable for use in testing
1212    the above definition of `getopt'.  */
1213
1214 int
1215 main (int argc, char **argv)
1216 {
1217   int c;
1218   int digit_optind = 0;
1219
1220   while (1)
1221     {
1222       int this_option_optind = optind ? optind : 1;
1223
1224       c = getopt (argc, argv, "abc:d:0123456789");
1225       if (c == -1)
1226         break;
1227
1228       switch (c)
1229         {
1230         case '0':
1231         case '1':
1232         case '2':
1233         case '3':
1234         case '4':
1235         case '5':
1236         case '6':
1237         case '7':
1238         case '8':
1239         case '9':
1240           if (digit_optind != 0 && digit_optind != this_option_optind)
1241             printf ("digits occur in two different argv-elements.\n");
1242           digit_optind = this_option_optind;
1243           printf ("option %c\n", c);
1244           break;
1245
1246         case 'a':
1247           printf ("option a\n");
1248           break;
1249
1250         case 'b':
1251           printf ("option b\n");
1252           break;
1253
1254         case 'c':
1255           printf ("option c with value '%s'\n", optarg);
1256           break;
1257
1258         case '?':
1259           break;
1260
1261         default:
1262           printf ("?? getopt returned character code 0%o ??\n", c);
1263         }
1264     }
1265
1266   if (optind < argc)
1267     {
1268       printf ("non-option ARGV-elements: ");
1269       while (optind < argc)
1270         printf ("%s ", argv[optind++]);
1271       printf ("\n");
1272     }
1273
1274   exit (0);
1275 }
1276
1277 #endif /* TEST */