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