include: Avoid some type redefinitions.
[wine.git] / libs / port / getopt.c
blob7c97192f4ec3d7fc4cc52642f08c0361558a58a8
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 drepper@gnu.org
4 before changing it!
5 Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002
6 Free Software Foundation, Inc.
7 This file is part of the GNU C Library.
9 The GNU C Library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
14 The GNU C Library 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 GNU
17 Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public
20 License along with the GNU C Library; if not, write to the Free
21 Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
22 MA 02110-1301, USA */
24 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
25 Ditto for AIX 3.2 and <stdlib.h>. */
26 #ifndef _NO_PROTO
27 # define _NO_PROTO
28 #endif
30 #define HAVE_CONFIG_H /* needed for Wine */
32 #ifdef HAVE_CONFIG_H
33 # include <config.h>
34 #endif
36 #ifdef HAVE_GETOPT_LONG_ONLY
37 #define ELIDE_CODE
38 #endif
40 #if !defined __STDC__ || !__STDC__
41 /* This is a separate conditional since some stdc systems
42 reject `defined (const)'. */
43 # ifndef const
44 # define const
45 # endif
46 #endif
48 #include <stdio.h>
50 /* Comment out all this code if we are using the GNU C Library, and are not
51 actually compiling the library itself. This code is part of the GNU C
52 Library, but also included in many other GNU distributions. Compiling
53 and linking in this code is a waste when using the GNU C library
54 (especially if it is a shared library). Rather than having every GNU
55 program understand `configure --with-gnu-libc' and omit the object files,
56 it is simpler to just do this in the source for each such file. */
58 #define GETOPT_INTERFACE_VERSION 2
59 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
60 # include <gnu-versions.h>
61 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
62 # define ELIDE_CODE
63 # endif
64 #endif
66 #ifndef ELIDE_CODE
69 /* This needs to come after some library #include
70 to get __GNU_LIBRARY__ defined. */
71 #ifdef __GNU_LIBRARY__
72 /* Don't include stdlib.h for non-GNU C libraries because some of them
73 contain conflicting prototypes for getopt. */
74 # include <stdlib.h>
75 # include <unistd.h>
76 #elif defined _MSC_VER
77 # include <stdlib.h>
78 #endif /* GNU C library. */
80 #ifdef VMS
81 # include <unixlib.h>
82 # ifdef HAVE_STRING_H
83 # include <string.h>
84 # endif
85 #endif
87 #ifndef _
88 /* This is for other GNU distributions with internationalized messages. */
89 # if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC
90 # include <libintl.h>
91 # ifndef _
92 # define _(msgid) gettext (msgid)
93 # endif
94 # else
95 # define _(msgid) (msgid)
96 # endif
97 # if defined _LIBC && defined USE_IN_LIBIO
98 # include <wchar.h>
99 # endif
100 #endif
102 #ifndef attribute_hidden
103 # define attribute_hidden
104 #endif
106 /* This version of `getopt' appears to the caller like standard Unix `getopt'
107 but it behaves differently for the user, since it allows the user
108 to intersperse the options with the other arguments.
110 As `getopt' works, it permutes the elements of ARGV so that,
111 when it is done, all the options precede everything else. Thus
112 all application programs are extended to handle flexible argument order.
114 Setting the environment variable POSIXLY_CORRECT disables permutation.
115 Then the behavior is completely standard.
117 GNU application programs can use a third alternative mode in which
118 they can distinguish the relative order of options and other arguments. */
120 #include "getopt.h"
122 /* For communication from `getopt' to the caller.
123 When `getopt' finds an option that takes an argument,
124 the argument value is returned here.
125 Also, when `ordering' is RETURN_IN_ORDER,
126 each non-option ARGV-element is returned here. */
128 char *optarg;
130 /* Index in ARGV of the next element to be scanned.
131 This is used for communication to and from the caller
132 and for communication between successive calls to `getopt'.
134 On entry to `getopt', zero means this is the first call; initialize.
136 When `getopt' returns -1, this is the index of the first of the
137 non-option elements that the caller should itself scan.
139 Otherwise, `optind' communicates from one call to the next
140 how much of ARGV has been scanned so far. */
142 /* 1003.2 says this must be 1 before any call. */
143 int optind = 1;
145 /* Formerly, initialization of getopt depended on optind==0, which
146 causes problems with re-calling getopt as programs generally don't
147 know that. */
149 int __getopt_initialized attribute_hidden;
151 /* The next char to be scanned in the option-element
152 in which the last option character we returned was found.
153 This allows us to pick up the scan where we left off.
155 If this is zero, or a null string, it means resume the scan
156 by advancing to the next ARGV-element. */
158 static char *nextchar;
160 /* Callers store zero here to inhibit the error message
161 for unrecognized options. */
163 int opterr = 1;
165 /* Set to an option character which was unrecognized.
166 This must be initialized on some systems to avoid linking in the
167 system's own getopt implementation. */
169 int optopt = '?';
171 /* Describe how to deal with options that follow non-option ARGV-elements.
173 If the caller did not specify anything,
174 the default is REQUIRE_ORDER if the environment variable
175 POSIXLY_CORRECT is defined, PERMUTE otherwise.
177 REQUIRE_ORDER means don't recognize them as options;
178 stop option processing when the first non-option is seen.
179 This is what Unix does.
180 This mode of operation is selected by either setting the environment
181 variable POSIXLY_CORRECT, or using `+' as the first character
182 of the list of option characters.
184 PERMUTE is the default. We permute the contents of ARGV as we scan,
185 so that eventually all the non-options are at the end. This allows options
186 to be given in any order, even with programs that were not written to
187 expect this.
189 RETURN_IN_ORDER is an option available to programs that were written
190 to expect options and other ARGV-elements in any order and that care about
191 the ordering of the two. We describe each non-option ARGV-element
192 as if it were the argument of an option with character code 1.
193 Using `-' as the first character of the list of option characters
194 selects this mode of operation.
196 The special argument `--' forces an end of option-scanning regardless
197 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
198 `--' can cause `getopt' to return -1 with `optind' != ARGC. */
200 static enum
202 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
203 } ordering;
205 /* Value of POSIXLY_CORRECT environment variable. */
206 static char *posixly_correct;
208 #include <string.h>
209 #define my_index strchr
211 /* If using GCC, we can safely declare strlen this way.
212 If not using GCC, it is ok not to declare it. */
213 #ifdef __GNUC__
214 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
215 That was relevant to code that was here before. */
216 # if (!defined __STDC__ || !__STDC__) && !defined strlen
217 /* gcc with -traditional declares the built-in strlen to return int,
218 and has done so at least since version 2.4.5. -- rms. */
219 extern int strlen (const char *);
220 # endif /* not __STDC__ */
221 #endif /* __GNUC__ */
223 /* Handle permutation of arguments. */
225 /* Describe the part of ARGV that contains non-options that have
226 been skipped. `first_nonopt' is the index in ARGV of the first of them;
227 `last_nonopt' is the index after the last of them. */
229 static int first_nonopt;
230 static int last_nonopt;
232 #ifdef _LIBC
233 /* Stored original parameters.
234 XXX This is no good solution. We should rather copy the args so
235 that we can compare them later. But we must not use malloc(3). */
236 extern int __libc_argc;
237 extern char **__libc_argv;
239 /* Bash 2.0 gives us an environment variable containing flags
240 indicating ARGV elements that should not be considered arguments. */
242 # ifdef USE_NONOPTION_FLAGS
243 /* Defined in getopt_init.c */
244 extern char *__getopt_nonoption_flags;
246 static int nonoption_flags_max_len;
247 static int nonoption_flags_len;
248 # endif
250 # ifdef USE_NONOPTION_FLAGS
251 # define SWAP_FLAGS(ch1, ch2) \
252 if (nonoption_flags_len > 0) \
254 char __tmp = __getopt_nonoption_flags[ch1]; \
255 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
256 __getopt_nonoption_flags[ch2] = __tmp; \
258 # else
259 # define SWAP_FLAGS(ch1, ch2)
260 # endif
261 #else /* !_LIBC */
262 # define SWAP_FLAGS(ch1, ch2)
263 #endif /* _LIBC */
265 /* Exchange two adjacent subsequences of ARGV.
266 One subsequence is elements [first_nonopt,last_nonopt)
267 which contains all the non-options that have been skipped so far.
268 The other is elements [last_nonopt,optind), which contains all
269 the options processed since those non-options were skipped.
271 `first_nonopt' and `last_nonopt' are relocated so that they describe
272 the new indices of the non-options in ARGV after they are moved. */
274 #if defined __STDC__ && __STDC__
275 static void exchange (char **);
276 #endif
278 static void
279 exchange (argv)
280 char **argv;
282 int bottom = first_nonopt;
283 int middle = last_nonopt;
284 int top = optind;
285 char *tem;
287 /* Exchange the shorter segment with the far end of the longer segment.
288 That puts the shorter segment into the right place.
289 It leaves the longer segment in the right place overall,
290 but it consists of two parts that need to be swapped next. */
292 #if defined _LIBC && defined USE_NONOPTION_FLAGS
293 /* First make sure the handling of the `__getopt_nonoption_flags'
294 string can work normally. Our top argument must be in the range
295 of the string. */
296 if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
298 /* We must extend the array. The user plays games with us and
299 presents new arguments. */
300 char *new_str = malloc (top + 1);
301 if (new_str == NULL)
302 nonoption_flags_len = nonoption_flags_max_len = 0;
303 else
305 memset (__mempcpy (new_str, __getopt_nonoption_flags,
306 nonoption_flags_max_len),
307 '\0', top + 1 - nonoption_flags_max_len);
308 nonoption_flags_max_len = top + 1;
309 __getopt_nonoption_flags = new_str;
312 #endif
314 while (top > middle && middle > bottom)
316 if (top - middle > middle - bottom)
318 /* Bottom segment is the short one. */
319 int len = middle - bottom;
320 register int i;
322 /* Swap it with the top part of the top segment. */
323 for (i = 0; i < len; i++)
325 tem = argv[bottom + i];
326 argv[bottom + i] = argv[top - (middle - bottom) + i];
327 argv[top - (middle - bottom) + i] = tem;
328 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
330 /* Exclude the moved bottom segment from further swapping. */
331 top -= len;
333 else
335 /* Top segment is the short one. */
336 int len = top - middle;
337 register int i;
339 /* Swap it with the bottom part of the bottom segment. */
340 for (i = 0; i < len; i++)
342 tem = argv[bottom + i];
343 argv[bottom + i] = argv[middle + i];
344 argv[middle + i] = tem;
345 SWAP_FLAGS (bottom + i, middle + i);
347 /* Exclude the moved top segment from further swapping. */
348 bottom += len;
352 /* Update records for the slots the non-options now occupy. */
354 first_nonopt += (optind - last_nonopt);
355 last_nonopt = optind;
358 /* Initialize the internal data when the first call is made. */
360 #if defined __STDC__ && __STDC__
361 static const char *_getopt_initialize (int, char *const *, const char *);
362 #endif
363 static const char *
364 _getopt_initialize (argc, argv, optstring)
365 int argc;
366 char *const *argv;
367 const char *optstring;
369 /* Start processing options with ARGV-element 1 (since ARGV-element 0
370 is the program name); the sequence of previously skipped
371 non-option ARGV-elements is empty. */
373 first_nonopt = last_nonopt = optind;
375 nextchar = NULL;
377 posixly_correct = getenv ("POSIXLY_CORRECT");
379 /* Determine how to handle the ordering of options and nonoptions. */
381 if (optstring[0] == '-')
383 ordering = RETURN_IN_ORDER;
384 ++optstring;
386 else if (optstring[0] == '+')
388 ordering = REQUIRE_ORDER;
389 ++optstring;
391 else if (posixly_correct != NULL)
392 ordering = REQUIRE_ORDER;
393 else
394 ordering = PERMUTE;
396 #if defined _LIBC && defined USE_NONOPTION_FLAGS
397 if (posixly_correct == NULL
398 && argc == __libc_argc && argv == __libc_argv)
400 if (nonoption_flags_max_len == 0)
402 if (__getopt_nonoption_flags == NULL
403 || __getopt_nonoption_flags[0] == '\0')
404 nonoption_flags_max_len = -1;
405 else
407 const char *orig_str = __getopt_nonoption_flags;
408 int len = nonoption_flags_max_len = strlen (orig_str);
409 if (nonoption_flags_max_len < argc)
410 nonoption_flags_max_len = argc;
411 __getopt_nonoption_flags = malloc (nonoption_flags_max_len);
412 if (__getopt_nonoption_flags == NULL)
413 nonoption_flags_max_len = -1;
414 else
415 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
416 '\0', nonoption_flags_max_len - len);
419 nonoption_flags_len = nonoption_flags_max_len;
421 else
422 nonoption_flags_len = 0;
423 #endif
425 return optstring;
428 /* Scan elements of ARGV (whose length is ARGC) for option characters
429 given in OPTSTRING.
431 If an element of ARGV starts with '-', and is not exactly "-" or "--",
432 then it is an option element. The characters of this element
433 (aside from the initial '-') are option characters. If `getopt'
434 is called repeatedly, it returns successively each of the option characters
435 from each of the option elements.
437 If `getopt' finds another option character, it returns that character,
438 updating `optind' and `nextchar' so that the next call to `getopt' can
439 resume the scan with the following option character or ARGV-element.
441 If there are no more option characters, `getopt' returns -1.
442 Then `optind' is the index in ARGV of the first ARGV-element
443 that is not an option. (The ARGV-elements have been permuted
444 so that those that are not options now come last.)
446 OPTSTRING is a string containing the legitimate option characters.
447 If an option character is seen that is not listed in OPTSTRING,
448 return '?' after printing an error message. If you set `opterr' to
449 zero, the error message is suppressed but we still return '?'.
451 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
452 so the following text in the same ARGV-element, or the text of the following
453 ARGV-element, is returned in `optarg'. Two colons mean an option that
454 wants an optional arg; if there is text in the current ARGV-element,
455 it is returned in `optarg', otherwise `optarg' is set to zero.
457 If OPTSTRING starts with `-' or `+', it requests different methods of
458 handling the non-option ARGV-elements.
459 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
461 Long-named options begin with `--' instead of `-'.
462 Their names may be abbreviated as long as the abbreviation is unique
463 or is an exact match for some defined option. If they have an
464 argument, it follows the option name in the same ARGV-element, separated
465 from the option name by a `=', or else the in next ARGV-element.
466 When `getopt' finds a long-named option, it returns 0 if that option's
467 `flag' field is nonzero, the value of the option's `val' field
468 if the `flag' field is zero.
470 The elements of ARGV aren't really const, because we permute them.
471 But we pretend they're const in the prototype to be compatible
472 with other systems.
474 LONGOPTS is a vector of `struct option' terminated by an
475 element containing a name which is zero.
477 LONGIND returns the index in LONGOPT of the long-named option found.
478 It is only valid when a long-named option has been found by the most
479 recent call.
481 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
482 long-named options. */
485 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
486 int argc;
487 char *const *argv;
488 const char *optstring;
489 const struct option *longopts;
490 int *longind;
491 int long_only;
493 int print_errors = opterr;
494 if (optstring[0] == ':')
495 print_errors = 0;
497 if (argc < 1)
498 return -1;
500 optarg = NULL;
502 if (optind == 0 || !__getopt_initialized)
504 if (optind == 0)
505 optind = 1; /* Don't scan ARGV[0], the program name. */
506 optstring = _getopt_initialize (argc, argv, optstring);
507 __getopt_initialized = 1;
510 /* Test whether ARGV[optind] points to a non-option argument.
511 Either it does not have option syntax, or there is an environment flag
512 from the shell indicating it is not an option. The later information
513 is only used when the used in the GNU libc. */
514 #if defined _LIBC && defined USE_NONOPTION_FLAGS
515 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
516 || (optind < nonoption_flags_len \
517 && __getopt_nonoption_flags[optind] == '1'))
518 #else
519 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
520 #endif
522 if (nextchar == NULL || *nextchar == '\0')
524 /* Advance to the next ARGV-element. */
526 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
527 moved back by the user (who may also have changed the arguments). */
528 if (last_nonopt > optind)
529 last_nonopt = optind;
530 if (first_nonopt > optind)
531 first_nonopt = optind;
533 if (ordering == PERMUTE)
535 /* If we have just processed some options following some non-options,
536 exchange them so that the options come first. */
538 if (first_nonopt != last_nonopt && last_nonopt != optind)
539 exchange ((char **) argv);
540 else if (last_nonopt != optind)
541 first_nonopt = optind;
543 /* Skip any additional non-options
544 and extend the range of non-options previously skipped. */
546 while (optind < argc && NONOPTION_P)
547 optind++;
548 last_nonopt = optind;
551 /* The special ARGV-element `--' means premature end of options.
552 Skip it like a null option,
553 then exchange with previous non-options as if it were an option,
554 then skip everything else like a non-option. */
556 if (optind != argc && !strcmp (argv[optind], "--"))
558 optind++;
560 if (first_nonopt != last_nonopt && last_nonopt != optind)
561 exchange ((char **) argv);
562 else if (first_nonopt == last_nonopt)
563 first_nonopt = optind;
564 last_nonopt = argc;
566 optind = argc;
569 /* If we have done all the ARGV-elements, stop the scan
570 and back over any non-options that we skipped and permuted. */
572 if (optind == argc)
574 /* Set the next-arg-index to point at the non-options
575 that we previously skipped, so the caller will digest them. */
576 if (first_nonopt != last_nonopt)
577 optind = first_nonopt;
578 return -1;
581 /* If we have come to a non-option and did not permute it,
582 either stop the scan or describe it to the caller and pass it by. */
584 if (NONOPTION_P)
586 if (ordering == REQUIRE_ORDER)
587 return -1;
588 optarg = argv[optind++];
589 return 1;
592 /* We have found another option-ARGV-element.
593 Skip the initial punctuation. */
595 nextchar = (argv[optind] + 1
596 + (longopts != NULL && argv[optind][1] == '-'));
599 /* Decode the current option-ARGV-element. */
601 /* Check whether the ARGV-element is a long option.
603 If long_only and the ARGV-element has the form "-f", where f is
604 a valid short option, don't consider it an abbreviated form of
605 a long option that starts with f. Otherwise there would be no
606 way to give the -f short option.
608 On the other hand, if there's a long option "fubar" and
609 the ARGV-element is "-fu", do consider that an abbreviation of
610 the long option, just like "--fu", and not "-f" with arg "u".
612 This distinction seems to be the most useful approach. */
614 if (longopts != NULL
615 && (argv[optind][1] == '-'
616 || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
618 char *nameend;
619 const struct option *p;
620 const struct option *pfound = NULL;
621 int exact = 0;
622 int ambig = 0;
623 int indfound = -1;
624 int option_index;
626 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
627 /* Do nothing. */ ;
629 /* Test all long options for either exact match
630 or abbreviated matches. */
631 for (p = longopts, option_index = 0; p->name; p++, option_index++)
632 if (!strncmp (p->name, nextchar, nameend - nextchar))
634 if ((unsigned int) (nameend - nextchar)
635 == (unsigned int) strlen (p->name))
637 /* Exact match found. */
638 pfound = p;
639 indfound = option_index;
640 exact = 1;
641 break;
643 else if (pfound == NULL)
645 /* First nonexact match found. */
646 pfound = p;
647 indfound = option_index;
649 else if (long_only
650 || pfound->has_arg != p->has_arg
651 || pfound->flag != p->flag
652 || pfound->val != p->val)
653 /* Second or later nonexact match found. */
654 ambig = 1;
657 if (ambig && !exact)
659 if (print_errors)
661 #if defined _LIBC && defined USE_IN_LIBIO
662 char *buf;
664 if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
665 argv[0], argv[optind]) >= 0)
668 if (_IO_fwide (stderr, 0) > 0)
669 __fwprintf (stderr, L"%s", buf);
670 else
671 fputs (buf, stderr);
673 free (buf);
675 #else
676 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
677 argv[0], argv[optind]);
678 #endif
680 nextchar += strlen (nextchar);
681 optind++;
682 optopt = 0;
683 return '?';
686 if (pfound != NULL)
688 option_index = indfound;
689 optind++;
690 if (*nameend)
692 /* Don't test has_arg with >, because some C compilers don't
693 allow it to be used on enums. */
694 if (pfound->has_arg)
695 optarg = nameend + 1;
696 else
698 if (print_errors)
700 #if defined _LIBC && defined USE_IN_LIBIO
701 char *buf;
702 int n;
703 #endif
705 if (argv[optind - 1][1] == '-')
707 /* --option */
708 #if defined _LIBC && defined USE_IN_LIBIO
709 n = __asprintf (&buf, _("\
710 %s: option `--%s' doesn't allow an argument\n"),
711 argv[0], pfound->name);
712 #else
713 fprintf (stderr, _("\
714 %s: option `--%s' doesn't allow an argument\n"),
715 argv[0], pfound->name);
716 #endif
718 else
720 /* +option or -option */
721 #if defined _LIBC && defined USE_IN_LIBIO
722 n = __asprintf (&buf, _("\
723 %s: option `%c%s' doesn't allow an argument\n"),
724 argv[0], argv[optind - 1][0],
725 pfound->name);
726 #else
727 fprintf (stderr, _("\
728 %s: option `%c%s' doesn't allow an argument\n"),
729 argv[0], argv[optind - 1][0], pfound->name);
730 #endif
733 #if defined _LIBC && defined USE_IN_LIBIO
734 if (n >= 0)
736 if (_IO_fwide (stderr, 0) > 0)
737 __fwprintf (stderr, L"%s", buf);
738 else
739 fputs (buf, stderr);
741 free (buf);
743 #endif
746 nextchar += strlen (nextchar);
748 optopt = pfound->val;
749 return '?';
752 else if (pfound->has_arg == 1)
754 if (optind < argc)
755 optarg = argv[optind++];
756 else
758 if (print_errors)
760 #if defined _LIBC && defined USE_IN_LIBIO
761 char *buf;
763 if (__asprintf (&buf, _("\
764 %s: option `%s' requires an argument\n"),
765 argv[0], argv[optind - 1]) >= 0)
767 if (_IO_fwide (stderr, 0) > 0)
768 __fwprintf (stderr, L"%s", buf);
769 else
770 fputs (buf, stderr);
772 free (buf);
774 #else
775 fprintf (stderr,
776 _("%s: option `%s' requires an argument\n"),
777 argv[0], argv[optind - 1]);
778 #endif
780 nextchar += strlen (nextchar);
781 optopt = pfound->val;
782 return optstring[0] == ':' ? ':' : '?';
785 nextchar += strlen (nextchar);
786 if (longind != NULL)
787 *longind = option_index;
788 if (pfound->flag)
790 *(pfound->flag) = pfound->val;
791 return 0;
793 return pfound->val;
796 /* Can't find it as a long option. If this is not getopt_long_only,
797 or the option starts with '--' or is not a valid short
798 option, then it's an error.
799 Otherwise interpret it as a short option. */
800 if (!long_only || argv[optind][1] == '-'
801 || my_index (optstring, *nextchar) == NULL)
803 if (print_errors)
805 #if defined _LIBC && defined USE_IN_LIBIO
806 char *buf;
807 int n;
808 #endif
810 if (argv[optind][1] == '-')
812 /* --option */
813 #if defined _LIBC && defined USE_IN_LIBIO
814 n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
815 argv[0], nextchar);
816 #else
817 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
818 argv[0], nextchar);
819 #endif
821 else
823 /* +option or -option */
824 #if defined _LIBC && defined USE_IN_LIBIO
825 n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
826 argv[0], argv[optind][0], nextchar);
827 #else
828 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
829 argv[0], argv[optind][0], nextchar);
830 #endif
833 #if defined _LIBC && defined USE_IN_LIBIO
834 if (n >= 0)
836 if (_IO_fwide (stderr, 0) > 0)
837 __fwprintf (stderr, L"%s", buf);
838 else
839 fputs (buf, stderr);
841 free (buf);
843 #endif
845 nextchar = (char *) "";
846 optind++;
847 optopt = 0;
848 return '?';
852 /* Look at and handle the next short option-character. */
855 char c = *nextchar++;
856 char *temp = my_index (optstring, c);
858 /* Increment `optind' when we start to process its last character. */
859 if (*nextchar == '\0')
860 ++optind;
862 if (temp == NULL || c == ':')
864 if (print_errors)
866 #if defined _LIBC && defined USE_IN_LIBIO
867 char *buf;
868 int n;
869 #endif
871 if (posixly_correct)
873 /* 1003.2 specifies the format of this message. */
874 #if defined _LIBC && defined USE_IN_LIBIO
875 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
876 argv[0], c);
877 #else
878 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
879 #endif
881 else
883 #if defined _LIBC && defined USE_IN_LIBIO
884 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
885 argv[0], c);
886 #else
887 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
888 #endif
891 #if defined _LIBC && defined USE_IN_LIBIO
892 if (n >= 0)
894 if (_IO_fwide (stderr, 0) > 0)
895 __fwprintf (stderr, L"%s", buf);
896 else
897 fputs (buf, stderr);
899 free (buf);
901 #endif
903 optopt = c;
904 return '?';
906 /* Convenience. Treat POSIX -W foo same as long option --foo */
907 if (temp[0] == 'W' && temp[1] == ';')
909 char *nameend;
910 const struct option *p;
911 const struct option *pfound = NULL;
912 int exact = 0;
913 int ambig = 0;
914 int indfound = 0;
915 int option_index;
917 /* This is an option that requires an argument. */
918 if (*nextchar != '\0')
920 optarg = nextchar;
921 /* If we end this ARGV-element by taking the rest as an arg,
922 we must advance to the next element now. */
923 optind++;
925 else if (optind == argc)
927 if (print_errors)
929 /* 1003.2 specifies the format of this message. */
930 #if defined _LIBC && defined USE_IN_LIBIO
931 char *buf;
933 if (__asprintf (&buf,
934 _("%s: option requires an argument -- %c\n"),
935 argv[0], c) >= 0)
937 if (_IO_fwide (stderr, 0) > 0)
938 __fwprintf (stderr, L"%s", buf);
939 else
940 fputs (buf, stderr);
942 free (buf);
944 #else
945 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
946 argv[0], c);
947 #endif
949 optopt = c;
950 if (optstring[0] == ':')
951 c = ':';
952 else
953 c = '?';
954 return c;
956 else
957 /* We already incremented `optind' once;
958 increment it again when taking next ARGV-elt as argument. */
959 optarg = argv[optind++];
961 /* optarg is now the argument, see if it's in the
962 table of longopts. */
964 for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
965 /* Do nothing. */ ;
967 /* Test all long options for either exact match
968 or abbreviated matches. */
969 for (p = longopts, option_index = 0; p->name; p++, option_index++)
970 if (!strncmp (p->name, nextchar, nameend - nextchar))
972 if ((unsigned int) (nameend - nextchar) == strlen (p->name))
974 /* Exact match found. */
975 pfound = p;
976 indfound = option_index;
977 exact = 1;
978 break;
980 else if (pfound == NULL)
982 /* First nonexact match found. */
983 pfound = p;
984 indfound = option_index;
986 else
987 /* Second or later nonexact match found. */
988 ambig = 1;
990 if (ambig && !exact)
992 if (print_errors)
994 #if defined _LIBC && defined USE_IN_LIBIO
995 char *buf;
997 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
998 argv[0], argv[optind]) >= 0)
1000 if (_IO_fwide (stderr, 0) > 0)
1001 __fwprintf (stderr, L"%s", buf);
1002 else
1003 fputs (buf, stderr);
1005 free (buf);
1007 #else
1008 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
1009 argv[0], argv[optind]);
1010 #endif
1012 nextchar += strlen (nextchar);
1013 optind++;
1014 return '?';
1016 if (pfound != NULL)
1018 option_index = indfound;
1019 if (*nameend)
1021 /* Don't test has_arg with >, because some C compilers don't
1022 allow it to be used on enums. */
1023 if (pfound->has_arg)
1024 optarg = nameend + 1;
1025 else
1027 if (print_errors)
1029 #if defined _LIBC && defined USE_IN_LIBIO
1030 char *buf;
1032 if (__asprintf (&buf, _("\
1033 %s: option `-W %s' doesn't allow an argument\n"),
1034 argv[0], pfound->name) >= 0)
1036 if (_IO_fwide (stderr, 0) > 0)
1037 __fwprintf (stderr, L"%s", buf);
1038 else
1039 fputs (buf, stderr);
1041 free (buf);
1043 #else
1044 fprintf (stderr, _("\
1045 %s: option `-W %s' doesn't allow an argument\n"),
1046 argv[0], pfound->name);
1047 #endif
1050 nextchar += strlen (nextchar);
1051 return '?';
1054 else if (pfound->has_arg == 1)
1056 if (optind < argc)
1057 optarg = argv[optind++];
1058 else
1060 if (print_errors)
1062 #if defined _LIBC && defined USE_IN_LIBIO
1063 char *buf;
1065 if (__asprintf (&buf, _("\
1066 %s: option `%s' requires an argument\n"),
1067 argv[0], argv[optind - 1]) >= 0)
1069 if (_IO_fwide (stderr, 0) > 0)
1070 __fwprintf (stderr, L"%s", buf);
1071 else
1072 fputs (buf, stderr);
1074 free (buf);
1076 #else
1077 fprintf (stderr,
1078 _("%s: option `%s' requires an argument\n"),
1079 argv[0], argv[optind - 1]);
1080 #endif
1082 nextchar += strlen (nextchar);
1083 return optstring[0] == ':' ? ':' : '?';
1086 nextchar += strlen (nextchar);
1087 if (longind != NULL)
1088 *longind = option_index;
1089 if (pfound->flag)
1091 *(pfound->flag) = pfound->val;
1092 return 0;
1094 return pfound->val;
1096 nextchar = NULL;
1097 return 'W'; /* Let the application handle it. */
1099 if (temp[1] == ':')
1101 if (temp[2] == ':')
1103 /* This is an option that accepts an argument optionally. */
1104 if (*nextchar != '\0')
1106 optarg = nextchar;
1107 optind++;
1109 else
1110 optarg = NULL;
1111 nextchar = NULL;
1113 else
1115 /* This is an option that requires an argument. */
1116 if (*nextchar != '\0')
1118 optarg = nextchar;
1119 /* If we end this ARGV-element by taking the rest as an arg,
1120 we must advance to the next element now. */
1121 optind++;
1123 else if (optind == argc)
1125 if (print_errors)
1127 /* 1003.2 specifies the format of this message. */
1128 #if defined _LIBC && defined USE_IN_LIBIO
1129 char *buf;
1131 if (__asprintf (&buf, _("\
1132 %s: option requires an argument -- %c\n"),
1133 argv[0], c) >= 0)
1135 if (_IO_fwide (stderr, 0) > 0)
1136 __fwprintf (stderr, L"%s", buf);
1137 else
1138 fputs (buf, stderr);
1140 free (buf);
1142 #else
1143 fprintf (stderr,
1144 _("%s: option requires an argument -- %c\n"),
1145 argv[0], c);
1146 #endif
1148 optopt = c;
1149 if (optstring[0] == ':')
1150 c = ':';
1151 else
1152 c = '?';
1154 else
1155 /* We already incremented `optind' once;
1156 increment it again when taking next ARGV-elt as argument. */
1157 optarg = argv[optind++];
1158 nextchar = NULL;
1161 return c;
1166 getopt (int argc, char * const *argv, const char *optstring)
1168 return _getopt_internal (argc, argv, optstring,
1169 NULL,
1170 NULL,
1174 #endif /* Not ELIDE_CODE. */
1176 #ifdef TEST
1178 /* Compile with -DTEST to make an executable for use in testing
1179 the above definition of `getopt'. */
1182 main (argc, argv)
1183 int argc;
1184 char **argv;
1186 int c;
1187 int digit_optind = 0;
1189 while (1)
1191 int this_option_optind = optind ? optind : 1;
1193 c = getopt (argc, argv, "abc:d:0123456789");
1194 if (c == -1)
1195 break;
1197 switch (c)
1199 case '0':
1200 case '1':
1201 case '2':
1202 case '3':
1203 case '4':
1204 case '5':
1205 case '6':
1206 case '7':
1207 case '8':
1208 case '9':
1209 if (digit_optind != 0 && digit_optind != this_option_optind)
1210 printf ("digits occur in two different argv-elements.\n");
1211 digit_optind = this_option_optind;
1212 printf ("option %c\n", c);
1213 break;
1215 case 'a':
1216 printf ("option a\n");
1217 break;
1219 case 'b':
1220 printf ("option b\n");
1221 break;
1223 case 'c':
1224 printf ("option c with value `%s'\n", optarg);
1225 break;
1227 case '?':
1228 break;
1230 default:
1231 printf ("?? getopt returned character code 0%o ??\n", c);
1235 if (optind < argc)
1237 printf ("non-option ARGV-elements: ");
1238 while (optind < argc)
1239 printf ("%s ", argv[optind++]);
1240 printf ("\n");
1243 exit (0);
1246 #endif /* TEST */