Back to index

glibc  2.9
getopt.c
Go to the documentation of this file.
00001 /* Getopt for GNU.
00002    NOTE: getopt is part of the C library, so if you don't know what
00003    "Keep this file name-space clean" means, talk to drepper@gnu.org
00004    before changing it!
00005    Copyright (C) 1987-1996,1998-2004,2008 Free Software Foundation, Inc.
00006    This file is part of the GNU C Library.
00007 
00008    The GNU C Library is free software; you can redistribute it and/or
00009    modify it under the terms of the GNU Lesser General Public
00010    License as published by the Free Software Foundation; either
00011    version 2.1 of the License, or (at your option) any later version.
00012 
00013    The GNU C Library is distributed in the hope that it will be useful,
00014    but WITHOUT ANY WARRANTY; without even the implied warranty of
00015    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016    Lesser General Public License for more details.
00017 
00018    You should have received a copy of the GNU Lesser General Public
00019    License along with the GNU C Library; if not, write to the Free
00020    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00021    02111-1307 USA.  */
00022 
00023 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
00024    Ditto for AIX 3.2 and <stdlib.h>.  */
00025 #ifndef _NO_PROTO
00026 # define _NO_PROTO
00027 #endif
00028 
00029 #ifdef HAVE_CONFIG_H
00030 # include <config.h>
00031 #endif
00032 
00033 #include <stdio.h>
00034 
00035 /* Comment out all this code if we are using the GNU C Library, and are not
00036    actually compiling the library itself.  This code is part of the GNU C
00037    Library, but also included in many other GNU distributions.  Compiling
00038    and linking in this code is a waste when using the GNU C library
00039    (especially if it is a shared library).  Rather than having every GNU
00040    program understand `configure --with-gnu-libc' and omit the object files,
00041    it is simpler to just do this in the source for each such file.  */
00042 
00043 #define GETOPT_INTERFACE_VERSION 2
00044 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
00045 # include <gnu-versions.h>
00046 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
00047 #  define ELIDE_CODE
00048 # endif
00049 #endif
00050 
00051 #ifndef ELIDE_CODE
00052 
00053 
00054 /* This needs to come after some library #include
00055    to get __GNU_LIBRARY__ defined.  */
00056 #ifdef __GNU_LIBRARY__
00057 /* Don't include stdlib.h for non-GNU C libraries because some of them
00058    contain conflicting prototypes for getopt.  */
00059 # include <stdlib.h>
00060 # include <unistd.h>
00061 #endif /* GNU C library.  */
00062 
00063 #include <string.h>
00064 
00065 #ifdef VMS
00066 # include <unixlib.h>
00067 #endif
00068 
00069 #ifdef _LIBC
00070 # include <libintl.h>
00071 #else
00072 # include "gettext.h"
00073 # define _(msgid) gettext (msgid)
00074 #endif
00075 
00076 #if defined _LIBC && defined USE_IN_LIBIO
00077 # include <wchar.h>
00078 #endif
00079 
00080 #ifndef attribute_hidden
00081 # define attribute_hidden
00082 #endif
00083 
00084 /* This version of `getopt' appears to the caller like standard Unix `getopt'
00085    but it behaves differently for the user, since it allows the user
00086    to intersperse the options with the other arguments.
00087 
00088    As `getopt' works, it permutes the elements of ARGV so that,
00089    when it is done, all the options precede everything else.  Thus
00090    all application programs are extended to handle flexible argument order.
00091 
00092    Setting the environment variable POSIXLY_CORRECT disables permutation.
00093    Then the behavior is completely standard.
00094 
00095    GNU application programs can use a third alternative mode in which
00096    they can distinguish the relative order of options and other arguments.  */
00097 
00098 #include "getopt.h"
00099 #include "getopt_int.h"
00100 
00101 /* For communication from `getopt' to the caller.
00102    When `getopt' finds an option that takes an argument,
00103    the argument value is returned here.
00104    Also, when `ordering' is RETURN_IN_ORDER,
00105    each non-option ARGV-element is returned here.  */
00106 
00107 char *optarg;
00108 
00109 /* Index in ARGV of the next element to be scanned.
00110    This is used for communication to and from the caller
00111    and for communication between successive calls to `getopt'.
00112 
00113    On entry to `getopt', zero means this is the first call; initialize.
00114 
00115    When `getopt' returns -1, this is the index of the first of the
00116    non-option elements that the caller should itself scan.
00117 
00118    Otherwise, `optind' communicates from one call to the next
00119    how much of ARGV has been scanned so far.  */
00120 
00121 /* 1003.2 says this must be 1 before any call.  */
00122 int optind = 1;
00123 
00124 /* Callers store zero here to inhibit the error message
00125    for unrecognized options.  */
00126 
00127 int opterr = 1;
00128 
00129 /* Set to an option character which was unrecognized.
00130    This must be initialized on some systems to avoid linking in the
00131    system's own getopt implementation.  */
00132 
00133 int optopt = '?';
00134 
00135 /* Keep a global copy of all internal members of getopt_data.  */
00136 
00137 static struct _getopt_data getopt_data;
00138 
00139 
00140 #ifndef __GNU_LIBRARY__
00141 
00142 /* Avoid depending on library functions or files
00143    whose names are inconsistent.  */
00144 
00145 #ifndef getenv
00146 extern char *getenv ();
00147 #endif
00148 
00149 #endif /* not __GNU_LIBRARY__ */
00150 
00151 #ifdef _LIBC
00152 /* Stored original parameters.
00153    XXX This is no good solution.  We should rather copy the args so
00154    that we can compare them later.  But we must not use malloc(3).  */
00155 extern int __libc_argc;
00156 extern char **__libc_argv;
00157 
00158 /* Bash 2.0 gives us an environment variable containing flags
00159    indicating ARGV elements that should not be considered arguments.  */
00160 
00161 # ifdef USE_NONOPTION_FLAGS
00162 /* Defined in getopt_init.c  */
00163 extern char *__getopt_nonoption_flags;
00164 # endif
00165 
00166 # ifdef USE_NONOPTION_FLAGS
00167 #  define SWAP_FLAGS(ch1, ch2) \
00168   if (d->__nonoption_flags_len > 0)                                         \
00169     {                                                                \
00170       char __tmp = __getopt_nonoption_flags[ch1];                           \
00171       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];        \
00172       __getopt_nonoption_flags[ch2] = __tmp;                                \
00173     }
00174 # else
00175 #  define SWAP_FLAGS(ch1, ch2)
00176 # endif
00177 #else  /* !_LIBC */
00178 # define SWAP_FLAGS(ch1, ch2)
00179 #endif /* _LIBC */
00180 
00181 /* Exchange two adjacent subsequences of ARGV.
00182    One subsequence is elements [first_nonopt,last_nonopt)
00183    which contains all the non-options that have been skipped so far.
00184    The other is elements [last_nonopt,optind), which contains all
00185    the options processed since those non-options were skipped.
00186 
00187    `first_nonopt' and `last_nonopt' are relocated so that they describe
00188    the new indices of the non-options in ARGV after they are moved.  */
00189 
00190 static void
00191 exchange (char **argv, struct _getopt_data *d)
00192 {
00193   int bottom = d->__first_nonopt;
00194   int middle = d->__last_nonopt;
00195   int top = d->optind;
00196   char *tem;
00197 
00198   /* Exchange the shorter segment with the far end of the longer segment.
00199      That puts the shorter segment into the right place.
00200      It leaves the longer segment in the right place overall,
00201      but it consists of two parts that need to be swapped next.  */
00202 
00203 #if defined _LIBC && defined USE_NONOPTION_FLAGS
00204   /* First make sure the handling of the `__getopt_nonoption_flags'
00205      string can work normally.  Our top argument must be in the range
00206      of the string.  */
00207   if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
00208     {
00209       /* We must extend the array.  The user plays games with us and
00210         presents new arguments.  */
00211       char *new_str = malloc (top + 1);
00212       if (new_str == NULL)
00213        d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
00214       else
00215        {
00216          memset (__mempcpy (new_str, __getopt_nonoption_flags,
00217                           d->__nonoption_flags_max_len),
00218                 '\0', top + 1 - d->__nonoption_flags_max_len);
00219          d->__nonoption_flags_max_len = top + 1;
00220          __getopt_nonoption_flags = new_str;
00221        }
00222     }
00223 #endif
00224 
00225   while (top > middle && middle > bottom)
00226     {
00227       if (top - middle > middle - bottom)
00228        {
00229          /* Bottom segment is the short one.  */
00230          int len = middle - bottom;
00231          register int i;
00232 
00233          /* Swap it with the top part of the top segment.  */
00234          for (i = 0; i < len; i++)
00235            {
00236              tem = argv[bottom + i];
00237              argv[bottom + i] = argv[top - (middle - bottom) + i];
00238              argv[top - (middle - bottom) + i] = tem;
00239              SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
00240            }
00241          /* Exclude the moved bottom segment from further swapping.  */
00242          top -= len;
00243        }
00244       else
00245        {
00246          /* Top segment is the short one.  */
00247          int len = top - middle;
00248          register int i;
00249 
00250          /* Swap it with the bottom part of the bottom segment.  */
00251          for (i = 0; i < len; i++)
00252            {
00253              tem = argv[bottom + i];
00254              argv[bottom + i] = argv[middle + i];
00255              argv[middle + i] = tem;
00256              SWAP_FLAGS (bottom + i, middle + i);
00257            }
00258          /* Exclude the moved top segment from further swapping.  */
00259          bottom += len;
00260        }
00261     }
00262 
00263   /* Update records for the slots the non-options now occupy.  */
00264 
00265   d->__first_nonopt += (d->optind - d->__last_nonopt);
00266   d->__last_nonopt = d->optind;
00267 }
00268 
00269 /* Initialize the internal data when the first call is made.  */
00270 
00271 static const char *
00272 _getopt_initialize (int argc, char *const *argv, const char *optstring,
00273                   struct _getopt_data *d)
00274 {
00275   /* Start processing options with ARGV-element 1 (since ARGV-element 0
00276      is the program name); the sequence of previously skipped
00277      non-option ARGV-elements is empty.  */
00278 
00279   d->__first_nonopt = d->__last_nonopt = d->optind;
00280 
00281   d->__nextchar = NULL;
00282 
00283   d->__posixly_correct = !!getenv ("POSIXLY_CORRECT");
00284 
00285   /* Determine how to handle the ordering of options and nonoptions.  */
00286 
00287   if (optstring[0] == '-')
00288     {
00289       d->__ordering = RETURN_IN_ORDER;
00290       ++optstring;
00291     }
00292   else if (optstring[0] == '+')
00293     {
00294       d->__ordering = REQUIRE_ORDER;
00295       ++optstring;
00296     }
00297   else if (d->__posixly_correct)
00298     d->__ordering = REQUIRE_ORDER;
00299   else
00300     d->__ordering = PERMUTE;
00301 
00302 #if defined _LIBC && defined USE_NONOPTION_FLAGS
00303   if (!d->__posixly_correct
00304       && argc == __libc_argc && argv == __libc_argv)
00305     {
00306       if (d->__nonoption_flags_max_len == 0)
00307        {
00308          if (__getopt_nonoption_flags == NULL
00309              || __getopt_nonoption_flags[0] == '\0')
00310            d->__nonoption_flags_max_len = -1;
00311          else
00312            {
00313              const char *orig_str = __getopt_nonoption_flags;
00314              int len = d->__nonoption_flags_max_len = strlen (orig_str);
00315              if (d->__nonoption_flags_max_len < argc)
00316               d->__nonoption_flags_max_len = argc;
00317              __getopt_nonoption_flags =
00318               (char *) malloc (d->__nonoption_flags_max_len);
00319              if (__getopt_nonoption_flags == NULL)
00320               d->__nonoption_flags_max_len = -1;
00321              else
00322               memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
00323                      '\0', d->__nonoption_flags_max_len - len);
00324            }
00325        }
00326       d->__nonoption_flags_len = d->__nonoption_flags_max_len;
00327     }
00328   else
00329     d->__nonoption_flags_len = 0;
00330 #endif
00331 
00332   return optstring;
00333 }
00334 
00335 /* Scan elements of ARGV (whose length is ARGC) for option characters
00336    given in OPTSTRING.
00337 
00338    If an element of ARGV starts with '-', and is not exactly "-" or "--",
00339    then it is an option element.  The characters of this element
00340    (aside from the initial '-') are option characters.  If `getopt'
00341    is called repeatedly, it returns successively each of the option characters
00342    from each of the option elements.
00343 
00344    If `getopt' finds another option character, it returns that character,
00345    updating `optind' and `nextchar' so that the next call to `getopt' can
00346    resume the scan with the following option character or ARGV-element.
00347 
00348    If there are no more option characters, `getopt' returns -1.
00349    Then `optind' is the index in ARGV of the first ARGV-element
00350    that is not an option.  (The ARGV-elements have been permuted
00351    so that those that are not options now come last.)
00352 
00353    OPTSTRING is a string containing the legitimate option characters.
00354    If an option character is seen that is not listed in OPTSTRING,
00355    return '?' after printing an error message.  If you set `opterr' to
00356    zero, the error message is suppressed but we still return '?'.
00357 
00358    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
00359    so the following text in the same ARGV-element, or the text of the following
00360    ARGV-element, is returned in `optarg'.  Two colons mean an option that
00361    wants an optional arg; if there is text in the current ARGV-element,
00362    it is returned in `optarg', otherwise `optarg' is set to zero.
00363 
00364    If OPTSTRING starts with `-' or `+', it requests different methods of
00365    handling the non-option ARGV-elements.
00366    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
00367 
00368    Long-named options begin with `--' instead of `-'.
00369    Their names may be abbreviated as long as the abbreviation is unique
00370    or is an exact match for some defined option.  If they have an
00371    argument, it follows the option name in the same ARGV-element, separated
00372    from the option name by a `=', or else the in next ARGV-element.
00373    When `getopt' finds a long-named option, it returns 0 if that option's
00374    `flag' field is nonzero, the value of the option's `val' field
00375    if the `flag' field is zero.
00376 
00377    The elements of ARGV aren't really const, because we permute them.
00378    But we pretend they're const in the prototype to be compatible
00379    with other systems.
00380 
00381    LONGOPTS is a vector of `struct option' terminated by an
00382    element containing a name which is zero.
00383 
00384    LONGIND returns the index in LONGOPT of the long-named option found.
00385    It is only valid when a long-named option has been found by the most
00386    recent call.
00387 
00388    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
00389    long-named options.  */
00390 
00391 int
00392 _getopt_internal_r (int argc, char *const *argv, const char *optstring,
00393                   const struct option *longopts, int *longind,
00394                   int long_only, struct _getopt_data *d)
00395 {
00396   int print_errors = d->opterr;
00397   if (optstring[0] == ':')
00398     print_errors = 0;
00399 
00400   if (argc < 1)
00401     return -1;
00402 
00403   d->optarg = NULL;
00404 
00405   if (d->optind == 0 || !d->__initialized)
00406     {
00407       if (d->optind == 0)
00408        d->optind = 1;       /* Don't scan ARGV[0], the program name.  */
00409       optstring = _getopt_initialize (argc, argv, optstring, d);
00410       d->__initialized = 1;
00411     }
00412 
00413   /* Test whether ARGV[optind] points to a non-option argument.
00414      Either it does not have option syntax, or there is an environment flag
00415      from the shell indicating it is not an option.  The later information
00416      is only used when the used in the GNU libc.  */
00417 #if defined _LIBC && defined USE_NONOPTION_FLAGS
00418 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
00419                     || (d->optind < d->__nonoption_flags_len                \
00420                        && __getopt_nonoption_flags[d->optind] == '1'))
00421 #else
00422 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
00423 #endif
00424 
00425   if (d->__nextchar == NULL || *d->__nextchar == '\0')
00426     {
00427       /* Advance to the next ARGV-element.  */
00428 
00429       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
00430         moved back by the user (who may also have changed the arguments).  */
00431       if (d->__last_nonopt > d->optind)
00432        d->__last_nonopt = d->optind;
00433       if (d->__first_nonopt > d->optind)
00434        d->__first_nonopt = d->optind;
00435 
00436       if (d->__ordering == PERMUTE)
00437        {
00438          /* If we have just processed some options following some non-options,
00439             exchange them so that the options come first.  */
00440 
00441          if (d->__first_nonopt != d->__last_nonopt
00442              && d->__last_nonopt != d->optind)
00443            exchange ((char **) argv, d);
00444          else if (d->__last_nonopt != d->optind)
00445            d->__first_nonopt = d->optind;
00446 
00447          /* Skip any additional non-options
00448             and extend the range of non-options previously skipped.  */
00449 
00450          while (d->optind < argc && NONOPTION_P)
00451            d->optind++;
00452          d->__last_nonopt = d->optind;
00453        }
00454 
00455       /* The special ARGV-element `--' means premature end of options.
00456         Skip it like a null option,
00457         then exchange with previous non-options as if it were an option,
00458         then skip everything else like a non-option.  */
00459 
00460       if (d->optind != argc && !strcmp (argv[d->optind], "--"))
00461        {
00462          d->optind++;
00463 
00464          if (d->__first_nonopt != d->__last_nonopt
00465              && d->__last_nonopt != d->optind)
00466            exchange ((char **) argv, d);
00467          else if (d->__first_nonopt == d->__last_nonopt)
00468            d->__first_nonopt = d->optind;
00469          d->__last_nonopt = argc;
00470 
00471          d->optind = argc;
00472        }
00473 
00474       /* If we have done all the ARGV-elements, stop the scan
00475         and back over any non-options that we skipped and permuted.  */
00476 
00477       if (d->optind == argc)
00478        {
00479          /* Set the next-arg-index to point at the non-options
00480             that we previously skipped, so the caller will digest them.  */
00481          if (d->__first_nonopt != d->__last_nonopt)
00482            d->optind = d->__first_nonopt;
00483          return -1;
00484        }
00485 
00486       /* If we have come to a non-option and did not permute it,
00487         either stop the scan or describe it to the caller and pass it by.  */
00488 
00489       if (NONOPTION_P)
00490        {
00491          if (d->__ordering == REQUIRE_ORDER)
00492            return -1;
00493          d->optarg = argv[d->optind++];
00494          return 1;
00495        }
00496 
00497       /* We have found another option-ARGV-element.
00498         Skip the initial punctuation.  */
00499 
00500       d->__nextchar = (argv[d->optind] + 1
00501                 + (longopts != NULL && argv[d->optind][1] == '-'));
00502     }
00503 
00504   /* Decode the current option-ARGV-element.  */
00505 
00506   /* Check whether the ARGV-element is a long option.
00507 
00508      If long_only and the ARGV-element has the form "-f", where f is
00509      a valid short option, don't consider it an abbreviated form of
00510      a long option that starts with f.  Otherwise there would be no
00511      way to give the -f short option.
00512 
00513      On the other hand, if there's a long option "fubar" and
00514      the ARGV-element is "-fu", do consider that an abbreviation of
00515      the long option, just like "--fu", and not "-f" with arg "u".
00516 
00517      This distinction seems to be the most useful approach.  */
00518 
00519   if (longopts != NULL
00520       && (argv[d->optind][1] == '-'
00521          || (long_only && (argv[d->optind][2]
00522                          || !strchr (optstring, argv[d->optind][1])))))
00523     {
00524       char *nameend;
00525       const struct option *p;
00526       const struct option *pfound = NULL;
00527       int exact = 0;
00528       int ambig = 0;
00529       int indfound = -1;
00530       int option_index;
00531 
00532       for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
00533        /* Do nothing.  */ ;
00534 
00535       /* Test all long options for either exact match
00536         or abbreviated matches.  */
00537       for (p = longopts, option_index = 0; p->name; p++, option_index++)
00538        if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
00539          {
00540            if ((unsigned int) (nameend - d->__nextchar)
00541               == (unsigned int) strlen (p->name))
00542              {
00543               /* Exact match found.  */
00544               pfound = p;
00545               indfound = option_index;
00546               exact = 1;
00547               break;
00548              }
00549            else if (pfound == NULL)
00550              {
00551               /* First nonexact match found.  */
00552               pfound = p;
00553               indfound = option_index;
00554              }
00555            else if (long_only
00556                    || pfound->has_arg != p->has_arg
00557                    || pfound->flag != p->flag
00558                    || pfound->val != p->val)
00559              /* Second or later nonexact match found.  */
00560              ambig = 1;
00561          }
00562 
00563       if (ambig && !exact)
00564        {
00565          if (print_errors)
00566            {
00567 #if defined _LIBC && defined USE_IN_LIBIO
00568              char *buf;
00569 
00570              if (__asprintf (&buf, _("%s: option '%s' is ambiguous\n"),
00571                            argv[0], argv[d->optind]) >= 0)
00572               {
00573                 _IO_flockfile (stderr);
00574 
00575                 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00576                 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
00577 
00578                 __fxprintf (NULL, "%s", buf);
00579 
00580                 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00581                 _IO_funlockfile (stderr);
00582 
00583                 free (buf);
00584               }
00585 #else
00586              fprintf (stderr, _("%s: option '%s' is ambiguous\n"),
00587                      argv[0], argv[d->optind]);
00588 #endif
00589            }
00590          d->__nextchar += strlen (d->__nextchar);
00591          d->optind++;
00592          d->optopt = 0;
00593          return '?';
00594        }
00595 
00596       if (pfound != NULL)
00597        {
00598          option_index = indfound;
00599          d->optind++;
00600          if (*nameend)
00601            {
00602              /* Don't test has_arg with >, because some C compilers don't
00603                allow it to be used on enums.  */
00604              if (pfound->has_arg)
00605               d->optarg = nameend + 1;
00606              else
00607               {
00608                 if (print_errors)
00609                   {
00610 #if defined _LIBC && defined USE_IN_LIBIO
00611                     char *buf;
00612                     int n;
00613 #endif
00614 
00615                     if (argv[d->optind - 1][1] == '-')
00616                      {
00617                        /* --option */
00618 #if defined _LIBC && defined USE_IN_LIBIO
00619                        n = __asprintf (&buf, _("\
00620 %s: option '--%s' doesn't allow an argument\n"),
00621                                      argv[0], pfound->name);
00622 #else
00623                        fprintf (stderr, _("\
00624 %s: option '--%s' doesn't allow an argument\n"),
00625                                argv[0], pfound->name);
00626 #endif
00627                      }
00628                     else
00629                      {
00630                        /* +option or -option */
00631 #if defined _LIBC && defined USE_IN_LIBIO
00632                        n = __asprintf (&buf, _("\
00633 %s: option '%c%s' doesn't allow an argument\n"),
00634                                      argv[0], argv[d->optind - 1][0],
00635                                      pfound->name);
00636 #else
00637                        fprintf (stderr, _("\
00638 %s: option '%c%s' doesn't allow an argument\n"),
00639                                argv[0], argv[d->optind - 1][0],
00640                                pfound->name);
00641 #endif
00642                      }
00643 
00644 #if defined _LIBC && defined USE_IN_LIBIO
00645                     if (n >= 0)
00646                      {
00647                        _IO_flockfile (stderr);
00648 
00649                        int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00650                        ((_IO_FILE *) stderr)->_flags2
00651                          |= _IO_FLAGS2_NOTCANCEL;
00652 
00653                        __fxprintf (NULL, "%s", buf);
00654 
00655                        ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00656                        _IO_funlockfile (stderr);
00657 
00658                        free (buf);
00659                      }
00660 #endif
00661                   }
00662 
00663                 d->__nextchar += strlen (d->__nextchar);
00664 
00665                 d->optopt = pfound->val;
00666                 return '?';
00667               }
00668            }
00669          else if (pfound->has_arg == 1)
00670            {
00671              if (d->optind < argc)
00672               d->optarg = argv[d->optind++];
00673              else
00674               {
00675                 if (print_errors)
00676                   {
00677 #if defined _LIBC && defined USE_IN_LIBIO
00678                     char *buf;
00679 
00680                     if (__asprintf (&buf, _("\
00681 %s: option '%s' requires an argument\n"),
00682                                   argv[0], argv[d->optind - 1]) >= 0)
00683                      {
00684                        _IO_flockfile (stderr);
00685 
00686                        int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00687                        ((_IO_FILE *) stderr)->_flags2
00688                          |= _IO_FLAGS2_NOTCANCEL;
00689 
00690                        __fxprintf (NULL, "%s", buf);
00691 
00692                        ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00693                        _IO_funlockfile (stderr);
00694 
00695                        free (buf);
00696                      }
00697 #else
00698                     fprintf (stderr,
00699                             _("%s: option '%s' requires an argument\n"),
00700                             argv[0], argv[d->optind - 1]);
00701 #endif
00702                   }
00703                 d->__nextchar += strlen (d->__nextchar);
00704                 d->optopt = pfound->val;
00705                 return optstring[0] == ':' ? ':' : '?';
00706               }
00707            }
00708          d->__nextchar += strlen (d->__nextchar);
00709          if (longind != NULL)
00710            *longind = option_index;
00711          if (pfound->flag)
00712            {
00713              *(pfound->flag) = pfound->val;
00714              return 0;
00715            }
00716          return pfound->val;
00717        }
00718 
00719       /* Can't find it as a long option.  If this is not getopt_long_only,
00720         or the option starts with '--' or is not a valid short
00721         option, then it's an error.
00722         Otherwise interpret it as a short option.  */
00723       if (!long_only || argv[d->optind][1] == '-'
00724          || strchr (optstring, *d->__nextchar) == NULL)
00725        {
00726          if (print_errors)
00727            {
00728 #if defined _LIBC && defined USE_IN_LIBIO
00729              char *buf;
00730              int n;
00731 #endif
00732 
00733              if (argv[d->optind][1] == '-')
00734               {
00735                 /* --option */
00736 #if defined _LIBC && defined USE_IN_LIBIO
00737                 n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"),
00738                               argv[0], d->__nextchar);
00739 #else
00740                 fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
00741                         argv[0], d->__nextchar);
00742 #endif
00743               }
00744              else
00745               {
00746                 /* +option or -option */
00747 #if defined _LIBC && defined USE_IN_LIBIO
00748                 n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"),
00749                               argv[0], argv[d->optind][0], d->__nextchar);
00750 #else
00751                 fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
00752                         argv[0], argv[d->optind][0], d->__nextchar);
00753 #endif
00754               }
00755 
00756 #if defined _LIBC && defined USE_IN_LIBIO
00757              if (n >= 0)
00758               {
00759                 _IO_flockfile (stderr);
00760 
00761                 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00762                 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
00763 
00764                 __fxprintf (NULL, "%s", buf);
00765 
00766                 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00767                 _IO_funlockfile (stderr);
00768 
00769                 free (buf);
00770               }
00771 #endif
00772            }
00773          d->__nextchar = (char *) "";
00774          d->optind++;
00775          d->optopt = 0;
00776          return '?';
00777        }
00778     }
00779 
00780   /* Look at and handle the next short option-character.  */
00781 
00782   {
00783     char c = *d->__nextchar++;
00784     char *temp = strchr (optstring, c);
00785 
00786     /* Increment `optind' when we start to process its last character.  */
00787     if (*d->__nextchar == '\0')
00788       ++d->optind;
00789 
00790     if (temp == NULL || c == ':')
00791       {
00792        if (print_errors)
00793          {
00794 #if defined _LIBC && defined USE_IN_LIBIO
00795            char *buf;
00796            int n;
00797 #endif
00798 
00799 #if defined _LIBC && defined USE_IN_LIBIO
00800            n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"),
00801                          argv[0], c);
00802 #else
00803            fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
00804 #endif
00805 
00806 #if defined _LIBC && defined USE_IN_LIBIO
00807            if (n >= 0)
00808              {
00809               _IO_flockfile (stderr);
00810 
00811               int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00812               ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
00813 
00814               __fxprintf (NULL, "%s", buf);
00815 
00816               ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00817               _IO_funlockfile (stderr);
00818 
00819               free (buf);
00820              }
00821 #endif
00822          }
00823        d->optopt = c;
00824        return '?';
00825       }
00826     /* Convenience. Treat POSIX -W foo same as long option --foo */
00827     if (temp[0] == 'W' && temp[1] == ';')
00828       {
00829        char *nameend;
00830        const struct option *p;
00831        const struct option *pfound = NULL;
00832        int exact = 0;
00833        int ambig = 0;
00834        int indfound = 0;
00835        int option_index;
00836 
00837        /* This is an option that requires an argument.  */
00838        if (*d->__nextchar != '\0')
00839          {
00840            d->optarg = d->__nextchar;
00841            /* If we end this ARGV-element by taking the rest as an arg,
00842               we must advance to the next element now.  */
00843            d->optind++;
00844          }
00845        else if (d->optind == argc)
00846          {
00847            if (print_errors)
00848              {
00849 #if defined _LIBC && defined USE_IN_LIBIO
00850               char *buf;
00851 
00852               if (__asprintf (&buf,
00853                             _("%s: option requires an argument -- '%c'\n"),
00854                             argv[0], c) >= 0)
00855                 {
00856                   _IO_flockfile (stderr);
00857 
00858                   int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00859                   ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
00860 
00861                   __fxprintf (NULL, "%s", buf);
00862 
00863                   ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00864                   _IO_funlockfile (stderr);
00865 
00866                   free (buf);
00867                 }
00868 #else
00869               fprintf (stderr,
00870                       _("%s: option requires an argument -- '%c'\n"),
00871                       argv[0], c);
00872 #endif
00873              }
00874            d->optopt = c;
00875            if (optstring[0] == ':')
00876              c = ':';
00877            else
00878              c = '?';
00879            return c;
00880          }
00881        else
00882          /* We already incremented `d->optind' once;
00883             increment it again when taking next ARGV-elt as argument.  */
00884          d->optarg = argv[d->optind++];
00885 
00886        /* optarg is now the argument, see if it's in the
00887           table of longopts.  */
00888 
00889        for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
00890             nameend++)
00891          /* Do nothing.  */ ;
00892 
00893        /* Test all long options for either exact match
00894           or abbreviated matches.  */
00895        for (p = longopts, option_index = 0; p->name; p++, option_index++)
00896          if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
00897            {
00898              if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
00899               {
00900                 /* Exact match found.  */
00901                 pfound = p;
00902                 indfound = option_index;
00903                 exact = 1;
00904                 break;
00905               }
00906              else if (pfound == NULL)
00907               {
00908                 /* First nonexact match found.  */
00909                 pfound = p;
00910                 indfound = option_index;
00911               }
00912              else
00913               /* Second or later nonexact match found.  */
00914               ambig = 1;
00915            }
00916        if (ambig && !exact)
00917          {
00918            if (print_errors)
00919              {
00920 #if defined _LIBC && defined USE_IN_LIBIO
00921               char *buf;
00922 
00923               if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"),
00924                             argv[0], argv[d->optind]) >= 0)
00925                 {
00926                   _IO_flockfile (stderr);
00927 
00928                   int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00929                   ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
00930 
00931                   __fxprintf (NULL, "%s", buf);
00932 
00933                   ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00934                   _IO_funlockfile (stderr);
00935 
00936                   free (buf);
00937                 }
00938 #else
00939               fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
00940                       argv[0], argv[d->optind]);
00941 #endif
00942              }
00943            d->__nextchar += strlen (d->__nextchar);
00944            d->optind++;
00945            return '?';
00946          }
00947        if (pfound != NULL)
00948          {
00949            option_index = indfound;
00950            if (*nameend)
00951              {
00952               /* Don't test has_arg with >, because some C compilers don't
00953                  allow it to be used on enums.  */
00954               if (pfound->has_arg)
00955                 d->optarg = nameend + 1;
00956               else
00957                 {
00958                   if (print_errors)
00959                     {
00960 #if defined _LIBC && defined USE_IN_LIBIO
00961                      char *buf;
00962 
00963                      if (__asprintf (&buf, _("\
00964 %s: option '-W %s' doesn't allow an argument\n"),
00965                                    argv[0], pfound->name) >= 0)
00966                        {
00967                          _IO_flockfile (stderr);
00968 
00969                          int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
00970                          ((_IO_FILE *) stderr)->_flags2
00971                            |= _IO_FLAGS2_NOTCANCEL;
00972 
00973                          __fxprintf (NULL, "%s", buf);
00974 
00975                          ((_IO_FILE *) stderr)->_flags2 = old_flags2;
00976                          _IO_funlockfile (stderr);
00977 
00978                          free (buf);
00979                        }
00980 #else
00981                      fprintf (stderr, _("\
00982 %s: option '-W %s' doesn't allow an argument\n"),
00983                              argv[0], pfound->name);
00984 #endif
00985                     }
00986 
00987                   d->__nextchar += strlen (d->__nextchar);
00988                   return '?';
00989                 }
00990              }
00991            else if (pfound->has_arg == 1)
00992              {
00993               if (d->optind < argc)
00994                 d->optarg = argv[d->optind++];
00995               else
00996                 {
00997                   if (print_errors)
00998                     {
00999 #if defined _LIBC && defined USE_IN_LIBIO
01000                      char *buf;
01001 
01002                      if (__asprintf (&buf, _("\
01003 %s: option '%s' requires an argument\n"),
01004                                    argv[0], argv[d->optind - 1]) >= 0)
01005                        {
01006                          _IO_flockfile (stderr);
01007 
01008                          int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
01009                          ((_IO_FILE *) stderr)->_flags2
01010                            |= _IO_FLAGS2_NOTCANCEL;
01011 
01012                          __fxprintf (NULL, "%s", buf);
01013 
01014                          ((_IO_FILE *) stderr)->_flags2 = old_flags2;
01015                          _IO_funlockfile (stderr);
01016 
01017                          free (buf);
01018                        }
01019 #else
01020                      fprintf (stderr,
01021                              _("%s: option '%s' requires an argument\n"),
01022                              argv[0], argv[d->optind - 1]);
01023 #endif
01024                     }
01025                   d->__nextchar += strlen (d->__nextchar);
01026                   return optstring[0] == ':' ? ':' : '?';
01027                 }
01028              }
01029            d->__nextchar += strlen (d->__nextchar);
01030            if (longind != NULL)
01031              *longind = option_index;
01032            if (pfound->flag)
01033              {
01034               *(pfound->flag) = pfound->val;
01035               return 0;
01036              }
01037            return pfound->val;
01038          }
01039          d->__nextchar = NULL;
01040          return 'W'; /* Let the application handle it.   */
01041       }
01042     if (temp[1] == ':')
01043       {
01044        if (temp[2] == ':')
01045          {
01046            /* This is an option that accepts an argument optionally.  */
01047            if (*d->__nextchar != '\0')
01048              {
01049               d->optarg = d->__nextchar;
01050               d->optind++;
01051              }
01052            else
01053              d->optarg = NULL;
01054            d->__nextchar = NULL;
01055          }
01056        else
01057          {
01058            /* This is an option that requires an argument.  */
01059            if (*d->__nextchar != '\0')
01060              {
01061               d->optarg = d->__nextchar;
01062               /* If we end this ARGV-element by taking the rest as an arg,
01063                  we must advance to the next element now.  */
01064               d->optind++;
01065              }
01066            else if (d->optind == argc)
01067              {
01068               if (print_errors)
01069                 {
01070 #if defined _LIBC && defined USE_IN_LIBIO
01071                   char *buf;
01072 
01073                   if (__asprintf (&buf, _("\
01074 %s: option requires an argument -- '%c'\n"),
01075                                 argv[0], c) >= 0)
01076                     {
01077                      _IO_flockfile (stderr);
01078 
01079                      int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
01080                      ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
01081 
01082                      __fxprintf (NULL, "%s", buf);
01083 
01084                      ((_IO_FILE *) stderr)->_flags2 = old_flags2;
01085                      _IO_funlockfile (stderr);
01086 
01087                      free (buf);
01088                     }
01089 #else
01090                   fprintf (stderr,
01091                           _("%s: option requires an argument -- '%c'\n"),
01092                           argv[0], c);
01093 #endif
01094                 }
01095               d->optopt = c;
01096               if (optstring[0] == ':')
01097                 c = ':';
01098               else
01099                 c = '?';
01100              }
01101            else
01102              /* We already incremented `optind' once;
01103                increment it again when taking next ARGV-elt as argument.  */
01104              d->optarg = argv[d->optind++];
01105            d->__nextchar = NULL;
01106          }
01107       }
01108     return c;
01109   }
01110 }
01111 
01112 int
01113 _getopt_internal (int argc, char *const *argv, const char *optstring,
01114                 const struct option *longopts, int *longind, int long_only)
01115 {
01116   int result;
01117 
01118   getopt_data.optind = optind;
01119   getopt_data.opterr = opterr;
01120 
01121   result = _getopt_internal_r (argc, argv, optstring, longopts,
01122                             longind, long_only, &getopt_data);
01123 
01124   optind = getopt_data.optind;
01125   optarg = getopt_data.optarg;
01126   optopt = getopt_data.optopt;
01127 
01128   return result;
01129 }
01130 
01131 int
01132 getopt (int argc, char *const *argv, const char *optstring)
01133 {
01134   return _getopt_internal (argc, argv, optstring,
01135                         (const struct option *) 0,
01136                         (int *) 0,
01137                         0);
01138 }
01139 
01140 #endif /* Not ELIDE_CODE.  */
01141 
01142 #ifdef TEST
01143 
01144 /* Compile with -DTEST to make an executable for use in testing
01145    the above definition of `getopt'.  */
01146 
01147 int
01148 main (int argc, char **argv)
01149 {
01150   int c;
01151   int digit_optind = 0;
01152 
01153   while (1)
01154     {
01155       int this_option_optind = optind ? optind : 1;
01156 
01157       c = getopt (argc, argv, "abc:d:0123456789");
01158       if (c == -1)
01159        break;
01160 
01161       switch (c)
01162        {
01163        case '0':
01164        case '1':
01165        case '2':
01166        case '3':
01167        case '4':
01168        case '5':
01169        case '6':
01170        case '7':
01171        case '8':
01172        case '9':
01173          if (digit_optind != 0 && digit_optind != this_option_optind)
01174            printf ("digits occur in two different argv-elements.\n");
01175          digit_optind = this_option_optind;
01176          printf ("option %c\n", c);
01177          break;
01178 
01179        case 'a':
01180          printf ("option a\n");
01181          break;
01182 
01183        case 'b':
01184          printf ("option b\n");
01185          break;
01186 
01187        case 'c':
01188          printf ("option c with value '%s'\n", optarg);
01189          break;
01190 
01191        case '?':
01192          break;
01193 
01194        default:
01195          printf ("?? getopt returned character code 0%o ??\n", c);
01196        }
01197     }
01198 
01199   if (optind < argc)
01200     {
01201       printf ("non-option ARGV-elements: ");
01202       while (optind < argc)
01203        printf ("%s ", argv[optind++]);
01204       printf ("\n");
01205     }
01206 
01207   exit (0);
01208 }
01209 
01210 #endif /* TEST */