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