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