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 roland@gnu.ai.mit.edu
4   before changing it!
5
6   Copyright (C) 1987, 88, 89, 90, 91, 92, 1993
7   	Free Software Foundation, Inc.
8
9   This program is free software; you can redistribute it and/or modify it
10   under the terms of the GNU General Public License as published by the
11   Free Software Foundation; either version 2, or (at your option) any
12   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, write to the Free Software
21   Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
22
23/* NOTE!!!  AIX requires this to be the first thing in the file.
24   Do not put ANYTHING before it!  */
25#if !defined (__GNUC__) && defined (_AIX)
26 #pragma alloca
27#endif
28
29#include "autoconf.h"
30
31#ifdef __GNUC__
32#define alloca __builtin_alloca
33#else /* not __GNUC__ */
34#if defined (HAVE_ALLOCA_H) || (defined(sparc) && (defined(sun) || (!defined(USG) && !defined(SVR4) && !defined(__svr4__))))
35#include <alloca.h>
36#else
37#ifndef _AIX
38char *alloca ();
39#endif
40#endif /* alloca.h */
41#endif /* not __GNUC__ */
42
43#if !__STDC__ && !defined(const) && IN_GCC
44#define const
45#endif
46
47/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.  */
48#ifndef _NO_PROTO
49#define _NO_PROTO
50#endif
51
52#include <stdio.h>
53
54/* Comment out all this code if we are using the GNU C Library, and are not
55   actually compiling the library itself.  This code is part of the GNU C
56   Library, but also included in many other GNU distributions.  Compiling
57   and linking in this code is a waste when using the GNU C library
58   (especially if it is a shared library).  Rather than having every GNU
59   program understand `configure --with-gnu-libc' and omit the object files,
60   it is simpler to just do this in the source for each such file.  */
61
62#if defined (_LIBC) || !defined (__GNU_LIBRARY__)
63
64
65/* This needs to come after some library #include
66   to get __GNU_LIBRARY__ defined.  */
67#ifdef	__GNU_LIBRARY__
68#undef	alloca
69/* Don't include stdlib.h for non-GNU C libraries because some of them
70   contain conflicting prototypes for getopt.  */
71#include <stdlib.h>
72#else	/* Not GNU C library.  */
73#define	__alloca	alloca
74#endif	/* GNU C library.  */
75
76/* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
77   long-named option.  Because this is not POSIX.2 compliant, it is
78   being phased out.  */
79/* #define GETOPT_COMPAT */
80
81/* This version of `getopt' appears to the caller like standard Unix `getopt'
82   but it behaves differently for the user, since it allows the user
83   to intersperse the options with the other arguments.
84
85   As `getopt' works, it permutes the elements of ARGV so that,
86   when it is done, all the options precede everything else.  Thus
87   all application programs are extended to handle flexible argument order.
88
89   Setting the environment variable POSIXLY_CORRECT disables permutation.
90   Then the behavior is completely standard.
91
92   GNU application programs can use a third alternative mode in which
93   they can distinguish the relative order of options and other arguments.  */
94
95#include "getopt.h"
96
97/* For communication from `getopt' to the caller.
98   When `getopt' finds an option that takes an argument,
99   the argument value is returned here.
100   Also, when `ordering' is RETURN_IN_ORDER,
101   each non-option ARGV-element is returned here.  */
102
103char *optarg = 0;
104
105/* Index in ARGV of the next element to be scanned.
106   This is used for communication to and from the caller
107   and for communication between successive calls to `getopt'.
108
109   On entry to `getopt', zero means this is the first call; initialize.
110
111   When `getopt' returns EOF, this is the index of the first of the
112   non-option elements that the caller should itself scan.
113
114   Otherwise, `optind' communicates from one call to the next
115   how much of ARGV has been scanned so far.  */
116
117/* XXX 1003.2 says this must be 1 before any call.  */
118int optind = 0;
119
120/* The next char to be scanned in the option-element
121   in which the last option character we returned was found.
122   This allows us to pick up the scan where we left off.
123
124   If this is zero, or a null string, it means resume the scan
125   by advancing to the next ARGV-element.  */
126
127static char *nextchar;
128
129/* Callers store zero here to inhibit the error message
130   for unrecognized options.  */
131
132int opterr = 1;
133
134/* Set to an option character which was unrecognized.
135   This must be initialized on some systems to avoid linking in the
136   system's own getopt implementation.  */
137
138int optopt = '?';
139
140/* Describe how to deal with options that follow non-option ARGV-elements.
141
142   If the caller did not specify anything,
143   the default is REQUIRE_ORDER if the environment variable
144   POSIXLY_CORRECT is defined, PERMUTE otherwise.
145
146   REQUIRE_ORDER means don't recognize them as options;
147   stop option processing when the first non-option is seen.
148   This is what Unix does.
149   This mode of operation is selected by either setting the environment
150   variable POSIXLY_CORRECT, or using `+' as the first character
151   of the list of option characters.
152
153   PERMUTE is the default.  We permute the contents of ARGV as we scan,
154   so that eventually all the non-options are at the end.  This allows options
155   to be given in any order, even with programs that were not written to
156   expect this.
157
158   RETURN_IN_ORDER is an option available to programs that were written
159   to expect options and other ARGV-elements in any order and that care about
160   the ordering of the two.  We describe each non-option ARGV-element
161   as if it were the argument of an option with character code 1.
162   Using `-' as the first character of the list of option characters
163   selects this mode of operation.
164
165   The special argument `--' forces an end of option-scanning regardless
166   of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
167   `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
168
169static enum
170{
171  REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
172} ordering;
173
174#ifdef	__GNU_LIBRARY__
175/* We want to avoid inclusion of string.h with non-GNU libraries
176   because there are many ways it can cause trouble.
177   On some systems, it contains special magic macros that don't work
178   in GCC.  */
179#include <string.h>
180#define	my_index	strchr
181#define	my_bcopy(src, dst, n)	memcpy ((dst), (src), (n))
182#else
183
184/* Avoid depending on library functions or files
185   whose names are inconsistent.  */
186
187char *getenv ();
188
189static char *
190my_index (str, chr)
191     const char *str;
192     int chr;
193{
194  while (*str)
195    {
196      if (*str == chr)
197	return (char *) str;
198      str++;
199    }
200  return 0;
201}
202
203static void
204my_bcopy (from, to, size)
205     const char *from;
206     char *to;
207     int size;
208{
209  int i;
210  for (i = 0; i < size; i++)
211    to[i] = from[i];
212}
213#endif				/* GNU C library.  */
214
215/* Handle permutation of arguments.  */
216
217/* Describe the part of ARGV that contains non-options that have
218   been skipped.  `first_nonopt' is the index in ARGV of the first of them;
219   `last_nonopt' is the index after the last of them.  */
220
221static int first_nonopt;
222static int last_nonopt;
223
224/* Exchange two adjacent subsequences of ARGV.
225   One subsequence is elements [first_nonopt,last_nonopt)
226   which contains all the non-options that have been skipped so far.
227   The other is elements [last_nonopt,optind), which contains all
228   the options processed since those non-options were skipped.
229
230   `first_nonopt' and `last_nonopt' are relocated so that they describe
231   the new indices of the non-options in ARGV after they are moved.  */
232
233static void
234exchange (argv)
235     char **argv;
236{
237  int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
238  char **temp = (char **) __alloca (nonopts_size);
239
240  /* Interchange the two blocks of data in ARGV.  */
241
242  my_bcopy ((char *) &argv[first_nonopt], (char *) temp, nonopts_size);
243  my_bcopy ((char *) &argv[last_nonopt], (char *) &argv[first_nonopt],
244	    (optind - last_nonopt) * sizeof (char *));
245  my_bcopy ((char *) temp,
246	    (char *) &argv[first_nonopt + optind - last_nonopt],
247	    nonopts_size);
248
249  /* Update records for the slots the non-options now occupy.  */
250
251  first_nonopt += (optind - last_nonopt);
252  last_nonopt = optind;
253}
254
255/* Scan elements of ARGV (whose length is ARGC) for option characters
256   given in OPTSTRING.
257
258   If an element of ARGV starts with '-', and is not exactly "-" or "--",
259   then it is an option element.  The characters of this element
260   (aside from the initial '-') are option characters.  If `getopt'
261   is called repeatedly, it returns successively each of the option characters
262   from each of the option elements.
263
264   If `getopt' finds another option character, it returns that character,
265   updating `optind' and `nextchar' so that the next call to `getopt' can
266   resume the scan with the following option character or ARGV-element.
267
268   If there are no more option characters, `getopt' returns `EOF'.
269   Then `optind' is the index in ARGV of the first ARGV-element
270   that is not an option.  (The ARGV-elements have been permuted
271   so that those that are not options now come last.)
272
273   OPTSTRING is a string containing the legitimate option characters.
274   If an option character is seen that is not listed in OPTSTRING,
275   return '?' after printing an error message.  If you set `opterr' to
276   zero, the error message is suppressed but we still return '?'.
277
278   If a char in OPTSTRING is followed by a colon, that means it wants an arg,
279   so the following text in the same ARGV-element, or the text of the following
280   ARGV-element, is returned in `optarg'.  Two colons mean an option that
281   wants an optional arg; if there is text in the current ARGV-element,
282   it is returned in `optarg', otherwise `optarg' is set to zero.
283
284   If OPTSTRING starts with `-' or `+', it requests different methods of
285   handling the non-option ARGV-elements.
286   See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
287
288   Long-named options begin with `--' instead of `-'.
289   Their names may be abbreviated as long as the abbreviation is unique
290   or is an exact match for some defined option.  If they have an
291   argument, it follows the option name in the same ARGV-element, separated
292   from the option name by a `=', or else the in next ARGV-element.
293   When `getopt' finds a long-named option, it returns 0 if that option's
294   `flag' field is nonzero, the value of the option's `val' field
295   if the `flag' field is zero.
296
297   The elements of ARGV aren't really const, because we permute them.
298   But we pretend they're const in the prototype to be compatible
299   with other systems.
300
301   LONGOPTS is a vector of `struct option' terminated by an
302   element containing a name which is zero.
303
304   LONGIND returns the index in LONGOPT of the long-named option found.
305   It is only valid when a long-named option has been found by the most
306   recent call.
307
308   If LONG_ONLY is nonzero, '-' as well as '--' can introduce
309   long-named options.  */
310
311int
312_getopt_internal (argc, argv, optstring, longopts, longind, long_only)
313     int argc;
314     char *const *argv;
315     const char *optstring;
316     const struct option *longopts;
317     int *longind;
318     int long_only;
319{
320  int option_index;
321
322  optarg = 0;
323
324  /* Initialize the internal data when the first call is made.
325     Start processing options with ARGV-element 1 (since ARGV-element 0
326     is the program name); the sequence of previously skipped
327     non-option ARGV-elements is empty.  */
328
329  if (optind == 0)
330    {
331      first_nonopt = last_nonopt = optind = 1;
332
333      nextchar = NULL;
334
335      /* Determine how to handle the ordering of options and nonoptions.  */
336
337      if (optstring[0] == '-')
338	{
339	  ordering = RETURN_IN_ORDER;
340	  ++optstring;
341	}
342      else if (optstring[0] == '+')
343	{
344	  ordering = REQUIRE_ORDER;
345	  ++optstring;
346	}
347      else if (getenv ("POSIXLY_CORRECT") != NULL)
348	ordering = REQUIRE_ORDER;
349      else
350	ordering = PERMUTE;
351    }
352
353  if (nextchar == NULL || *nextchar == '\0')
354    {
355      if (ordering == PERMUTE)
356	{
357	  /* If we have just processed some options following some non-options,
358	     exchange them so that the options come first.  */
359
360	  if (first_nonopt != last_nonopt && last_nonopt != optind)
361	    exchange ((char **) argv);
362	  else if (last_nonopt != optind)
363	    first_nonopt = optind;
364
365	  /* Now skip any additional non-options
366	     and extend the range of non-options previously skipped.  */
367
368	  while (optind < argc
369		 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
370#ifdef GETOPT_COMPAT
371		 && (longopts == NULL
372		     || argv[optind][0] != '+' || argv[optind][1] == '\0')
373#endif				/* GETOPT_COMPAT */
374		 )
375	    optind++;
376	  last_nonopt = optind;
377	}
378
379      /* Special ARGV-element `--' means premature end of options.
380	 Skip it like a null option,
381	 then exchange with previous non-options as if it were an option,
382	 then skip everything else like a non-option.  */
383
384      if (optind != argc && !strcmp (argv[optind], "--"))
385	{
386	  optind++;
387
388	  if (first_nonopt != last_nonopt && last_nonopt != optind)
389	    exchange ((char **) argv);
390	  else if (first_nonopt == last_nonopt)
391	    first_nonopt = optind;
392	  last_nonopt = argc;
393
394	  optind = argc;
395	}
396
397      /* If we have done all the ARGV-elements, stop the scan
398	 and back over any non-options that we skipped and permuted.  */
399
400      if (optind == argc)
401	{
402	  /* Set the next-arg-index to point at the non-options
403	     that we previously skipped, so the caller will digest them.  */
404	  if (first_nonopt != last_nonopt)
405	    optind = first_nonopt;
406	  return EOF;
407	}
408
409      /* If we have come to a non-option and did not permute it,
410	 either stop the scan or describe it to the caller and pass it by.  */
411
412      if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
413#ifdef GETOPT_COMPAT
414	  && (longopts == NULL
415	      || argv[optind][0] != '+' || argv[optind][1] == '\0')
416#endif				/* GETOPT_COMPAT */
417	  )
418	{
419	  if (ordering == REQUIRE_ORDER)
420	    return EOF;
421	  optarg = argv[optind++];
422	  return 1;
423	}
424
425      /* We have found another option-ARGV-element.
426	 Start decoding its characters.  */
427
428      nextchar = (argv[optind] + 1
429		  + (longopts != NULL && argv[optind][1] == '-'));
430    }
431
432  if (longopts != NULL
433      && ((argv[optind][0] == '-'
434	   && (argv[optind][1] == '-' || long_only))
435#ifdef GETOPT_COMPAT
436	  || argv[optind][0] == '+'
437#endif				/* GETOPT_COMPAT */
438	  ))
439    {
440      const struct option *p;
441      char *s = nextchar;
442      int exact = 0;
443      int ambig = 0;
444      const struct option *pfound = NULL;
445      int indfound;
446
447      while (*s && *s != '=')
448	s++;
449
450      /* Test all options for either exact match or abbreviated matches.  */
451      for (p = longopts, option_index = 0; p->name;
452	   p++, option_index++)
453	if (!strncmp (p->name, nextchar, s - nextchar))
454	  {
455	    if (s - nextchar == strlen (p->name))
456	      {
457		/* Exact match found.  */
458		pfound = p;
459		indfound = option_index;
460		exact = 1;
461		break;
462	      }
463	    else if (pfound == NULL)
464	      {
465		/* First nonexact match found.  */
466		pfound = p;
467		indfound = option_index;
468	      }
469	    else
470	      /* Second nonexact match found.  */
471	      ambig = 1;
472	  }
473
474      if (ambig && !exact)
475	{
476	  if (opterr)
477	    fprintf (stderr, "%s: option `%s' is ambiguous\n",
478		     argv[0], argv[optind]);
479	  nextchar += strlen (nextchar);
480	  optind++;
481	  return '?';
482	}
483
484      if (pfound != NULL)
485	{
486	  option_index = indfound;
487	  optind++;
488	  if (*s)
489	    {
490	      /* Don't test has_arg with >, because some C compilers don't
491		 allow it to be used on enums.  */
492	      if (pfound->has_arg)
493		optarg = s + 1;
494	      else
495		{
496		  if (opterr)
497		    {
498		      if (argv[optind - 1][1] == '-')
499			/* --option */
500			fprintf (stderr,
501				 "%s: option `--%s' doesn't allow an argument\n",
502				 argv[0], pfound->name);
503		      else
504			/* +option or -option */
505			fprintf (stderr,
506			     "%s: option `%c%s' doesn't allow an argument\n",
507			     argv[0], argv[optind - 1][0], pfound->name);
508		    }
509		  nextchar += strlen (nextchar);
510		  return '?';
511		}
512	    }
513	  else if (pfound->has_arg == 1)
514	    {
515	      if (optind < argc)
516		optarg = argv[optind++];
517	      else
518		{
519		  if (opterr)
520		    fprintf (stderr, "%s: option `%s' requires an argument\n",
521			     argv[0], argv[optind - 1]);
522		  nextchar += strlen (nextchar);
523		  return optstring[0] == ':' ? ':' : '?';
524		}
525	    }
526	  nextchar += strlen (nextchar);
527	  if (longind != NULL)
528	    *longind = option_index;
529	  if (pfound->flag)
530	    {
531	      *(pfound->flag) = pfound->val;
532	      return 0;
533	    }
534	  return pfound->val;
535	}
536      /* Can't find it as a long option.  If this is not getopt_long_only,
537	 or the option starts with '--' or is not a valid short
538	 option, then it's an error.
539	 Otherwise interpret it as a short option.  */
540      if (!long_only || argv[optind][1] == '-'
541#ifdef GETOPT_COMPAT
542	  || argv[optind][0] == '+'
543#endif				/* GETOPT_COMPAT */
544	  || my_index (optstring, *nextchar) == NULL)
545	{
546	  if (opterr)
547	    {
548	      if (argv[optind][1] == '-')
549		/* --option */
550		fprintf (stderr, "%s: unrecognized option `--%s'\n",
551			 argv[0], nextchar);
552	      else
553		/* +option or -option */
554		fprintf (stderr, "%s: unrecognized option `%c%s'\n",
555			 argv[0], argv[optind][0], nextchar);
556	    }
557	  nextchar = (char *) "";
558	  optind++;
559	  return '?';
560	}
561    }
562
563  /* Look at and handle the next option-character.  */
564
565  {
566    char c = *nextchar++;
567    char *temp = my_index (optstring, c);
568
569    /* Increment `optind' when we start to process its last character.  */
570    if (*nextchar == '\0')
571      ++optind;
572
573    if (temp == NULL || c == ':')
574      {
575	if (opterr)
576	  {
577#if 0
578	    if (c < 040 || c >= 0177)
579	      fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
580		       argv[0], c);
581	    else
582	      fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
583#else
584	    /* 1003.2 specifies the format of this message.  */
585	    fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
586#endif
587	  }
588	optopt = c;
589	return '?';
590      }
591    if (temp[1] == ':')
592      {
593	if (temp[2] == ':')
594	  {
595	    /* This is an option that accepts an argument optionally.  */
596	    if (*nextchar != '\0')
597	      {
598		optarg = nextchar;
599		optind++;
600	      }
601	    else
602	      optarg = 0;
603	    nextchar = NULL;
604	  }
605	else
606	  {
607	    /* This is an option that requires an argument.  */
608	    if (*nextchar != '\0')
609	      {
610		optarg = nextchar;
611		/* If we end this ARGV-element by taking the rest as an arg,
612		   we must advance to the next element now.  */
613		optind++;
614	      }
615	    else if (optind == argc)
616	      {
617		if (opterr)
618		  {
619#if 0
620		    fprintf (stderr, "%s: option `-%c' requires an argument\n",
621			     argv[0], c);
622#else
623		    /* 1003.2 specifies the format of this message.  */
624		    fprintf (stderr, "%s: option requires an argument -- %c\n",
625			     argv[0], c);
626#endif
627		  }
628		optopt = c;
629		if (optstring[0] == ':')
630		  c = ':';
631		else
632		  c = '?';
633	      }
634	    else
635	      /* We already incremented `optind' once;
636		 increment it again when taking next ARGV-elt as argument.  */
637	      optarg = argv[optind++];
638	    nextchar = NULL;
639	  }
640      }
641    return c;
642  }
643}
644
645int
646getopt (argc, argv, optstring)
647     int argc;
648     char *const *argv;
649     const char *optstring;
650{
651  return _getopt_internal (argc, argv, optstring,
652			   (const struct option *) 0,
653			   (int *) 0,
654			   0);
655}
656
657#endif	/* _LIBC or not __GNU_LIBRARY__.  */
658
659#ifdef TEST
660
661/* Compile with -DTEST to make an executable for use in testing
662   the above definition of `getopt'.  */
663
664int
665main (argc, argv)
666     int argc;
667     char **argv;
668{
669  int c;
670  int digit_optind = 0;
671
672  while (1)
673    {
674      int this_option_optind = optind ? optind : 1;
675
676      c = getopt (argc, argv, "abc:d:0123456789");
677      if (c == EOF)
678	break;
679
680      switch (c)
681	{
682	case '0':
683	case '1':
684	case '2':
685	case '3':
686	case '4':
687	case '5':
688	case '6':
689	case '7':
690	case '8':
691	case '9':
692	  if (digit_optind != 0 && digit_optind != this_option_optind)
693	    printf ("digits occur in two different argv-elements.\n");
694	  digit_optind = this_option_optind;
695	  printf ("option %c\n", c);
696	  break;
697
698	case 'a':
699	  printf ("option a\n");
700	  break;
701
702	case 'b':
703	  printf ("option b\n");
704	  break;
705
706	case 'c':
707	  printf ("option c with value `%s'\n", optarg);
708	  break;
709
710	case '?':
711	  break;
712
713	default:
714	  printf ("?? getopt returned character code 0%o ??\n", c);
715	}
716    }
717
718  if (optind < argc)
719    {
720      printf ("non-option ARGV-elements: ");
721      while (optind < argc)
722	printf ("%s ", argv[optind++]);
723      printf ("\n");
724    }
725
726  exit (0);
727}
728
729#endif /* TEST */
730