1 /* Getopt for GNU.
2    Copyright (C) 1987-2018 Free Software Foundation, Inc.
3    This file is part of the GNU C Library and is also part of gnulib.
4    Patches to this file should be submitted to both projects.
5 
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10 
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15 
16    You should have received a copy of the GNU Lesser General Public
17    License along with the GNU C Library; if not, see
18    <http://www.gnu.org/licenses/>.  */
19 
20 #if !defined(_LIBC) && !defined(_GETOPT_STANDALONE)
21 # include <config.h>
22 #endif
23 
24 #include "getopt.h"
25 
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #ifndef _GETOPT_STANDALONE
30 #include <unistd.h>
31 #endif
32 
33 #ifdef _LIBC
34 /* When used as part of glibc, error printing must be done differently
35    for standards compliance.  getopt is not a cancellation point, so
36    it must not call functions that are, and it is specified by an
37    older standard than stdio locking, so it must not refer to
38    functions in the "user namespace" related to stdio locking.
39    Finally, it must use glibc's internal message translation so that
40    the messages are looked up in the proper text domain.  */
41 # include <libintl.h>
42 # define fprintf __fxprintf_nocancel
43 # define flockfile(fp) _IO_flockfile (fp)
44 # define funlockfile(fp) _IO_funlockfile (fp)
45 #else
46 #ifndef _GETOPT_STANDALONE
47 # include "gettext.h"
48 # define _(msgid) gettext (msgid)
49 #else
50 # define _(msgid) (msgid)
51 #endif
52 /* When used standalone, flockfile and funlockfile might not be
53    available.  */
54 # ifndef _POSIX_THREAD_SAFE_FUNCTIONS
55 #  define flockfile(fp) /* nop */
56 #  define funlockfile(fp) /* nop */
57 # endif
58 /* When used standalone, do not attempt to use alloca.  */
59 # define __libc_use_alloca(size) 0
60 # undef alloca
61 # define alloca(size) (abort (), (void *)0)
62 #endif
63 
64 /* This implementation of 'getopt' has three modes for handling
65    options interspersed with non-option arguments.  It can stop
66    scanning for options at the first non-option argument encountered,
67    as POSIX specifies.  It can continue scanning for options after the
68    first non-option argument, but permute 'argv' as it goes so that,
69    after 'getopt' is done, all the options precede all the non-option
70    arguments and 'optind' points to the first non-option argument.
71    Or, it can report non-option arguments as if they were arguments to
72    the option character '\x01'.
73 
74    The default behavior of 'getopt_long' is to permute the argument list.
75    When this implementation is used standalone, the default behavior of
76    'getopt' is to stop at the first non-option argument, but when it is
77    used as part of GNU libc it also permutes the argument list.  In both
78    cases, setting the environment variable POSIXLY_CORRECT to any value
79    disables permutation.
80 
81    If the first character of the OPTSTRING argument to 'getopt' or
82    'getopt_long' is '+', both functions will stop at the first
83    non-option argument.  If it is '-', both functions will report
84    non-option arguments as arguments to the option character '\x01'.  */
85 
86 #include "getopt_int.h"
87 
88 /* For communication from 'getopt' to the caller.
89    When 'getopt' finds an option that takes an argument,
90    the argument value is returned here.
91    Also, when 'ordering' is RETURN_IN_ORDER,
92    each non-option ARGV-element is returned here.  */
93 
94 char *optarg;
95 
96 /* Index in ARGV of the next element to be scanned.
97    This is used for communication to and from the caller
98    and for communication between successive calls to 'getopt'.
99 
100    On entry to 'getopt', zero means this is the first call; initialize.
101 
102    When 'getopt' returns -1, this is the index of the first of the
103    non-option elements that the caller should itself scan.
104 
105    Otherwise, 'optind' communicates from one call to the next
106    how much of ARGV has been scanned so far.  */
107 
108 /* 1003.2 says this must be 1 before any call.  */
109 int optind = 1;
110 
111 /* Callers store zero here to inhibit the error message
112    for unrecognized options.  */
113 
114 int opterr = 1;
115 
116 /* Set to an option character which was unrecognized.
117    This must be initialized on some systems to avoid linking in the
118    system's own getopt implementation.  */
119 
120 int optopt = '?';
121 
122 /* Keep a global copy of all internal members of getopt_data.  */
123 
124 static struct _getopt_data getopt_data;
125 
126 /* Exchange two adjacent subsequences of ARGV.
127    One subsequence is elements [first_nonopt,last_nonopt)
128    which contains all the non-options that have been skipped so far.
129    The other is elements [last_nonopt,optind), which contains all
130    the options processed since those non-options were skipped.
131 
132    'first_nonopt' and 'last_nonopt' are relocated so that they describe
133    the new indices of the non-options in ARGV after they are moved.  */
134 
135 static void
exchange(char ** argv,struct _getopt_data * d)136 exchange (char **argv, struct _getopt_data *d)
137 {
138   int bottom = d->__first_nonopt;
139   int middle = d->__last_nonopt;
140   int top = d->optind;
141   char *tem;
142 
143   /* Exchange the shorter segment with the far end of the longer segment.
144      That puts the shorter segment into the right place.
145      It leaves the longer segment in the right place overall,
146      but it consists of two parts that need to be swapped next.  */
147 
148   while (top > middle && middle > bottom)
149     {
150       if (top - middle > middle - bottom)
151 	{
152 	  /* Bottom segment is the short one.  */
153 	  int len = middle - bottom;
154 	  int i;
155 
156 	  /* Swap it with the top part of the top segment.  */
157 	  for (i = 0; i < len; i++)
158 	    {
159 	      tem = argv[bottom + i];
160 	      argv[bottom + i] = argv[top - (middle - bottom) + i];
161 	      argv[top - (middle - bottom) + i] = tem;
162 	    }
163 	  /* Exclude the moved bottom segment from further swapping.  */
164 	  top -= len;
165 	}
166       else
167 	{
168 	  /* Top segment is the short one.  */
169 	  int len = top - middle;
170 	  int i;
171 
172 	  /* Swap it with the bottom part of the bottom segment.  */
173 	  for (i = 0; i < len; i++)
174 	    {
175 	      tem = argv[bottom + i];
176 	      argv[bottom + i] = argv[middle + i];
177 	      argv[middle + i] = tem;
178 	    }
179 	  /* Exclude the moved top segment from further swapping.  */
180 	  bottom += len;
181 	}
182     }
183 
184   /* Update records for the slots the non-options now occupy.  */
185 
186   d->__first_nonopt += (d->optind - d->__last_nonopt);
187   d->__last_nonopt = d->optind;
188 }
189 
190 /* Process the argument starting with d->__nextchar as a long option.
191    d->optind should *not* have been advanced over this argument.
192 
193    If the value returned is -1, it was not actually a long option, the
194    state is unchanged, and the argument should be processed as a set
195    of short options (this can only happen when long_only is true).
196    Otherwise, the option (and its argument, if any) have been consumed
197    and the return value is the value to return from _getopt_internal_r.  */
198 static int
process_long_option(int argc,char ** argv,const char * optstring,const struct option * longopts,int * longind,int long_only,struct _getopt_data * d,int print_errors,const char * prefix)199 process_long_option (int argc, char **argv, const char *optstring,
200 		     const struct option *longopts, int *longind,
201 		     int long_only, struct _getopt_data *d,
202 		     int print_errors, const char *prefix)
203 {
204   char *nameend;
205   size_t namelen;
206   const struct option *p;
207   const struct option *pfound = NULL;
208   int n_options;
209   int option_index;
210 
211   for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
212     /* Do nothing.  */ ;
213   namelen = nameend - d->__nextchar;
214 
215   /* First look for an exact match, counting the options as a side
216      effect.  */
217   for (p = longopts, n_options = 0; p->name; p++, n_options++)
218     if (!strncmp (p->name, d->__nextchar, namelen)
219 	&& namelen == strlen (p->name))
220       {
221 	/* Exact match found.  */
222 	pfound = p;
223 	option_index = n_options;
224 	break;
225       }
226 
227   if (pfound == NULL)
228     {
229       /* Didn't find an exact match, so look for abbreviations.  */
230       unsigned char *ambig_set = NULL;
231       int ambig_malloced = 0;
232       int ambig_fallback = 0;
233       int indfound = -1;
234 
235       for (p = longopts, option_index = 0; p->name; p++, option_index++)
236 	if (!strncmp (p->name, d->__nextchar, namelen))
237 	  {
238 	    if (pfound == NULL)
239 	      {
240 		/* First nonexact match found.  */
241 		pfound = p;
242 		indfound = option_index;
243 	      }
244 	    else if (long_only
245 		     || pfound->has_arg != p->has_arg
246 		     || pfound->flag != p->flag
247 		     || pfound->val != p->val)
248 	      {
249 		/* Second or later nonexact match found.  */
250 		if (!ambig_fallback)
251 		  {
252 		    if (!print_errors)
253 		      /* Don't waste effort tracking the ambig set if
254 			 we're not going to print it anyway.  */
255 		      ambig_fallback = 1;
256 		    else if (!ambig_set)
257 		      {
258 			if (__libc_use_alloca (n_options))
259 			  ambig_set = alloca (n_options);
260 			else if ((ambig_set = malloc (n_options)) == NULL)
261 			  /* Fall back to simpler error message.  */
262 			  ambig_fallback = 1;
263 			else
264 			  ambig_malloced = 1;
265 
266 			if (ambig_set)
267 			  {
268 			    memset (ambig_set, 0, n_options);
269 			    ambig_set[indfound] = 1;
270 			  }
271 		      }
272 		    if (ambig_set)
273 		      ambig_set[option_index] = 1;
274 		  }
275 	      }
276 	  }
277 
278       if (ambig_set || ambig_fallback)
279 	{
280 	  if (print_errors)
281 	    {
282 	      if (ambig_fallback)
283 		fprintf (stderr, _("%s: option '%s%s' is ambiguous\n"),
284 			 argv[0], prefix, d->__nextchar);
285 	      else
286 		{
287 		  flockfile (stderr);
288 		  fprintf (stderr,
289 			   _("%s: option '%s%s' is ambiguous; possibilities:"),
290 			   argv[0], prefix, d->__nextchar);
291 
292 		  for (option_index = 0; option_index < n_options; option_index++)
293 		    if (ambig_set[option_index])
294 		      fprintf (stderr, " '%s%s'",
295 			       prefix, longopts[option_index].name);
296 
297 		  /* This must use 'fprintf' even though it's only
298 		     printing a single character, so that it goes through
299 		     __fxprintf_nocancel when compiled as part of glibc.  */
300 		  fprintf (stderr, "\n");
301 		  funlockfile (stderr);
302 		}
303 	    }
304 	  if (ambig_malloced)
305 	    free (ambig_set);
306 	  d->__nextchar += strlen (d->__nextchar);
307 	  d->optind++;
308 	  d->optopt = 0;
309 	  return '?';
310 	}
311 
312       option_index = indfound;
313     }
314 
315   if (pfound == NULL)
316     {
317       /* Can't find it as a long option.  If this is not getopt_long_only,
318 	 or the option starts with '--' or is not a valid short option,
319 	 then it's an error.  */
320       if (!long_only || argv[d->optind][1] == '-'
321 	  || strchr (optstring, *d->__nextchar) == NULL)
322 	{
323 	  if (print_errors)
324 	    fprintf (stderr, _("%s: unrecognized option '%s%s'\n"),
325 		     argv[0], prefix, d->__nextchar);
326 
327 	  d->__nextchar = NULL;
328 	  d->optind++;
329 	  d->optopt = 0;
330 	  return '?';
331 	}
332 
333       /* Otherwise interpret it as a short option.  */
334       return -1;
335     }
336 
337   /* We have found a matching long option.  Consume it.  */
338   d->optind++;
339   d->__nextchar = NULL;
340   if (*nameend)
341     {
342       /* Don't test has_arg with >, because some C compilers don't
343 	 allow it to be used on enums.  */
344       if (pfound->has_arg)
345 	d->optarg = nameend + 1;
346       else
347 	{
348 	  if (print_errors)
349 	    fprintf (stderr,
350 		     _("%s: option '%s%s' doesn't allow an argument\n"),
351 		     argv[0], prefix, pfound->name);
352 
353 	  d->optopt = pfound->val;
354 	  return '?';
355 	}
356     }
357   else if (pfound->has_arg == 1)
358     {
359       if (d->optind < argc)
360 	d->optarg = argv[d->optind++];
361       else
362 	{
363 	  if (print_errors)
364 	    fprintf (stderr,
365 		     _("%s: option '%s%s' requires an argument\n"),
366 		     argv[0], prefix, pfound->name);
367 
368 	  d->optopt = pfound->val;
369 	  return optstring[0] == ':' ? ':' : '?';
370 	}
371     }
372 
373   if (longind != NULL)
374     *longind = option_index;
375   if (pfound->flag)
376     {
377       *(pfound->flag) = pfound->val;
378       return 0;
379     }
380   return pfound->val;
381 }
382 
383 #ifndef _GL_UNUSED
384 # ifdef __GNUC__
385 #  define _GL_UNUSED __attribute__((__unused__))
386 # else
387 #  define _GL_UNUSED
388 # endif
389 #endif
390 
391 /* Initialize internal data upon the first call to getopt.  */
392 
393 static const char *
_getopt_initialize(int argc _GL_UNUSED,char ** argv _GL_UNUSED,const char * optstring,struct _getopt_data * d,int posixly_correct)394 _getopt_initialize (int argc _GL_UNUSED,
395 		    char **argv _GL_UNUSED, const char *optstring,
396 		    struct _getopt_data *d, int posixly_correct)
397 {
398   /* Start processing options with ARGV-element 1 (since ARGV-element 0
399      is the program name); the sequence of previously skipped
400      non-option ARGV-elements is empty.  */
401   if (d->optind == 0)
402     d->optind = 1;
403 
404   d->__first_nonopt = d->__last_nonopt = d->optind;
405   d->__nextchar = NULL;
406 
407   /* Determine how to handle the ordering of options and nonoptions.  */
408   if (optstring[0] == '-')
409     {
410       d->__ordering = RETURN_IN_ORDER;
411       ++optstring;
412     }
413   else if (optstring[0] == '+')
414     {
415       d->__ordering = REQUIRE_ORDER;
416       ++optstring;
417     }
418   else if (posixly_correct || !!getenv ("POSIXLY_CORRECT"))
419     d->__ordering = REQUIRE_ORDER;
420   else
421     d->__ordering = PERMUTE;
422 
423   d->__initialized = 1;
424   return optstring;
425 }
426 
427 /* Scan elements of ARGV (whose length is ARGC) for option characters
428    given in OPTSTRING.
429 
430    If an element of ARGV starts with '-', and is not exactly "-" or "--",
431    then it is an option element.  The characters of this element
432    (aside from the initial '-') are option characters.  If 'getopt'
433    is called repeatedly, it returns successively each of the option characters
434    from each of the option elements.
435 
436    If 'getopt' finds another option character, it returns that character,
437    updating 'optind' and 'nextchar' so that the next call to 'getopt' can
438    resume the scan with the following option character or ARGV-element.
439 
440    If there are no more option characters, 'getopt' returns -1.
441    Then 'optind' is the index in ARGV of the first ARGV-element
442    that is not an option.  (The ARGV-elements have been permuted
443    so that those that are not options now come last.)
444 
445    OPTSTRING is a string containing the legitimate option characters.
446    If an option character is seen that is not listed in OPTSTRING,
447    return '?' after printing an error message.  If you set 'opterr' to
448    zero, the error message is suppressed but we still return '?'.
449 
450    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
451    so the following text in the same ARGV-element, or the text of the following
452    ARGV-element, is returned in 'optarg'.  Two colons mean an option that
453    wants an optional arg; if there is text in the current ARGV-element,
454    it is returned in 'optarg', otherwise 'optarg' is set to zero.
455 
456    If OPTSTRING starts with '-' or '+', it requests different methods of
457    handling the non-option ARGV-elements.
458    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
459 
460    Long-named options begin with '--' instead of '-'.
461    Their names may be abbreviated as long as the abbreviation is unique
462    or is an exact match for some defined option.  If they have an
463    argument, it follows the option name in the same ARGV-element, separated
464    from the option name by a '=', or else the in next ARGV-element.
465    When 'getopt' finds a long-named option, it returns 0 if that option's
466    'flag' field is nonzero, the value of the option's 'val' field
467    if the 'flag' field is zero.
468 
469    The elements of ARGV aren't really const, because we permute them.
470    But we pretend they're const in the prototype to be compatible
471    with other systems.
472 
473    LONGOPTS is a vector of 'struct option' terminated by an
474    element containing a name which is zero.
475 
476    LONGIND returns the index in LONGOPT of the long-named option found.
477    It is only valid when a long-named option has been found by the most
478    recent call.
479 
480    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
481    long-named options.  */
482 
483 int
_getopt_internal_r(int argc,char ** argv,const char * optstring,const struct option * longopts,int * longind,int long_only,struct _getopt_data * d,int posixly_correct)484 _getopt_internal_r (int argc, char **argv, const char *optstring,
485 		    const struct option *longopts, int *longind,
486 		    int long_only, struct _getopt_data *d, int posixly_correct)
487 {
488   int print_errors = d->opterr;
489 
490   if (argc < 1)
491     return -1;
492 
493   d->optarg = NULL;
494 
495   if (d->optind == 0 || !d->__initialized)
496     optstring = _getopt_initialize (argc, argv, optstring, d, posixly_correct);
497   else if (optstring[0] == '-' || optstring[0] == '+')
498     optstring++;
499 
500   if (optstring[0] == ':')
501     print_errors = 0;
502 
503   /* Test whether ARGV[optind] points to a non-option argument.  */
504 #define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
505 
506   if (d->__nextchar == NULL || *d->__nextchar == '\0')
507     {
508       /* Advance to the next ARGV-element.  */
509 
510       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
511 	 moved back by the user (who may also have changed the arguments).  */
512       if (d->__last_nonopt > d->optind)
513 	d->__last_nonopt = d->optind;
514       if (d->__first_nonopt > d->optind)
515 	d->__first_nonopt = d->optind;
516 
517       if (d->__ordering == PERMUTE)
518 	{
519 	  /* If we have just processed some options following some non-options,
520 	     exchange them so that the options come first.  */
521 
522 	  if (d->__first_nonopt != d->__last_nonopt
523 	      && d->__last_nonopt != d->optind)
524 	    exchange (argv, d);
525 	  else if (d->__last_nonopt != d->optind)
526 	    d->__first_nonopt = d->optind;
527 
528 	  /* Skip any additional non-options
529 	     and extend the range of non-options previously skipped.  */
530 
531 	  while (d->optind < argc && NONOPTION_P)
532 	    d->optind++;
533 	  d->__last_nonopt = d->optind;
534 	}
535 
536       /* The special ARGV-element '--' means premature end of options.
537 	 Skip it like a null option,
538 	 then exchange with previous non-options as if it were an option,
539 	 then skip everything else like a non-option.  */
540 
541       if (d->optind != argc && !strcmp (argv[d->optind], "--"))
542 	{
543 	  d->optind++;
544 
545 	  if (d->__first_nonopt != d->__last_nonopt
546 	      && d->__last_nonopt != d->optind)
547 	    exchange (argv, d);
548 	  else if (d->__first_nonopt == d->__last_nonopt)
549 	    d->__first_nonopt = d->optind;
550 	  d->__last_nonopt = argc;
551 
552 	  d->optind = argc;
553 	}
554 
555       /* If we have done all the ARGV-elements, stop the scan
556 	 and back over any non-options that we skipped and permuted.  */
557 
558       if (d->optind == argc)
559 	{
560 	  /* Set the next-arg-index to point at the non-options
561 	     that we previously skipped, so the caller will digest them.  */
562 	  if (d->__first_nonopt != d->__last_nonopt)
563 	    d->optind = d->__first_nonopt;
564 	  return -1;
565 	}
566 
567       /* If we have come to a non-option and did not permute it,
568 	 either stop the scan or describe it to the caller and pass it by.  */
569 
570       if (NONOPTION_P)
571 	{
572 	  if (d->__ordering == REQUIRE_ORDER)
573 	    return -1;
574 	  d->optarg = argv[d->optind++];
575 	  return 1;
576 	}
577 
578       /* We have found another option-ARGV-element.
579 	 Check whether it might be a long option.  */
580       if (longopts)
581 	{
582 	  if (argv[d->optind][1] == '-')
583 	    {
584 	      /* "--foo" is always a long option.  The special option
585 		 "--" was handled above.  */
586 	      d->__nextchar = argv[d->optind] + 2;
587 	      return process_long_option (argc, argv, optstring, longopts,
588 					  longind, long_only, d,
589 					  print_errors, "--");
590 	    }
591 
592 	  /* If long_only and the ARGV-element has the form "-f",
593 	     where f is a valid short option, don't consider it an
594 	     abbreviated form of a long option that starts with f.
595 	     Otherwise there would be no way to give the -f short
596 	     option.
597 
598 	     On the other hand, if there's a long option "fubar" and
599 	     the ARGV-element is "-fu", do consider that an
600 	     abbreviation of the long option, just like "--fu", and
601 	     not "-f" with arg "u".
602 
603 	     This distinction seems to be the most useful approach.  */
604 	  if (long_only && (argv[d->optind][2]
605 			    || !strchr (optstring, argv[d->optind][1])))
606 	    {
607 	      int code;
608 	      d->__nextchar = argv[d->optind] + 1;
609 	      code = process_long_option (argc, argv, optstring, longopts,
610 					  longind, long_only, d,
611 					  print_errors, "-");
612 	      if (code != -1)
613 		return code;
614 	    }
615 	}
616 
617       /* It is not a long option.  Skip the initial punctuation.  */
618       d->__nextchar = argv[d->optind] + 1;
619     }
620 
621   /* Look at and handle the next short option-character.  */
622 
623   {
624     char c = *d->__nextchar++;
625     const char *temp = strchr (optstring, c);
626 
627     /* Increment 'optind' when we start to process its last character.  */
628     if (*d->__nextchar == '\0')
629       ++d->optind;
630 
631     if (temp == NULL || c == ':' || c == ';')
632       {
633 	if (print_errors)
634 	  fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
635 	d->optopt = c;
636 	return '?';
637       }
638 
639     /* Convenience. Treat POSIX -W foo same as long option --foo */
640     if (temp[0] == 'W' && temp[1] == ';' && longopts != NULL)
641       {
642 	/* This is an option that requires an argument.  */
643 	if (*d->__nextchar != '\0')
644 	  d->optarg = d->__nextchar;
645 	else if (d->optind == argc)
646 	  {
647 	    if (print_errors)
648 	      fprintf (stderr,
649 		       _("%s: option requires an argument -- '%c'\n"),
650 		       argv[0], c);
651 
652 	    d->optopt = c;
653 	    if (optstring[0] == ':')
654 	      c = ':';
655 	    else
656 	      c = '?';
657 	    return c;
658 	  }
659 	else
660 	  d->optarg = argv[d->optind];
661 
662 	d->__nextchar = d->optarg;
663 	d->optarg = NULL;
664 	return process_long_option (argc, argv, optstring, longopts, longind,
665 				    0 /* long_only */, d, print_errors, "-W ");
666       }
667     if (temp[1] == ':')
668       {
669 	if (temp[2] == ':')
670 	  {
671 	    /* This is an option that accepts an argument optionally.  */
672 	    if (*d->__nextchar != '\0')
673 	      {
674 		d->optarg = d->__nextchar;
675 		d->optind++;
676 	      }
677 	    else
678 	      d->optarg = NULL;
679 	    d->__nextchar = NULL;
680 	  }
681 	else
682 	  {
683 	    /* This is an option that requires an argument.  */
684 	    if (*d->__nextchar != '\0')
685 	      {
686 		d->optarg = d->__nextchar;
687 		/* If we end this ARGV-element by taking the rest as an arg,
688 		   we must advance to the next element now.  */
689 		d->optind++;
690 	      }
691 	    else if (d->optind == argc)
692 	      {
693 		if (print_errors)
694 		  fprintf (stderr,
695 			   _("%s: option requires an argument -- '%c'\n"),
696 			   argv[0], c);
697 
698 		d->optopt = c;
699 		if (optstring[0] == ':')
700 		  c = ':';
701 		else
702 		  c = '?';
703 	      }
704 	    else
705 	      /* We already incremented 'optind' once;
706 		 increment it again when taking next ARGV-elt as argument.  */
707 	      d->optarg = argv[d->optind++];
708 	    d->__nextchar = NULL;
709 	  }
710       }
711     return c;
712   }
713 }
714 
715 int
_getopt_internal(int argc,char ** argv,const char * optstring,const struct option * longopts,int * longind,int long_only,int posixly_correct)716 _getopt_internal (int argc, char **argv, const char *optstring,
717 		  const struct option *longopts, int *longind, int long_only,
718 		  int posixly_correct)
719 {
720   int result;
721 
722   getopt_data.optind = optind;
723   getopt_data.opterr = opterr;
724 
725   result = _getopt_internal_r (argc, argv, optstring, longopts,
726 			       longind, long_only, &getopt_data,
727 			       posixly_correct);
728 
729   optind = getopt_data.optind;
730   optarg = getopt_data.optarg;
731   optopt = getopt_data.optopt;
732 
733   return result;
734 }
735 
736 /* glibc gets a LSB-compliant getopt and a POSIX-complaint __posix_getopt.
737    Standalone applications just get a POSIX-compliant getopt.
738    POSIX and LSB both require these functions to take 'char *const *argv'
739    even though this is incorrect (because of the permutation).  */
740 #define GETOPT_ENTRY(NAME, POSIXLY_CORRECT)			\
741   int								\
742   NAME (int argc, char *const *argv, const char *optstring)	\
743   {								\
744     return _getopt_internal (argc, (char **)argv, optstring,	\
745 			     0, 0, 0, POSIXLY_CORRECT);		\
746   }
747 
748 #ifdef _LIBC
749 GETOPT_ENTRY(getopt, 0)
750 GETOPT_ENTRY(__posix_getopt, 1)
751 #else
752 GETOPT_ENTRY(getopt, 1)
753 #endif
754 
755 
756 #ifdef TEST
757 
758 /* Compile with -DTEST to make an executable for use in testing
759    the above definition of 'getopt'.  */
760 
761 int
main(int argc,char ** argv)762 main (int argc, char **argv)
763 {
764   int c;
765   int digit_optind = 0;
766 
767   while (1)
768     {
769       int this_option_optind = optind ? optind : 1;
770 
771       c = getopt (argc, argv, "abc:d:0123456789");
772       if (c == -1)
773 	break;
774 
775       switch (c)
776 	{
777 	case '0':
778 	case '1':
779 	case '2':
780 	case '3':
781 	case '4':
782 	case '5':
783 	case '6':
784 	case '7':
785 	case '8':
786 	case '9':
787 	  if (digit_optind != 0 && digit_optind != this_option_optind)
788 	    printf ("digits occur in two different argv-elements.\n");
789 	  digit_optind = this_option_optind;
790 	  printf ("option %c\n", c);
791 	  break;
792 
793 	case 'a':
794 	  printf ("option a\n");
795 	  break;
796 
797 	case 'b':
798 	  printf ("option b\n");
799 	  break;
800 
801 	case 'c':
802 	  printf ("option c with value '%s'\n", optarg);
803 	  break;
804 
805 	case '?':
806 	  break;
807 
808 	default:
809 	  printf ("?? getopt returned character code 0%o ??\n", c);
810 	}
811     }
812 
813   if (optind < argc)
814     {
815       printf ("non-option ARGV-elements: ");
816       while (optind < argc)
817 	printf ("%s ", argv[optind++]);
818       printf ("\n");
819     }
820 
821   exit (0);
822 }
823 
824 #endif /* TEST */
825