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