Include <string.h> in sysdeps/unix/sysv/linux/mmap64.c.
[glibc.git] / posix / getopt.c
blob5497fc4247194a5ca252b7a61303103f67e02c35
1 /* Getopt for GNU.
2 NOTE: getopt is 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-2013 Free Software Foundation, Inc.
6 This file is part of the GNU C Library.
8 The GNU C Library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
13 The GNU C Library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public
19 License along with the GNU C Library; if not, see
20 <http://www.gnu.org/licenses/>. */
22 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
23 Ditto for AIX 3.2 and <stdlib.h>. */
24 #ifndef _NO_PROTO
25 # define _NO_PROTO
26 #endif
28 #ifdef HAVE_CONFIG_H
29 # include <config.h>
30 #endif
32 #include <stdio.h>
34 /* Comment out all this code if we are using the GNU C Library, and are not
35 actually compiling the library itself. This code is part of the GNU C
36 Library, but also included in many other GNU distributions. Compiling
37 and linking in this code is a waste when using the GNU C library
38 (especially if it is a shared library). Rather than having every GNU
39 program understand `configure --with-gnu-libc' and omit the object files,
40 it is simpler to just do this in the source for each such file. */
42 #define GETOPT_INTERFACE_VERSION 2
43 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
44 # include <gnu-versions.h>
45 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
46 # define ELIDE_CODE
47 # endif
48 #endif
50 #ifndef ELIDE_CODE
53 /* This needs to come after some library #include
54 to get __GNU_LIBRARY__ defined. */
55 #ifdef __GNU_LIBRARY__
56 /* Don't include stdlib.h for non-GNU C libraries because some of them
57 contain conflicting prototypes for getopt. */
58 # include <stdlib.h>
59 # include <unistd.h>
60 #endif /* GNU C library. */
62 #include <string.h>
64 #ifdef VMS
65 # include <unixlib.h>
66 #endif
68 #ifdef _LIBC
69 # include <libintl.h>
70 #else
71 # include "gettext.h"
72 # define _(msgid) gettext (msgid)
73 #endif
75 #if defined _LIBC
76 # include <wchar.h>
77 #endif
79 #ifndef attribute_hidden
80 # define attribute_hidden
81 #endif
83 /* This version of `getopt' appears to the caller like standard Unix `getopt'
84 but it behaves differently for the user, since it allows the user
85 to intersperse the options with the other arguments.
87 As `getopt' works, it permutes the elements of ARGV so that,
88 when it is done, all the options precede everything else. Thus
89 all application programs are extended to handle flexible argument order.
91 Setting the environment variable POSIXLY_CORRECT disables permutation.
92 Then the behavior is completely standard.
94 GNU application programs can use a third alternative mode in which
95 they can distinguish the relative order of options and other arguments. */
97 #include "getopt.h"
98 #include "getopt_int.h"
100 /* For communication from `getopt' to the caller.
101 When `getopt' finds an option that takes an argument,
102 the argument value is returned here.
103 Also, when `ordering' is RETURN_IN_ORDER,
104 each non-option ARGV-element is returned here. */
106 char *optarg;
108 /* Index in ARGV of the next element to be scanned.
109 This is used for communication to and from the caller
110 and for communication between successive calls to `getopt'.
112 On entry to `getopt', zero means this is the first call; initialize.
114 When `getopt' returns -1, this is the index of the first of the
115 non-option elements that the caller should itself scan.
117 Otherwise, `optind' communicates from one call to the next
118 how much of ARGV has been scanned so far. */
120 /* 1003.2 says this must be 1 before any call. */
121 int optind = 1;
123 /* Callers store zero here to inhibit the error message
124 for unrecognized options. */
126 int opterr = 1;
128 /* Set to an option character which was unrecognized.
129 This must be initialized on some systems to avoid linking in the
130 system's own getopt implementation. */
132 int optopt = '?';
134 /* Keep a global copy of all internal members of getopt_data. */
136 static struct _getopt_data getopt_data;
139 #ifndef __GNU_LIBRARY__
141 /* Avoid depending on library functions or files
142 whose names are inconsistent. */
144 #ifndef getenv
145 extern char *getenv ();
146 #endif
148 #endif /* not __GNU_LIBRARY__ */
150 #ifdef _LIBC
151 /* Stored original parameters.
152 XXX This is no good solution. We should rather copy the args so
153 that we can compare them later. But we must not use malloc(3). */
154 extern int __libc_argc;
155 extern char **__libc_argv;
157 /* Bash 2.0 gives us an environment variable containing flags
158 indicating ARGV elements that should not be considered arguments. */
160 # ifdef USE_NONOPTION_FLAGS
161 /* Defined in getopt_init.c */
162 extern char *__getopt_nonoption_flags;
163 # endif
165 # ifdef USE_NONOPTION_FLAGS
166 # define SWAP_FLAGS(ch1, ch2) \
167 if (d->__nonoption_flags_len > 0) \
169 char __tmp = __getopt_nonoption_flags[ch1]; \
170 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
171 __getopt_nonoption_flags[ch2] = __tmp; \
173 # else
174 # define SWAP_FLAGS(ch1, ch2)
175 # endif
176 #else /* !_LIBC */
177 # define SWAP_FLAGS(ch1, ch2)
178 #endif /* _LIBC */
180 /* Exchange two adjacent subsequences of ARGV.
181 One subsequence is elements [first_nonopt,last_nonopt)
182 which contains all the non-options that have been skipped so far.
183 The other is elements [last_nonopt,optind), which contains all
184 the options processed since those non-options were skipped.
186 `first_nonopt' and `last_nonopt' are relocated so that they describe
187 the new indices of the non-options in ARGV after they are moved. */
189 static void
190 exchange (char **argv, struct _getopt_data *d)
192 int bottom = d->__first_nonopt;
193 int middle = d->__last_nonopt;
194 int top = d->optind;
195 char *tem;
197 /* Exchange the shorter segment with the far end of the longer segment.
198 That puts the shorter segment into the right place.
199 It leaves the longer segment in the right place overall,
200 but it consists of two parts that need to be swapped next. */
202 #if defined _LIBC && defined USE_NONOPTION_FLAGS
203 /* First make sure the handling of the `__getopt_nonoption_flags'
204 string can work normally. Our top argument must be in the range
205 of the string. */
206 if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
208 /* We must extend the array. The user plays games with us and
209 presents new arguments. */
210 char *new_str = malloc (top + 1);
211 if (new_str == NULL)
212 d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
213 else
215 memset (__mempcpy (new_str, __getopt_nonoption_flags,
216 d->__nonoption_flags_max_len),
217 '\0', top + 1 - d->__nonoption_flags_max_len);
218 d->__nonoption_flags_max_len = top + 1;
219 __getopt_nonoption_flags = new_str;
222 #endif
224 while (top > middle && middle > bottom)
226 if (top - middle > middle - bottom)
228 /* Bottom segment is the short one. */
229 int len = middle - bottom;
230 int i;
232 /* Swap it with the top part of the top segment. */
233 for (i = 0; i < len; i++)
235 tem = argv[bottom + i];
236 argv[bottom + i] = argv[top - (middle - bottom) + i];
237 argv[top - (middle - bottom) + i] = tem;
238 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
240 /* Exclude the moved bottom segment from further swapping. */
241 top -= len;
243 else
245 /* Top segment is the short one. */
246 int len = top - middle;
247 int i;
249 /* Swap it with the bottom part of the bottom segment. */
250 for (i = 0; i < len; i++)
252 tem = argv[bottom + i];
253 argv[bottom + i] = argv[middle + i];
254 argv[middle + i] = tem;
255 SWAP_FLAGS (bottom + i, middle + i);
257 /* Exclude the moved top segment from further swapping. */
258 bottom += len;
262 /* Update records for the slots the non-options now occupy. */
264 d->__first_nonopt += (d->optind - d->__last_nonopt);
265 d->__last_nonopt = d->optind;
268 /* Initialize the internal data when the first call is made. */
270 static const char *
271 _getopt_initialize (int argc, char *const *argv, const char *optstring,
272 struct _getopt_data *d, int posixly_correct)
274 /* Start processing options with ARGV-element 1 (since ARGV-element 0
275 is the program name); the sequence of previously skipped
276 non-option ARGV-elements is empty. */
278 d->__first_nonopt = d->__last_nonopt = d->optind;
280 d->__nextchar = NULL;
282 d->__posixly_correct = posixly_correct | !!getenv ("POSIXLY_CORRECT");
284 /* Determine how to handle the ordering of options and nonoptions. */
286 if (optstring[0] == '-')
288 d->__ordering = RETURN_IN_ORDER;
289 ++optstring;
291 else if (optstring[0] == '+')
293 d->__ordering = REQUIRE_ORDER;
294 ++optstring;
296 else if (d->__posixly_correct)
297 d->__ordering = REQUIRE_ORDER;
298 else
299 d->__ordering = PERMUTE;
301 #if defined _LIBC && defined USE_NONOPTION_FLAGS
302 if (!d->__posixly_correct
303 && argc == __libc_argc && argv == __libc_argv)
305 if (d->__nonoption_flags_max_len == 0)
307 if (__getopt_nonoption_flags == NULL
308 || __getopt_nonoption_flags[0] == '\0')
309 d->__nonoption_flags_max_len = -1;
310 else
312 const char *orig_str = __getopt_nonoption_flags;
313 int len = d->__nonoption_flags_max_len = strlen (orig_str);
314 if (d->__nonoption_flags_max_len < argc)
315 d->__nonoption_flags_max_len = argc;
316 __getopt_nonoption_flags =
317 (char *) malloc (d->__nonoption_flags_max_len);
318 if (__getopt_nonoption_flags == NULL)
319 d->__nonoption_flags_max_len = -1;
320 else
321 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
322 '\0', d->__nonoption_flags_max_len - len);
325 d->__nonoption_flags_len = d->__nonoption_flags_max_len;
327 else
328 d->__nonoption_flags_len = 0;
329 #endif
331 return optstring;
334 /* Scan elements of ARGV (whose length is ARGC) for option characters
335 given in OPTSTRING.
337 If an element of ARGV starts with '-', and is not exactly "-" or "--",
338 then it is an option element. The characters of this element
339 (aside from the initial '-') are option characters. If `getopt'
340 is called repeatedly, it returns successively each of the option characters
341 from each of the option elements.
343 If `getopt' finds another option character, it returns that character,
344 updating `optind' and `nextchar' so that the next call to `getopt' can
345 resume the scan with the following option character or ARGV-element.
347 If there are no more option characters, `getopt' returns -1.
348 Then `optind' is the index in ARGV of the first ARGV-element
349 that is not an option. (The ARGV-elements have been permuted
350 so that those that are not options now come last.)
352 OPTSTRING is a string containing the legitimate option characters.
353 If an option character is seen that is not listed in OPTSTRING,
354 return '?' after printing an error message. If you set `opterr' to
355 zero, the error message is suppressed but we still return '?'.
357 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
358 so the following text in the same ARGV-element, or the text of the following
359 ARGV-element, is returned in `optarg'. Two colons mean an option that
360 wants an optional arg; if there is text in the current ARGV-element,
361 it is returned in `optarg', otherwise `optarg' is set to zero.
363 If OPTSTRING starts with `-' or `+', it requests different methods of
364 handling the non-option ARGV-elements.
365 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
367 Long-named options begin with `--' instead of `-'.
368 Their names may be abbreviated as long as the abbreviation is unique
369 or is an exact match for some defined option. If they have an
370 argument, it follows the option name in the same ARGV-element, separated
371 from the option name by a `=', or else the in next ARGV-element.
372 When `getopt' finds a long-named option, it returns 0 if that option's
373 `flag' field is nonzero, the value of the option's `val' field
374 if the `flag' field is zero.
376 The elements of ARGV aren't really const, because we permute them.
377 But we pretend they're const in the prototype to be compatible
378 with other systems.
380 LONGOPTS is a vector of `struct option' terminated by an
381 element containing a name which is zero.
383 LONGIND returns the index in LONGOPT of the long-named option found.
384 It is only valid when a long-named option has been found by the most
385 recent call.
387 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
388 long-named options. */
391 _getopt_internal_r (int argc, char *const *argv, const char *optstring,
392 const struct option *longopts, int *longind,
393 int long_only, struct _getopt_data *d, int posixly_correct)
395 int print_errors = d->opterr;
397 if (argc < 1)
398 return -1;
400 d->optarg = NULL;
402 if (d->optind == 0 || !d->__initialized)
404 if (d->optind == 0)
405 d->optind = 1; /* Don't scan ARGV[0], the program name. */
406 optstring = _getopt_initialize (argc, argv, optstring, d,
407 posixly_correct);
408 d->__initialized = 1;
410 else if (optstring[0] == '-' || optstring[0] == '+')
411 optstring++;
412 if (optstring[0] == ':')
413 print_errors = 0;
415 /* Test whether ARGV[optind] points to a non-option argument.
416 Either it does not have option syntax, or there is an environment flag
417 from the shell indicating it is not an option. The later information
418 is only used when the used in the GNU libc. */
419 #if defined _LIBC && defined USE_NONOPTION_FLAGS
420 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
421 || (d->optind < d->__nonoption_flags_len \
422 && __getopt_nonoption_flags[d->optind] == '1'))
423 #else
424 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
425 #endif
427 if (d->__nextchar == NULL || *d->__nextchar == '\0')
429 /* Advance to the next ARGV-element. */
431 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
432 moved back by the user (who may also have changed the arguments). */
433 if (d->__last_nonopt > d->optind)
434 d->__last_nonopt = d->optind;
435 if (d->__first_nonopt > d->optind)
436 d->__first_nonopt = d->optind;
438 if (d->__ordering == PERMUTE)
440 /* If we have just processed some options following some non-options,
441 exchange them so that the options come first. */
443 if (d->__first_nonopt != d->__last_nonopt
444 && d->__last_nonopt != d->optind)
445 exchange ((char **) argv, d);
446 else if (d->__last_nonopt != d->optind)
447 d->__first_nonopt = d->optind;
449 /* Skip any additional non-options
450 and extend the range of non-options previously skipped. */
452 while (d->optind < argc && NONOPTION_P)
453 d->optind++;
454 d->__last_nonopt = d->optind;
457 /* The special ARGV-element `--' means premature end of options.
458 Skip it like a null option,
459 then exchange with previous non-options as if it were an option,
460 then skip everything else like a non-option. */
462 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
464 d->optind++;
466 if (d->__first_nonopt != d->__last_nonopt
467 && d->__last_nonopt != d->optind)
468 exchange ((char **) argv, d);
469 else if (d->__first_nonopt == d->__last_nonopt)
470 d->__first_nonopt = d->optind;
471 d->__last_nonopt = argc;
473 d->optind = argc;
476 /* If we have done all the ARGV-elements, stop the scan
477 and back over any non-options that we skipped and permuted. */
479 if (d->optind == argc)
481 /* Set the next-arg-index to point at the non-options
482 that we previously skipped, so the caller will digest them. */
483 if (d->__first_nonopt != d->__last_nonopt)
484 d->optind = d->__first_nonopt;
485 return -1;
488 /* If we have come to a non-option and did not permute it,
489 either stop the scan or describe it to the caller and pass it by. */
491 if (NONOPTION_P)
493 if (d->__ordering == REQUIRE_ORDER)
494 return -1;
495 d->optarg = argv[d->optind++];
496 return 1;
499 /* We have found another option-ARGV-element.
500 Skip the initial punctuation. */
502 d->__nextchar = (argv[d->optind] + 1
503 + (longopts != NULL && argv[d->optind][1] == '-'));
506 /* Decode the current option-ARGV-element. */
508 /* Check whether the ARGV-element is a long option.
510 If long_only and the ARGV-element has the form "-f", where f is
511 a valid short option, don't consider it an abbreviated form of
512 a long option that starts with f. Otherwise there would be no
513 way to give the -f short option.
515 On the other hand, if there's a long option "fubar" and
516 the ARGV-element is "-fu", do consider that an abbreviation of
517 the long option, just like "--fu", and not "-f" with arg "u".
519 This distinction seems to be the most useful approach. */
521 if (longopts != NULL
522 && (argv[d->optind][1] == '-'
523 || (long_only && (argv[d->optind][2]
524 || !strchr (optstring, argv[d->optind][1])))))
526 char *nameend;
527 unsigned int namelen;
528 const struct option *p;
529 const struct option *pfound = NULL;
530 struct option_list
532 const struct option *p;
533 struct option_list *next;
534 } *ambig_list = NULL;
535 int exact = 0;
536 int indfound = -1;
537 int option_index;
539 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
540 /* Do nothing. */ ;
541 namelen = nameend - d->__nextchar;
543 /* Test all long options for either exact match
544 or abbreviated matches. */
545 for (p = longopts, option_index = 0; p->name; p++, option_index++)
546 if (!strncmp (p->name, d->__nextchar, namelen))
548 if (namelen == (unsigned int) strlen (p->name))
550 /* Exact match found. */
551 pfound = p;
552 indfound = option_index;
553 exact = 1;
554 break;
556 else if (pfound == NULL)
558 /* First nonexact match found. */
559 pfound = p;
560 indfound = option_index;
562 else if (long_only
563 || pfound->has_arg != p->has_arg
564 || pfound->flag != p->flag
565 || pfound->val != p->val)
567 /* Second or later nonexact match found. */
568 struct option_list *newp = alloca (sizeof (*newp));
569 newp->p = p;
570 newp->next = ambig_list;
571 ambig_list = newp;
575 if (ambig_list != NULL && !exact)
577 if (print_errors)
579 struct option_list first;
580 first.p = pfound;
581 first.next = ambig_list;
582 ambig_list = &first;
584 #if defined _LIBC
585 char *buf = NULL;
586 size_t buflen = 0;
588 FILE *fp = open_memstream (&buf, &buflen);
589 if (fp != NULL)
591 fprintf (fp,
592 _("%s: option '%s' is ambiguous; possibilities:"),
593 argv[0], argv[d->optind]);
597 fprintf (fp, " '--%s'", ambig_list->p->name);
598 ambig_list = ambig_list->next;
600 while (ambig_list != NULL);
602 fputc_unlocked ('\n', fp);
604 if (__builtin_expect (fclose (fp) != EOF, 1))
606 _IO_flockfile (stderr);
608 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
609 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
611 __fxprintf (NULL, "%s", buf);
613 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
614 _IO_funlockfile (stderr);
616 free (buf);
619 #else
620 fprintf (stderr,
621 _("%s: option '%s' is ambiguous; possibilities:"),
622 argv[0], argv[d->optind]);
625 fprintf (stderr, " '--%s'", ambig_list->p->name);
626 ambig_list = ambig_list->next;
628 while (ambig_list != NULL);
630 fputc ('\n', stderr);
631 #endif
633 d->__nextchar += strlen (d->__nextchar);
634 d->optind++;
635 d->optopt = 0;
636 return '?';
639 if (pfound != NULL)
641 option_index = indfound;
642 d->optind++;
643 if (*nameend)
645 /* Don't test has_arg with >, because some C compilers don't
646 allow it to be used on enums. */
647 if (pfound->has_arg)
648 d->optarg = nameend + 1;
649 else
651 if (print_errors)
653 #if defined _LIBC
654 char *buf;
655 int n;
656 #endif
658 if (argv[d->optind - 1][1] == '-')
660 /* --option */
661 #if defined _LIBC
662 n = __asprintf (&buf, _("\
663 %s: option '--%s' doesn't allow an argument\n"),
664 argv[0], pfound->name);
665 #else
666 fprintf (stderr, _("\
667 %s: option '--%s' doesn't allow an argument\n"),
668 argv[0], pfound->name);
669 #endif
671 else
673 /* +option or -option */
674 #if defined _LIBC
675 n = __asprintf (&buf, _("\
676 %s: option '%c%s' doesn't allow an argument\n"),
677 argv[0], argv[d->optind - 1][0],
678 pfound->name);
679 #else
680 fprintf (stderr, _("\
681 %s: option '%c%s' doesn't allow an argument\n"),
682 argv[0], argv[d->optind - 1][0],
683 pfound->name);
684 #endif
687 #if defined _LIBC
688 if (n >= 0)
690 _IO_flockfile (stderr);
692 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
693 ((_IO_FILE *) stderr)->_flags2
694 |= _IO_FLAGS2_NOTCANCEL;
696 __fxprintf (NULL, "%s", buf);
698 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
699 _IO_funlockfile (stderr);
701 free (buf);
703 #endif
706 d->__nextchar += strlen (d->__nextchar);
708 d->optopt = pfound->val;
709 return '?';
712 else if (pfound->has_arg == 1)
714 if (d->optind < argc)
715 d->optarg = argv[d->optind++];
716 else
718 if (print_errors)
720 #if defined _LIBC
721 char *buf;
723 if (__asprintf (&buf, _("\
724 %s: option '--%s' requires an argument\n"),
725 argv[0], pfound->name) >= 0)
727 _IO_flockfile (stderr);
729 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
730 ((_IO_FILE *) stderr)->_flags2
731 |= _IO_FLAGS2_NOTCANCEL;
733 __fxprintf (NULL, "%s", buf);
735 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
736 _IO_funlockfile (stderr);
738 free (buf);
740 #else
741 fprintf (stderr,
742 _("%s: option '--%s' requires an argument\n"),
743 argv[0], pfound->name);
744 #endif
746 d->__nextchar += strlen (d->__nextchar);
747 d->optopt = pfound->val;
748 return optstring[0] == ':' ? ':' : '?';
751 d->__nextchar += strlen (d->__nextchar);
752 if (longind != NULL)
753 *longind = option_index;
754 if (pfound->flag)
756 *(pfound->flag) = pfound->val;
757 return 0;
759 return pfound->val;
762 /* Can't find it as a long option. If this is not getopt_long_only,
763 or the option starts with '--' or is not a valid short
764 option, then it's an error.
765 Otherwise interpret it as a short option. */
766 if (!long_only || argv[d->optind][1] == '-'
767 || strchr (optstring, *d->__nextchar) == NULL)
769 if (print_errors)
771 #if defined _LIBC
772 char *buf;
773 int n;
774 #endif
776 if (argv[d->optind][1] == '-')
778 /* --option */
779 #if defined _LIBC
780 n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"),
781 argv[0], d->__nextchar);
782 #else
783 fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
784 argv[0], d->__nextchar);
785 #endif
787 else
789 /* +option or -option */
790 #if defined _LIBC
791 n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"),
792 argv[0], argv[d->optind][0], d->__nextchar);
793 #else
794 fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
795 argv[0], argv[d->optind][0], d->__nextchar);
796 #endif
799 #if defined _LIBC
800 if (n >= 0)
802 _IO_flockfile (stderr);
804 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
805 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
807 __fxprintf (NULL, "%s", buf);
809 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
810 _IO_funlockfile (stderr);
812 free (buf);
814 #endif
816 d->__nextchar = (char *) "";
817 d->optind++;
818 d->optopt = 0;
819 return '?';
823 /* Look at and handle the next short option-character. */
826 char c = *d->__nextchar++;
827 char *temp = strchr (optstring, c);
829 /* Increment `optind' when we start to process its last character. */
830 if (*d->__nextchar == '\0')
831 ++d->optind;
833 if (temp == NULL || c == ':' || c == ';')
835 if (print_errors)
837 #if defined _LIBC
838 char *buf;
839 int n;
840 #endif
842 #if defined _LIBC
843 n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"),
844 argv[0], c);
845 #else
846 fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
847 #endif
849 #if defined _LIBC
850 if (n >= 0)
852 _IO_flockfile (stderr);
854 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
855 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
857 __fxprintf (NULL, "%s", buf);
859 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
860 _IO_funlockfile (stderr);
862 free (buf);
864 #endif
866 d->optopt = c;
867 return '?';
869 /* Convenience. Treat POSIX -W foo same as long option --foo */
870 if (temp[0] == 'W' && temp[1] == ';')
872 if (longopts == NULL)
873 goto no_longs;
875 char *nameend;
876 const struct option *p;
877 const struct option *pfound = NULL;
878 int exact = 0;
879 int ambig = 0;
880 int indfound = 0;
881 int option_index;
883 /* This is an option that requires an argument. */
884 if (*d->__nextchar != '\0')
886 d->optarg = d->__nextchar;
887 /* If we end this ARGV-element by taking the rest as an arg,
888 we must advance to the next element now. */
889 d->optind++;
891 else if (d->optind == argc)
893 if (print_errors)
895 #if defined _LIBC
896 char *buf;
898 if (__asprintf (&buf,
899 _("%s: option requires an argument -- '%c'\n"),
900 argv[0], c) >= 0)
902 _IO_flockfile (stderr);
904 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
905 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
907 __fxprintf (NULL, "%s", buf);
909 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
910 _IO_funlockfile (stderr);
912 free (buf);
914 #else
915 fprintf (stderr,
916 _("%s: option requires an argument -- '%c'\n"),
917 argv[0], c);
918 #endif
920 d->optopt = c;
921 if (optstring[0] == ':')
922 c = ':';
923 else
924 c = '?';
925 return c;
927 else
928 /* We already incremented `d->optind' once;
929 increment it again when taking next ARGV-elt as argument. */
930 d->optarg = argv[d->optind++];
932 /* optarg is now the argument, see if it's in the
933 table of longopts. */
935 for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
936 nameend++)
937 /* Do nothing. */ ;
939 /* Test all long options for either exact match
940 or abbreviated matches. */
941 for (p = longopts, option_index = 0; p->name; p++, option_index++)
942 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
944 if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
946 /* Exact match found. */
947 pfound = p;
948 indfound = option_index;
949 exact = 1;
950 break;
952 else if (pfound == NULL)
954 /* First nonexact match found. */
955 pfound = p;
956 indfound = option_index;
958 else if (long_only
959 || pfound->has_arg != p->has_arg
960 || pfound->flag != p->flag
961 || pfound->val != p->val)
962 /* Second or later nonexact match found. */
963 ambig = 1;
965 if (ambig && !exact)
967 if (print_errors)
969 #if defined _LIBC
970 char *buf;
972 if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"),
973 argv[0], d->optarg) >= 0)
975 _IO_flockfile (stderr);
977 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
978 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
980 __fxprintf (NULL, "%s", buf);
982 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
983 _IO_funlockfile (stderr);
985 free (buf);
987 #else
988 fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
989 argv[0], d->optarg);
990 #endif
992 d->__nextchar += strlen (d->__nextchar);
993 d->optind++;
994 return '?';
996 if (pfound != NULL)
998 option_index = indfound;
999 if (*nameend)
1001 /* Don't test has_arg with >, because some C compilers don't
1002 allow it to be used on enums. */
1003 if (pfound->has_arg)
1004 d->optarg = nameend + 1;
1005 else
1007 if (print_errors)
1009 #if defined _LIBC
1010 char *buf;
1012 if (__asprintf (&buf, _("\
1013 %s: option '-W %s' doesn't allow an argument\n"),
1014 argv[0], pfound->name) >= 0)
1016 _IO_flockfile (stderr);
1018 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1019 ((_IO_FILE *) stderr)->_flags2
1020 |= _IO_FLAGS2_NOTCANCEL;
1022 __fxprintf (NULL, "%s", buf);
1024 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1025 _IO_funlockfile (stderr);
1027 free (buf);
1029 #else
1030 fprintf (stderr, _("\
1031 %s: option '-W %s' doesn't allow an argument\n"),
1032 argv[0], pfound->name);
1033 #endif
1036 d->__nextchar += strlen (d->__nextchar);
1037 return '?';
1040 else if (pfound->has_arg == 1)
1042 if (d->optind < argc)
1043 d->optarg = argv[d->optind++];
1044 else
1046 if (print_errors)
1048 #if defined _LIBC
1049 char *buf;
1051 if (__asprintf (&buf, _("\
1052 %s: option '-W %s' requires an argument\n"),
1053 argv[0], pfound->name) >= 0)
1055 _IO_flockfile (stderr);
1057 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1058 ((_IO_FILE *) stderr)->_flags2
1059 |= _IO_FLAGS2_NOTCANCEL;
1061 __fxprintf (NULL, "%s", buf);
1063 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1064 _IO_funlockfile (stderr);
1066 free (buf);
1068 #else
1069 fprintf (stderr, _("\
1070 %s: option '-W %s' requires an argument\n"),
1071 argv[0], pfound->name);
1072 #endif
1074 d->__nextchar += strlen (d->__nextchar);
1075 return optstring[0] == ':' ? ':' : '?';
1078 else
1079 d->optarg = NULL;
1080 d->__nextchar += strlen (d->__nextchar);
1081 if (longind != NULL)
1082 *longind = option_index;
1083 if (pfound->flag)
1085 *(pfound->flag) = pfound->val;
1086 return 0;
1088 return pfound->val;
1091 no_longs:
1092 d->__nextchar = NULL;
1093 return 'W'; /* Let the application handle it. */
1095 if (temp[1] == ':')
1097 if (temp[2] == ':')
1099 /* This is an option that accepts an argument optionally. */
1100 if (*d->__nextchar != '\0')
1102 d->optarg = d->__nextchar;
1103 d->optind++;
1105 else
1106 d->optarg = NULL;
1107 d->__nextchar = NULL;
1109 else
1111 /* This is an option that requires an argument. */
1112 if (*d->__nextchar != '\0')
1114 d->optarg = d->__nextchar;
1115 /* If we end this ARGV-element by taking the rest as an arg,
1116 we must advance to the next element now. */
1117 d->optind++;
1119 else if (d->optind == argc)
1121 if (print_errors)
1123 #if defined _LIBC
1124 char *buf;
1126 if (__asprintf (&buf, _("\
1127 %s: option requires an argument -- '%c'\n"),
1128 argv[0], c) >= 0)
1130 _IO_flockfile (stderr);
1132 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1133 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1135 __fxprintf (NULL, "%s", buf);
1137 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1138 _IO_funlockfile (stderr);
1140 free (buf);
1142 #else
1143 fprintf (stderr,
1144 _("%s: option requires an argument -- '%c'\n"),
1145 argv[0], c);
1146 #endif
1148 d->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 d->optarg = argv[d->optind++];
1158 d->__nextchar = NULL;
1161 return c;
1166 _getopt_internal (int argc, char *const *argv, const char *optstring,
1167 const struct option *longopts, int *longind, int long_only,
1168 int posixly_correct)
1170 int result;
1172 getopt_data.optind = optind;
1173 getopt_data.opterr = opterr;
1175 result = _getopt_internal_r (argc, argv, optstring, longopts,
1176 longind, long_only, &getopt_data,
1177 posixly_correct);
1179 optind = getopt_data.optind;
1180 optarg = getopt_data.optarg;
1181 optopt = getopt_data.optopt;
1183 return result;
1187 getopt (int argc, char *const *argv, const char *optstring)
1189 return _getopt_internal (argc, argv, optstring,
1190 (const struct option *) 0,
1191 (int *) 0,
1192 0, 0);
1195 #ifdef _LIBC
1197 __posix_getopt (int argc, char *const *argv, const char *optstring)
1199 return _getopt_internal (argc, argv, optstring,
1200 (const struct option *) 0,
1201 (int *) 0,
1202 0, 1);
1204 #endif
1206 #endif /* Not ELIDE_CODE. */
1208 #ifdef TEST
1210 /* Compile with -DTEST to make an executable for use in testing
1211 the above definition of `getopt'. */
1214 main (int argc, char **argv)
1216 int c;
1217 int digit_optind = 0;
1219 while (1)
1221 int this_option_optind = optind ? optind : 1;
1223 c = getopt (argc, argv, "abc:d:0123456789");
1224 if (c == -1)
1225 break;
1227 switch (c)
1229 case '0':
1230 case '1':
1231 case '2':
1232 case '3':
1233 case '4':
1234 case '5':
1235 case '6':
1236 case '7':
1237 case '8':
1238 case '9':
1239 if (digit_optind != 0 && digit_optind != this_option_optind)
1240 printf ("digits occur in two different argv-elements.\n");
1241 digit_optind = this_option_optind;
1242 printf ("option %c\n", c);
1243 break;
1245 case 'a':
1246 printf ("option a\n");
1247 break;
1249 case 'b':
1250 printf ("option b\n");
1251 break;
1253 case 'c':
1254 printf ("option c with value '%s'\n", optarg);
1255 break;
1257 case '?':
1258 break;
1260 default:
1261 printf ("?? getopt returned character code 0%o ??\n", c);
1265 if (optind < argc)
1267 printf ("non-option ARGV-elements: ");
1268 while (optind < argc)
1269 printf ("%s ", argv[optind++]);
1270 printf ("\n");
1273 exit (0);
1276 #endif /* TEST */