File indexing completed on 2024-12-22 04:04:11

0001 /* Getopt for GNU.
0002    NOTE: getopt is now part of the C library, so if you don't know what
0003    "Keep this file name-space clean" means, talk to drepper@gnu.org
0004    before changing it!
0005 
0006    Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000
0007     Free Software Foundation, Inc.
0008 
0009    The GNU C Library is free software; you can redistribute it and/or
0010    modify it under the terms of the GNU Library General Public License as
0011    published by the Free Software Foundation; either version 2 of the
0012    License, or (at your option) any later version.
0013 
0014    The GNU C Library is distributed in the hope that it will be useful,
0015    but WITHOUT ANY WARRANTY; without even the implied warranty of
0016    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0017    Library General Public License for more details.
0018 
0019    You should have received a copy of the GNU Library General Public
0020    License along with the GNU C Library; see the file COPYING.LIB.  If not,
0021    write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
0022    Boston, MA 02110-1301, USA.  */
0023 
0024 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
0025    Ditto for AIX 3.2 and <stdlib.h>.  */
0026 #ifndef _NO_PROTO
0027 # define _NO_PROTO
0028 #endif
0029 
0030 #ifdef HAVE_CONFIG_H
0031 # include <config.h>
0032 #endif
0033 
0034 #if !defined __STDC__ || !__STDC__
0035 /* This is a separate conditional since some stdc systems
0036    reject `defined (const)'.  */
0037 # ifndef const
0038 #  define const
0039 # endif
0040 #endif
0041 
0042 #include <stdio.h>
0043 
0044 /* This needs to come after some library #include
0045    to get __GNU_LIBRARY__ defined.  */
0046 #ifdef  __GNU_LIBRARY__
0047 /* Don't include stdlib.h for non-GNU C libraries because some of them
0048    contain conflicting prototypes for getopt.  */
0049 # include <stdlib.h>
0050 # include <unistd.h>
0051 #endif  /* GNU C library.  */
0052 
0053 #ifdef VMS
0054 # include <unixlib.h>
0055 # if HAVE_STRING_H - 0
0056 #  include <string.h>
0057 # endif
0058 #endif
0059 
0060 #ifndef _
0061 /* This is for other GNU distributions with internationalized messages.  */
0062 # if defined HAVE_LIBINTL_H || defined _LIBC
0063 #  include <libintl.h>
0064 #  ifndef _
0065 #   define _(msgid) gettext (msgid)
0066 #  endif
0067 # else
0068 #  define _(msgid)  (msgid)
0069 # endif
0070 #endif
0071 
0072 /* This version of `getopt' appears to the caller like standard Unix `getopt'
0073    but it behaves differently for the user, since it allows the user
0074    to intersperse the options with the other arguments.
0075 
0076    As `getopt' works, it permutes the elements of ARGV so that,
0077    when it is done, all the options precede everything else.  Thus
0078    all application programs are extended to handle flexible argument order.
0079 
0080    Setting the environment variable POSIXLY_CORRECT disables permutation.
0081    Then the behavior is completely standard.
0082 
0083    GNU application programs can use a third alternative mode in which
0084    they can distinguish the relative order of options and other arguments.  */
0085 
0086 #include "getopt.h"
0087 
0088 /* For communication from `getopt' to the caller.
0089    When `getopt' finds an option that takes an argument,
0090    the argument value is returned here.
0091    Also, when `ordering' is RETURN_IN_ORDER,
0092    each non-option ARGV-element is returned here.  */
0093 
0094 char *optarg;
0095 
0096 /* Index in ARGV of the next element to be scanned.
0097    This is used for communication to and from the caller
0098    and for communication between successive calls to `getopt'.
0099 
0100    On entry to `getopt', zero means this is the first call; initialize.
0101 
0102    When `getopt' returns -1, this is the index of the first of the
0103    non-option elements that the caller should itself scan.
0104 
0105    Otherwise, `optind' communicates from one call to the next
0106    how much of ARGV has been scanned so far.  */
0107 
0108 /* 1003.2 says this must be 1 before any call.  */
0109 int optind = 1;
0110 
0111 /* Formerly, initialization of getopt depended on optind==0, which
0112    causes problems with re-calling getopt as programs generally don't
0113    know that. */
0114 
0115 int __getopt_initialized;
0116 
0117 /* The next char to be scanned in the option-element
0118    in which the last option character we returned was found.
0119    This allows us to pick up the scan where we left off.
0120 
0121    If this is zero, or a null string, it means resume the scan
0122    by advancing to the next ARGV-element.  */
0123 
0124 static char *nextchar;
0125 
0126 /* Callers store zero here to inhibit the error message
0127    for unrecognized options.  */
0128 
0129 int opterr = 1;
0130 
0131 /* Set to an option character which was unrecognized.
0132    This must be initialized on some systems to avoid linking in the
0133    system's own getopt implementation.  */
0134 
0135 int optopt = '?';
0136 
0137 /* Describe how to deal with options that follow non-option ARGV-elements.
0138 
0139    If the caller did not specify anything,
0140    the default is REQUIRE_ORDER if the environment variable
0141    POSIXLY_CORRECT is defined, PERMUTE otherwise.
0142 
0143    REQUIRE_ORDER means don't recognize them as options;
0144    stop option processing when the first non-option is seen.
0145    This is what Unix does.
0146    This mode of operation is selected by either setting the environment
0147    variable POSIXLY_CORRECT, or using `+' as the first character
0148    of the list of option characters.
0149 
0150    PERMUTE is the default.  We permute the contents of ARGV as we scan,
0151    so that eventually all the non-options are at the end.  This allows options
0152    to be given in any order, even with programs that were not written to
0153    expect this.
0154 
0155    RETURN_IN_ORDER is an option available to programs that were written
0156    to expect options and other ARGV-elements in any order and that care about
0157    the ordering of the two.  We describe each non-option ARGV-element
0158    as if it were the argument of an option with character code 1.
0159    Using `-' as the first character of the list of option characters
0160    selects this mode of operation.
0161 
0162    The special argument `--' forces an end of option-scanning regardless
0163    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
0164    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
0165 
0166 static enum
0167 {
0168   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
0169 } ordering;
0170 
0171 /* Value of POSIXLY_CORRECT environment variable.  */
0172 static char *posixly_correct;
0173 
0174 #ifdef  __GNU_LIBRARY__
0175 /* We want to avoid inclusion of string.h with non-GNU libraries
0176    because there are many ways it can cause trouble.
0177    On some systems, it contains special magic macros that don't work
0178    in GCC.  */
0179 # include <string.h>
0180 # define my_index   strchr
0181 #else
0182 
0183 # if HAVE_STRING_H
0184 #  include <string.h>
0185 # else
0186 #  include <strings.h>
0187 # endif
0188 
0189 /* Avoid depending on library functions or files
0190    whose names are inconsistent.  */
0191 
0192 #ifndef getenv
0193 extern char *getenv ();
0194 #endif
0195 
0196 static char *
0197 my_index (str, chr)
0198      const char *str;
0199      int chr;
0200 {
0201   while (*str)
0202     {
0203       if (*str == chr)
0204     return (char *) str;
0205       str++;
0206     }
0207   return 0;
0208 }
0209 
0210 /* If using GCC, we can safely declare strlen this way.
0211    If not using GCC, it is ok not to declare it.  */
0212 #ifdef __GNUC__
0213 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
0214    That was relevant to code that was here before.  */
0215 # if (!defined __STDC__ || !__STDC__) && !defined strlen
0216 /* gcc with -traditional declares the built-in strlen to return int,
0217    and has done so at least since version 2.4.5. -- rms.  */
0218 extern int strlen (const char *);
0219 # endif /* not __STDC__ */
0220 #endif /* __GNUC__ */
0221 
0222 #endif /* not __GNU_LIBRARY__ */
0223 
0224 /* Handle permutation of arguments.  */
0225 
0226 /* Describe the part of ARGV that contains non-options that have
0227    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
0228    `last_nonopt' is the index after the last of them.  */
0229 
0230 static int first_nonopt;
0231 static int last_nonopt;
0232 
0233 #ifdef _LIBC
0234 /* Bash 2.0 gives us an environment variable containing flags
0235    indicating ARGV elements that should not be considered arguments.  */
0236 
0237 /* Defined in getopt_init.c  */
0238 extern char *__getopt_nonoption_flags;
0239 
0240 static int nonoption_flags_max_len;
0241 static int nonoption_flags_len;
0242 
0243 static int original_argc;
0244 static char *const *original_argv;
0245 
0246 /* Make sure the environment variable bash 2.0 puts in the environment
0247    is valid for the getopt call we must make sure that the ARGV passed
0248    to getopt is that one passed to the process.  */
0249 static void
0250 __attribute__ ((unused))
0251 store_args_and_env (int argc, char *const *argv)
0252 {
0253   /* XXX This is no good solution.  We should rather copy the args so
0254      that we can compare them later.  But we must not use malloc(3).  */
0255   original_argc = argc;
0256   original_argv = argv;
0257 }
0258 # ifdef text_set_element
0259 text_set_element (__libc_subinit, store_args_and_env);
0260 # endif /* text_set_element */
0261 
0262 # define SWAP_FLAGS(ch1, ch2) \
0263   if (nonoption_flags_len > 0)                            \
0264     {                                         \
0265       char __tmp = __getopt_nonoption_flags[ch1];                 \
0266       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
0267       __getopt_nonoption_flags[ch2] = __tmp;                      \
0268     }
0269 #else   /* !_LIBC */
0270 # define SWAP_FLAGS(ch1, ch2)
0271 #endif  /* _LIBC */
0272 
0273 /* Exchange two adjacent subsequences of ARGV.
0274    One subsequence is elements [first_nonopt,last_nonopt)
0275    which contains all the non-options that have been skipped so far.
0276    The other is elements [last_nonopt,optind), which contains all
0277    the options processed since those non-options were skipped.
0278 
0279    `first_nonopt' and `last_nonopt' are relocated so that they describe
0280    the new indices of the non-options in ARGV after they are moved.  */
0281 
0282 #if defined __STDC__ && __STDC__
0283 static void exchange (char **);
0284 #endif
0285 
0286 static void
0287 exchange (argv)
0288      char **argv;
0289 {
0290   int bottom = first_nonopt;
0291   int middle = last_nonopt;
0292   int top = optind;
0293   char *tem;
0294 
0295   /* Exchange the shorter segment with the far end of the longer segment.
0296      That puts the shorter segment into the right place.
0297      It leaves the longer segment in the right place overall,
0298      but it consists of two parts that need to be swapped next.  */
0299 
0300 #ifdef _LIBC
0301   /* First make sure the handling of the `__getopt_nonoption_flags'
0302      string can work normally.  Our top argument must be in the range
0303      of the string.  */
0304   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
0305     {
0306       /* We must extend the array.  The user plays games with us and
0307      presents new arguments.  */
0308       char *new_str = malloc (top + 1);
0309       if (new_str == NULL)
0310     nonoption_flags_len = nonoption_flags_max_len = 0;
0311       else
0312     {
0313       memset (__mempcpy (new_str, __getopt_nonoption_flags,
0314                  nonoption_flags_max_len),
0315           '\0', top + 1 - nonoption_flags_max_len);
0316       nonoption_flags_max_len = top + 1;
0317       __getopt_nonoption_flags = new_str;
0318     }
0319     }
0320 #endif
0321 
0322   while (top > middle && middle > bottom)
0323     {
0324       if (top - middle > middle - bottom)
0325     {
0326       /* Bottom segment is the short one.  */
0327       int len = middle - bottom;
0328       register int i;
0329 
0330       /* Swap it with the top part of the top segment.  */
0331       for (i = 0; i < len; i++)
0332         {
0333           tem = argv[bottom + i];
0334           argv[bottom + i] = argv[top - (middle - bottom) + i];
0335           argv[top - (middle - bottom) + i] = tem;
0336           SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
0337         }
0338       /* Exclude the moved bottom segment from further swapping.  */
0339       top -= len;
0340     }
0341       else
0342     {
0343       /* Top segment is the short one.  */
0344       int len = top - middle;
0345       register int i;
0346 
0347       /* Swap it with the bottom part of the bottom segment.  */
0348       for (i = 0; i < len; i++)
0349         {
0350           tem = argv[bottom + i];
0351           argv[bottom + i] = argv[middle + i];
0352           argv[middle + i] = tem;
0353           SWAP_FLAGS (bottom + i, middle + i);
0354         }
0355       /* Exclude the moved top segment from further swapping.  */
0356       bottom += len;
0357     }
0358     }
0359 
0360   /* Update records for the slots the non-options now occupy.  */
0361 
0362   first_nonopt += (optind - last_nonopt);
0363   last_nonopt = optind;
0364 }
0365 
0366 /* Initialize the internal data when the first call is made.  */
0367 
0368 #if defined __STDC__ && __STDC__
0369 static const char *_getopt_initialize (int, char *const *, const char *);
0370 #endif
0371 static const char *
0372 _getopt_initialize (argc, argv, optstring)
0373      int argc;
0374      char *const *argv;
0375      const char *optstring;
0376 {
0377   /* Start processing options with ARGV-element 1 (since ARGV-element 0
0378      is the program name); the sequence of previously skipped
0379      non-option ARGV-elements is empty.  */
0380 
0381   first_nonopt = last_nonopt = optind;
0382 
0383   nextchar = NULL;
0384 
0385   posixly_correct = getenv ("POSIXLY_CORRECT");
0386 
0387   /* Determine how to handle the ordering of options and nonoptions.  */
0388 
0389   if (optstring[0] == '-')
0390     {
0391       ordering = RETURN_IN_ORDER;
0392       ++optstring;
0393     }
0394   else if (optstring[0] == '+')
0395     {
0396       ordering = REQUIRE_ORDER;
0397       ++optstring;
0398     }
0399   else if (posixly_correct != NULL)
0400     ordering = REQUIRE_ORDER;
0401   else
0402     ordering = PERMUTE;
0403 
0404 #ifdef _LIBC
0405   if (posixly_correct == NULL
0406       && argc == original_argc && argv == original_argv)
0407     {
0408       if (nonoption_flags_max_len == 0)
0409     {
0410       if (__getopt_nonoption_flags == NULL
0411           || __getopt_nonoption_flags[0] == '\0')
0412         nonoption_flags_max_len = -1;
0413       else
0414         {
0415           const char *orig_str = __getopt_nonoption_flags;
0416           int len = nonoption_flags_max_len = strlen (orig_str);
0417           if (nonoption_flags_max_len < argc)
0418         nonoption_flags_max_len = argc;
0419           __getopt_nonoption_flags =
0420         (char *) malloc (nonoption_flags_max_len);
0421           if (__getopt_nonoption_flags == NULL)
0422         nonoption_flags_max_len = -1;
0423           else
0424         memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
0425             '\0', nonoption_flags_max_len - len);
0426         }
0427     }
0428       nonoption_flags_len = nonoption_flags_max_len;
0429     }
0430   else
0431     nonoption_flags_len = 0;
0432 #endif
0433 
0434   return optstring;
0435 }
0436 
0437 /* Scan elements of ARGV (whose length is ARGC) for option characters
0438    given in OPTSTRING.
0439 
0440    If an element of ARGV starts with '-', and is not exactly "-" or "--",
0441    then it is an option element.  The characters of this element
0442    (aside from the initial '-') are option characters.  If `getopt'
0443    is called repeatedly, it returns successively each of the option characters
0444    from each of the option elements.
0445 
0446    If `getopt' finds another option character, it returns that character,
0447    updating `optind' and `nextchar' so that the next call to `getopt' can
0448    resume the scan with the following option character or ARGV-element.
0449 
0450    If there are no more option characters, `getopt' returns -1.
0451    Then `optind' is the index in ARGV of the first ARGV-element
0452    that is not an option.  (The ARGV-elements have been permuted
0453    so that those that are not options now come last.)
0454 
0455    OPTSTRING is a string containing the legitimate option characters.
0456    If an option character is seen that is not listed in OPTSTRING,
0457    return '?' after printing an error message.  If you set `opterr' to
0458    zero, the error message is suppressed but we still return '?'.
0459 
0460    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
0461    so the following text in the same ARGV-element, or the text of the following
0462    ARGV-element, is returned in `optarg'.  Two colons mean an option that
0463    wants an optional arg; if there is text in the current ARGV-element,
0464    it is returned in `optarg', otherwise `optarg' is set to zero.
0465 
0466    If OPTSTRING starts with `-' or `+', it requests different methods of
0467    handling the non-option ARGV-elements.
0468    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
0469 
0470    Long-named options begin with `--' instead of `-'.
0471    Their names may be abbreviated as long as the abbreviation is unique
0472    or is an exact match for some defined option.  If they have an
0473    argument, it follows the option name in the same ARGV-element, separated
0474    from the option name by a `=', or else the in next ARGV-element.
0475    When `getopt' finds a long-named option, it returns 0 if that option's
0476    `flag' field is nonzero, the value of the option's `val' field
0477    if the `flag' field is zero.
0478 
0479    The elements of ARGV aren't really const, because we permute them.
0480    But we pretend they're const in the prototype to be compatible
0481    with other systems.
0482 
0483    LONGOPTS is a vector of `struct option' terminated by an
0484    element containing a name which is zero.
0485 
0486    LONGIND returns the index in LONGOPT of the long-named option found.
0487    It is only valid when a long-named option has been found by the most
0488    recent call.
0489 
0490    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
0491    long-named options.  */
0492 
0493 int
0494 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
0495      int argc;
0496      char *const *argv;
0497      const char *optstring;
0498      const struct option *longopts;
0499      int *longind;
0500      int long_only;
0501 {
0502   int print_errors = opterr;
0503   if (optstring[0] == ':')
0504     print_errors = 0;
0505 
0506   if (argc < 1)
0507     return -1;
0508 
0509   optarg = NULL;
0510 
0511   if (optind == 0 || !__getopt_initialized)
0512     {
0513       if (optind == 0)
0514     optind = 1; /* Don't scan ARGV[0], the program name.  */
0515       optstring = _getopt_initialize (argc, argv, optstring);
0516       __getopt_initialized = 1;
0517     }
0518 
0519   /* Test whether ARGV[optind] points to a non-option argument.
0520      Either it does not have option syntax, or there is an environment flag
0521      from the shell indicating it is not an option.  The later information
0522      is only used when the used in the GNU libc.  */
0523 #ifdef _LIBC
0524 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'       \
0525               || (optind < nonoption_flags_len                \
0526               && __getopt_nonoption_flags[optind] == '1'))
0527 #else
0528 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
0529 #endif
0530 
0531   if (nextchar == NULL || *nextchar == '\0')
0532     {
0533       /* Advance to the next ARGV-element.  */
0534 
0535       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
0536      moved back by the user (who may also have changed the arguments).  */
0537       if (last_nonopt > optind)
0538     last_nonopt = optind;
0539       if (first_nonopt > optind)
0540     first_nonopt = optind;
0541 
0542       if (ordering == PERMUTE)
0543     {
0544       /* If we have just processed some options following some non-options,
0545          exchange them so that the options come first.  */
0546 
0547       if (first_nonopt != last_nonopt && last_nonopt != optind)
0548         exchange ((char **) argv);
0549       else if (last_nonopt != optind)
0550         first_nonopt = optind;
0551 
0552       /* Skip any additional non-options
0553          and extend the range of non-options previously skipped.  */
0554 
0555       while (optind < argc && NONOPTION_P)
0556         optind++;
0557       last_nonopt = optind;
0558     }
0559 
0560       /* The special ARGV-element `--' means premature end of options.
0561      Skip it like a null option,
0562      then exchange with previous non-options as if it were an option,
0563      then skip everything else like a non-option.  */
0564 
0565       if (optind != argc && !strcmp (argv[optind], "--"))
0566     {
0567       optind++;
0568 
0569       if (first_nonopt != last_nonopt && last_nonopt != optind)
0570         exchange ((char **) argv);
0571       else if (first_nonopt == last_nonopt)
0572         first_nonopt = optind;
0573       last_nonopt = argc;
0574 
0575       optind = argc;
0576     }
0577 
0578       /* If we have done all the ARGV-elements, stop the scan
0579      and back over any non-options that we skipped and permuted.  */
0580 
0581       if (optind == argc)
0582     {
0583       /* Set the next-arg-index to point at the non-options
0584          that we previously skipped, so the caller will digest them.  */
0585       if (first_nonopt != last_nonopt)
0586         optind = first_nonopt;
0587       return -1;
0588     }
0589 
0590       /* If we have come to a non-option and did not permute it,
0591      either stop the scan or describe it to the caller and pass it by.  */
0592 
0593       if (NONOPTION_P)
0594     {
0595       if (ordering == REQUIRE_ORDER)
0596         return -1;
0597       optarg = argv[optind++];
0598       return 1;
0599     }
0600 
0601       /* We have found another option-ARGV-element.
0602      Skip the initial punctuation.  */
0603 
0604       nextchar = (argv[optind] + 1
0605           + (longopts != NULL && argv[optind][1] == '-'));
0606     }
0607 
0608   /* Decode the current option-ARGV-element.  */
0609 
0610   /* Check whether the ARGV-element is a long option.
0611 
0612      If long_only and the ARGV-element has the form "-f", where f is
0613      a valid short option, don't consider it an abbreviated form of
0614      a long option that starts with f.  Otherwise there would be no
0615      way to give the -f short option.
0616 
0617      On the other hand, if there's a long option "fubar" and
0618      the ARGV-element is "-fu", do consider that an abbreviation of
0619      the long option, just like "--fu", and not "-f" with arg "u".
0620 
0621      This distinction seems to be the most useful approach.  */
0622 
0623   if (longopts != NULL
0624       && (argv[optind][1] == '-'
0625       || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
0626     {
0627       char *nameend;
0628       const struct option *p;
0629       const struct option *pfound = NULL;
0630       int exact = 0;
0631       int ambig = 0;
0632       int indfound = -1;
0633       int option_index;
0634 
0635       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
0636     /* Do nothing.  */ ;
0637 
0638       /* Test all long options for either exact match
0639      or abbreviated matches.  */
0640       for (p = longopts, option_index = 0; p->name; p++, option_index++)
0641     if (!strncmp (p->name, nextchar, nameend - nextchar))
0642       {
0643         if ((unsigned int) (nameend - nextchar)
0644         == (unsigned int) strlen (p->name))
0645           {
0646         /* Exact match found.  */
0647         pfound = p;
0648         indfound = option_index;
0649         exact = 1;
0650         break;
0651           }
0652         else if (pfound == NULL)
0653           {
0654         /* First nonexact match found.  */
0655         pfound = p;
0656         indfound = option_index;
0657           }
0658         else if (long_only
0659              || pfound->has_arg != p->has_arg
0660              || pfound->flag != p->flag
0661              || pfound->val != p->val)
0662           /* Second or later nonexact match found.  */
0663           ambig = 1;
0664       }
0665 
0666       if (ambig && !exact)
0667     {
0668       if (print_errors)
0669         fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
0670              argv[0], argv[optind]);
0671       nextchar += strlen (nextchar);
0672       optind++;
0673       optopt = 0;
0674       return '?';
0675     }
0676 
0677       if (pfound != NULL)
0678     {
0679       option_index = indfound;
0680       optind++;
0681       if (*nameend)
0682         {
0683           /* Don't test has_arg with >, because some C compilers don't
0684          allow it to be used on enums.  */
0685           if (pfound->has_arg)
0686         optarg = nameend + 1;
0687           else
0688         {
0689           if (print_errors)
0690             {
0691               if (argv[optind - 1][1] == '-')
0692             /* --option */
0693             fprintf (stderr,
0694                  _("%s: option `--%s' doesn't allow an argument\n"),
0695                  argv[0], pfound->name);
0696               else
0697             /* +option or -option */
0698             fprintf (stderr,
0699                  _("%s: option `%c%s' doesn't allow an argument\n"),
0700                  argv[0], argv[optind - 1][0], pfound->name);
0701             }
0702 
0703           nextchar += strlen (nextchar);
0704 
0705           optopt = pfound->val;
0706           return '?';
0707         }
0708         }
0709       else if (pfound->has_arg == 1)
0710         {
0711           if (optind < argc)
0712         optarg = argv[optind++];
0713           else
0714         {
0715           if (print_errors)
0716             fprintf (stderr,
0717                _("%s: option `%s' requires an argument\n"),
0718                argv[0], argv[optind - 1]);
0719           nextchar += strlen (nextchar);
0720           optopt = pfound->val;
0721           return optstring[0] == ':' ? ':' : '?';
0722         }
0723         }
0724       nextchar += strlen (nextchar);
0725       if (longind != NULL)
0726         *longind = option_index;
0727       if (pfound->flag)
0728         {
0729           *(pfound->flag) = pfound->val;
0730           return 0;
0731         }
0732       return pfound->val;
0733     }
0734 
0735       /* Can't find it as a long option.  If this is not getopt_long_only,
0736      or the option starts with '--' or is not a valid short
0737      option, then it's an error.
0738      Otherwise interpret it as a short option.  */
0739       if (!long_only || argv[optind][1] == '-'
0740       || my_index (optstring, *nextchar) == NULL)
0741     {
0742       if (print_errors)
0743         {
0744           if (argv[optind][1] == '-')
0745         /* --option */
0746         fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
0747              argv[0], nextchar);
0748           else
0749         /* +option or -option */
0750         fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
0751              argv[0], argv[optind][0], nextchar);
0752         }
0753       nextchar = (char *) "";
0754       optind++;
0755       optopt = 0;
0756       return '?';
0757     }
0758     }
0759 
0760   /* Look at and handle the next short option-character.  */
0761 
0762   {
0763     char c = *nextchar++;
0764     char *temp = my_index (optstring, c);
0765 
0766     /* Increment `optind' when we start to process its last character.  */
0767     if (*nextchar == '\0')
0768       ++optind;
0769 
0770     if (temp == NULL || c == ':')
0771       {
0772     if (print_errors)
0773       {
0774         if (posixly_correct)
0775           /* 1003.2 specifies the format of this message.  */
0776           fprintf (stderr, _("%s: illegal option -- %c\n"),
0777                argv[0], c);
0778         else
0779           fprintf (stderr, _("%s: invalid option -- %c\n"),
0780                argv[0], c);
0781       }
0782     optopt = c;
0783     return '?';
0784       }
0785     /* Convenience. Treat POSIX -W foo same as long option --foo */
0786     if (temp[0] == 'W' && temp[1] == ';')
0787       {
0788     char *nameend;
0789     const struct option *p;
0790     const struct option *pfound = NULL;
0791     int exact = 0;
0792     int ambig = 0;
0793     int indfound = 0;
0794     int option_index;
0795 
0796     /* This is an option that requires an argument.  */
0797     if (*nextchar != '\0')
0798       {
0799         optarg = nextchar;
0800         /* If we end this ARGV-element by taking the rest as an arg,
0801            we must advance to the next element now.  */
0802         optind++;
0803       }
0804     else if (optind == argc)
0805       {
0806         if (print_errors)
0807           {
0808         /* 1003.2 specifies the format of this message.  */
0809         fprintf (stderr, _("%s: option requires an argument -- %c\n"),
0810              argv[0], c);
0811           }
0812         optopt = c;
0813         if (optstring[0] == ':')
0814           c = ':';
0815         else
0816           c = '?';
0817         return c;
0818       }
0819     else
0820       /* We already incremented `optind' once;
0821          increment it again when taking next ARGV-elt as argument.  */
0822       optarg = argv[optind++];
0823 
0824     /* optarg is now the argument, see if it's in the
0825        table of longopts.  */
0826 
0827     for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
0828       /* Do nothing.  */ ;
0829 
0830     /* Test all long options for either exact match
0831        or abbreviated matches.  */
0832     for (p = longopts, option_index = 0; p->name; p++, option_index++)
0833       if (!strncmp (p->name, nextchar, nameend - nextchar))
0834         {
0835           if ((unsigned int) (nameend - nextchar) == strlen (p->name))
0836         {
0837           /* Exact match found.  */
0838           pfound = p;
0839           indfound = option_index;
0840           exact = 1;
0841           break;
0842         }
0843           else if (pfound == NULL)
0844         {
0845           /* First nonexact match found.  */
0846           pfound = p;
0847           indfound = option_index;
0848         }
0849           else
0850         /* Second or later nonexact match found.  */
0851         ambig = 1;
0852         }
0853     if (ambig && !exact)
0854       {
0855         if (print_errors)
0856           fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
0857                argv[0], argv[optind]);
0858         nextchar += strlen (nextchar);
0859         optind++;
0860         return '?';
0861       }
0862     if (pfound != NULL)
0863       {
0864         option_index = indfound;
0865         if (*nameend)
0866           {
0867         /* Don't test has_arg with >, because some C compilers don't
0868            allow it to be used on enums.  */
0869         if (pfound->has_arg)
0870           optarg = nameend + 1;
0871         else
0872           {
0873             if (print_errors)
0874               fprintf (stderr, _("%s: option `-W %s' doesn't allow an argument\n"),
0875                    argv[0], pfound->name);
0876 
0877             nextchar += strlen (nextchar);
0878             return '?';
0879           }
0880           }
0881         else if (pfound->has_arg == 1)
0882           {
0883         if (optind < argc)
0884           optarg = argv[optind++];
0885         else
0886           {
0887             if (print_errors)
0888               fprintf (stderr,
0889                    _("%s: option `%s' requires an argument\n"),
0890                    argv[0], argv[optind - 1]);
0891             nextchar += strlen (nextchar);
0892             return optstring[0] == ':' ? ':' : '?';
0893           }
0894           }
0895         nextchar += strlen (nextchar);
0896         if (longind != NULL)
0897           *longind = option_index;
0898         if (pfound->flag)
0899           {
0900         *(pfound->flag) = pfound->val;
0901         return 0;
0902           }
0903         return pfound->val;
0904       }
0905       nextchar = NULL;
0906       return 'W';   /* Let the application handle it.   */
0907       }
0908     if (temp[1] == ':')
0909       {
0910     if (temp[2] == ':')
0911       {
0912         /* This is an option that accepts an argument optionally.  */
0913         if (*nextchar != '\0')
0914           {
0915         optarg = nextchar;
0916         optind++;
0917           }
0918         else
0919           optarg = NULL;
0920         nextchar = NULL;
0921       }
0922     else
0923       {
0924         /* This is an option that requires an argument.  */
0925         if (*nextchar != '\0')
0926           {
0927         optarg = nextchar;
0928         /* If we end this ARGV-element by taking the rest as an arg,
0929            we must advance to the next element now.  */
0930         optind++;
0931           }
0932         else if (optind == argc)
0933           {
0934         if (print_errors)
0935           {
0936             /* 1003.2 specifies the format of this message.  */
0937             fprintf (stderr,
0938                  _("%s: option requires an argument -- %c\n"),
0939                  argv[0], c);
0940           }
0941         optopt = c;
0942         if (optstring[0] == ':')
0943           c = ':';
0944         else
0945           c = '?';
0946           }
0947         else
0948           /* We already incremented `optind' once;
0949          increment it again when taking next ARGV-elt as argument.  */
0950           optarg = argv[optind++];
0951         nextchar = NULL;
0952       }
0953       }
0954     return c;
0955   }
0956 }
0957 
0958 int
0959 getopt (argc, argv, optstring)
0960      int argc;
0961      char *const *argv;
0962      const char *optstring;
0963 {
0964   return _getopt_internal (argc, argv, optstring,
0965                (const struct option *) 0,
0966                (int *) 0,
0967                0);
0968 }
0969 
0970 
0971 #ifdef TEST
0972 
0973 /* Compile with -DTEST to make an executable for use in testing
0974    the above definition of `getopt'.  */
0975 
0976 int
0977 main (argc, argv)
0978      int argc;
0979      char **argv;
0980 {
0981   int c;
0982   int digit_optind = 0;
0983 
0984   while (1)
0985     {
0986       int this_option_optind = optind ? optind : 1;
0987 
0988       c = getopt (argc, argv, "abc:d:0123456789");
0989       if (c == -1)
0990     break;
0991 
0992       switch (c)
0993     {
0994     case '0':
0995     case '1':
0996     case '2':
0997     case '3':
0998     case '4':
0999     case '5':
1000     case '6':
1001     case '7':
1002     case '8':
1003     case '9':
1004       if (digit_optind != 0 && digit_optind != this_option_optind)
1005         printf ("digits occur in two different argv-elements.\n");
1006       digit_optind = this_option_optind;
1007       printf ("option %c\n", c);
1008       break;
1009 
1010     case 'a':
1011       printf ("option a\n");
1012       break;
1013 
1014     case 'b':
1015       printf ("option b\n");
1016       break;
1017 
1018     case 'c':
1019       printf ("option c with value `%s'\n", optarg);
1020       break;
1021 
1022     case '?':
1023       break;
1024 
1025     default:
1026       printf ("?? getopt returned character code 0%o ??\n", c);
1027     }
1028     }
1029 
1030   if (optind < argc)
1031     {
1032       printf ("non-option ARGV-elements: ");
1033       while (optind < argc)
1034     printf ("%s ", argv[optind++]);
1035       printf ("\n");
1036     }
1037 
1038   exit (0);
1039 }
1040 
1041 #endif /* TEST */