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