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