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 
6    Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98
7    	Free Software Foundation, Inc.
8 
9    NOTE: This source is derived from an old version taken from the GNU C
10    Library (glibc).
11 
12    This program is free software; you can redistribute it and/or modify it
13    under the terms of the GNU General Public License as published by the
14    Free Software Foundation; either version 2, or (at your option) any
15    later version.
16 
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21 
22    You should have received a copy of the GNU General Public License
23    along with this program; if not, write to the Free Software
24    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
25    USA.  */
26 
27 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
28    Ditto for AIX 3.2 and <stdlib.h>.  */
29 #ifndef _NO_PROTO
30 # define _NO_PROTO
31 #endif
32 #include "stddefs.h"
33 #if (HAVE_STDIO_H == 1)
34 #	include <stdio.h>
35 #endif
36 
37 /* This needs to come after some library #include
38    to get __GNU_LIBRARY__ defined.  */
39 #ifdef	__GNU_LIBRARY__
40 /* Don't include stdlib.h for non-GNU C libraries because some of them
41    contain conflicting prototypes for getopt.  */
42 #if (HAVE_STDLIB_H == 1)
43 #	include <stdlib.h>
44 #endif
45 #if (HAVE_UNISTD_H == 1)
46 #	include <unistd.h>
47 #endif
48 #endif	/* GNU C library.  */
49 
50 #ifdef VMS
51 #	if (HAVE_UNIXLIB_H == 1)
52 #		include <unixlib.h>
53 #	endif
54 #	if HAVE_STRING_H - 0
55 #  		include <string.h>
56 #	endif
57 #endif
58 
59 /* This version of `getopt' appears to the caller like standard Unix `getopt'
60    but it behaves differently for the user, since it allows the user
61    to intersperse the options with the other arguments.
62 
63    As `getopt' works, it permutes the elements of ARGV so that,
64    when it is done, all the options precede everything else.  Thus
65    all application programs are extended to handle flexible argument order.
66 
67    Setting the environment variable POSIXLY_CORRECT disables permutation.
68    Then the behavior is completely standard.
69 
70    GNU application programs can use a third alternative mode in which
71    they can distinguish the relative order of options and other arguments.  */
72 
73 #include "getopt_long.h"
74 
75 /* For communication from `getopt' to the caller.
76    When `getopt' finds an option that takes an argument,
77    the argument value is returned here.
78    Also, when `ordering' is RETURN_IN_ORDER,
79    each non-option ARGV-element is returned here.  */
80 
81 char *optarg = NULL;
82 
83 /* Index in ARGV of the next element to be scanned.
84    This is used for communication to and from the caller
85    and for communication between successive calls to `getopt'.
86 
87    On entry to `getopt', zero means this is the first call; initialize.
88 
89    When `getopt' returns -1, this is the index of the first of the
90    non-option elements that the caller should itself scan.
91 
92    Otherwise, `optind' communicates from one call to the next
93    how much of ARGV has been scanned so far.  */
94 
95 /* 1003.2 says this must be 1 before any call.  */
96 int optind = 1;
97 
98 /* Formerly, initialization of getopt depended on optind==0, which
99    causes problems with re-calling getopt as programs generally don't
100    know that. */
101 
102 int __getopt_initialized = 0;
103 
104 /* The next char to be scanned in the option-element
105    in which the last option character we returned was found.
106    This allows us to pick up the scan where we left off.
107 
108    If this is zero, or a null string, it means resume the scan
109    by advancing to the next ARGV-element.  */
110 
111 static char *nextchar;
112 
113 /* Callers store zero here to inhibit the error message
114    for unrecognized options.  */
115 
116 int opterr = 1;
117 
118 /* Set to an option character which was unrecognized.
119    This must be initialized on some systems to avoid linking in the
120    system's own getopt implementation.  */
121 
122 int optopt = '?';
123 
124 /* Describe how to deal with options that follow non-option ARGV-elements.
125 
126    If the caller did not specify anything,
127    the default is REQUIRE_ORDER if the environment variable
128    POSIXLY_CORRECT is defined, PERMUTE otherwise.
129 
130    REQUIRE_ORDER means don't recognize them as options;
131    stop option processing when the first non-option is seen.
132    This is what Unix does.
133    This mode of operation is selected by either setting the environment
134    variable POSIXLY_CORRECT, or using `+' as the first character
135    of the list of option characters.
136 
137    PERMUTE is the default.  We permute the contents of ARGV as we scan,
138    so that eventually all the non-options are at the end.  This allows options
139    to be given in any order, even with programs that were not written to
140    expect this.
141 
142    RETURN_IN_ORDER is an option available to programs that were written
143    to expect options and other ARGV-elements in any order and that care about
144    the ordering of the two.  We describe each non-option ARGV-element
145    as if it were the argument of an option with character code 1.
146    Using `-' as the first character of the list of option characters
147    selects this mode of operation.
148 
149    The special argument `--' forces an end of option-scanning regardless
150    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
151    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
152 
153 static enum
154 {
155   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
156 } ordering;
157 
158 /* Value of POSIXLY_CORRECT environment variable.  */
159 static char *posixly_correct;
160 
161 #ifdef	__GNU_LIBRARY__
162 /* We want to avoid inclusion of string.h with non-GNU libraries
163    because there are many ways it can cause trouble.
164    On some systems, it contains special magic macros that don't work
165    in GCC.  */
166 # include <string.h>
167 # define my_index	strchr
168 #else
169 
170 # if HAVE_STRING_H
171 #  include <string.h>
172 # else
173 #  if HAVE_STRINGS_H
174 #   include <strings.h>
175 #  endif
176 # endif
177 
178 /* Avoid depending on library functions or files
179    whose names are inconsistent.  */
180 
181 #ifndef getenv
182 extern char *getenv ();
183 #endif
184 
185 static char *
my_index(str,chr)186 my_index (str, chr)
187      const char *str;
188      int chr;
189 {
190   while (*str)
191     {
192       if (*str == chr)
193 	return (char *) str;
194       str++;
195     }
196   return 0;
197 }
198 
199 /* If using GCC, we can safely declare strlen this way.
200    If not using GCC, it is ok not to declare it.  */
201 #ifdef __GNUC__
202 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
203    That was relevant to code that was here before.  */
204 # if (!defined __STDC__ || !__STDC__) && !defined strlen
205 /* gcc with -traditional declares the built-in strlen to return int,
206    and has done so at least since version 2.4.5. -- rms.  */
207 extern int strlen (const char *);
208 # endif /* not __STDC__ */
209 #endif /* __GNUC__ */
210 
211 #endif /* not __GNU_LIBRARY__ */
212 
213 /* Handle permutation of arguments.  */
214 
215 /* Describe the part of ARGV that contains non-options that have
216    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
217    `last_nonopt' is the index after the last of them.  */
218 
219 static int first_nonopt;
220 static int last_nonopt;
221 
222 #ifdef _LIBC
223 /* Bash 2.0 gives us an environment variable containing flags
224    indicating ARGV elements that should not be considered arguments.  */
225 
226 /* Defined in getopt_init.c  */
227 extern char *__getopt_nonoption_flags;
228 
229 static int nonoption_flags_max_len;
230 static int nonoption_flags_len;
231 
232 static int original_argc;
233 static char *const *original_argv;
234 
235 /* Make sure the environment variable bash 2.0 puts in the environment
236    is valid for the getopt call we must make sure that the ARGV passed
237    to getopt is that one passed to the process.  */
238 static void
239 __attribute__ ((unused))
store_args_and_env(int argc,char * const * argv)240 store_args_and_env (int argc, char *const *argv)
241 {
242   /* XXX This is no good solution.  We should rather copy the args so
243      that we can compare them later.  But we must not use malloc(3).  */
244   original_argc = argc;
245   original_argv = argv;
246 }
247 # ifdef text_set_element
248 text_set_element (__libc_subinit, store_args_and_env);
249 # endif /* text_set_element */
250 
251 # define SWAP_FLAGS(ch1, ch2) \
252   if (nonoption_flags_len > 0)						      \
253     {									      \
254       char __tmp = __getopt_nonoption_flags[ch1];			      \
255       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];	      \
256       __getopt_nonoption_flags[ch2] = __tmp;				      \
257     }
258 #else	/* !_LIBC */
259 # define SWAP_FLAGS(ch1, ch2)
260 #endif	/* _LIBC */
261 
262 /* Exchange two adjacent subsequences of ARGV.
263    One subsequence is elements [first_nonopt,last_nonopt)
264    which contains all the non-options that have been skipped so far.
265    The other is elements [last_nonopt,optind), which contains all
266    the options processed since those non-options were skipped.
267 
268    `first_nonopt' and `last_nonopt' are relocated so that they describe
269    the new indices of the non-options in ARGV after they are moved.  */
270 
271 #if defined __STDC__ && __STDC__
272 static void exchange (char **);
273 #endif
274 
275 static void
exchange(argv)276 exchange (argv)
277      char **argv;
278 {
279   int bottom = first_nonopt;
280   int middle = last_nonopt;
281   int top = optind;
282   char *tem;
283 
284   /* Exchange the shorter segment with the far end of the longer segment.
285      That puts the shorter segment into the right place.
286      It leaves the longer segment in the right place overall,
287      but it consists of two parts that need to be swapped next.  */
288 
289 #ifdef _LIBC
290   /* First make sure the handling of the `__getopt_nonoption_flags'
291      string can work normally.  Our top argument must be in the range
292      of the string.  */
293   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
294     {
295       /* We must extend the array.  The user plays games with us and
296 	 presents new arguments.  */
297       char *new_str = malloc (top + 1);
298       if (new_str == NULL)
299 	nonoption_flags_len = nonoption_flags_max_len = 0;
300       else
301 	{
302 	  memset (__mempcpy (new_str, __getopt_nonoption_flags,
303 			     nonoption_flags_max_len),
304 		  '\0', top + 1 - nonoption_flags_max_len);
305 	  nonoption_flags_max_len = top + 1;
306 	  __getopt_nonoption_flags = new_str;
307 	}
308     }
309 #endif
310 
311   while (top > middle && middle > bottom)
312     {
313       if (top - middle > middle - bottom)
314 	{
315 	  /* Bottom segment is the short one.  */
316 	  int len = middle - bottom;
317 	  register int i;
318 
319 	  /* Swap it with the top part of the top segment.  */
320 	  for (i = 0; i < len; i++)
321 	    {
322 	      tem = argv[bottom + i];
323 	      argv[bottom + i] = argv[top - (middle - bottom) + i];
324 	      argv[top - (middle - bottom) + i] = tem;
325 	      SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
326 	    }
327 	  /* Exclude the moved bottom segment from further swapping.  */
328 	  top -= len;
329 	}
330       else
331 	{
332 	  /* Top segment is the short one.  */
333 	  int len = top - middle;
334 	  register int i;
335 
336 	  /* Swap it with the bottom part of the bottom segment.  */
337 	  for (i = 0; i < len; i++)
338 	    {
339 	      tem = argv[bottom + i];
340 	      argv[bottom + i] = argv[middle + i];
341 	      argv[middle + i] = tem;
342 	      SWAP_FLAGS (bottom + i, middle + i);
343 	    }
344 	  /* Exclude the moved top segment from further swapping.  */
345 	  bottom += len;
346 	}
347     }
348 
349   /* Update records for the slots the non-options now occupy.  */
350 
351   first_nonopt += (optind - last_nonopt);
352   last_nonopt = optind;
353 }
354 
355 /* Initialize the internal data when the first call is made.  */
356 
357 #if defined __STDC__ && __STDC__
358 static const char *_getopt_initialize (int, char *const *, const char *);
359 #endif
360 static const char *
_getopt_initialize(argc,argv,optstring)361 _getopt_initialize (argc, argv, optstring)
362      int argc;
363      char *const *argv;
364      const char *optstring;
365 {
366   /* Start processing options with ARGV-element 1 (since ARGV-element 0
367      is the program name); the sequence of previously skipped
368      non-option ARGV-elements is empty.  */
369 
370   first_nonopt = last_nonopt = optind;
371 
372   nextchar = NULL;
373 
374   posixly_correct = getenv ("POSIXLY_CORRECT");
375 
376   /* Determine how to handle the ordering of options and nonoptions.  */
377 
378   if (optstring[0] == '-')
379     {
380       ordering = RETURN_IN_ORDER;
381       ++optstring;
382     }
383   else if (optstring[0] == '+')
384     {
385       ordering = REQUIRE_ORDER;
386       ++optstring;
387     }
388   else if (posixly_correct != NULL)
389     ordering = REQUIRE_ORDER;
390   else
391     ordering = PERMUTE;
392 
393 #ifdef _LIBC
394   if (posixly_correct == NULL
395       && argc == original_argc && argv == original_argv)
396     {
397       if (nonoption_flags_max_len == 0)
398 	{
399 	  if (__getopt_nonoption_flags == NULL
400 	      || __getopt_nonoption_flags[0] == '\0')
401 	    nonoption_flags_max_len = -1;
402 	  else
403 	    {
404 	      const char *orig_str = __getopt_nonoption_flags;
405 	      int len = nonoption_flags_max_len = strlen (orig_str);
406 	      if (nonoption_flags_max_len < argc)
407 		nonoption_flags_max_len = argc;
408 	      __getopt_nonoption_flags =
409 		(char *) malloc (nonoption_flags_max_len);
410 	      if (__getopt_nonoption_flags == NULL)
411 		nonoption_flags_max_len = -1;
412 	      else
413 		memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
414 			'\0', nonoption_flags_max_len - len);
415 	    }
416 	}
417       nonoption_flags_len = nonoption_flags_max_len;
418     }
419   else
420     nonoption_flags_len = 0;
421 #endif
422 
423   return optstring;
424 }
425 
426 /* Scan elements of ARGV (whose length is ARGC) for option characters
427    given in OPTSTRING.
428 
429    If an element of ARGV starts with '-', and is not exactly "-" or "--",
430    then it is an option element.  The characters of this element
431    (aside from the initial '-') are option characters.  If `getopt'
432    is called repeatedly, it returns successively each of the option characters
433    from each of the option elements.
434 
435    If `getopt' finds another option character, it returns that character,
436    updating `optind' and `nextchar' so that the next call to `getopt' can
437    resume the scan with the following option character or ARGV-element.
438 
439    If there are no more option characters, `getopt' returns -1.
440    Then `optind' is the index in ARGV of the first ARGV-element
441    that is not an option.  (The ARGV-elements have been permuted
442    so that those that are not options now come last.)
443 
444    OPTSTRING is a string containing the legitimate option characters.
445    If an option character is seen that is not listed in OPTSTRING,
446    return '?' after printing an error message.  If you set `opterr' to
447    zero, the error message is suppressed but we still return '?'.
448 
449    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
450    so the following text in the same ARGV-element, or the text of the following
451    ARGV-element, is returned in `optarg'.  Two colons mean an option that
452    wants an optional arg; if there is text in the current ARGV-element,
453    it is returned in `optarg', otherwise `optarg' is set to zero.
454 
455    If OPTSTRING starts with `-' or `+', it requests different methods of
456    handling the non-option ARGV-elements.
457    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
458 
459    Long-named options begin with `--' instead of `-'.
460    Their names may be abbreviated as long as the abbreviation is unique
461    or is an exact match for some defined option.  If they have an
462    argument, it follows the option name in the same ARGV-element, separated
463    from the option name by a `=', or else the in next ARGV-element.
464    When `getopt' finds a long-named option, it returns 0 if that option's
465    `flag' field is nonzero, the value of the option's `val' field
466    if the `flag' field is zero.
467 
468    The elements of ARGV aren't really const, because we permute them.
469    But we pretend they're const in the prototype to be compatible
470    with other systems.
471 
472    LONGOPTS is a vector of `struct option' terminated by an
473    element containing a name which is zero.
474 
475    LONGIND returns the index in LONGOPT of the long-named option found.
476    It is only valid when a long-named option has been found by the most
477    recent call.
478 
479    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
480    long-named options.  */
481 
482 int
_getopt_internal(argc,argv,optstring,longopts,longind,long_only)483 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
484      int argc;
485      char *const *argv;
486      const char *optstring;
487      const struct option *longopts;
488      int *longind;
489      int long_only;
490 {
491   optarg = NULL;
492 
493   if (optind == 0 || !__getopt_initialized)
494     {
495       if (optind == 0)
496 	optind = 1;	/* Don't scan ARGV[0], the program name.  */
497       optstring = _getopt_initialize (argc, argv, optstring);
498       __getopt_initialized = 1;
499     }
500 
501   /* Test whether ARGV[optind] points to a non-option argument.
502      Either it does not have option syntax, or there is an environment flag
503      from the shell indicating it is not an option.  The later information
504      is only used when the used in the GNU libc.  */
505 #ifdef _LIBC
506 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'	      \
507 		      || (optind < nonoption_flags_len			      \
508 			  && __getopt_nonoption_flags[optind] == '1'))
509 #else
510 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
511 #endif
512 
513   if (nextchar == NULL || *nextchar == '\0')
514     {
515       /* Advance to the next ARGV-element.  */
516 
517       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
518 	 moved back by the user (who may also have changed the arguments).  */
519       if (last_nonopt > optind)
520 	last_nonopt = optind;
521       if (first_nonopt > optind)
522 	first_nonopt = optind;
523 
524       if (ordering == PERMUTE)
525 	{
526 	  /* If we have just processed some options following some non-options,
527 	     exchange them so that the options come first.  */
528 
529 	  if (first_nonopt != last_nonopt && last_nonopt != optind)
530 	    exchange ((char **) argv);
531 	  else if (last_nonopt != optind)
532 	    first_nonopt = optind;
533 
534 	  /* Skip any additional non-options
535 	     and extend the range of non-options previously skipped.  */
536 
537 	  while (optind < argc && NONOPTION_P)
538 	    optind++;
539 	  last_nonopt = optind;
540 	}
541 
542       /* The special ARGV-element `--' means premature end of options.
543 	 Skip it like a null option,
544 	 then exchange with previous non-options as if it were an option,
545 	 then skip everything else like a non-option.  */
546 
547       if (optind != argc && !strcmp (argv[optind], "--"))
548 	{
549 	  optind++;
550 
551 	  if (first_nonopt != last_nonopt && last_nonopt != optind)
552 	    exchange ((char **) argv);
553 	  else if (first_nonopt == last_nonopt)
554 	    first_nonopt = optind;
555 	  last_nonopt = argc;
556 
557 	  optind = argc;
558 	}
559 
560       /* If we have done all the ARGV-elements, stop the scan
561 	 and back over any non-options that we skipped and permuted.  */
562 
563       if (optind == argc)
564 	{
565 	  /* Set the next-arg-index to point at the non-options
566 	     that we previously skipped, so the caller will digest them.  */
567 	  if (first_nonopt != last_nonopt)
568 	    optind = first_nonopt;
569 	  return -1;
570 	}
571 
572       /* If we have come to a non-option and did not permute it,
573 	 either stop the scan or describe it to the caller and pass it by.  */
574 
575       if (NONOPTION_P)
576 	{
577 	  if (ordering == REQUIRE_ORDER)
578 	    return -1;
579 	  optarg = argv[optind++];
580 	  return 1;
581 	}
582 
583       /* We have found another option-ARGV-element.
584 	 Skip the initial punctuation.  */
585 
586       nextchar = (argv[optind] + 1
587 		  + (longopts != NULL && argv[optind][1] == '-'));
588     }
589 
590   /* Decode the current option-ARGV-element.  */
591 
592   /* Check whether the ARGV-element is a long option.
593 
594      If long_only and the ARGV-element has the form "-f", where f is
595      a valid short option, don't consider it an abbreviated form of
596      a long option that starts with f.  Otherwise there would be no
597      way to give the -f short option.
598 
599      On the other hand, if there's a long option "fubar" and
600      the ARGV-element is "-fu", do consider that an abbreviation of
601      the long option, just like "--fu", and not "-f" with arg "u".
602 
603      This distinction seems to be the most useful approach.  */
604 
605   if (longopts != NULL
606       && (argv[optind][1] == '-'
607 	  || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
608     {
609       char *nameend;
610       const struct option *p;
611       const struct option *pfound = NULL;
612       int exact = 0;
613       int ambig = 0;
614       int indfound = -1;
615       int option_index;
616 
617       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
618 	/* Do nothing.  */ ;
619 
620       /* Test all long options for either exact match
621 	 or abbreviated matches.  */
622       for (p = longopts, option_index = 0; p->name; p++, option_index++)
623 	if (!strncmp (p->name, nextchar, nameend - nextchar))
624 	  {
625 	    if ((unsigned int) (nameend - nextchar)
626 		== (unsigned int) strlen (p->name))
627 	      {
628 		/* Exact match found.  */
629 		pfound = p;
630 		indfound = option_index;
631 		exact = 1;
632 		break;
633 	      }
634 	    else if (pfound == NULL)
635 	      {
636 		/* First nonexact match found.  */
637 		pfound = p;
638 		indfound = option_index;
639 	      }
640 	    else
641 	      /* Second or later nonexact match found.  */
642 	      ambig = 1;
643 	  }
644 
645       if (ambig && !exact)
646 	{
647 	  if (opterr)
648 	    fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
649 		     argv[0], argv[optind]);
650 	  nextchar += strlen (nextchar);
651 	  optind++;
652 	  optopt = 0;
653 	  return '?';
654 	}
655 
656       if (pfound != NULL)
657 	{
658 	  option_index = indfound;
659 	  optind++;
660 	  if (*nameend)
661 	    {
662 	      /* Don't test has_arg with >, because some C compilers don't
663 		 allow it to be used on enums.  */
664 	      if (pfound->has_arg)
665 		optarg = nameend + 1;
666 	      else
667 		{
668 		  if (opterr)
669 		    {
670 		      if (argv[optind - 1][1] == '-')
671 			/* --option */
672 			fprintf (stderr,
673 				 _("%s: option `--%s' doesn't allow an argument\n"),
674 				 argv[0], pfound->name);
675 		      else
676 			/* +option or -option */
677 			fprintf (stderr,
678 				 _("%s: option `%c%s' doesn't allow an argument\n"),
679 				 argv[0], argv[optind - 1][0], pfound->name);
680 
681 		      nextchar += strlen (nextchar);
682 
683 		      optopt = pfound->val;
684 		      return '?';
685 		    }
686 		}
687 	    }
688 	  else if (pfound->has_arg == 1)
689 	    {
690 	      if (optind < argc)
691 		optarg = argv[optind++];
692 	      else
693 		{
694 		  if (opterr)
695 		    fprintf (stderr,
696 			   _("%s: option `%s' requires an argument\n"),
697 			   argv[0], argv[optind - 1]);
698 		  nextchar += strlen (nextchar);
699 		  optopt = pfound->val;
700 		  return optstring[0] == ':' ? ':' : '?';
701 		}
702 	    }
703 	  nextchar += strlen (nextchar);
704 	  if (longind != NULL)
705 	    *longind = option_index;
706 	  if (pfound->flag)
707 	    {
708 	      *(pfound->flag) = pfound->val;
709 	      return 0;
710 	    }
711 	  return pfound->val;
712 	}
713 
714       /* Can't find it as a long option.  If this is not getopt_long_only,
715 	 or the option starts with '--' or is not a valid short
716 	 option, then it's an error.
717 	 Otherwise interpret it as a short option.  */
718       if (!long_only || argv[optind][1] == '-'
719 	  || my_index (optstring, *nextchar) == NULL)
720 	{
721 	  if (opterr)
722 	    {
723 	      if (argv[optind][1] == '-')
724 		/* --option */
725 		fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
726 			 argv[0], nextchar);
727 	      else
728 		/* +option or -option */
729 		fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
730 			 argv[0], argv[optind][0], nextchar);
731 	    }
732 	  nextchar = (char *) "";
733 	  optind++;
734 	  optopt = 0;
735 	  return '?';
736 	}
737     }
738 
739   /* Look at and handle the next short option-character.  */
740 
741   {
742     char c = *nextchar++;
743     char *temp = my_index (optstring, c);
744 
745     /* Increment `optind' when we start to process its last character.  */
746     if (*nextchar == '\0')
747       ++optind;
748 
749     if (temp == NULL || c == ':')
750       {
751 	if (opterr)
752 	  {
753 	    if (posixly_correct)
754 	      /* 1003.2 specifies the format of this message.  */
755 	      fprintf (stderr, _("%s: illegal option -- %c\n"),
756 		       argv[0], c);
757 	    else
758 	      fprintf (stderr, _("%s: invalid option -- %c\n"),
759 		       argv[0], c);
760 	  }
761 	optopt = c;
762 	return '?';
763       }
764     /* Convenience. Treat POSIX -W foo same as long option --foo */
765     if (temp[0] == 'W' && temp[1] == ';')
766       {
767 	char *nameend;
768 	const struct option *p;
769 	const struct option *pfound = NULL;
770 	int exact = 0;
771 	int ambig = 0;
772 	int indfound = 0;
773 	int option_index;
774 
775 	/* This is an option that requires an argument.  */
776 	if (*nextchar != '\0')
777 	  {
778 	    optarg = nextchar;
779 	    /* If we end this ARGV-element by taking the rest as an arg,
780 	       we must advance to the next element now.  */
781 	    optind++;
782 	  }
783 	else if (optind == argc)
784 	  {
785 	    if (opterr)
786 	      {
787 		/* 1003.2 specifies the format of this message.  */
788 		fprintf (stderr, _("%s: option requires an argument -- %c\n"),
789 			 argv[0], c);
790 	      }
791 	    optopt = c;
792 	    if (optstring[0] == ':')
793 	      c = ':';
794 	    else
795 	      c = '?';
796 	    return c;
797 	  }
798 	else
799 	  /* We already incremented `optind' once;
800 	     increment it again when taking next ARGV-elt as argument.  */
801 	  optarg = argv[optind++];
802 
803 	/* optarg is now the argument, see if it's in the
804 	   table of longopts.  */
805 
806 	for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
807 	  /* Do nothing.  */ ;
808 
809 	/* Test all long options for either exact match
810 	   or abbreviated matches.  */
811 	for (p = longopts, option_index = 0; p->name; p++, option_index++)
812 	  if (!strncmp (p->name, nextchar, nameend - nextchar))
813 	    {
814 	      if ((unsigned int) (nameend - nextchar) == strlen (p->name))
815 		{
816 		  /* Exact match found.  */
817 		  pfound = p;
818 		  indfound = option_index;
819 		  exact = 1;
820 		  break;
821 		}
822 	      else if (pfound == NULL)
823 		{
824 		  /* First nonexact match found.  */
825 		  pfound = p;
826 		  indfound = option_index;
827 		}
828 	      else
829 		/* Second or later nonexact match found.  */
830 		ambig = 1;
831 	    }
832 	if (ambig && !exact)
833 	  {
834 	    if (opterr)
835 	      fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
836 		       argv[0], argv[optind]);
837 	    nextchar += strlen (nextchar);
838 	    optind++;
839 	    return '?';
840 	  }
841 	if (pfound != NULL)
842 	  {
843 	    option_index = indfound;
844 	    if (*nameend)
845 	      {
846 		/* Don't test has_arg with >, because some C compilers don't
847 		   allow it to be used on enums.  */
848 		if (pfound->has_arg)
849 		  optarg = nameend + 1;
850 		else
851 		  {
852 		    if (opterr)
853 		      fprintf (stderr, _("\
854 %s: option `-W %s' doesn't allow an argument\n"),
855 			       argv[0], pfound->name);
856 
857 		    nextchar += strlen (nextchar);
858 		    return '?';
859 		  }
860 	      }
861 	    else if (pfound->has_arg == 1)
862 	      {
863 		if (optind < argc)
864 		  optarg = argv[optind++];
865 		else
866 		  {
867 		    if (opterr)
868 		      fprintf (stderr,
869 			       _("%s: option `%s' requires an argument\n"),
870 			       argv[0], argv[optind - 1]);
871 		    nextchar += strlen (nextchar);
872 		    return optstring[0] == ':' ? ':' : '?';
873 		  }
874 	      }
875 	    nextchar += strlen (nextchar);
876 	    if (longind != NULL)
877 	      *longind = option_index;
878 	    if (pfound->flag)
879 	      {
880 		*(pfound->flag) = pfound->val;
881 		return 0;
882 	      }
883 	    return pfound->val;
884 	  }
885 	  nextchar = NULL;
886 	  return 'W';	/* Let the application handle it.   */
887       }
888     if (temp[1] == ':')
889       {
890 	if (temp[2] == ':')
891 	  {
892 	    /* This is an option that accepts an argument optionally.  */
893 	    if (*nextchar != '\0')
894 	      {
895 		optarg = nextchar;
896 		optind++;
897 	      }
898 	    else
899 	      optarg = NULL;
900 	    nextchar = NULL;
901 	  }
902 	else
903 	  {
904 	    /* This is an option that requires an argument.  */
905 	    if (*nextchar != '\0')
906 	      {
907 		optarg = nextchar;
908 		/* If we end this ARGV-element by taking the rest as an arg,
909 		   we must advance to the next element now.  */
910 		optind++;
911 	      }
912 	    else if (optind == argc)
913 	      {
914 		if (opterr)
915 		  {
916 		    /* 1003.2 specifies the format of this message.  */
917 		    fprintf (stderr,
918 			   _("%s: option requires an argument -- %c\n"),
919 			   argv[0], c);
920 		  }
921 		optopt = c;
922 		if (optstring[0] == ':')
923 		  c = ':';
924 		else
925 		  c = '?';
926 	      }
927 	    else
928 	      /* We already incremented `optind' once;
929 		 increment it again when taking next ARGV-elt as argument.  */
930 	      optarg = argv[optind++];
931 	    nextchar = NULL;
932 	  }
933       }
934     return c;
935   }
936 }
937 
938 int
getopt(argc,argv,optstring)939 getopt (argc, argv, optstring)
940      int argc;
941      char *const *argv;
942      const char *optstring;
943 {
944   return _getopt_internal (argc, argv, optstring,
945 			   (const struct option *) 0,
946 			   (int *) 0,
947 			   0);
948 }
949 
950 int
getopt_long(argc,argv,options,long_options,opt_index)951 getopt_long (argc, argv, options, long_options, opt_index)
952      int argc;
953      char *const *argv;
954      const char *options;
955      const struct option *long_options;
956      int *opt_index;
957 {
958   return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
959 }
960