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