Fix a few 'gcc -fanalyzer' warnings.
[pwmd.git] / src / getopt_long.c
blobe8d210a57b30d6f1b5cbbc7e59df07be2e049e73
2 /* Getopt for GNU
4 Now part of GNU Queue. GNU Queue http://www.gnuqueue.org
6 NOTE: getopt is now part of the C library, so if you don't know what
7 "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
8 before changing it!
10 Copyright (C) 1987, 88, 89, 90, 91, 1992 Free Software Foundation, Inc.
12 This program is free software; you can redistribute it and/or modify it
13 under the terms of the GNU General Public License as published by the
14 Free Software Foundation; either version 2, or (at your option) any
15 later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 This file was modified slightly by Ian Lance Taylor, June 1992, for
27 Taylor UUCP. */
29 //#include "queue.h"
31 /* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
32 long-named option. Because this is not POSIX.2 compliant, it is
33 being phased out. */
34 #undef GETOPT_COMPAT
36 /* This version of `getopt' appears to the caller like standard Unix `getopt'
37 but it behaves differently for the user, since it allows the user
38 to intersperse the options with the other arguments.
40 As `getopt' works, it permutes the elements of ARGV so that,
41 when it is done, all the options precede everything else. Thus
42 all application programs are extended to handle flexible argument order.
44 Setting the environment variable POSIXLY_CORRECT disables permutation.
45 Then the behavior is completely standard.
47 GNU application programs can use a third alternative mode in which
48 they can distinguish the relative order of options and other arguments. */
50 #include <stdio.h>
51 #include <string.h>
52 #include <stdlib.h>
53 #include "getopt_long.h"
55 /* For communication from `getopt' to the caller.
56 When `getopt' finds an option that takes an argument,
57 the argument value is returned here.
58 Also, when `ordering' is RETURN_IN_ORDER,
59 each non-option ARGV-element is returned here. */
61 char *optarg = 0;
63 /* Index in ARGV of the next element to be scanned.
64 This is used for communication to and from the caller
65 and for communication between successive calls to `getopt'.
67 On entry to `getopt', zero means this is the first call; initialize.
69 When `getopt' returns EOF, this is the index of the first of the
70 non-option elements that the caller should itself scan.
72 Otherwise, `optind' communicates from one call to the next
73 how much of ARGV has been scanned so far. */
75 int optind = 0;
77 /* The next char to be scanned in the option-element
78 in which the last option character we returned was found.
79 This allows us to pick up the scan where we left off.
81 If this is zero, or a null string, it means resume the scan
82 by advancing to the next ARGV-element. */
84 static char *nextchar;
86 /* Callers store zero here to inhibit the error message
87 for unrecognized options. */
89 int opterr = 1;
91 /* Describe how to deal with options that follow non-option ARGV-elements.
93 If the caller did not specify anything,
94 the default is REQUIRE_ORDER if the environment variable
95 POSIXLY_CORRECT is defined, PERMUTE otherwise.
97 REQUIRE_ORDER means don't recognize them as options;
98 stop option processing when the first non-option is seen.
99 This is what Unix does.
100 This mode of operation is selected by either setting the environment
101 variable POSIXLY_CORRECT, or using `+' as the first character
102 of the list of option characters.
104 PERMUTE is the default. We permute the contents of ARGV as we scan,
105 so that eventually all the non-options are at the end. This allows options
106 to be given in any order, even with programs that were not written to
107 expect this.
109 RETURN_IN_ORDER is an option available to programs that were written
110 to expect options and other ARGV-elements in any order and that care about
111 the ordering of the two. We describe each non-option ARGV-element
112 as if it were the argument of an option with character code 1.
113 Using `-' as the first character of the list of option characters
114 selects this mode of operation.
116 The special argument `--' forces an end of option-scanning regardless
117 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
118 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
120 static enum
122 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
124 ordering;
126 #define my_index strchr
127 #define my_bcopy(src, dst, n) memcpy ((dst), (src), (n))
129 /* Handle permutation of arguments. */
131 /* Describe the part of ARGV that contains non-options that have
132 been skipped. `first_nonopt' is the index in ARGV of the first of them;
133 `last_nonopt' is the index after the last of them. */
135 static int first_nonopt;
136 static int last_nonopt;
138 /* Exchange two adjacent subsequences of ARGV.
139 One subsequence is elements [first_nonopt,last_nonopt)
140 which contains all the non-options that have been skipped so far.
141 The other is elements [last_nonopt,optind), which contains all
142 the options processed since those non-options were skipped.
144 `first_nonopt' and `last_nonopt' are relocated so that they describe
145 the new indices of the non-options in ARGV after they are moved. */
147 static void
148 exchange (argv)
149 char **argv;
151 size_t nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
152 char **temp = (char **) malloc (nonopts_size);
154 if (temp == NULL)
155 abort ();
157 /* Interchange the two blocks of data in ARGV. */
159 my_bcopy ((char *) &argv[first_nonopt], (char *) temp, nonopts_size);
160 my_bcopy ((char *) &argv[last_nonopt], (char *) &argv[first_nonopt],
161 (optind - last_nonopt) * sizeof (char *));
162 my_bcopy ((char *) temp,
163 (char *) &argv[first_nonopt + optind - last_nonopt],
164 nonopts_size);
166 free (temp);
168 /* Update records for the slots the non-options now occupy. */
170 first_nonopt += (optind - last_nonopt);
171 last_nonopt = optind;
174 /* Scan elements of ARGV (whose length is ARGC) for option characters
175 given in OPTSTRING.
177 If an element of ARGV starts with '-', and is not exactly "-" or "--",
178 then it is an option element. The characters of this element
179 (aside from the initial '-') are option characters. If `getopt'
180 is called repeatedly, it returns successively each of the option characters
181 from each of the option elements.
183 If `getopt' finds another option character, it returns that character,
184 updating `optind' and `nextchar' so that the next call to `getopt' can
185 resume the scan with the following option character or ARGV-element.
187 If there are no more option characters, `getopt' returns `EOF'.
188 Then `optind' is the index in ARGV of the first ARGV-element
189 that is not an option. (The ARGV-elements have been permuted
190 so that those that are not options now come last.)
192 OPTSTRING is a string containing the legitimate option characters.
193 If an option character is seen that is not listed in OPTSTRING,
194 return '?' after printing an error message. If you set `opterr' to
195 zero, the error message is suppressed but we still return '?'.
197 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
198 so the following text in the same ARGV-element, or the text of the following
199 ARGV-element, is returned in `optarg'. Two colons mean an option that
200 wants an optional arg; if there is text in the current ARGV-element,
201 it is returned in `optarg', otherwise `optarg' is set to zero.
203 If OPTSTRING starts with `-' or `+', it requests different methods of
204 handling the non-option ARGV-elements.
205 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
207 Long-named options begin with `--' instead of `-'.
208 Their names may be abbreviated as long as the abbreviation is unique
209 or is an exact match for some defined option. If they have an
210 argument, it follows the option name in the same ARGV-element, separated
211 from the option name by a `=', or else the in next ARGV-element.
212 When `getopt' finds a long-named option, it returns 0 if that option's
213 `flag' field is nonzero, the value of the option's `val' field
214 if the `flag' field is zero.
216 The elements of ARGV aren't really const, because we permute them.
217 But we pretend they're const in the prototype to be compatible
218 with other systems.
220 LONGOPTS is a vector of `struct option' terminated by an
221 element containing a name which is zero.
223 LONGIND returns the index in LONGOPT of the long-named option found.
224 It is only valid when a long-named option has been found by the most
225 recent call.
227 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
228 long-named options. */
231 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
232 int argc;
233 char *const *argv;
234 const char *optstring;
235 const struct option *longopts;
236 int *longind;
237 int long_only;
239 int option_index;
241 optarg = 0;
243 /* Initialize the internal data when the first call is made. Start
244 * processing options with ARGV-element 1 (since ARGV-element 0 is the
245 * program name); the sequence of previously skipped non-option
246 * ARGV-elements is empty. */
248 if (optind == 0)
250 first_nonopt = last_nonopt = optind = 1;
252 nextchar = NULL;
254 /* Determine how to handle the ordering of options and nonoptions. */
256 if (optstring[0] == '-')
258 ordering = RETURN_IN_ORDER;
259 ++optstring;
261 else if (optstring[0] == '+')
263 ordering = REQUIRE_ORDER;
264 ++optstring;
266 else if (getenv ("POSIXLY_CORRECT") != NULL)
267 ordering = REQUIRE_ORDER;
268 else
269 ordering = PERMUTE;
272 if (nextchar == NULL || *nextchar == '\0')
274 if (ordering == PERMUTE)
276 /* If we have just processed some options following some non-options,
277 * exchange them so that the options come first. */
279 if (first_nonopt != last_nonopt && last_nonopt != optind)
280 exchange ((char **) argv);
281 else if (last_nonopt != optind)
282 first_nonopt = optind;
284 /* Now skip any additional non-options and extend the range of
285 * non-options previously skipped. */
287 while (optind < argc
288 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
289 #ifdef GETOPT_COMPAT
290 && (longopts == NULL || argv[optind][0] != '+'
291 || argv[optind][1] == '\0')
292 #endif /* GETOPT_COMPAT */
294 optind++;
295 last_nonopt = optind;
298 /* Special ARGV-element `--' means premature end of options. Skip it like
299 * a null option, then exchange with previous non-options as if it were
300 * an option, then skip everything else like a non-option. */
302 if (optind != argc && !strcmp (argv[optind], "--"))
304 optind++;
306 if (first_nonopt != last_nonopt && last_nonopt != optind)
307 exchange ((char **) argv);
308 else if (first_nonopt == last_nonopt)
309 first_nonopt = optind;
310 last_nonopt = argc;
312 optind = argc;
315 /* If we have done all the ARGV-elements, stop the scan and back over any
316 * non-options that we skipped and permuted. */
318 if (optind == argc)
320 /* Set the next-arg-index to point at the non-options that we
321 * previously skipped, so the caller will digest them. */
322 if (first_nonopt != last_nonopt)
323 optind = first_nonopt;
324 return EOF;
327 /* If we have come to a non-option and did not permute it, either stop
328 * the scan or describe it to the caller and pass it by. */
330 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
331 #ifdef GETOPT_COMPAT
332 && (longopts == NULL || argv[optind][0] != '+'
333 || argv[optind][1] == '\0')
334 #endif /* GETOPT_COMPAT */
337 if (ordering == REQUIRE_ORDER)
338 return EOF;
339 optarg = argv[optind++];
340 return 1;
343 /* We have found another option-ARGV-element. Start decoding its
344 * characters. */
346 nextchar =
347 (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-'));
350 if (longopts != NULL
351 && ((argv[optind][0] == '-' && (argv[optind][1] == '-' || long_only))
352 #ifdef GETOPT_COMPAT
353 || argv[optind][0] == '+'
354 #endif /* GETOPT_COMPAT */
357 const struct option *p;
358 char *s = nextchar;
359 int exact = 0;
360 int ambig = 0;
361 const struct option *pfound = NULL;
362 int indfound = 0;
364 while (*s && *s != '=')
365 s++;
367 /* Test all options for either exact match or abbreviated matches. */
368 for (p = longopts, option_index = 0; p->name; p++, option_index++)
369 if (!strncmp (p->name, nextchar, (size_t) (s - nextchar)))
371 if (s - nextchar == strlen (p->name))
373 /* Exact match found. */
374 pfound = p;
375 indfound = option_index;
376 exact = 1;
377 break;
379 else if (pfound == NULL)
381 /* First nonexact match found. */
382 pfound = p;
383 indfound = option_index;
385 else
386 /* Second nonexact match found. */
387 ambig = 1;
390 if (ambig && !exact)
392 if (opterr)
393 fprintf (stderr, "%s: option `%s' is ambiguous\n", argv[0],
394 argv[optind]);
395 nextchar += strlen (nextchar);
396 optind++;
397 return '?';
400 if (pfound != NULL)
402 option_index = indfound;
403 optind++;
404 if (*s)
406 /* Don't test has_arg with >, because some C compilers don't allow it
407 * to be used on enums. */
408 if (pfound->has_arg)
409 optarg = s + 1;
410 else
412 if (opterr)
414 if (argv[optind - 1][1] == '-')
415 /* --option */
416 fprintf (stderr,
417 "%s: option `--%s' doesn't allow an argument\n",
418 argv[0], pfound->name);
419 else
420 /* +option or -option */
421 fprintf (stderr,
422 "%s: option `%c%s' doesn't allow an argument\n",
423 argv[0], argv[optind - 1][0], pfound->name);
425 nextchar += strlen (nextchar);
426 return '?';
429 else if (pfound->has_arg == 1)
431 if (optind < argc)
432 optarg = argv[optind++];
433 else
435 if (opterr)
436 fprintf (stderr, "%s: option `%s' requires an argument\n",
437 argv[0], argv[optind - 1]);
438 nextchar += strlen (nextchar);
439 return '?';
442 nextchar += strlen (nextchar);
443 if (longind != NULL)
444 *longind = option_index;
445 if (pfound->flag)
447 *(pfound->flag) = pfound->val;
448 return 0;
450 return pfound->val;
452 /* Can't find it as a long option. If this is not getopt_long_only, or
453 * the option starts with '--' or is not a valid short option, then it's
454 * an error. Otherwise interpret it as a short option. */
455 if (!long_only || argv[optind][1] == '-'
456 #ifdef GETOPT_COMPAT
457 || argv[optind][0] == '+'
458 #endif /* GETOPT_COMPAT */
459 || my_index (optstring, *nextchar) == NULL)
461 if (opterr)
463 if (argv[optind][1] == '-')
464 /* --option */
465 fprintf (stderr, "%s: unrecognized option `--%s'\n", argv[0],
466 nextchar);
467 else
468 /* +option or -option */
469 fprintf (stderr, "%s: unrecognized option `%c%s'\n", argv[0],
470 argv[optind][0], nextchar);
472 nextchar = (char *) "";
473 optind++;
474 return '?';
478 /* Look at and handle the next option-character. */
481 char c = *nextchar++;
482 char *temp = my_index (optstring, c);
484 /* Increment `optind' when we start to process its last character. */
485 if (*nextchar == '\0')
486 ++optind;
488 if (temp == NULL || c == ':')
490 if (opterr)
492 if (c < 040 || c >= 0177)
493 fprintf (stderr,
494 "%s: unrecognized option, character code 0%o\n",
495 argv[0], (unsigned char) (c));
496 else
497 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
499 return '?';
501 if (temp[1] == ':')
503 if (temp[2] == ':')
505 /* This is an option that accepts an argument optionally. */
506 if (*nextchar != '\0')
508 optarg = nextchar;
509 optind++;
511 else
512 optarg = 0;
513 nextchar = NULL;
515 else
517 /* This is an option that requires an argument. */
518 if (*nextchar != '\0')
520 optarg = nextchar;
521 /* If we end this ARGV-element by taking the rest as an arg, we
522 * must advance to the next element now. */
523 optind++;
525 else if (optind == argc)
527 if (opterr)
528 fprintf (stderr, "%s: option `-%c' requires an argument\n",
529 argv[0], c);
530 c = '?';
532 else
533 /* We already incremented `optind' once; increment it again when
534 * taking next ARGV-elt as argument. */
535 optarg = argv[optind++];
536 nextchar = NULL;
539 return c;
544 getopt (argc, argv, optstring)
545 int argc;
546 char *const *argv;
547 const char *optstring;
549 return _getopt_internal (argc, argv, optstring, (const struct option *) 0,
550 (int *) 0, 0);
553 #ifdef TEST
555 /* Compile with -DTEST to make an executable for use in testing
556 the above definition of `getopt'. */
559 main (argc, argv)
560 int argc;
561 char **argv;
563 int c;
564 int digit_optind = 0;
566 while (1)
568 int this_option_optind = optind ? optind : 1;
570 c = getopt (argc, argv, "abc:d:0123456789");
571 if (c == EOF)
572 break;
574 switch (c)
576 case '0':
577 case '1':
578 case '2':
579 case '3':
580 case '4':
581 case '5':
582 case '6':
583 case '7':
584 case '8':
585 case '9':
586 if (digit_optind != 0 && digit_optind != this_option_optind)
587 printf ("digits occur in two different argv-elements.\n");
588 digit_optind = this_option_optind;
589 printf ("option %c\n", c);
590 break;
592 case 'a':
593 printf ("option a\n");
594 break;
596 case 'b':
597 printf ("option b\n");
598 break;
600 case 'c':
601 printf ("option c with value `%s'\n", optarg);
602 break;
604 case '?':
605 break;
607 default:
608 printf ("?? getopt returned character code 0%o ??\n", c);
612 if (optind < argc)
614 printf ("non-option ARGV-elements: ");
615 while (optind < argc)
616 printf ("%s ", argv[optind++]);
617 printf ("\n");
620 exit (0);
623 #endif /* TEST */
625 /* getopt_long and getopt_long_only entry points for GNU getopt.
626 Copyright (C) 1987, 88, 89, 90, 91, 92, 1993
627 Free Software Foundation, Inc.
629 This program is free software; you can redistribute it and/or
630 modify it under the terms of the GNU Library General Public License
631 as published by the Free Software Foundation; either version 2, or
632 (at your option) any later version.
634 This program is distributed in the hope that it will be useful,
635 but WITHOUT ANY WARRANTY; without even the implied warranty of
636 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
637 GNU Library General Public License for more details.
639 You should have received a copy of the GNU Library General Public License
640 along with this program; if not, write to the Free Software
641 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
643 #ifdef HAVE_CONFIG_H
644 #if defined (emacs) || defined (CONFIG_BROKETS)
646 /* We use <config.h> instead of "config.h" so that a compilation
647 using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
648 (which it would do because it found this file in $srcdir). */
649 #include <config.h>
650 #else
651 #include "config.h"
652 #endif
653 #endif
655 #include "getopt_long.h"
657 #ifndef __STDC__
659 /* This is a separate conditional since some stdc systems
660 reject `defined (const)'. */
661 #ifndef const
662 #define const
663 #endif
664 #endif
666 #include <stdio.h>
668 /* Comment out all this code if we are using the GNU C Library, and are not
669 actually compiling the library itself. This code is part of the GNU C
670 Library, but also included in many other GNU distributions. Compiling
671 and linking in this code is a waste when using the GNU C library
672 (especially if it is a shared library). Rather than having every GNU
673 program understand `configure --with-gnu-libc' and omit the object files,
674 it is simpler to just do this in the source for each such file. */
676 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
678 /* This needs to come after some library #include
679 to get __GNU_LIBRARY__ defined. */
680 #ifdef __GNU_LIBRARY__
681 #include <stdlib.h>
682 #else
683 char *getenv ();
684 #endif
686 #ifndef NULL
687 #define NULL 0
688 #endif
691 getopt_long (argc, argv, options, long_options, opt_index)
692 int argc;
693 char *const *argv;
694 const char *options;
695 const struct option *long_options;
696 int *opt_index;
698 return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
701 /* Like getopt_long, but '-' as well as '--' can indicate a long option.
702 If an option that starts with '-' (not '--') doesn't match a long option,
703 but does match a short option, it is parsed as a short option
704 instead. */
707 getopt_long_only (argc, argv, options, long_options, opt_index)
708 int argc;
709 char *const *argv;
710 const char *options;
711 const struct option *long_options;
712 int *opt_index;
714 return _getopt_internal (argc, argv, options, long_options, opt_index, 1);
717 #endif /* _LIBC or not __GNU_LIBRARY__. */
719 #ifdef TEST
721 #include <stdio.h>
724 main (argc, argv)
725 int argc;
726 char **argv;
728 int c;
729 int digit_optind = 0;
731 while (1)
733 int this_option_optind = optind ? optind : 1;
734 int option_index = 0;
735 static struct option long_options[] = {
736 {"add", 1, 0, 0},
737 {"append", 0, 0, 0},
738 {"delete", 1, 0, 0},
739 {"verbose", 0, 0, 0},
740 {"create", 0, 0, 0},
741 {"file", 1, 0, 0},
742 {0, 0, 0, 0}
746 getopt_long (argc, argv, "abc:d:0123456789", long_options,
747 &option_index);
748 if (c == EOF)
749 break;
751 switch (c)
753 case 0:
754 printf ("option %s", long_options[option_index].name);
755 if (optarg)
756 printf (" with arg %s", optarg);
757 printf ("\n");
758 break;
760 case '0':
761 case '1':
762 case '2':
763 case '3':
764 case '4':
765 case '5':
766 case '6':
767 case '7':
768 case '8':
769 case '9':
770 if (digit_optind != 0 && digit_optind != this_option_optind)
771 printf ("digits occur in two different argv-elements.\n");
772 digit_optind = this_option_optind;
773 printf ("option %c\n", c);
774 break;
776 case 'a':
777 printf ("option a\n");
778 break;
780 case 'b':
781 printf ("option b\n");
782 break;
784 case 'c':
785 printf ("option c with value `%s'\n", optarg);
786 break;
788 case 'd':
789 printf ("option d with value `%s'\n", optarg);
790 break;
792 case '?':
793 break;
795 default:
796 printf ("?? getopt returned character code 0%o ??\n", c);
800 if (optind < argc)
802 printf ("non-option ARGV-elements: ");
803 while (optind < argc)
804 printf ("%s ", argv[optind++]);
805 printf ("\n");
808 exit (0);
811 #endif /* TEST */