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