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