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