Back to index

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