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