Update m4/ax_pthread.m4.
[libpwmd.git] / src / getopt_long.c
blobf33660769273055f66275326106111fa2d5f472e
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 exchange(argv)
148 char **argv;
150 size_t nonopts_size = (last_nonopt - first_nonopt) * sizeof(char *);
151 char **temp = (char **) malloc(nonopts_size);
153 if (temp == NULL)
154 abort();
156 /* Interchange the two blocks of data in ARGV. */
158 my_bcopy((char *) &argv[first_nonopt], (char *) temp, nonopts_size);
159 my_bcopy((char *) &argv[last_nonopt], (char *) &argv[first_nonopt],
160 (optind - last_nonopt) * sizeof(char *));
161 my_bcopy((char *) temp, (char *) &argv[first_nonopt + optind - last_nonopt],
162 nonopts_size);
164 free(temp);
166 /* Update records for the slots the non-options now occupy. */
168 first_nonopt += (optind - last_nonopt);
169 last_nonopt = optind;
172 /* Scan elements of ARGV (whose length is ARGC) for option characters
173 given in OPTSTRING.
175 If an element of ARGV starts with '-', and is not exactly "-" or "--",
176 then it is an option element. The characters of this element
177 (aside from the initial '-') are option characters. If `getopt'
178 is called repeatedly, it returns successively each of the option characters
179 from each of the option elements.
181 If `getopt' finds another option character, it returns that character,
182 updating `optind' and `nextchar' so that the next call to `getopt' can
183 resume the scan with the following option character or ARGV-element.
185 If there are no more option characters, `getopt' returns `EOF'.
186 Then `optind' is the index in ARGV of the first ARGV-element
187 that is not an option. (The ARGV-elements have been permuted
188 so that those that are not options now come last.)
190 OPTSTRING is a string containing the legitimate option characters.
191 If an option character is seen that is not listed in OPTSTRING,
192 return '?' after printing an error message. If you set `opterr' to
193 zero, the error message is suppressed but we still return '?'.
195 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
196 so the following text in the same ARGV-element, or the text of the following
197 ARGV-element, is returned in `optarg'. Two colons mean an option that
198 wants an optional arg; if there is text in the current ARGV-element,
199 it is returned in `optarg', otherwise `optarg' is set to zero.
201 If OPTSTRING starts with `-' or `+', it requests different methods of
202 handling the non-option ARGV-elements.
203 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
205 Long-named options begin with `--' instead of `-'.
206 Their names may be abbreviated as long as the abbreviation is unique
207 or is an exact match for some defined option. If they have an
208 argument, it follows the option name in the same ARGV-element, separated
209 from the option name by a `=', or else the in next ARGV-element.
210 When `getopt' finds a long-named option, it returns 0 if that option's
211 `flag' field is nonzero, the value of the option's `val' field
212 if the `flag' field is zero.
214 The elements of ARGV aren't really const, because we permute them.
215 But we pretend they're const in the prototype to be compatible
216 with other systems.
218 LONGOPTS is a vector of `struct option' terminated by an
219 element containing a name which is zero.
221 LONGIND returns the index in LONGOPT of the long-named option found.
222 It is only valid when a long-named option has been found by the most
223 recent call.
225 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
226 long-named options. */
228 int _getopt_internal(argc, argv, optstring, longopts, longind, long_only)
229 int argc;
230 char *const *argv;
231 const char *optstring;
232 const struct option *longopts;
233 int *longind;
234 int long_only;
236 int option_index;
238 optarg = 0;
240 /* Initialize the internal data when the first call is made. Start
241 * processing options with ARGV-element 1 (since ARGV-element 0 is the
242 * program name); the sequence of previously skipped non-option
243 * ARGV-elements is empty. */
245 if (optind == 0)
247 first_nonopt = last_nonopt = optind = 1;
249 nextchar = NULL;
251 /* Determine how to handle the ordering of options and nonoptions. */
253 if (optstring[0] == '-')
255 ordering = RETURN_IN_ORDER;
256 ++optstring;
258 else if (optstring[0] == '+')
260 ordering = REQUIRE_ORDER;
261 ++optstring;
263 else if (getenv("POSIXLY_CORRECT") != NULL)
264 ordering = REQUIRE_ORDER;
265 else
266 ordering = PERMUTE;
269 if (nextchar == NULL || *nextchar == '\0')
271 if (ordering == PERMUTE)
273 /* If we have just processed some options following some non-options,
274 * exchange them so that the options come first. */
276 if (first_nonopt != last_nonopt && last_nonopt != optind)
277 exchange((char **) argv);
278 else if (last_nonopt != optind)
279 first_nonopt = optind;
281 /* Now skip any additional non-options and extend the range of
282 * non-options previously skipped. */
284 while (optind < argc
285 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
286 #ifdef GETOPT_COMPAT
287 && (longopts == NULL || argv[optind][0] != '+'
288 || argv[optind][1] == '\0')
289 #endif /* GETOPT_COMPAT */
291 optind++;
292 last_nonopt = optind;
295 /* Special ARGV-element `--' means premature end of options. Skip it like
296 * a null option, then exchange with previous non-options as if it were
297 * an option, then skip everything else like a non-option. */
299 if (optind != argc && !strcmp(argv[optind], "--"))
301 optind++;
303 if (first_nonopt != last_nonopt && last_nonopt != optind)
304 exchange((char **) argv);
305 else if (first_nonopt == last_nonopt)
306 first_nonopt = optind;
307 last_nonopt = argc;
309 optind = argc;
312 /* If we have done all the ARGV-elements, stop the scan and back over any
313 * non-options that we skipped and permuted. */
315 if (optind == argc)
317 /* Set the next-arg-index to point at the non-options that we
318 * previously skipped, so the caller will digest them. */
319 if (first_nonopt != last_nonopt)
320 optind = first_nonopt;
321 return EOF;
324 /* If we have come to a non-option and did not permute it, either stop
325 * the scan or describe it to the caller and pass it by. */
327 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
328 #ifdef GETOPT_COMPAT
329 && (longopts == NULL || argv[optind][0] != '+'
330 || argv[optind][1] == '\0')
331 #endif /* GETOPT_COMPAT */
334 if (ordering == REQUIRE_ORDER)
335 return EOF;
336 optarg = argv[optind++];
337 return 1;
340 /* We have found another option-ARGV-element. Start decoding its
341 * characters. */
343 nextchar =
344 (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-'));
347 if (longopts != NULL
348 && ((argv[optind][0] == '-' && (argv[optind][1] == '-' || long_only))
349 #ifdef GETOPT_COMPAT
350 || argv[optind][0] == '+'
351 #endif /* GETOPT_COMPAT */
354 const struct option *p;
355 char *s = nextchar;
356 int exact = 0;
357 int ambig = 0;
358 const struct option *pfound = NULL;
359 int indfound = 0;
361 while (*s && *s != '=')
362 s++;
364 /* Test all options for either exact match or abbreviated matches. */
365 for (p = longopts, option_index = 0; p->name; p++, option_index++)
366 if (!strncmp(p->name, nextchar, (size_t) (s - nextchar)))
368 if (s - nextchar == strlen(p->name))
370 /* Exact match found. */
371 pfound = p;
372 indfound = option_index;
373 exact = 1;
374 break;
376 else if (pfound == NULL)
378 /* First nonexact match found. */
379 pfound = p;
380 indfound = option_index;
382 else
383 /* Second nonexact match found. */
384 ambig = 1;
387 if (ambig && !exact)
389 if (opterr)
390 fprintf(stderr, "%s: option `%s' is ambiguous\n", argv[0],
391 argv[optind]);
392 nextchar += strlen(nextchar);
393 optind++;
394 return '?';
397 if (pfound != NULL)
399 option_index = indfound;
400 optind++;
401 if (*s)
403 /* Don't test has_arg with >, because some C compilers don't allow it
404 * to be used on enums. */
405 if (pfound->has_arg)
406 optarg = s + 1;
407 else
409 if (opterr)
411 if (argv[optind - 1][1] == '-')
412 /* --option */
413 fprintf(stderr, "%s: option `--%s' doesn't allow an argument\n",
414 argv[0], pfound->name);
415 else
416 /* +option or -option */
417 fprintf(stderr, "%s: option `%c%s' doesn't allow an argument\n",
418 argv[0], argv[optind - 1][0], pfound->name);
420 nextchar += strlen(nextchar);
421 return '?';
424 else if (pfound->has_arg == 1)
426 if (optind < argc)
427 optarg = argv[optind++];
428 else
430 if (opterr)
431 fprintf(stderr, "%s: option `%s' requires an argument\n", argv[0],
432 argv[optind - 1]);
433 nextchar += strlen(nextchar);
434 return '?';
437 nextchar += strlen(nextchar);
438 if (longind != NULL)
439 *longind = option_index;
440 if (pfound->flag)
442 *(pfound->flag) = pfound->val;
443 return 0;
445 return pfound->val;
447 /* Can't find it as a long option. If this is not getopt_long_only, or
448 * the option starts with '--' or is not a valid short option, then it's
449 * an error. Otherwise interpret it as a short option. */
450 if (!long_only || argv[optind][1] == '-'
451 #ifdef GETOPT_COMPAT
452 || argv[optind][0] == '+'
453 #endif /* GETOPT_COMPAT */
454 || my_index(optstring, *nextchar) == NULL)
456 if (opterr)
458 if (argv[optind][1] == '-')
459 /* --option */
460 fprintf(stderr, "%s: unrecognized option `--%s'\n", argv[0],
461 nextchar);
462 else
463 /* +option or -option */
464 fprintf(stderr, "%s: unrecognized option `%c%s'\n", argv[0],
465 argv[optind][0], nextchar);
467 nextchar = (char *) "";
468 optind++;
469 return '?';
473 /* Look at and handle the next option-character. */
476 char c = *nextchar++;
477 char *temp = my_index(optstring, c);
479 /* Increment `optind' when we start to process its last character. */
480 if (*nextchar == '\0')
481 ++optind;
483 if (temp == NULL || c == ':')
485 if (opterr)
487 if (c < 040 || c >= 0177)
488 fprintf(stderr, "%s: unrecognized option, character code 0%o\n",
489 argv[0], (unsigned char) (c));
490 else
491 fprintf(stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
493 return '?';
495 if (temp[1] == ':')
497 if (temp[2] == ':')
499 /* This is an option that accepts an argument optionally. */
500 if (*nextchar != '\0')
502 optarg = nextchar;
503 optind++;
505 else
506 optarg = 0;
507 nextchar = NULL;
509 else
511 /* This is an option that requires an argument. */
512 if (*nextchar != '\0')
514 optarg = nextchar;
515 /* If we end this ARGV-element by taking the rest as an arg, we
516 * must advance to the next element now. */
517 optind++;
519 else if (optind == argc)
521 if (opterr)
522 fprintf(stderr, "%s: option `-%c' requires an argument\n",
523 argv[0], c);
524 c = '?';
526 else
527 /* We already incremented `optind' once; increment it again when
528 * taking next ARGV-elt as argument. */
529 optarg = argv[optind++];
530 nextchar = NULL;
533 return c;
537 int getopt(argc, argv, optstring)
538 int argc;
539 char *const *argv;
540 const char *optstring;
542 return _getopt_internal(argc, argv, optstring, (const struct option *) 0,
543 (int *) 0, 0);
546 #ifdef TEST
548 /* Compile with -DTEST to make an executable for use in testing
549 the above definition of `getopt'. */
551 int main(argc, argv)
552 int argc;
553 char **argv;
555 int c;
556 int digit_optind = 0;
558 while (1)
560 int this_option_optind = optind ? optind : 1;
562 c = getopt(argc, argv, "abc:d:0123456789");
563 if (c == EOF)
564 break;
566 switch (c)
568 case '0':
569 case '1':
570 case '2':
571 case '3':
572 case '4':
573 case '5':
574 case '6':
575 case '7':
576 case '8':
577 case '9':
578 if (digit_optind != 0 && digit_optind != this_option_optind)
579 printf("digits occur in two different argv-elements.\n");
580 digit_optind = this_option_optind;
581 printf("option %c\n", c);
582 break;
584 case 'a':
585 printf("option a\n");
586 break;
588 case 'b':
589 printf("option b\n");
590 break;
592 case 'c':
593 printf("option c with value `%s'\n", optarg);
594 break;
596 case '?':
597 break;
599 default:
600 printf("?? getopt returned character code 0%o ??\n", c);
604 if (optind < argc)
606 printf("non-option ARGV-elements: ");
607 while (optind < argc)
608 printf("%s ", argv[optind++]);
609 printf("\n");
612 exit(0);
615 #endif /* TEST */
617 /* getopt_long and getopt_long_only entry points for GNU getopt.
618 Copyright (C) 1987, 88, 89, 90, 91, 92, 1993
619 Free Software Foundation, Inc.
621 This program is free software; you can redistribute it and/or
622 modify it under the terms of the GNU Library General Public License
623 as published by the Free Software Foundation; either version 2, or
624 (at your option) any later version.
626 This program is distributed in the hope that it will be useful,
627 but WITHOUT ANY WARRANTY; without even the implied warranty of
628 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
629 GNU Library General Public License for more details.
631 You should have received a copy of the GNU Library General Public License
632 along with this program; if not, write to the Free Software
633 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
635 #ifdef HAVE_CONFIG_H
636 #if defined (emacs) || defined (CONFIG_BROKETS)
638 /* We use <config.h> instead of "config.h" so that a compilation
639 using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
640 (which it would do because it found this file in $srcdir). */
641 #include <config.h>
642 #else
643 #include "config.h"
644 #endif
645 #endif
647 #include "getopt_long.h"
649 #ifndef __STDC__
651 /* This is a separate conditional since some stdc systems
652 reject `defined (const)'. */
653 #ifndef const
654 #define const
655 #endif
656 #endif
658 #include <stdio.h>
660 /* Comment out all this code if we are using the GNU C Library, and are not
661 actually compiling the library itself. This code is part of the GNU C
662 Library, but also included in many other GNU distributions. Compiling
663 and linking in this code is a waste when using the GNU C library
664 (especially if it is a shared library). Rather than having every GNU
665 program understand `configure --with-gnu-libc' and omit the object files,
666 it is simpler to just do this in the source for each such file. */
668 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
670 /* This needs to come after some library #include
671 to get __GNU_LIBRARY__ defined. */
672 #ifdef __GNU_LIBRARY__
673 #include <stdlib.h>
674 #else
675 char *getenv();
676 #endif
678 #ifndef NULL
679 #define NULL 0
680 #endif
682 int getopt_long(argc, argv, options, long_options, opt_index)
683 int argc;
684 char *const *argv;
685 const char *options;
686 const struct option *long_options;
687 int *opt_index;
689 return _getopt_internal(argc, argv, options, long_options, opt_index, 0);
692 /* Like getopt_long, but '-' as well as '--' can indicate a long option.
693 If an option that starts with '-' (not '--') doesn't match a long option,
694 but does match a short option, it is parsed as a short option
695 instead. */
697 int getopt_long_only(argc, argv, options, long_options, opt_index)
698 int argc;
699 char *const *argv;
700 const char *options;
701 const struct option *long_options;
702 int *opt_index;
704 return _getopt_internal(argc, argv, options, long_options, opt_index, 1);
707 #endif /* _LIBC or not __GNU_LIBRARY__. */
709 #ifdef TEST
711 #include <stdio.h>
713 int main(argc, argv)
714 int argc;
715 char **argv;
717 int c;
718 int digit_optind = 0;
720 while (1)
722 int this_option_optind = optind ? optind : 1;
723 int option_index = 0;
724 static struct option long_options[] = {
725 {"add", 1, 0, 0},
726 {"append", 0, 0, 0},
727 {"delete", 1, 0, 0},
728 {"verbose", 0, 0, 0},
729 {"create", 0, 0, 0},
730 {"file", 1, 0, 0},
731 {0, 0, 0, 0}
735 getopt_long(argc, argv, "abc:d:0123456789", long_options,
736 &option_index);
737 if (c == EOF)
738 break;
740 switch (c)
742 case 0:
743 printf("option %s", long_options[option_index].name);
744 if (optarg)
745 printf(" with arg %s", optarg);
746 printf("\n");
747 break;
749 case '0':
750 case '1':
751 case '2':
752 case '3':
753 case '4':
754 case '5':
755 case '6':
756 case '7':
757 case '8':
758 case '9':
759 if (digit_optind != 0 && digit_optind != this_option_optind)
760 printf("digits occur in two different argv-elements.\n");
761 digit_optind = this_option_optind;
762 printf("option %c\n", c);
763 break;
765 case 'a':
766 printf("option a\n");
767 break;
769 case 'b':
770 printf("option b\n");
771 break;
773 case 'c':
774 printf("option c with value `%s'\n", optarg);
775 break;
777 case 'd':
778 printf("option d with value `%s'\n", optarg);
779 break;
781 case '?':
782 break;
784 default:
785 printf("?? getopt returned character code 0%o ??\n", c);
789 if (optind < argc)
791 printf("non-option ARGV-elements: ");
792 while (optind < argc)
793 printf("%s ", argv[optind++]);
794 printf("\n");
797 exit(0);
800 #endif /* TEST */