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