Code

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