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