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