tuklib: Update tuklib_attr_noreturn for C11/C17 and C23.
[xz.git] / lib / getopt.c
blobf8fc003d391fb1df46b0ea37aea679511882db51
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,2003,2004,2006
6 Free Software Foundation, Inc.
7 This file is part of the GNU C Library.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1, or (at your option)
12 any later version.
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 Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public License along
20 with this program; if not, write to the Free Software Foundation,
21 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
23 #ifndef _LIBC
24 # include <config.h>
25 #endif
27 #include "getopt.h"
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #ifndef _MSC_VER
33 # include <unistd.h>
34 #endif
36 #ifdef __VMS
37 # include <unixlib.h>
38 #endif
40 /* Completely disable NLS for getopt. We won't include translations for it
41 anyway. If the system lacks getopt_long, missing translations probably
42 aren't a problem. */
44 #ifdef _LIBC
45 # include <libintl.h>
46 #else
47 # include "gettext.h"
48 # define _(msgid) gettext (msgid)
49 #endif
51 #define _(msgid) (msgid)
53 #if defined _LIBC && defined USE_IN_LIBIO
54 # include <wchar.h>
55 #endif
57 #ifndef attribute_hidden
58 # define attribute_hidden
59 #endif
61 /* Unlike standard Unix `getopt', functions like `getopt_long'
62 let the user intersperse the options with the other arguments.
64 As `getopt_long' works, it permutes the elements of ARGV so that,
65 when it is done, all the options precede everything else. Thus
66 all application programs are extended to handle flexible argument order.
68 Using `getopt' or setting the environment variable POSIXLY_CORRECT
69 disables permutation.
70 Then the application's behavior is completely standard.
72 GNU application programs can use a third alternative mode in which
73 they can distinguish the relative order of options and other arguments. */
75 #include "getopt_int.h"
77 /* For communication from `getopt' to the caller.
78 When `getopt' finds an option that takes an argument,
79 the argument value is returned here.
80 Also, when `ordering' is RETURN_IN_ORDER,
81 each non-option ARGV-element is returned here. */
83 char *optarg;
85 /* Index in ARGV of the next element to be scanned.
86 This is used for communication to and from the caller
87 and for communication between successive calls to `getopt'.
89 On entry to `getopt', zero means this is the first call; initialize.
91 When `getopt' returns -1, this is the index of the first of the
92 non-option elements that the caller should itself scan.
94 Otherwise, `optind' communicates from one call to the next
95 how much of ARGV has been scanned so far. */
97 /* 1003.2 says this must be 1 before any call. */
98 int optind = 1;
100 /* Callers store zero here to inhibit the error message
101 for unrecognized options. */
103 int opterr = 1;
105 /* Set to an option character which was unrecognized.
106 This must be initialized on some systems to avoid linking in the
107 system's own getopt implementation. */
109 int optopt = '?';
111 /* Keep a global copy of all internal members of getopt_data. */
113 static struct _getopt_data getopt_data;
116 #if defined HAVE_DECL_GETENV && !HAVE_DECL_GETENV
117 extern char *getenv ();
118 #endif
120 #ifdef _LIBC
121 /* Stored original parameters.
122 XXX This is no good solution. We should rather copy the args so
123 that we can compare them later. But we must not use malloc(3). */
124 extern int __libc_argc;
125 extern char **__libc_argv;
127 /* Bash 2.0 gives us an environment variable containing flags
128 indicating ARGV elements that should not be considered arguments. */
130 # ifdef USE_NONOPTION_FLAGS
131 /* Defined in getopt_init.c */
132 extern char *__getopt_nonoption_flags;
133 # endif
135 # ifdef USE_NONOPTION_FLAGS
136 # define SWAP_FLAGS(ch1, ch2) \
137 if (d->__nonoption_flags_len > 0) \
139 char __tmp = __getopt_nonoption_flags[ch1]; \
140 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
141 __getopt_nonoption_flags[ch2] = __tmp; \
143 # else
144 # define SWAP_FLAGS(ch1, ch2)
145 # endif
146 #else /* !_LIBC */
147 # define SWAP_FLAGS(ch1, ch2)
148 #endif /* _LIBC */
150 /* Exchange two adjacent subsequences of ARGV.
151 One subsequence is elements [first_nonopt,last_nonopt)
152 which contains all the non-options that have been skipped so far.
153 The other is elements [last_nonopt,optind), which contains all
154 the options processed since those non-options were skipped.
156 `first_nonopt' and `last_nonopt' are relocated so that they describe
157 the new indices of the non-options in ARGV after they are moved. */
159 static void
160 exchange (char **argv, struct _getopt_data *d)
162 int bottom = d->__first_nonopt;
163 int middle = d->__last_nonopt;
164 int top = d->optind;
165 char *tem;
167 /* Exchange the shorter segment with the far end of the longer segment.
168 That puts the shorter segment into the right place.
169 It leaves the longer segment in the right place overall,
170 but it consists of two parts that need to be swapped next. */
172 #if defined _LIBC && defined USE_NONOPTION_FLAGS
173 /* First make sure the handling of the `__getopt_nonoption_flags'
174 string can work normally. Our top argument must be in the range
175 of the string. */
176 if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
178 /* We must extend the array. The user plays games with us and
179 presents new arguments. */
180 char *new_str = malloc (top + 1);
181 if (new_str == NULL)
182 d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
183 else
185 memset (__mempcpy (new_str, __getopt_nonoption_flags,
186 d->__nonoption_flags_max_len),
187 '\0', top + 1 - d->__nonoption_flags_max_len);
188 d->__nonoption_flags_max_len = top + 1;
189 __getopt_nonoption_flags = new_str;
192 #endif
194 while (top > middle && middle > bottom)
196 if (top - middle > middle - bottom)
198 /* Bottom segment is the short one. */
199 int len = middle - bottom;
200 register int i;
202 /* Swap it with the top part of the top segment. */
203 for (i = 0; i < len; i++)
205 tem = argv[bottom + i];
206 argv[bottom + i] = argv[top - (middle - bottom) + i];
207 argv[top - (middle - bottom) + i] = tem;
208 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
210 /* Exclude the moved bottom segment from further swapping. */
211 top -= len;
213 else
215 /* Top segment is the short one. */
216 int len = top - middle;
217 register int i;
219 /* Swap it with the bottom part of the bottom segment. */
220 for (i = 0; i < len; i++)
222 tem = argv[bottom + i];
223 argv[bottom + i] = argv[middle + i];
224 argv[middle + i] = tem;
225 SWAP_FLAGS (bottom + i, middle + i);
227 /* Exclude the moved top segment from further swapping. */
228 bottom += len;
232 /* Update records for the slots the non-options now occupy. */
234 d->__first_nonopt += (d->optind - d->__last_nonopt);
235 d->__last_nonopt = d->optind;
238 /* Initialize the internal data when the first call is made. */
240 static const char *
241 _getopt_initialize (int argc, char **argv, const char *optstring,
242 int posixly_correct, struct _getopt_data *d)
244 /* Start processing options with ARGV-element 1 (since ARGV-element 0
245 is the program name); the sequence of previously skipped
246 non-option ARGV-elements is empty. */
248 d->__first_nonopt = d->__last_nonopt = d->optind;
250 d->__nextchar = NULL;
252 d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT");
254 /* Determine how to handle the ordering of options and nonoptions. */
256 if (optstring[0] == '-')
258 d->__ordering = RETURN_IN_ORDER;
259 ++optstring;
261 else if (optstring[0] == '+')
263 d->__ordering = REQUIRE_ORDER;
264 ++optstring;
266 else if (d->__posixly_correct)
267 d->__ordering = REQUIRE_ORDER;
268 else
269 d->__ordering = PERMUTE;
271 #if defined _LIBC && defined USE_NONOPTION_FLAGS
272 if (!d->__posixly_correct
273 && argc == __libc_argc && argv == __libc_argv)
275 if (d->__nonoption_flags_max_len == 0)
277 if (__getopt_nonoption_flags == NULL
278 || __getopt_nonoption_flags[0] == '\0')
279 d->__nonoption_flags_max_len = -1;
280 else
282 const char *orig_str = __getopt_nonoption_flags;
283 int len = d->__nonoption_flags_max_len = strlen (orig_str);
284 if (d->__nonoption_flags_max_len < argc)
285 d->__nonoption_flags_max_len = argc;
286 __getopt_nonoption_flags =
287 (char *) malloc (d->__nonoption_flags_max_len);
288 if (__getopt_nonoption_flags == NULL)
289 d->__nonoption_flags_max_len = -1;
290 else
291 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
292 '\0', d->__nonoption_flags_max_len - len);
295 d->__nonoption_flags_len = d->__nonoption_flags_max_len;
297 else
298 d->__nonoption_flags_len = 0;
299 #endif
301 return optstring;
304 /* Scan elements of ARGV (whose length is ARGC) for option characters
305 given in OPTSTRING.
307 If an element of ARGV starts with '-', and is not exactly "-" or "--",
308 then it is an option element. The characters of this element
309 (aside from the initial '-') are option characters. If `getopt'
310 is called repeatedly, it returns successively each of the option characters
311 from each of the option elements.
313 If `getopt' finds another option character, it returns that character,
314 updating `optind' and `nextchar' so that the next call to `getopt' can
315 resume the scan with the following option character or ARGV-element.
317 If there are no more option characters, `getopt' returns -1.
318 Then `optind' is the index in ARGV of the first ARGV-element
319 that is not an option. (The ARGV-elements have been permuted
320 so that those that are not options now come last.)
322 OPTSTRING is a string containing the legitimate option characters.
323 If an option character is seen that is not listed in OPTSTRING,
324 return '?' after printing an error message. If you set `opterr' to
325 zero, the error message is suppressed but we still return '?'.
327 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
328 so the following text in the same ARGV-element, or the text of the following
329 ARGV-element, is returned in `optarg'. Two colons mean an option that
330 wants an optional arg; if there is text in the current ARGV-element,
331 it is returned in `optarg', otherwise `optarg' is set to zero.
333 If OPTSTRING starts with `-' or `+', it requests different methods of
334 handling the non-option ARGV-elements.
335 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
337 Long-named options begin with `--' instead of `-'.
338 Their names may be abbreviated as long as the abbreviation is unique
339 or is an exact match for some defined option. If they have an
340 argument, it follows the option name in the same ARGV-element, separated
341 from the option name by a `=', or else the in next ARGV-element.
342 When `getopt' finds a long-named option, it returns 0 if that option's
343 `flag' field is nonzero, the value of the option's `val' field
344 if the `flag' field is zero.
346 LONGOPTS is a vector of `struct option' terminated by an
347 element containing a name which is zero.
349 LONGIND returns the index in LONGOPT of the long-named option found.
350 It is only valid when a long-named option has been found by the most
351 recent call.
353 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
354 long-named options.
356 If POSIXLY_CORRECT is nonzero, behave as if the POSIXLY_CORRECT
357 environment variable were set. */
360 _getopt_internal_r (int argc, char **argv, const char *optstring,
361 const struct option *longopts, int *longind,
362 int long_only, int posixly_correct, struct _getopt_data *d)
364 int print_errors = d->opterr;
365 if (optstring[0] == ':')
366 print_errors = 0;
368 if (argc < 1)
369 return -1;
371 d->optarg = NULL;
373 if (d->optind == 0 || !d->__initialized)
375 if (d->optind == 0)
376 d->optind = 1; /* Don't scan ARGV[0], the program name. */
377 optstring = _getopt_initialize (argc, argv, optstring,
378 posixly_correct, d);
379 d->__initialized = 1;
382 /* Test whether ARGV[optind] points to a non-option argument.
383 Either it does not have option syntax, or there is an environment flag
384 from the shell indicating it is not an option. The later information
385 is only used when the used in the GNU libc. */
386 #if defined _LIBC && defined USE_NONOPTION_FLAGS
387 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
388 || (d->optind < d->__nonoption_flags_len \
389 && __getopt_nonoption_flags[d->optind] == '1'))
390 #else
391 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
392 #endif
394 if (d->__nextchar == NULL || *d->__nextchar == '\0')
396 /* Advance to the next ARGV-element. */
398 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
399 moved back by the user (who may also have changed the arguments). */
400 if (d->__last_nonopt > d->optind)
401 d->__last_nonopt = d->optind;
402 if (d->__first_nonopt > d->optind)
403 d->__first_nonopt = d->optind;
405 if (d->__ordering == PERMUTE)
407 /* If we have just processed some options following some non-options,
408 exchange them so that the options come first. */
410 if (d->__first_nonopt != d->__last_nonopt
411 && d->__last_nonopt != d->optind)
412 exchange ((char **) argv, d);
413 else if (d->__last_nonopt != d->optind)
414 d->__first_nonopt = d->optind;
416 /* Skip any additional non-options
417 and extend the range of non-options previously skipped. */
419 while (d->optind < argc && NONOPTION_P)
420 d->optind++;
421 d->__last_nonopt = d->optind;
424 /* The special ARGV-element `--' means premature end of options.
425 Skip it like a null option,
426 then exchange with previous non-options as if it were an option,
427 then skip everything else like a non-option. */
429 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
431 d->optind++;
433 if (d->__first_nonopt != d->__last_nonopt
434 && d->__last_nonopt != d->optind)
435 exchange ((char **) argv, d);
436 else if (d->__first_nonopt == d->__last_nonopt)
437 d->__first_nonopt = d->optind;
438 d->__last_nonopt = argc;
440 d->optind = argc;
443 /* If we have done all the ARGV-elements, stop the scan
444 and back over any non-options that we skipped and permuted. */
446 if (d->optind == argc)
448 /* Set the next-arg-index to point at the non-options
449 that we previously skipped, so the caller will digest them. */
450 if (d->__first_nonopt != d->__last_nonopt)
451 d->optind = d->__first_nonopt;
452 return -1;
455 /* If we have come to a non-option and did not permute it,
456 either stop the scan or describe it to the caller and pass it by. */
458 if (NONOPTION_P)
460 if (d->__ordering == REQUIRE_ORDER)
461 return -1;
462 d->optarg = argv[d->optind++];
463 return 1;
466 /* We have found another option-ARGV-element.
467 Skip the initial punctuation. */
469 d->__nextchar = (argv[d->optind] + 1
470 + (longopts != NULL && argv[d->optind][1] == '-'));
473 /* Decode the current option-ARGV-element. */
475 /* Check whether the ARGV-element is a long option.
477 If long_only and the ARGV-element has the form "-f", where f is
478 a valid short option, don't consider it an abbreviated form of
479 a long option that starts with f. Otherwise there would be no
480 way to give the -f short option.
482 On the other hand, if there's a long option "fubar" and
483 the ARGV-element is "-fu", do consider that an abbreviation of
484 the long option, just like "--fu", and not "-f" with arg "u".
486 This distinction seems to be the most useful approach. */
488 if (longopts != NULL
489 && (argv[d->optind][1] == '-'
490 || (long_only && (argv[d->optind][2]
491 || !strchr (optstring, argv[d->optind][1])))))
493 char *nameend;
494 const struct option *p;
495 const struct option *pfound = NULL;
496 int exact = 0;
497 int ambig = 0;
498 int indfound = -1;
499 int option_index;
501 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
502 /* Do nothing. */ ;
504 /* Test all long options for either exact match
505 or abbreviated matches. */
506 for (p = longopts, option_index = 0; p->name; p++, option_index++)
507 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
509 if ((unsigned int) (nameend - d->__nextchar)
510 == (unsigned int) strlen (p->name))
512 /* Exact match found. */
513 pfound = p;
514 indfound = option_index;
515 exact = 1;
516 break;
518 else if (pfound == NULL)
520 /* First nonexact match found. */
521 pfound = p;
522 indfound = option_index;
524 else if (long_only
525 || pfound->has_arg != p->has_arg
526 || pfound->flag != p->flag
527 || pfound->val != p->val)
528 /* Second or later nonexact match found. */
529 ambig = 1;
532 if (ambig && !exact)
534 if (print_errors)
536 #if defined _LIBC && defined USE_IN_LIBIO
537 char *buf;
539 if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
540 argv[0], argv[d->optind]) >= 0)
542 _IO_flockfile (stderr);
544 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
545 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
547 __fxprintf (NULL, "%s", buf);
549 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
550 _IO_funlockfile (stderr);
552 free (buf);
554 #else
555 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
556 argv[0], argv[d->optind]);
557 #endif
559 d->__nextchar += strlen (d->__nextchar);
560 d->optind++;
561 d->optopt = 0;
562 return '?';
565 if (pfound != NULL)
567 option_index = indfound;
568 d->optind++;
569 if (*nameend)
571 /* Don't test has_arg with >, because some C compilers don't
572 allow it to be used on enums. */
573 if (pfound->has_arg)
574 d->optarg = nameend + 1;
575 else
577 if (print_errors)
579 #if defined _LIBC && defined USE_IN_LIBIO
580 char *buf;
581 int n;
582 #endif
584 if (argv[d->optind - 1][1] == '-')
586 /* --option */
587 #if defined _LIBC && defined USE_IN_LIBIO
588 n = __asprintf (&buf, _("\
589 %s: option `--%s' doesn't allow an argument\n"),
590 argv[0], pfound->name);
591 #else
592 fprintf (stderr, _("\
593 %s: option `--%s' doesn't allow an argument\n"),
594 argv[0], pfound->name);
595 #endif
597 else
599 /* +option or -option */
600 #if defined _LIBC && defined USE_IN_LIBIO
601 n = __asprintf (&buf, _("\
602 %s: option `%c%s' doesn't allow an argument\n"),
603 argv[0], argv[d->optind - 1][0],
604 pfound->name);
605 #else
606 fprintf (stderr, _("\
607 %s: option `%c%s' doesn't allow an argument\n"),
608 argv[0], argv[d->optind - 1][0],
609 pfound->name);
610 #endif
613 #if defined _LIBC && defined USE_IN_LIBIO
614 if (n >= 0)
616 _IO_flockfile (stderr);
618 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
619 ((_IO_FILE *) stderr)->_flags2
620 |= _IO_FLAGS2_NOTCANCEL;
622 __fxprintf (NULL, "%s", buf);
624 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
625 _IO_funlockfile (stderr);
627 free (buf);
629 #endif
632 d->__nextchar += strlen (d->__nextchar);
634 d->optopt = pfound->val;
635 return '?';
638 else if (pfound->has_arg == 1)
640 if (d->optind < argc)
641 d->optarg = argv[d->optind++];
642 else
644 if (print_errors)
646 #if defined _LIBC && defined USE_IN_LIBIO
647 char *buf;
649 if (__asprintf (&buf, _("\
650 %s: option `%s' requires an argument\n"),
651 argv[0], argv[d->optind - 1]) >= 0)
653 _IO_flockfile (stderr);
655 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
656 ((_IO_FILE *) stderr)->_flags2
657 |= _IO_FLAGS2_NOTCANCEL;
659 __fxprintf (NULL, "%s", buf);
661 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
662 _IO_funlockfile (stderr);
664 free (buf);
666 #else
667 fprintf (stderr,
668 _("%s: option `%s' requires an argument\n"),
669 argv[0], argv[d->optind - 1]);
670 #endif
672 d->__nextchar += strlen (d->__nextchar);
673 d->optopt = pfound->val;
674 return optstring[0] == ':' ? ':' : '?';
677 d->__nextchar += strlen (d->__nextchar);
678 if (longind != NULL)
679 *longind = option_index;
680 if (pfound->flag)
682 *(pfound->flag) = pfound->val;
683 return 0;
685 return pfound->val;
688 /* Can't find it as a long option. If this is not getopt_long_only,
689 or the option starts with '--' or is not a valid short
690 option, then it's an error.
691 Otherwise interpret it as a short option. */
692 if (!long_only || argv[d->optind][1] == '-'
693 || strchr (optstring, *d->__nextchar) == NULL)
695 if (print_errors)
697 #if defined _LIBC && defined USE_IN_LIBIO
698 char *buf;
699 int n;
700 #endif
702 if (argv[d->optind][1] == '-')
704 /* --option */
705 #if defined _LIBC && defined USE_IN_LIBIO
706 n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
707 argv[0], d->__nextchar);
708 #else
709 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
710 argv[0], d->__nextchar);
711 #endif
713 else
715 /* +option or -option */
716 #if defined _LIBC && defined USE_IN_LIBIO
717 n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
718 argv[0], argv[d->optind][0], d->__nextchar);
719 #else
720 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
721 argv[0], argv[d->optind][0], d->__nextchar);
722 #endif
725 #if defined _LIBC && defined USE_IN_LIBIO
726 if (n >= 0)
728 _IO_flockfile (stderr);
730 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
731 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
733 __fxprintf (NULL, "%s", buf);
735 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
736 _IO_funlockfile (stderr);
738 free (buf);
740 #endif
742 d->__nextchar = (char *) "";
743 d->optind++;
744 d->optopt = 0;
745 return '?';
749 /* Look at and handle the next short option-character. */
752 char c = *d->__nextchar++;
753 char *temp = strchr (optstring, c);
755 /* Increment `optind' when we start to process its last character. */
756 if (*d->__nextchar == '\0')
757 ++d->optind;
759 if (temp == NULL || c == ':')
761 if (print_errors)
763 #if defined _LIBC && defined USE_IN_LIBIO
764 char *buf;
765 int n;
766 #endif
768 if (d->__posixly_correct)
770 /* 1003.2 specifies the format of this message. */
771 #if defined _LIBC && defined USE_IN_LIBIO
772 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
773 argv[0], c);
774 #else
775 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
776 #endif
778 else
780 #if defined _LIBC && defined USE_IN_LIBIO
781 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
782 argv[0], c);
783 #else
784 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
785 #endif
788 #if defined _LIBC && defined USE_IN_LIBIO
789 if (n >= 0)
791 _IO_flockfile (stderr);
793 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
794 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
796 __fxprintf (NULL, "%s", buf);
798 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
799 _IO_funlockfile (stderr);
801 free (buf);
803 #endif
805 d->optopt = c;
806 return '?';
808 /* Convenience. Treat POSIX -W foo same as long option --foo */
809 if (temp[0] == 'W' && temp[1] == ';')
811 char *nameend;
812 const struct option *p;
813 const struct option *pfound = NULL;
814 int exact = 0;
815 int ambig = 0;
816 int indfound = 0;
817 int option_index;
819 /* This is an option that requires an argument. */
820 if (*d->__nextchar != '\0')
822 d->optarg = d->__nextchar;
823 /* If we end this ARGV-element by taking the rest as an arg,
824 we must advance to the next element now. */
825 d->optind++;
827 else if (d->optind == argc)
829 if (print_errors)
831 /* 1003.2 specifies the format of this message. */
832 #if defined _LIBC && defined USE_IN_LIBIO
833 char *buf;
835 if (__asprintf (&buf,
836 _("%s: option requires an argument -- %c\n"),
837 argv[0], c) >= 0)
839 _IO_flockfile (stderr);
841 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
842 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
844 __fxprintf (NULL, "%s", buf);
846 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
847 _IO_funlockfile (stderr);
849 free (buf);
851 #else
852 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
853 argv[0], c);
854 #endif
856 d->optopt = c;
857 if (optstring[0] == ':')
858 c = ':';
859 else
860 c = '?';
861 return c;
863 else
864 /* We already incremented `d->optind' once;
865 increment it again when taking next ARGV-elt as argument. */
866 d->optarg = argv[d->optind++];
868 /* optarg is now the argument, see if it's in the
869 table of longopts. */
871 for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
872 nameend++)
873 /* Do nothing. */ ;
875 /* Test all long options for either exact match
876 or abbreviated matches. */
877 for (p = longopts, option_index = 0; p->name; p++, option_index++)
878 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
880 if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
882 /* Exact match found. */
883 pfound = p;
884 indfound = option_index;
885 exact = 1;
886 break;
888 else if (pfound == NULL)
890 /* First nonexact match found. */
891 pfound = p;
892 indfound = option_index;
894 else
895 /* Second or later nonexact match found. */
896 ambig = 1;
898 if (ambig && !exact)
900 if (print_errors)
902 #if defined _LIBC && defined USE_IN_LIBIO
903 char *buf;
905 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
906 argv[0], argv[d->optind]) >= 0)
908 _IO_flockfile (stderr);
910 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
911 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
913 __fxprintf (NULL, "%s", buf);
915 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
916 _IO_funlockfile (stderr);
918 free (buf);
920 #else
921 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
922 argv[0], argv[d->optind]);
923 #endif
925 d->__nextchar += strlen (d->__nextchar);
926 d->optind++;
927 return '?';
929 if (pfound != NULL)
931 option_index = indfound;
932 if (*nameend)
934 /* Don't test has_arg with >, because some C compilers don't
935 allow it to be used on enums. */
936 if (pfound->has_arg)
937 d->optarg = nameend + 1;
938 else
940 if (print_errors)
942 #if defined _LIBC && defined USE_IN_LIBIO
943 char *buf;
945 if (__asprintf (&buf, _("\
946 %s: option `-W %s' doesn't allow an argument\n"),
947 argv[0], pfound->name) >= 0)
949 _IO_flockfile (stderr);
951 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
952 ((_IO_FILE *) stderr)->_flags2
953 |= _IO_FLAGS2_NOTCANCEL;
955 __fxprintf (NULL, "%s", buf);
957 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
958 _IO_funlockfile (stderr);
960 free (buf);
962 #else
963 fprintf (stderr, _("\
964 %s: option `-W %s' doesn't allow an argument\n"),
965 argv[0], pfound->name);
966 #endif
969 d->__nextchar += strlen (d->__nextchar);
970 return '?';
973 else if (pfound->has_arg == 1)
975 if (d->optind < argc)
976 d->optarg = argv[d->optind++];
977 else
979 if (print_errors)
981 #if defined _LIBC && defined USE_IN_LIBIO
982 char *buf;
984 if (__asprintf (&buf, _("\
985 %s: option `%s' requires an argument\n"),
986 argv[0], argv[d->optind - 1]) >= 0)
988 _IO_flockfile (stderr);
990 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
991 ((_IO_FILE *) stderr)->_flags2
992 |= _IO_FLAGS2_NOTCANCEL;
994 __fxprintf (NULL, "%s", buf);
996 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
997 _IO_funlockfile (stderr);
999 free (buf);
1001 #else
1002 fprintf (stderr,
1003 _("%s: option `%s' requires an argument\n"),
1004 argv[0], argv[d->optind - 1]);
1005 #endif
1007 d->__nextchar += strlen (d->__nextchar);
1008 return optstring[0] == ':' ? ':' : '?';
1011 d->__nextchar += strlen (d->__nextchar);
1012 if (longind != NULL)
1013 *longind = option_index;
1014 if (pfound->flag)
1016 *(pfound->flag) = pfound->val;
1017 return 0;
1019 return pfound->val;
1021 d->__nextchar = NULL;
1022 return 'W'; /* Let the application handle it. */
1024 if (temp[1] == ':')
1026 if (temp[2] == ':')
1028 /* This is an option that accepts an argument optionally. */
1029 if (*d->__nextchar != '\0')
1031 d->optarg = d->__nextchar;
1032 d->optind++;
1034 else
1035 d->optarg = NULL;
1036 d->__nextchar = NULL;
1038 else
1040 /* This is an option that requires an argument. */
1041 if (*d->__nextchar != '\0')
1043 d->optarg = d->__nextchar;
1044 /* If we end this ARGV-element by taking the rest as an arg,
1045 we must advance to the next element now. */
1046 d->optind++;
1048 else if (d->optind == argc)
1050 if (print_errors)
1052 /* 1003.2 specifies the format of this message. */
1053 #if defined _LIBC && defined USE_IN_LIBIO
1054 char *buf;
1056 if (__asprintf (&buf, _("\
1057 %s: option requires an argument -- %c\n"),
1058 argv[0], c) >= 0)
1060 _IO_flockfile (stderr);
1062 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1063 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1065 __fxprintf (NULL, "%s", buf);
1067 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1068 _IO_funlockfile (stderr);
1070 free (buf);
1072 #else
1073 fprintf (stderr,
1074 _("%s: option requires an argument -- %c\n"),
1075 argv[0], c);
1076 #endif
1078 d->optopt = c;
1079 if (optstring[0] == ':')
1080 c = ':';
1081 else
1082 c = '?';
1084 else
1085 /* We already incremented `optind' once;
1086 increment it again when taking next ARGV-elt as argument. */
1087 d->optarg = argv[d->optind++];
1088 d->__nextchar = NULL;
1091 return c;
1096 _getopt_internal (int argc, char **argv, const char *optstring,
1097 const struct option *longopts, int *longind,
1098 int long_only, int posixly_correct)
1100 int result;
1102 getopt_data.optind = optind;
1103 getopt_data.opterr = opterr;
1105 result = _getopt_internal_r (argc, argv, optstring, longopts, longind,
1106 long_only, posixly_correct, &getopt_data);
1108 optind = getopt_data.optind;
1109 optarg = getopt_data.optarg;
1110 optopt = getopt_data.optopt;
1112 return result;
1115 /* glibc gets a LSB-compliant getopt.
1116 Standalone applications get a POSIX-compliant getopt. */
1117 #if _LIBC
1118 enum { POSIXLY_CORRECT = 0 };
1119 #else
1120 enum { POSIXLY_CORRECT = 1 };
1121 #endif
1124 getopt (int argc, char *const *argv, const char *optstring)
1126 return _getopt_internal (argc, (char **) argv, optstring, NULL, NULL, 0,
1127 POSIXLY_CORRECT);
1131 #ifdef TEST
1133 /* Compile with -DTEST to make an executable for use in testing
1134 the above definition of `getopt'. */
1137 main (int argc, char **argv)
1139 int c;
1140 int digit_optind = 0;
1142 while (1)
1144 int this_option_optind = optind ? optind : 1;
1146 c = getopt (argc, argv, "abc:d:0123456789");
1147 if (c == -1)
1148 break;
1150 switch (c)
1152 case '0':
1153 case '1':
1154 case '2':
1155 case '3':
1156 case '4':
1157 case '5':
1158 case '6':
1159 case '7':
1160 case '8':
1161 case '9':
1162 if (digit_optind != 0 && digit_optind != this_option_optind)
1163 printf ("digits occur in two different argv-elements.\n");
1164 digit_optind = this_option_optind;
1165 printf ("option %c\n", c);
1166 break;
1168 case 'a':
1169 printf ("option a\n");
1170 break;
1172 case 'b':
1173 printf ("option b\n");
1174 break;
1176 case 'c':
1177 printf ("option c with value `%s'\n", optarg);
1178 break;
1180 case '?':
1181 break;
1183 default:
1184 printf ("?? getopt returned character code 0%o ??\n", c);
1188 if (optind < argc)
1190 printf ("non-option ARGV-elements: ");
1191 while (optind < argc)
1192 printf ("%s ", argv[optind++]);
1193 printf ("\n");
1196 exit (0);
1199 #endif /* TEST */