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