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