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