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