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