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