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