Home | History | Annotate | Line # | Download | only in lib
getopt.c revision 1.1
      1 /*	$NetBSD: getopt.c,v 1.1 2016/01/13 03:15:30 christos Exp $	*/
      2 
      3 /* Getopt for GNU.
      4    NOTE: getopt is now part of the C library, so if you don't know what
      5    "Keep this file name-space clean" means, talk to drepper (at) gnu.org
      6    before changing it!
      7    Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001
      8    	Free Software Foundation, Inc.
      9    This file is part of the GNU C Library.
     10 
     11    This program is free software; you can redistribute it and/or modify
     12    it under the terms of the GNU General Public License as published by
     13    the Free Software Foundation; either version 2, or (at your option)
     14    any later version.
     15 
     16    This program is distributed in the hope that it will be useful,
     17    but WITHOUT ANY WARRANTY; without even the implied warranty of
     18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     19    GNU General Public License for more details.
     20 
     21    You should have received a copy of the GNU General Public License
     22    along with this program; if not, write to the Free Software Foundation,
     23    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
     24 
     25 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
     27    Ditto for AIX 3.2 and <stdlib.h>.  */
     28 #ifndef _NO_PROTO
     29 # define _NO_PROTO
     30 #endif
     31 
     32 #ifdef HAVE_CONFIG_H
     33 # include <config.h>
     34 #endif
     35 
     36 #if !defined __STDC__ || !__STDC__
     37 /* This is a separate conditional since some stdc systems
     38    reject `defined (const)'.  */
     39 # ifndef const
     40 #  define const
     41 # endif
     42 #endif
     43 
     44 #include <stdio.h>
     45 
     46 /* Comment out all this code if we are using the GNU C Library, and are not
     47    actually compiling the library itself.  This code is part of the GNU C
     48    Library, but also included in many other GNU distributions.  Compiling
     49    and linking in this code is a waste when using the GNU C library
     50    (especially if it is a shared library).  Rather than having every GNU
     51    program understand `configure --with-gnu-libc' and omit the object files,
     52    it is simpler to just do this in the source for each such file.  */
     53 
     54 #define GETOPT_INTERFACE_VERSION 2
     55 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
     56 # include <gnu-versions.h>
     57 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
     58 #  define ELIDE_CODE
     59 # endif
     60 #endif
     61 
     62 #ifndef ELIDE_CODE
     63 
     64 
     65 /* This needs to come after some library #include
     66    to get __GNU_LIBRARY__ defined.  */
     67 #ifdef	__GNU_LIBRARY__
     68 /* Don't include stdlib.h for non-GNU C libraries because some of them
     69    contain conflicting prototypes for getopt.  */
     70 # include <stdlib.h>
     71 # include <unistd.h>
     72 #endif	/* GNU C library.  */
     73 
     74 #ifdef VMS
     75 # include <unixlib.h>
     76 # if HAVE_STRING_H - 0
     77 #  include <string.h>
     78 # endif
     79 #endif
     80 
     81 #ifndef _
     82 /* This is for other GNU distributions with internationalized messages.  */
     83 # if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
     84 #  include <libintl.h>
     85 #  ifndef _
     86 #   define _(msgid)	gettext (msgid)
     87 #  endif
     88 # else
     89 #  define _(msgid)	(msgid)
     90 # endif
     91 #endif
     92 
     93 /* This version of `getopt' appears to the caller like standard Unix `getopt'
     94    but it behaves differently for the user, since it allows the user
     95    to intersperse the options with the other arguments.
     96 
     97    As `getopt' works, it permutes the elements of ARGV so that,
     98    when it is done, all the options precede everything else.  Thus
     99    all application programs are extended to handle flexible argument order.
    100 
    101    Setting the environment variable POSIXLY_CORRECT disables permutation.
    102    Then the behavior is completely standard.
    103 
    104    GNU application programs can use a third alternative mode in which
    105    they can distinguish the relative order of options and other arguments.  */
    106 
    107 #include "getopt.h"
    108 
    109 /* For communication from `getopt' to the caller.
    110    When `getopt' finds an option that takes an argument,
    111    the argument value is returned here.
    112    Also, when `ordering' is RETURN_IN_ORDER,
    113    each non-option ARGV-element is returned here.  */
    114 
    115 char *optarg;
    116 
    117 /* Index in ARGV of the next element to be scanned.
    118    This is used for communication to and from the caller
    119    and for communication between successive calls to `getopt'.
    120 
    121    On entry to `getopt', zero means this is the first call; initialize.
    122 
    123    When `getopt' returns -1, this is the index of the first of the
    124    non-option elements that the caller should itself scan.
    125 
    126    Otherwise, `optind' communicates from one call to the next
    127    how much of ARGV has been scanned so far.  */
    128 
    129 /* 1003.2 says this must be 1 before any call.  */
    130 int optind = 1;
    131 
    132 /* Formerly, initialization of getopt depended on optind==0, which
    133    causes problems with re-calling getopt as programs generally don't
    134    know that. */
    135 
    136 int __getopt_initialized;
    137 
    138 /* The next char to be scanned in the option-element
    139    in which the last option character we returned was found.
    140    This allows us to pick up the scan where we left off.
    141 
    142    If this is zero, or a null string, it means resume the scan
    143    by advancing to the next ARGV-element.  */
    144 
    145 static char *nextchar;
    146 
    147 /* Callers store zero here to inhibit the error message
    148    for unrecognized options.  */
    149 
    150 int opterr = 1;
    151 
    152 /* Set to an option character which was unrecognized.
    153    This must be initialized on some systems to avoid linking in the
    154    system's own getopt implementation.  */
    155 
    156 int optopt = '?';
    157 
    158 /* Describe how to deal with options that follow non-option ARGV-elements.
    159 
    160    If the caller did not specify anything,
    161    the default is REQUIRE_ORDER if the environment variable
    162    POSIXLY_CORRECT is defined, PERMUTE otherwise.
    163 
    164    REQUIRE_ORDER means don't recognize them as options;
    165    stop option processing when the first non-option is seen.
    166    This is what Unix does.
    167    This mode of operation is selected by either setting the environment
    168    variable POSIXLY_CORRECT, or using `+' as the first character
    169    of the list of option characters.
    170 
    171    PERMUTE is the default.  We permute the contents of ARGV as we scan,
    172    so that eventually all the non-options are at the end.  This allows options
    173    to be given in any order, even with programs that were not written to
    174    expect this.
    175 
    176    RETURN_IN_ORDER is an option available to programs that were written
    177    to expect options and other ARGV-elements in any order and that care about
    178    the ordering of the two.  We describe each non-option ARGV-element
    179    as if it were the argument of an option with character code 1.
    180    Using `-' as the first character of the list of option characters
    181    selects this mode of operation.
    182 
    183    The special argument `--' forces an end of option-scanning regardless
    184    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
    185    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
    186 
    187 static enum
    188 {
    189   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
    190 } ordering;
    191 
    192 /* Value of POSIXLY_CORRECT environment variable.  */
    193 static char *posixly_correct;
    194 
    195 #ifdef	__GNU_LIBRARY__
    197 /* We want to avoid inclusion of string.h with non-GNU libraries
    198    because there are many ways it can cause trouble.
    199    On some systems, it contains special magic macros that don't work
    200    in GCC.  */
    201 # include <string.h>
    202 # define my_index	strchr
    203 #else
    204 
    205 # if HAVE_STRING_H
    206 #  include <string.h>
    207 # else
    208 #  include <strings.h>
    209 # endif
    210 
    211 /* Avoid depending on library functions or files
    212    whose names are inconsistent.  */
    213 
    214 #ifndef getenv
    215 extern char *getenv ();
    216 #endif
    217 
    218 static char *
    219 my_index (str, chr)
    220      const char *str;
    221      int chr;
    222 {
    223   while (*str)
    224     {
    225       if (*str == chr)
    226 	return (char *) str;
    227       str++;
    228     }
    229   return 0;
    230 }
    231 
    232 /* If using GCC, we can safely declare strlen this way.
    233    If not using GCC, it is ok not to declare it.  */
    234 #ifdef __GNUC__
    235 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
    236    That was relevant to code that was here before.  */
    237 # if (!defined __STDC__ || !__STDC__) && !defined strlen
    238 /* gcc with -traditional declares the built-in strlen to return int,
    239    and has done so at least since version 2.4.5. -- rms.  */
    240 extern int strlen (const char *);
    241 # endif /* not __STDC__ */
    242 #endif /* __GNUC__ */
    243 
    244 #endif /* not __GNU_LIBRARY__ */
    245 
    246 /* Handle permutation of arguments.  */
    248 
    249 /* Describe the part of ARGV that contains non-options that have
    250    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
    251    `last_nonopt' is the index after the last of them.  */
    252 
    253 static int first_nonopt;
    254 static int last_nonopt;
    255 
    256 #ifdef _LIBC
    257 /* Bash 2.0 gives us an environment variable containing flags
    258    indicating ARGV elements that should not be considered arguments.  */
    259 
    260 #ifdef USE_NONOPTION_FLAGS
    261 /* Defined in getopt_init.c  */
    262 extern char *__getopt_nonoption_flags;
    263 
    264 static int nonoption_flags_max_len;
    265 static int nonoption_flags_len;
    266 #endif
    267 
    268 static int original_argc;
    269 static char *const *original_argv;
    270 
    271 /* Make sure the environment variable bash 2.0 puts in the environment
    272    is valid for the getopt call we must make sure that the ARGV passed
    273    to getopt is that one passed to the process.  */
    274 static void
    275 __attribute__ ((unused))
    276 store_args_and_env (int argc, char *const *argv)
    277 {
    278   /* XXX This is no good solution.  We should rather copy the args so
    279      that we can compare them later.  But we must not use malloc(3).  */
    280   original_argc = argc;
    281   original_argv = argv;
    282 }
    283 # ifdef text_set_element
    284 text_set_element (__libc_subinit, store_args_and_env);
    285 # endif /* text_set_element */
    286 
    287 # ifdef USE_NONOPTION_FLAGS
    288 #  define SWAP_FLAGS(ch1, ch2) \
    289   if (nonoption_flags_len > 0)						      \
    290     {									      \
    291       char __tmp = __getopt_nonoption_flags[ch1];			      \
    292       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];	      \
    293       __getopt_nonoption_flags[ch2] = __tmp;				      \
    294     }
    295 # else
    296 #  define SWAP_FLAGS(ch1, ch2)
    297 # endif
    298 #else	/* !_LIBC */
    299 # define SWAP_FLAGS(ch1, ch2)
    300 #endif	/* _LIBC */
    301 
    302 /* Exchange two adjacent subsequences of ARGV.
    303    One subsequence is elements [first_nonopt,last_nonopt)
    304    which contains all the non-options that have been skipped so far.
    305    The other is elements [last_nonopt,optind), which contains all
    306    the options processed since those non-options were skipped.
    307 
    308    `first_nonopt' and `last_nonopt' are relocated so that they describe
    309    the new indices of the non-options in ARGV after they are moved.  */
    310 
    311 #if defined __STDC__ && __STDC__
    312 static void exchange (char **);
    313 #endif
    314 
    315 static void
    316 exchange (argv)
    317      char **argv;
    318 {
    319   int bottom = first_nonopt;
    320   int middle = last_nonopt;
    321   int top = optind;
    322   char *tem;
    323 
    324   /* Exchange the shorter segment with the far end of the longer segment.
    325      That puts the shorter segment into the right place.
    326      It leaves the longer segment in the right place overall,
    327      but it consists of two parts that need to be swapped next.  */
    328 
    329 #if defined _LIBC && defined USE_NONOPTION_FLAGS
    330   /* First make sure the handling of the `__getopt_nonoption_flags'
    331      string can work normally.  Our top argument must be in the range
    332      of the string.  */
    333   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
    334     {
    335       /* We must extend the array.  The user plays games with us and
    336 	 presents new arguments.  */
    337       char *new_str = malloc (top + 1);
    338       if (new_str == NULL)
    339 	nonoption_flags_len = nonoption_flags_max_len = 0;
    340       else
    341 	{
    342 	  memset (__mempcpy (new_str, __getopt_nonoption_flags,
    343 			     nonoption_flags_max_len),
    344 		  '\0', top + 1 - nonoption_flags_max_len);
    345 	  nonoption_flags_max_len = top + 1;
    346 	  __getopt_nonoption_flags = new_str;
    347 	}
    348     }
    349 #endif
    350 
    351   while (top > middle && middle > bottom)
    352     {
    353       if (top - middle > middle - bottom)
    354 	{
    355 	  /* Bottom segment is the short one.  */
    356 	  int len = middle - bottom;
    357 	  register int i;
    358 
    359 	  /* Swap it with the top part of the top segment.  */
    360 	  for (i = 0; i < len; i++)
    361 	    {
    362 	      tem = argv[bottom + i];
    363 	      argv[bottom + i] = argv[top - (middle - bottom) + i];
    364 	      argv[top - (middle - bottom) + i] = tem;
    365 	      SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
    366 	    }
    367 	  /* Exclude the moved bottom segment from further swapping.  */
    368 	  top -= len;
    369 	}
    370       else
    371 	{
    372 	  /* Top segment is the short one.  */
    373 	  int len = top - middle;
    374 	  register int i;
    375 
    376 	  /* Swap it with the bottom part of the bottom segment.  */
    377 	  for (i = 0; i < len; i++)
    378 	    {
    379 	      tem = argv[bottom + i];
    380 	      argv[bottom + i] = argv[middle + i];
    381 	      argv[middle + i] = tem;
    382 	      SWAP_FLAGS (bottom + i, middle + i);
    383 	    }
    384 	  /* Exclude the moved top segment from further swapping.  */
    385 	  bottom += len;
    386 	}
    387     }
    388 
    389   /* Update records for the slots the non-options now occupy.  */
    390 
    391   first_nonopt += (optind - last_nonopt);
    392   last_nonopt = optind;
    393 }
    394 
    395 /* Initialize the internal data when the first call is made.  */
    396 
    397 #if defined __STDC__ && __STDC__
    398 static const char *_getopt_initialize (int, char *const *, const char *);
    399 #endif
    400 static const char *
    401 _getopt_initialize (argc, argv, optstring)
    402      int argc;
    403      char *const *argv;
    404      const char *optstring;
    405 {
    406   /* Start processing options with ARGV-element 1 (since ARGV-element 0
    407      is the program name); the sequence of previously skipped
    408      non-option ARGV-elements is empty.  */
    409 
    410   first_nonopt = last_nonopt = optind;
    411 
    412   nextchar = NULL;
    413 
    414   posixly_correct = getenv ("POSIXLY_CORRECT");
    415 
    416   /* Determine how to handle the ordering of options and nonoptions.  */
    417 
    418   if (optstring[0] == '-')
    419     {
    420       ordering = RETURN_IN_ORDER;
    421       ++optstring;
    422     }
    423   else if (optstring[0] == '+')
    424     {
    425       ordering = REQUIRE_ORDER;
    426       ++optstring;
    427     }
    428   else if (posixly_correct != NULL)
    429     ordering = REQUIRE_ORDER;
    430   else
    431     ordering = PERMUTE;
    432 
    433 #if defined _LIBC && defined USE_NONOPTION_FLAGS
    434   if (posixly_correct == NULL
    435       && argc == original_argc && argv == original_argv)
    436     {
    437       if (nonoption_flags_max_len == 0)
    438 	{
    439 	  if (__getopt_nonoption_flags == NULL
    440 	      || __getopt_nonoption_flags[0] == '\0')
    441 	    nonoption_flags_max_len = -1;
    442 	  else
    443 	    {
    444 	      const char *orig_str = __getopt_nonoption_flags;
    445 	      int len = nonoption_flags_max_len = strlen (orig_str);
    446 	      if (nonoption_flags_max_len < argc)
    447 		nonoption_flags_max_len = argc;
    448 	      __getopt_nonoption_flags =
    449 		(char *) malloc (nonoption_flags_max_len);
    450 	      if (__getopt_nonoption_flags == NULL)
    451 		nonoption_flags_max_len = -1;
    452 	      else
    453 		memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
    454 			'\0', nonoption_flags_max_len - len);
    455 	    }
    456 	}
    457       nonoption_flags_len = nonoption_flags_max_len;
    458     }
    459   else
    460     nonoption_flags_len = 0;
    461 #endif
    462 
    463   return optstring;
    464 }
    465 
    466 /* Scan elements of ARGV (whose length is ARGC) for option characters
    468    given in OPTSTRING.
    469 
    470    If an element of ARGV starts with '-', and is not exactly "-" or "--",
    471    then it is an option element.  The characters of this element
    472    (aside from the initial '-') are option characters.  If `getopt'
    473    is called repeatedly, it returns successively each of the option characters
    474    from each of the option elements.
    475 
    476    If `getopt' finds another option character, it returns that character,
    477    updating `optind' and `nextchar' so that the next call to `getopt' can
    478    resume the scan with the following option character or ARGV-element.
    479 
    480    If there are no more option characters, `getopt' returns -1.
    481    Then `optind' is the index in ARGV of the first ARGV-element
    482    that is not an option.  (The ARGV-elements have been permuted
    483    so that those that are not options now come last.)
    484 
    485    OPTSTRING is a string containing the legitimate option characters.
    486    If an option character is seen that is not listed in OPTSTRING,
    487    return '?' after printing an error message.  If you set `opterr' to
    488    zero, the error message is suppressed but we still return '?'.
    489 
    490    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
    491    so the following text in the same ARGV-element, or the text of the following
    492    ARGV-element, is returned in `optarg'.  Two colons mean an option that
    493    wants an optional arg; if there is text in the current ARGV-element,
    494    it is returned in `optarg', otherwise `optarg' is set to zero.
    495 
    496    If OPTSTRING starts with `-' or `+', it requests different methods of
    497    handling the non-option ARGV-elements.
    498    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
    499 
    500    Long-named options begin with `--' instead of `-'.
    501    Their names may be abbreviated as long as the abbreviation is unique
    502    or is an exact match for some defined option.  If they have an
    503    argument, it follows the option name in the same ARGV-element, separated
    504    from the option name by a `=', or else the in next ARGV-element.
    505    When `getopt' finds a long-named option, it returns 0 if that option's
    506    `flag' field is nonzero, the value of the option's `val' field
    507    if the `flag' field is zero.
    508 
    509    The elements of ARGV aren't really const, because we permute them.
    510    But we pretend they're const in the prototype to be compatible
    511    with other systems.
    512 
    513    LONGOPTS is a vector of `struct option' terminated by an
    514    element containing a name which is zero.
    515 
    516    LONGIND returns the index in LONGOPT of the long-named option found.
    517    It is only valid when a long-named option has been found by the most
    518    recent call.
    519 
    520    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
    521    long-named options.  */
    522 
    523 int
    524 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
    525      int argc;
    526      char *const *argv;
    527      const char *optstring;
    528      const struct option *longopts;
    529      int *longind;
    530      int long_only;
    531 {
    532   int print_errors = opterr;
    533   if (optstring[0] == ':')
    534     print_errors = 0;
    535 
    536   if (argc < 1)
    537     return -1;
    538 
    539   optarg = NULL;
    540 
    541   if (optind == 0 || !__getopt_initialized)
    542     {
    543       if (optind == 0)
    544 	optind = 1;	/* Don't scan ARGV[0], the program name.  */
    545       optstring = _getopt_initialize (argc, argv, optstring);
    546       __getopt_initialized = 1;
    547     }
    548 
    549   /* Test whether ARGV[optind] points to a non-option argument.
    550      Either it does not have option syntax, or there is an environment flag
    551      from the shell indicating it is not an option.  The later information
    552      is only used when the used in the GNU libc.  */
    553 #if defined _LIBC && defined USE_NONOPTION_FLAGS
    554 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'	      \
    555 		      || (optind < nonoption_flags_len			      \
    556 			  && __getopt_nonoption_flags[optind] == '1'))
    557 #else
    558 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
    559 #endif
    560 
    561   if (nextchar == NULL || *nextchar == '\0')
    562     {
    563       /* Advance to the next ARGV-element.  */
    564 
    565       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
    566 	 moved back by the user (who may also have changed the arguments).  */
    567       if (last_nonopt > optind)
    568 	last_nonopt = optind;
    569       if (first_nonopt > optind)
    570 	first_nonopt = optind;
    571 
    572       if (ordering == PERMUTE)
    573 	{
    574 	  /* If we have just processed some options following some non-options,
    575 	     exchange them so that the options come first.  */
    576 
    577 	  if (first_nonopt != last_nonopt && last_nonopt != optind)
    578 	    exchange ((char **) argv);
    579 	  else if (last_nonopt != optind)
    580 	    first_nonopt = optind;
    581 
    582 	  /* Skip any additional non-options
    583 	     and extend the range of non-options previously skipped.  */
    584 
    585 	  while (optind < argc && NONOPTION_P)
    586 	    optind++;
    587 	  last_nonopt = optind;
    588 	}
    589 
    590       /* The special ARGV-element `--' means premature end of options.
    591 	 Skip it like a null option,
    592 	 then exchange with previous non-options as if it were an option,
    593 	 then skip everything else like a non-option.  */
    594 
    595       if (optind != argc && !strcmp (argv[optind], "--"))
    596 	{
    597 	  optind++;
    598 
    599 	  if (first_nonopt != last_nonopt && last_nonopt != optind)
    600 	    exchange ((char **) argv);
    601 	  else if (first_nonopt == last_nonopt)
    602 	    first_nonopt = optind;
    603 	  last_nonopt = argc;
    604 
    605 	  optind = argc;
    606 	}
    607 
    608       /* If we have done all the ARGV-elements, stop the scan
    609 	 and back over any non-options that we skipped and permuted.  */
    610 
    611       if (optind == argc)
    612 	{
    613 	  /* Set the next-arg-index to point at the non-options
    614 	     that we previously skipped, so the caller will digest them.  */
    615 	  if (first_nonopt != last_nonopt)
    616 	    optind = first_nonopt;
    617 	  return -1;
    618 	}
    619 
    620       /* If we have come to a non-option and did not permute it,
    621 	 either stop the scan or describe it to the caller and pass it by.  */
    622 
    623       if (NONOPTION_P)
    624 	{
    625 	  if (ordering == REQUIRE_ORDER)
    626 	    return -1;
    627 	  optarg = argv[optind++];
    628 	  return 1;
    629 	}
    630 
    631       /* We have found another option-ARGV-element.
    632 	 Skip the initial punctuation.  */
    633 
    634       nextchar = (argv[optind] + 1
    635 		  + (longopts != NULL && argv[optind][1] == '-'));
    636     }
    637 
    638   /* Decode the current option-ARGV-element.  */
    639 
    640   /* Check whether the ARGV-element is a long option.
    641 
    642      If long_only and the ARGV-element has the form "-f", where f is
    643      a valid short option, don't consider it an abbreviated form of
    644      a long option that starts with f.  Otherwise there would be no
    645      way to give the -f short option.
    646 
    647      On the other hand, if there's a long option "fubar" and
    648      the ARGV-element is "-fu", do consider that an abbreviation of
    649      the long option, just like "--fu", and not "-f" with arg "u".
    650 
    651      This distinction seems to be the most useful approach.  */
    652 
    653   if (longopts != NULL
    654       && (argv[optind][1] == '-'
    655 	  || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
    656     {
    657       char *nameend;
    658       const struct option *p;
    659       const struct option *pfound = NULL;
    660       int exact = 0;
    661       int ambig = 0;
    662       int indfound = -1;
    663       int option_index;
    664 
    665       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
    666 	/* Do nothing.  */ ;
    667 
    668       /* Test all long options for either exact match
    669 	 or abbreviated matches.  */
    670       for (p = longopts, option_index = 0; p->name; p++, option_index++)
    671 	if (!strncmp (p->name, nextchar, nameend - nextchar))
    672 	  {
    673 	    if ((unsigned int) (nameend - nextchar)
    674 		== (unsigned int) strlen (p->name))
    675 	      {
    676 		/* Exact match found.  */
    677 		pfound = p;
    678 		indfound = option_index;
    679 		exact = 1;
    680 		break;
    681 	      }
    682 	    else if (pfound == NULL)
    683 	      {
    684 		/* First nonexact match found.  */
    685 		pfound = p;
    686 		indfound = option_index;
    687 	      }
    688 	    else if (long_only
    689 		     || pfound->has_arg != p->has_arg
    690 		     || pfound->flag != p->flag
    691 		     || pfound->val != p->val)
    692 	      /* Second or later nonexact match found.  */
    693 	      ambig = 1;
    694 	  }
    695 
    696       if (ambig && !exact)
    697 	{
    698 	  if (print_errors)
    699 	    fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
    700 		     argv[0], argv[optind]);
    701 	  nextchar += strlen (nextchar);
    702 	  optind++;
    703 	  optopt = 0;
    704 	  return '?';
    705 	}
    706 
    707       if (pfound != NULL)
    708 	{
    709 	  option_index = indfound;
    710 	  optind++;
    711 	  if (*nameend)
    712 	    {
    713 	      /* Don't test has_arg with >, because some C compilers don't
    714 		 allow it to be used on enums.  */
    715 	      if (pfound->has_arg)
    716 		optarg = nameend + 1;
    717 	      else
    718 		{
    719 		  if (print_errors)
    720 		    {
    721 		      if (argv[optind - 1][1] == '-')
    722 			/* --option */
    723 			fprintf (stderr,
    724 				 _("%s: option `--%s' doesn't allow an argument\n"),
    725 				 argv[0], pfound->name);
    726 		      else
    727 			/* +option or -option */
    728 			fprintf (stderr,
    729 				 _("%s: option `%c%s' doesn't allow an argument\n"),
    730 				 argv[0], argv[optind - 1][0], pfound->name);
    731 		    }
    732 
    733 		  nextchar += strlen (nextchar);
    734 
    735 		  optopt = pfound->val;
    736 		  return '?';
    737 		}
    738 	    }
    739 	  else if (pfound->has_arg == 1)
    740 	    {
    741 	      if (optind < argc)
    742 		optarg = argv[optind++];
    743 	      else
    744 		{
    745 		  if (print_errors)
    746 		    fprintf (stderr,
    747 			   _("%s: option `%s' requires an argument\n"),
    748 			   argv[0], argv[optind - 1]);
    749 		  nextchar += strlen (nextchar);
    750 		  optopt = pfound->val;
    751 		  return optstring[0] == ':' ? ':' : '?';
    752 		}
    753 	    }
    754 	  nextchar += strlen (nextchar);
    755 	  if (longind != NULL)
    756 	    *longind = option_index;
    757 	  if (pfound->flag)
    758 	    {
    759 	      *(pfound->flag) = pfound->val;
    760 	      return 0;
    761 	    }
    762 	  return pfound->val;
    763 	}
    764 
    765       /* Can't find it as a long option.  If this is not getopt_long_only,
    766 	 or the option starts with '--' or is not a valid short
    767 	 option, then it's an error.
    768 	 Otherwise interpret it as a short option.  */
    769       if (!long_only || argv[optind][1] == '-'
    770 	  || my_index (optstring, *nextchar) == NULL)
    771 	{
    772 	  if (print_errors)
    773 	    {
    774 	      if (argv[optind][1] == '-')
    775 		/* --option */
    776 		fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
    777 			 argv[0], nextchar);
    778 	      else
    779 		/* +option or -option */
    780 		fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
    781 			 argv[0], argv[optind][0], nextchar);
    782 	    }
    783 	  nextchar = (char *) "";
    784 	  optind++;
    785 	  optopt = 0;
    786 	  return '?';
    787 	}
    788     }
    789 
    790   /* Look at and handle the next short option-character.  */
    791 
    792   {
    793     char c = *nextchar++;
    794     char *temp = my_index (optstring, c);
    795 
    796     /* Increment `optind' when we start to process its last character.  */
    797     if (*nextchar == '\0')
    798       ++optind;
    799 
    800     if (temp == NULL || c == ':')
    801       {
    802 	if (print_errors)
    803 	  {
    804 	    if (posixly_correct)
    805 	      /* 1003.2 specifies the format of this message.  */
    806 	      fprintf (stderr, _("%s: illegal option -- %c\n"),
    807 		       argv[0], c);
    808 	    else
    809 	      fprintf (stderr, _("%s: invalid option -- %c\n"),
    810 		       argv[0], c);
    811 	  }
    812 	optopt = c;
    813 	return '?';
    814       }
    815     /* Convenience. Treat POSIX -W foo same as long option --foo */
    816     if (temp[0] == 'W' && temp[1] == ';')
    817       {
    818 	char *nameend;
    819 	const struct option *p;
    820 	const struct option *pfound = NULL;
    821 	int exact = 0;
    822 	int ambig = 0;
    823 	int indfound = 0;
    824 	int option_index;
    825 
    826 	/* This is an option that requires an argument.  */
    827 	if (*nextchar != '\0')
    828 	  {
    829 	    optarg = nextchar;
    830 	    /* If we end this ARGV-element by taking the rest as an arg,
    831 	       we must advance to the next element now.  */
    832 	    optind++;
    833 	  }
    834 	else if (optind == argc)
    835 	  {
    836 	    if (print_errors)
    837 	      {
    838 		/* 1003.2 specifies the format of this message.  */
    839 		fprintf (stderr, _("%s: option requires an argument -- %c\n"),
    840 			 argv[0], c);
    841 	      }
    842 	    optopt = c;
    843 	    if (optstring[0] == ':')
    844 	      c = ':';
    845 	    else
    846 	      c = '?';
    847 	    return c;
    848 	  }
    849 	else
    850 	  /* We already incremented `optind' once;
    851 	     increment it again when taking next ARGV-elt as argument.  */
    852 	  optarg = argv[optind++];
    853 
    854 	/* optarg is now the argument, see if it's in the
    855 	   table of longopts.  */
    856 
    857 	for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
    858 	  /* Do nothing.  */ ;
    859 
    860 	/* Test all long options for either exact match
    861 	   or abbreviated matches.  */
    862 	for (p = longopts, option_index = 0; p->name; p++, option_index++)
    863 	  if (!strncmp (p->name, nextchar, nameend - nextchar))
    864 	    {
    865 	      if ((unsigned int) (nameend - nextchar) == strlen (p->name))
    866 		{
    867 		  /* Exact match found.  */
    868 		  pfound = p;
    869 		  indfound = option_index;
    870 		  exact = 1;
    871 		  break;
    872 		}
    873 	      else if (pfound == NULL)
    874 		{
    875 		  /* First nonexact match found.  */
    876 		  pfound = p;
    877 		  indfound = option_index;
    878 		}
    879 	      else
    880 		/* Second or later nonexact match found.  */
    881 		ambig = 1;
    882 	    }
    883 	if (ambig && !exact)
    884 	  {
    885 	    if (print_errors)
    886 	      fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
    887 		       argv[0], argv[optind]);
    888 	    nextchar += strlen (nextchar);
    889 	    optind++;
    890 	    return '?';
    891 	  }
    892 	if (pfound != NULL)
    893 	  {
    894 	    option_index = indfound;
    895 	    if (*nameend)
    896 	      {
    897 		/* Don't test has_arg with >, because some C compilers don't
    898 		   allow it to be used on enums.  */
    899 		if (pfound->has_arg)
    900 		  optarg = nameend + 1;
    901 		else
    902 		  {
    903 		    if (print_errors)
    904 		      fprintf (stderr, _("\
    905 %s: option `-W %s' doesn't allow an argument\n"),
    906 			       argv[0], pfound->name);
    907 
    908 		    nextchar += strlen (nextchar);
    909 		    return '?';
    910 		  }
    911 	      }
    912 	    else if (pfound->has_arg == 1)
    913 	      {
    914 		if (optind < argc)
    915 		  optarg = argv[optind++];
    916 		else
    917 		  {
    918 		    if (print_errors)
    919 		      fprintf (stderr,
    920 			       _("%s: option `%s' requires an argument\n"),
    921 			       argv[0], argv[optind - 1]);
    922 		    nextchar += strlen (nextchar);
    923 		    return optstring[0] == ':' ? ':' : '?';
    924 		  }
    925 	      }
    926 	    nextchar += strlen (nextchar);
    927 	    if (longind != NULL)
    928 	      *longind = option_index;
    929 	    if (pfound->flag)
    930 	      {
    931 		*(pfound->flag) = pfound->val;
    932 		return 0;
    933 	      }
    934 	    return pfound->val;
    935 	  }
    936 	  nextchar = NULL;
    937 	  return 'W';	/* Let the application handle it.   */
    938       }
    939     if (temp[1] == ':')
    940       {
    941 	if (temp[2] == ':')
    942 	  {
    943 	    /* This is an option that accepts an argument optionally.  */
    944 	    if (*nextchar != '\0')
    945 	      {
    946 		optarg = nextchar;
    947 		optind++;
    948 	      }
    949 	    else
    950 	      optarg = NULL;
    951 	    nextchar = NULL;
    952 	  }
    953 	else
    954 	  {
    955 	    /* This is an option that requires an argument.  */
    956 	    if (*nextchar != '\0')
    957 	      {
    958 		optarg = nextchar;
    959 		/* If we end this ARGV-element by taking the rest as an arg,
    960 		   we must advance to the next element now.  */
    961 		optind++;
    962 	      }
    963 	    else if (optind == argc)
    964 	      {
    965 		if (print_errors)
    966 		  {
    967 		    /* 1003.2 specifies the format of this message.  */
    968 		    fprintf (stderr,
    969 			     _("%s: option requires an argument -- %c\n"),
    970 			     argv[0], c);
    971 		  }
    972 		optopt = c;
    973 		if (optstring[0] == ':')
    974 		  c = ':';
    975 		else
    976 		  c = '?';
    977 	      }
    978 	    else
    979 	      /* We already incremented `optind' once;
    980 		 increment it again when taking next ARGV-elt as argument.  */
    981 	      optarg = argv[optind++];
    982 	    nextchar = NULL;
    983 	  }
    984       }
    985     return c;
    986   }
    987 }
    988 
    989 int
    990 getopt (argc, argv, optstring)
    991      int argc;
    992      char *const *argv;
    993      const char *optstring;
    994 {
    995   return _getopt_internal (argc, argv, optstring,
    996 			   (const struct option *) 0,
    997 			   (int *) 0,
    998 			   0);
    999 }
   1000 
   1001 #endif	/* Not ELIDE_CODE.  */
   1002 
   1003 #ifdef TEST
   1005 
   1006 /* Compile with -DTEST to make an executable for use in testing
   1007    the above definition of `getopt'.  */
   1008 
   1009 int
   1010 main (argc, argv)
   1011      int argc;
   1012      char **argv;
   1013 {
   1014   int c;
   1015   int digit_optind = 0;
   1016 
   1017   while (1)
   1018     {
   1019       int this_option_optind = optind ? optind : 1;
   1020 
   1021       c = getopt (argc, argv, "abc:d:0123456789");
   1022       if (c == -1)
   1023 	break;
   1024 
   1025       switch (c)
   1026 	{
   1027 	case '0':
   1028 	case '1':
   1029 	case '2':
   1030 	case '3':
   1031 	case '4':
   1032 	case '5':
   1033 	case '6':
   1034 	case '7':
   1035 	case '8':
   1036 	case '9':
   1037 	  if (digit_optind != 0 && digit_optind != this_option_optind)
   1038 	    printf ("digits occur in two different argv-elements.\n");
   1039 	  digit_optind = this_option_optind;
   1040 	  printf ("option %c\n", c);
   1041 	  break;
   1042 
   1043 	case 'a':
   1044 	  printf ("option a\n");
   1045 	  break;
   1046 
   1047 	case 'b':
   1048 	  printf ("option b\n");
   1049 	  break;
   1050 
   1051 	case 'c':
   1052 	  printf ("option c with value `%s'\n", optarg);
   1053 	  break;
   1054 
   1055 	case '?':
   1056 	  break;
   1057 
   1058 	default:
   1059 	  printf ("?? getopt returned character code 0%o ??\n", c);
   1060 	}
   1061     }
   1062 
   1063   if (optind < argc)
   1064     {
   1065       printf ("non-option ARGV-elements: ");
   1066       while (optind < argc)
   1067 	printf ("%s ", argv[optind++]);
   1068       printf ("\n");
   1069     }
   1070 
   1071   exit (0);
   1072 }
   1073 
   1074 #endif /* TEST */
   1075