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