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