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 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32
33 #ifdef __GNUC__
34 #define alloca __builtin_alloca
35 #else /* not __GNUC__ */
36 #if defined (HAVE_ALLOCA_H) || (defined(sparc) && (defined(sun) || (!defined(USG) && !defined(SVR4) && !defined(__svr4__))))
37 #include <alloca.h>
38 #else
39 #ifdef _MSC_VER
40 #include <malloc.h>
41 #else
42 #ifndef _AIX
43 char *alloca ();
44 #endif
45 #endif
46 #endif /* alloca.h */
47 #endif /* not __GNUC__ */
48
49 #if !__STDC__ && !defined(const) && IN_GCC
50 #define const
51 #endif
52
53 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. */
54 #ifndef _NO_PROTO
55 #define _NO_PROTO
56 #endif
57
58 #include <stdio.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 = 0;
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
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 ();
194
195 static char *
my_index(str,chr)196 my_index (str, chr)
197 const char *str;
198 int chr;
199 {
200 while (*str)
201 {
202 if (*str == chr)
203 return (char *) str;
204 str++;
205 }
206 return 0;
207 }
208
209 static void
my_bcopy(from,to,size)210 my_bcopy (from, to, size)
211 const char *from;
212 char *to;
213 int size;
214 {
215 int i;
216 for (i = 0; i < size; i++)
217 to[i] = from[i];
218 }
219 #endif /* GNU C library. */
220
221 /* Handle permutation of arguments. */
222
223 /* Describe the part of ARGV that contains non-options that have
224 been skipped. `first_nonopt' is the index in ARGV of the first of them;
225 `last_nonopt' is the index after the last of them. */
226
227 static int first_nonopt;
228 static int last_nonopt;
229
230 /* Exchange two adjacent subsequences of ARGV.
231 One subsequence is elements [first_nonopt,last_nonopt)
232 which contains all the non-options that have been skipped so far.
233 The other is elements [last_nonopt,optind), which contains all
234 the options processed since those non-options were skipped.
235
236 `first_nonopt' and `last_nonopt' are relocated so that they describe
237 the new indices of the non-options in ARGV after they are moved. */
238
239 static void
exchange(argv)240 exchange (argv)
241 char **argv;
242 {
243 int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
244 char **temp = (char **) __alloca (nonopts_size);
245
246 /* Interchange the two blocks of data in ARGV. */
247
248 my_bcopy ((char *) &argv[first_nonopt], (char *) temp, nonopts_size);
249 my_bcopy ((char *) &argv[last_nonopt], (char *) &argv[first_nonopt],
250 (optind - last_nonopt) * sizeof (char *));
251 my_bcopy ((char *) temp,
252 (char *) &argv[first_nonopt + optind - last_nonopt],
253 nonopts_size);
254
255 /* Update records for the slots the non-options now occupy. */
256
257 first_nonopt += (optind - last_nonopt);
258 last_nonopt = optind;
259 }
260
261 /* Scan elements of ARGV (whose length is ARGC) for option characters
262 given in OPTSTRING.
263
264 If an element of ARGV starts with '-', and is not exactly "-" or "--",
265 then it is an option element. The characters of this element
266 (aside from the initial '-') are option characters. If `getopt'
267 is called repeatedly, it returns successively each of the option characters
268 from each of the option elements.
269
270 If `getopt' finds another option character, it returns that character,
271 updating `optind' and `nextchar' so that the next call to `getopt' can
272 resume the scan with the following option character or ARGV-element.
273
274 If there are no more option characters, `getopt' returns `EOF'.
275 Then `optind' is the index in ARGV of the first ARGV-element
276 that is not an option. (The ARGV-elements have been permuted
277 so that those that are not options now come last.)
278
279 OPTSTRING is a string containing the legitimate option characters.
280 If an option character is seen that is not listed in OPTSTRING,
281 return '?' after printing an error message. If you set `opterr' to
282 zero, the error message is suppressed but we still return '?'.
283
284 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
285 so the following text in the same ARGV-element, or the text of the following
286 ARGV-element, is returned in `optarg'. Two colons mean an option that
287 wants an optional arg; if there is text in the current ARGV-element,
288 it is returned in `optarg', otherwise `optarg' is set to zero.
289
290 If OPTSTRING starts with `-' or `+', it requests different methods of
291 handling the non-option ARGV-elements.
292 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
293
294 Long-named options begin with `--' instead of `-'.
295 Their names may be abbreviated as long as the abbreviation is unique
296 or is an exact match for some defined option. If they have an
297 argument, it follows the option name in the same ARGV-element, separated
298 from the option name by a `=', or else the in next ARGV-element.
299 When `getopt' finds a long-named option, it returns 0 if that option's
300 `flag' field is nonzero, the value of the option's `val' field
301 if the `flag' field is zero.
302
303 The elements of ARGV aren't really const, because we permute them.
304 But we pretend they're const in the prototype to be compatible
305 with other systems.
306
307 LONGOPTS is a vector of `struct option' terminated by an
308 element containing a name which is zero.
309
310 LONGIND returns the index in LONGOPT of the long-named option found.
311 It is only valid when a long-named option has been found by the most
312 recent call.
313
314 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
315 long-named options. */
316
317 int
_getopt_internal(argc,argv,optstring,longopts,longind,long_only)318 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
319 int argc;
320 char *const *argv;
321 const char *optstring;
322 const struct option *longopts;
323 int *longind;
324 int long_only;
325 {
326 int option_index;
327
328 optarg = 0;
329
330 /* Initialize the internal data when the first call is made.
331 Start processing options with ARGV-element 1 (since ARGV-element 0
332 is the program name); the sequence of previously skipped
333 non-option ARGV-elements is empty. */
334
335 if (optind == 0)
336 {
337 first_nonopt = last_nonopt = optind = 1;
338
339 nextchar = NULL;
340
341 /* Determine how to handle the ordering of options and nonoptions. */
342
343 if (optstring[0] == '-')
344 {
345 ordering = RETURN_IN_ORDER;
346 ++optstring;
347 }
348 else if (optstring[0] == '+')
349 {
350 ordering = REQUIRE_ORDER;
351 ++optstring;
352 }
353 else if (getenv ("POSIXLY_CORRECT") != NULL)
354 ordering = REQUIRE_ORDER;
355 else
356 ordering = PERMUTE;
357 }
358
359 if (nextchar == NULL || *nextchar == '\0')
360 {
361 if (ordering == PERMUTE)
362 {
363 /* If we have just processed some options following some non-options,
364 exchange them so that the options come first. */
365
366 if (first_nonopt != last_nonopt && last_nonopt != optind)
367 exchange ((char **) argv);
368 else if (last_nonopt != optind)
369 first_nonopt = optind;
370
371 /* Now skip any additional non-options
372 and extend the range of non-options previously skipped. */
373
374 while (optind < argc
375 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
376 #ifdef GETOPT_COMPAT
377 && (longopts == NULL
378 || argv[optind][0] != '+' || argv[optind][1] == '\0')
379 #endif /* GETOPT_COMPAT */
380 )
381 optind++;
382 last_nonopt = optind;
383 }
384
385 /* Special ARGV-element `--' means premature end of options.
386 Skip it like a null option,
387 then exchange with previous non-options as if it were an option,
388 then skip everything else like a non-option. */
389
390 if (optind != argc && !strcmp (argv[optind], "--"))
391 {
392 optind++;
393
394 if (first_nonopt != last_nonopt && last_nonopt != optind)
395 exchange ((char **) argv);
396 else if (first_nonopt == last_nonopt)
397 first_nonopt = optind;
398 last_nonopt = argc;
399
400 optind = argc;
401 }
402
403 /* If we have done all the ARGV-elements, stop the scan
404 and back over any non-options that we skipped and permuted. */
405
406 if (optind == argc)
407 {
408 /* Set the next-arg-index to point at the non-options
409 that we previously skipped, so the caller will digest them. */
410 if (first_nonopt != last_nonopt)
411 optind = first_nonopt;
412 return EOF;
413 }
414
415 /* If we have come to a non-option and did not permute it,
416 either stop the scan or describe it to the caller and pass it by. */
417
418 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
419 #ifdef GETOPT_COMPAT
420 && (longopts == NULL
421 || argv[optind][0] != '+' || argv[optind][1] == '\0')
422 #endif /* GETOPT_COMPAT */
423 )
424 {
425 if (ordering == REQUIRE_ORDER)
426 return EOF;
427 optarg = argv[optind++];
428 return 1;
429 }
430
431 /* We have found another option-ARGV-element.
432 Start decoding its characters. */
433
434 nextchar = (argv[optind] + 1
435 + (longopts != NULL && argv[optind][1] == '-'));
436 }
437
438 if (longopts != NULL
439 && ((argv[optind][0] == '-'
440 && (argv[optind][1] == '-' || long_only))
441 #ifdef GETOPT_COMPAT
442 || argv[optind][0] == '+'
443 #endif /* GETOPT_COMPAT */
444 ))
445 {
446 const struct option *p;
447 char *s = nextchar;
448 int exact = 0;
449 int ambig = 0;
450 const struct option *pfound = NULL;
451 int indfound;
452
453 while (*s && *s != '=')
454 s++;
455
456 /* Test all options for either exact match or abbreviated matches. */
457 for (p = longopts, option_index = 0; p->name;
458 p++, option_index++)
459 if (!strncmp (p->name, nextchar, s - nextchar))
460 {
461 if (s - nextchar == strlen (p->name))
462 {
463 /* Exact match found. */
464 pfound = p;
465 indfound = option_index;
466 exact = 1;
467 break;
468 }
469 else if (pfound == NULL)
470 {
471 /* First nonexact match found. */
472 pfound = p;
473 indfound = option_index;
474 }
475 else
476 /* Second nonexact match found. */
477 ambig = 1;
478 }
479
480 if (ambig && !exact)
481 {
482 if (opterr)
483 fprintf (stderr, "%s: option `%s' is ambiguous\n",
484 argv[0], argv[optind]);
485 nextchar += strlen (nextchar);
486 optind++;
487 return '?';
488 }
489
490 if (pfound != NULL)
491 {
492 option_index = indfound;
493 optind++;
494 if (*s)
495 {
496 /* Don't test has_arg with >, because some C compilers don't
497 allow it to be used on enums. */
498 if (pfound->has_arg)
499 optarg = s + 1;
500 else
501 {
502 if (opterr)
503 {
504 if (argv[optind - 1][1] == '-')
505 /* --option */
506 fprintf (stderr,
507 "%s: option `--%s' doesn't allow an argument\n",
508 argv[0], pfound->name);
509 else
510 /* +option or -option */
511 fprintf (stderr,
512 "%s: option `%c%s' doesn't allow an argument\n",
513 argv[0], argv[optind - 1][0], pfound->name);
514 }
515 nextchar += strlen (nextchar);
516 return '?';
517 }
518 }
519 else if (pfound->has_arg == 1)
520 {
521 if (optind < argc)
522 optarg = argv[optind++];
523 else
524 {
525 if (opterr)
526 fprintf (stderr, "%s: option `%s' requires an argument\n",
527 argv[0], argv[optind - 1]);
528 nextchar += strlen (nextchar);
529 return optstring[0] == ':' ? ':' : '?';
530 }
531 }
532 nextchar += strlen (nextchar);
533 if (longind != NULL)
534 *longind = option_index;
535 if (pfound->flag)
536 {
537 *(pfound->flag) = pfound->val;
538 return 0;
539 }
540 return pfound->val;
541 }
542 /* Can't find it as a long option. If this is not getopt_long_only,
543 or the option starts with '--' or is not a valid short
544 option, then it's an error.
545 Otherwise interpret it as a short option. */
546 if (!long_only || argv[optind][1] == '-'
547 #ifdef GETOPT_COMPAT
548 || argv[optind][0] == '+'
549 #endif /* GETOPT_COMPAT */
550 || my_index (optstring, *nextchar) == NULL)
551 {
552 if (opterr)
553 {
554 if (argv[optind][1] == '-')
555 /* --option */
556 fprintf (stderr, "%s: unrecognized option `--%s'\n",
557 argv[0], nextchar);
558 else
559 /* +option or -option */
560 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
561 argv[0], argv[optind][0], nextchar);
562 }
563 nextchar = (char *) "";
564 optind++;
565 return '?';
566 }
567 }
568
569 /* Look at and handle the next option-character. */
570
571 {
572 char c = *nextchar++;
573 char *temp = my_index (optstring, c);
574
575 /* Increment `optind' when we start to process its last character. */
576 if (*nextchar == '\0')
577 ++optind;
578
579 if (temp == NULL || c == ':')
580 {
581 if (opterr)
582 {
583 #if 0
584 if (c < 040 || c >= 0177)
585 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
586 argv[0], c);
587 else
588 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
589 #else
590 /* 1003.2 specifies the format of this message. */
591 fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
592 #endif
593 }
594 optopt = c;
595 return '?';
596 }
597 if (temp[1] == ':')
598 {
599 if (temp[2] == ':')
600 {
601 /* This is an option that accepts an argument optionally. */
602 if (*nextchar != '\0')
603 {
604 optarg = nextchar;
605 optind++;
606 }
607 else
608 optarg = 0;
609 nextchar = NULL;
610 }
611 else
612 {
613 /* This is an option that requires an argument. */
614 if (*nextchar != '\0')
615 {
616 optarg = nextchar;
617 /* If we end this ARGV-element by taking the rest as an arg,
618 we must advance to the next element now. */
619 optind++;
620 }
621 else if (optind == argc)
622 {
623 if (opterr)
624 {
625 #if 0
626 fprintf (stderr, "%s: option `-%c' requires an argument\n",
627 argv[0], c);
628 #else
629 /* 1003.2 specifies the format of this message. */
630 fprintf (stderr, "%s: option requires an argument -- %c\n",
631 argv[0], c);
632 #endif
633 }
634 optopt = c;
635 if (optstring[0] == ':')
636 c = ':';
637 else
638 c = '?';
639 }
640 else
641 /* We already incremented `optind' once;
642 increment it again when taking next ARGV-elt as argument. */
643 optarg = argv[optind++];
644 nextchar = NULL;
645 }
646 }
647 return c;
648 }
649 }
650
651 int
getopt(argc,argv,optstring)652 getopt (argc, argv, optstring)
653 int argc;
654 char *const *argv;
655 const char *optstring;
656 {
657 return _getopt_internal (argc, argv, optstring,
658 (const struct option *) 0,
659 (int *) 0,
660 0);
661 }
662
663 #endif /* _LIBC or not __GNU_LIBRARY__. */
664
665 #ifdef TEST
666
667 /* Compile with -DTEST to make an executable for use in testing
668 the above definition of `getopt'. */
669
670 int
main(argc,argv)671 main (argc, argv)
672 int argc;
673 char **argv;
674 {
675 int c;
676 int digit_optind = 0;
677
678 while (1)
679 {
680 int this_option_optind = optind ? optind : 1;
681
682 c = getopt (argc, argv, "abc:d:0123456789");
683 if (c == EOF)
684 break;
685
686 switch (c)
687 {
688 case '0':
689 case '1':
690 case '2':
691 case '3':
692 case '4':
693 case '5':
694 case '6':
695 case '7':
696 case '8':
697 case '9':
698 if (digit_optind != 0 && digit_optind != this_option_optind)
699 printf ("digits occur in two different argv-elements.\n");
700 digit_optind = this_option_optind;
701 printf ("option %c\n", c);
702 break;
703
704 case 'a':
705 printf ("option a\n");
706 break;
707
708 case 'b':
709 printf ("option b\n");
710 break;
711
712 case 'c':
713 printf ("option c with value `%s'\n", optarg);
714 break;
715
716 case '?':
717 break;
718
719 default:
720 printf ("?? getopt returned character code 0%o ??\n", c);
721 }
722 }
723
724 if (optind < argc)
725 {
726 printf ("non-option ARGV-elements: ");
727 while (optind < argc)
728 printf ("%s ", argv[optind++]);
729 printf ("\n");
730 }
731
732 exit (0);
733 }
734
735 #endif /* TEST */
736