getutent implementation for Linux/s390-32.
[glibc/history.git] / posix / getopt.c
blob965bfdd3ac955c2e96425d1e55a68fe4ebdba955
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-1996,1998-2004,2008 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, write to the Free
20 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 02111-1307 USA. */
23 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
24 Ditto for AIX 3.2 and <stdlib.h>. */
25 #ifndef _NO_PROTO
26 # define _NO_PROTO
27 #endif
29 #ifdef HAVE_CONFIG_H
30 # include <config.h>
31 #endif
33 #include <stdio.h>
35 /* Comment out all this code if we are using the GNU C Library, and are not
36 actually compiling the library itself. This code is part of the GNU C
37 Library, but also included in many other GNU distributions. Compiling
38 and linking in this code is a waste when using the GNU C library
39 (especially if it is a shared library). Rather than having every GNU
40 program understand `configure --with-gnu-libc' and omit the object files,
41 it is simpler to just do this in the source for each such file. */
43 #define GETOPT_INTERFACE_VERSION 2
44 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
45 # include <gnu-versions.h>
46 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
47 # define ELIDE_CODE
48 # endif
49 #endif
51 #ifndef ELIDE_CODE
54 /* This needs to come after some library #include
55 to get __GNU_LIBRARY__ defined. */
56 #ifdef __GNU_LIBRARY__
57 /* Don't include stdlib.h for non-GNU C libraries because some of them
58 contain conflicting prototypes for getopt. */
59 # include <stdlib.h>
60 # include <unistd.h>
61 #endif /* GNU C library. */
63 #include <string.h>
65 #ifdef VMS
66 # include <unixlib.h>
67 #endif
69 #ifdef _LIBC
70 # include <libintl.h>
71 #else
72 # include "gettext.h"
73 # define _(msgid) gettext (msgid)
74 #endif
76 #if defined _LIBC && defined USE_IN_LIBIO
77 # include <wchar.h>
78 #endif
80 #ifndef attribute_hidden
81 # define attribute_hidden
82 #endif
84 /* This version of `getopt' appears to the caller like standard Unix `getopt'
85 but it behaves differently for the user, since it allows the user
86 to intersperse the options with the other arguments.
88 As `getopt' works, it permutes the elements of ARGV so that,
89 when it is done, all the options precede everything else. Thus
90 all application programs are extended to handle flexible argument order.
92 Setting the environment variable POSIXLY_CORRECT disables permutation.
93 Then the behavior is completely standard.
95 GNU application programs can use a third alternative mode in which
96 they can distinguish the relative order of options and other arguments. */
98 #include "getopt.h"
99 #include "getopt_int.h"
101 /* For communication from `getopt' to the caller.
102 When `getopt' finds an option that takes an argument,
103 the argument value is returned here.
104 Also, when `ordering' is RETURN_IN_ORDER,
105 each non-option ARGV-element is returned here. */
107 char *optarg;
109 /* Index in ARGV of the next element to be scanned.
110 This is used for communication to and from the caller
111 and for communication between successive calls to `getopt'.
113 On entry to `getopt', zero means this is the first call; initialize.
115 When `getopt' returns -1, this is the index of the first of the
116 non-option elements that the caller should itself scan.
118 Otherwise, `optind' communicates from one call to the next
119 how much of ARGV has been scanned so far. */
121 /* 1003.2 says this must be 1 before any call. */
122 int optind = 1;
124 /* Callers store zero here to inhibit the error message
125 for unrecognized options. */
127 int opterr = 1;
129 /* Set to an option character which was unrecognized.
130 This must be initialized on some systems to avoid linking in the
131 system's own getopt implementation. */
133 int optopt = '?';
135 /* Keep a global copy of all internal members of getopt_data. */
137 static struct _getopt_data getopt_data;
140 #ifndef __GNU_LIBRARY__
142 /* Avoid depending on library functions or files
143 whose names are inconsistent. */
145 #ifndef getenv
146 extern char *getenv ();
147 #endif
149 #endif /* not __GNU_LIBRARY__ */
151 #ifdef _LIBC
152 /* Stored original parameters.
153 XXX This is no good solution. We should rather copy the args so
154 that we can compare them later. But we must not use malloc(3). */
155 extern int __libc_argc;
156 extern char **__libc_argv;
158 /* Bash 2.0 gives us an environment variable containing flags
159 indicating ARGV elements that should not be considered arguments. */
161 # ifdef USE_NONOPTION_FLAGS
162 /* Defined in getopt_init.c */
163 extern char *__getopt_nonoption_flags;
164 # endif
166 # ifdef USE_NONOPTION_FLAGS
167 # define SWAP_FLAGS(ch1, ch2) \
168 if (d->__nonoption_flags_len > 0) \
170 char __tmp = __getopt_nonoption_flags[ch1]; \
171 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
172 __getopt_nonoption_flags[ch2] = __tmp; \
174 # else
175 # define SWAP_FLAGS(ch1, ch2)
176 # endif
177 #else /* !_LIBC */
178 # define SWAP_FLAGS(ch1, ch2)
179 #endif /* _LIBC */
181 /* Exchange two adjacent subsequences of ARGV.
182 One subsequence is elements [first_nonopt,last_nonopt)
183 which contains all the non-options that have been skipped so far.
184 The other is elements [last_nonopt,optind), which contains all
185 the options processed since those non-options were skipped.
187 `first_nonopt' and `last_nonopt' are relocated so that they describe
188 the new indices of the non-options in ARGV after they are moved. */
190 static void
191 exchange (char **argv, struct _getopt_data *d)
193 int bottom = d->__first_nonopt;
194 int middle = d->__last_nonopt;
195 int top = d->optind;
196 char *tem;
198 /* Exchange the shorter segment with the far end of the longer segment.
199 That puts the shorter segment into the right place.
200 It leaves the longer segment in the right place overall,
201 but it consists of two parts that need to be swapped next. */
203 #if defined _LIBC && defined USE_NONOPTION_FLAGS
204 /* First make sure the handling of the `__getopt_nonoption_flags'
205 string can work normally. Our top argument must be in the range
206 of the string. */
207 if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
209 /* We must extend the array. The user plays games with us and
210 presents new arguments. */
211 char *new_str = malloc (top + 1);
212 if (new_str == NULL)
213 d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
214 else
216 memset (__mempcpy (new_str, __getopt_nonoption_flags,
217 d->__nonoption_flags_max_len),
218 '\0', top + 1 - d->__nonoption_flags_max_len);
219 d->__nonoption_flags_max_len = top + 1;
220 __getopt_nonoption_flags = new_str;
223 #endif
225 while (top > middle && middle > bottom)
227 if (top - middle > middle - bottom)
229 /* Bottom segment is the short one. */
230 int len = middle - bottom;
231 register int i;
233 /* Swap it with the top part of the top segment. */
234 for (i = 0; i < len; i++)
236 tem = argv[bottom + i];
237 argv[bottom + i] = argv[top - (middle - bottom) + i];
238 argv[top - (middle - bottom) + i] = tem;
239 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
241 /* Exclude the moved bottom segment from further swapping. */
242 top -= len;
244 else
246 /* Top segment is the short one. */
247 int len = top - middle;
248 register int i;
250 /* Swap it with the bottom part of the bottom segment. */
251 for (i = 0; i < len; i++)
253 tem = argv[bottom + i];
254 argv[bottom + i] = argv[middle + i];
255 argv[middle + i] = tem;
256 SWAP_FLAGS (bottom + i, middle + i);
258 /* Exclude the moved top segment from further swapping. */
259 bottom += len;
263 /* Update records for the slots the non-options now occupy. */
265 d->__first_nonopt += (d->optind - d->__last_nonopt);
266 d->__last_nonopt = d->optind;
269 /* Initialize the internal data when the first call is made. */
271 static const char *
272 _getopt_initialize (int argc, char *const *argv, const char *optstring,
273 struct _getopt_data *d)
275 /* Start processing options with ARGV-element 1 (since ARGV-element 0
276 is the program name); the sequence of previously skipped
277 non-option ARGV-elements is empty. */
279 d->__first_nonopt = d->__last_nonopt = d->optind;
281 d->__nextchar = NULL;
283 d->__posixly_correct = !!getenv ("POSIXLY_CORRECT");
285 /* Determine how to handle the ordering of options and nonoptions. */
287 if (optstring[0] == '-')
289 d->__ordering = RETURN_IN_ORDER;
290 ++optstring;
292 else if (optstring[0] == '+')
294 d->__ordering = REQUIRE_ORDER;
295 ++optstring;
297 else if (d->__posixly_correct)
298 d->__ordering = REQUIRE_ORDER;
299 else
300 d->__ordering = PERMUTE;
302 #if defined _LIBC && defined USE_NONOPTION_FLAGS
303 if (!d->__posixly_correct
304 && argc == __libc_argc && argv == __libc_argv)
306 if (d->__nonoption_flags_max_len == 0)
308 if (__getopt_nonoption_flags == NULL
309 || __getopt_nonoption_flags[0] == '\0')
310 d->__nonoption_flags_max_len = -1;
311 else
313 const char *orig_str = __getopt_nonoption_flags;
314 int len = d->__nonoption_flags_max_len = strlen (orig_str);
315 if (d->__nonoption_flags_max_len < argc)
316 d->__nonoption_flags_max_len = argc;
317 __getopt_nonoption_flags =
318 (char *) malloc (d->__nonoption_flags_max_len);
319 if (__getopt_nonoption_flags == NULL)
320 d->__nonoption_flags_max_len = -1;
321 else
322 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
323 '\0', d->__nonoption_flags_max_len - len);
326 d->__nonoption_flags_len = d->__nonoption_flags_max_len;
328 else
329 d->__nonoption_flags_len = 0;
330 #endif
332 return optstring;
335 /* Scan elements of ARGV (whose length is ARGC) for option characters
336 given in OPTSTRING.
338 If an element of ARGV starts with '-', and is not exactly "-" or "--",
339 then it is an option element. The characters of this element
340 (aside from the initial '-') are option characters. If `getopt'
341 is called repeatedly, it returns successively each of the option characters
342 from each of the option elements.
344 If `getopt' finds another option character, it returns that character,
345 updating `optind' and `nextchar' so that the next call to `getopt' can
346 resume the scan with the following option character or ARGV-element.
348 If there are no more option characters, `getopt' returns -1.
349 Then `optind' is the index in ARGV of the first ARGV-element
350 that is not an option. (The ARGV-elements have been permuted
351 so that those that are not options now come last.)
353 OPTSTRING is a string containing the legitimate option characters.
354 If an option character is seen that is not listed in OPTSTRING,
355 return '?' after printing an error message. If you set `opterr' to
356 zero, the error message is suppressed but we still return '?'.
358 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
359 so the following text in the same ARGV-element, or the text of the following
360 ARGV-element, is returned in `optarg'. Two colons mean an option that
361 wants an optional arg; if there is text in the current ARGV-element,
362 it is returned in `optarg', otherwise `optarg' is set to zero.
364 If OPTSTRING starts with `-' or `+', it requests different methods of
365 handling the non-option ARGV-elements.
366 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
368 Long-named options begin with `--' instead of `-'.
369 Their names may be abbreviated as long as the abbreviation is unique
370 or is an exact match for some defined option. If they have an
371 argument, it follows the option name in the same ARGV-element, separated
372 from the option name by a `=', or else the in next ARGV-element.
373 When `getopt' finds a long-named option, it returns 0 if that option's
374 `flag' field is nonzero, the value of the option's `val' field
375 if the `flag' field is zero.
377 The elements of ARGV aren't really const, because we permute them.
378 But we pretend they're const in the prototype to be compatible
379 with other systems.
381 LONGOPTS is a vector of `struct option' terminated by an
382 element containing a name which is zero.
384 LONGIND returns the index in LONGOPT of the long-named option found.
385 It is only valid when a long-named option has been found by the most
386 recent call.
388 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
389 long-named options. */
392 _getopt_internal_r (int argc, char *const *argv, const char *optstring,
393 const struct option *longopts, int *longind,
394 int long_only, struct _getopt_data *d)
396 int print_errors = d->opterr;
397 if (optstring[0] == ':')
398 print_errors = 0;
400 if (argc < 1)
401 return -1;
403 d->optarg = NULL;
405 if (d->optind == 0 || !d->__initialized)
407 if (d->optind == 0)
408 d->optind = 1; /* Don't scan ARGV[0], the program name. */
409 optstring = _getopt_initialize (argc, argv, optstring, d);
410 d->__initialized = 1;
413 /* Test whether ARGV[optind] points to a non-option argument.
414 Either it does not have option syntax, or there is an environment flag
415 from the shell indicating it is not an option. The later information
416 is only used when the used in the GNU libc. */
417 #if defined _LIBC && defined USE_NONOPTION_FLAGS
418 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
419 || (d->optind < d->__nonoption_flags_len \
420 && __getopt_nonoption_flags[d->optind] == '1'))
421 #else
422 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
423 #endif
425 if (d->__nextchar == NULL || *d->__nextchar == '\0')
427 /* Advance to the next ARGV-element. */
429 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
430 moved back by the user (who may also have changed the arguments). */
431 if (d->__last_nonopt > d->optind)
432 d->__last_nonopt = d->optind;
433 if (d->__first_nonopt > d->optind)
434 d->__first_nonopt = d->optind;
436 if (d->__ordering == PERMUTE)
438 /* If we have just processed some options following some non-options,
439 exchange them so that the options come first. */
441 if (d->__first_nonopt != d->__last_nonopt
442 && d->__last_nonopt != d->optind)
443 exchange ((char **) argv, d);
444 else if (d->__last_nonopt != d->optind)
445 d->__first_nonopt = d->optind;
447 /* Skip any additional non-options
448 and extend the range of non-options previously skipped. */
450 while (d->optind < argc && NONOPTION_P)
451 d->optind++;
452 d->__last_nonopt = d->optind;
455 /* The special ARGV-element `--' means premature end of options.
456 Skip it like a null option,
457 then exchange with previous non-options as if it were an option,
458 then skip everything else like a non-option. */
460 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
462 d->optind++;
464 if (d->__first_nonopt != d->__last_nonopt
465 && d->__last_nonopt != d->optind)
466 exchange ((char **) argv, d);
467 else if (d->__first_nonopt == d->__last_nonopt)
468 d->__first_nonopt = d->optind;
469 d->__last_nonopt = argc;
471 d->optind = argc;
474 /* If we have done all the ARGV-elements, stop the scan
475 and back over any non-options that we skipped and permuted. */
477 if (d->optind == argc)
479 /* Set the next-arg-index to point at the non-options
480 that we previously skipped, so the caller will digest them. */
481 if (d->__first_nonopt != d->__last_nonopt)
482 d->optind = d->__first_nonopt;
483 return -1;
486 /* If we have come to a non-option and did not permute it,
487 either stop the scan or describe it to the caller and pass it by. */
489 if (NONOPTION_P)
491 if (d->__ordering == REQUIRE_ORDER)
492 return -1;
493 d->optarg = argv[d->optind++];
494 return 1;
497 /* We have found another option-ARGV-element.
498 Skip the initial punctuation. */
500 d->__nextchar = (argv[d->optind] + 1
501 + (longopts != NULL && argv[d->optind][1] == '-'));
504 /* Decode the current option-ARGV-element. */
506 /* Check whether the ARGV-element is a long option.
508 If long_only and the ARGV-element has the form "-f", where f is
509 a valid short option, don't consider it an abbreviated form of
510 a long option that starts with f. Otherwise there would be no
511 way to give the -f short option.
513 On the other hand, if there's a long option "fubar" and
514 the ARGV-element is "-fu", do consider that an abbreviation of
515 the long option, just like "--fu", and not "-f" with arg "u".
517 This distinction seems to be the most useful approach. */
519 if (longopts != NULL
520 && (argv[d->optind][1] == '-'
521 || (long_only && (argv[d->optind][2]
522 || !strchr (optstring, argv[d->optind][1])))))
524 char *nameend;
525 const struct option *p;
526 const struct option *pfound = NULL;
527 int exact = 0;
528 int ambig = 0;
529 int indfound = -1;
530 int option_index;
532 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
533 /* Do nothing. */ ;
535 /* Test all long options for either exact match
536 or abbreviated matches. */
537 for (p = longopts, option_index = 0; p->name; p++, option_index++)
538 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
540 if ((unsigned int) (nameend - d->__nextchar)
541 == (unsigned int) strlen (p->name))
543 /* Exact match found. */
544 pfound = p;
545 indfound = option_index;
546 exact = 1;
547 break;
549 else if (pfound == NULL)
551 /* First nonexact match found. */
552 pfound = p;
553 indfound = option_index;
555 else if (long_only
556 || pfound->has_arg != p->has_arg
557 || pfound->flag != p->flag
558 || pfound->val != p->val)
559 /* Second or later nonexact match found. */
560 ambig = 1;
563 if (ambig && !exact)
565 if (print_errors)
567 #if defined _LIBC && defined USE_IN_LIBIO
568 char *buf;
570 if (__asprintf (&buf, _("%s: option '%s' is ambiguous\n"),
571 argv[0], argv[d->optind]) >= 0)
573 _IO_flockfile (stderr);
575 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
576 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
578 __fxprintf (NULL, "%s", buf);
580 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
581 _IO_funlockfile (stderr);
583 free (buf);
585 #else
586 fprintf (stderr, _("%s: option '%s' is ambiguous\n"),
587 argv[0], argv[d->optind]);
588 #endif
590 d->__nextchar += strlen (d->__nextchar);
591 d->optind++;
592 d->optopt = 0;
593 return '?';
596 if (pfound != NULL)
598 option_index = indfound;
599 d->optind++;
600 if (*nameend)
602 /* Don't test has_arg with >, because some C compilers don't
603 allow it to be used on enums. */
604 if (pfound->has_arg)
605 d->optarg = nameend + 1;
606 else
608 if (print_errors)
610 #if defined _LIBC && defined USE_IN_LIBIO
611 char *buf;
612 int n;
613 #endif
615 if (argv[d->optind - 1][1] == '-')
617 /* --option */
618 #if defined _LIBC && defined USE_IN_LIBIO
619 n = __asprintf (&buf, _("\
620 %s: option '--%s' doesn't allow an argument\n"),
621 argv[0], pfound->name);
622 #else
623 fprintf (stderr, _("\
624 %s: option '--%s' doesn't allow an argument\n"),
625 argv[0], pfound->name);
626 #endif
628 else
630 /* +option or -option */
631 #if defined _LIBC && defined USE_IN_LIBIO
632 n = __asprintf (&buf, _("\
633 %s: option '%c%s' doesn't allow an argument\n"),
634 argv[0], argv[d->optind - 1][0],
635 pfound->name);
636 #else
637 fprintf (stderr, _("\
638 %s: option '%c%s' doesn't allow an argument\n"),
639 argv[0], argv[d->optind - 1][0],
640 pfound->name);
641 #endif
644 #if defined _LIBC && defined USE_IN_LIBIO
645 if (n >= 0)
647 _IO_flockfile (stderr);
649 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
650 ((_IO_FILE *) stderr)->_flags2
651 |= _IO_FLAGS2_NOTCANCEL;
653 __fxprintf (NULL, "%s", buf);
655 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
656 _IO_funlockfile (stderr);
658 free (buf);
660 #endif
663 d->__nextchar += strlen (d->__nextchar);
665 d->optopt = pfound->val;
666 return '?';
669 else if (pfound->has_arg == 1)
671 if (d->optind < argc)
672 d->optarg = argv[d->optind++];
673 else
675 if (print_errors)
677 #if defined _LIBC && defined USE_IN_LIBIO
678 char *buf;
680 if (__asprintf (&buf, _("\
681 %s: option '%s' requires an argument\n"),
682 argv[0], argv[d->optind - 1]) >= 0)
684 _IO_flockfile (stderr);
686 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
687 ((_IO_FILE *) stderr)->_flags2
688 |= _IO_FLAGS2_NOTCANCEL;
690 __fxprintf (NULL, "%s", buf);
692 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
693 _IO_funlockfile (stderr);
695 free (buf);
697 #else
698 fprintf (stderr,
699 _("%s: option '%s' requires an argument\n"),
700 argv[0], argv[d->optind - 1]);
701 #endif
703 d->__nextchar += strlen (d->__nextchar);
704 d->optopt = pfound->val;
705 return optstring[0] == ':' ? ':' : '?';
708 d->__nextchar += strlen (d->__nextchar);
709 if (longind != NULL)
710 *longind = option_index;
711 if (pfound->flag)
713 *(pfound->flag) = pfound->val;
714 return 0;
716 return pfound->val;
719 /* Can't find it as a long option. If this is not getopt_long_only,
720 or the option starts with '--' or is not a valid short
721 option, then it's an error.
722 Otherwise interpret it as a short option. */
723 if (!long_only || argv[d->optind][1] == '-'
724 || strchr (optstring, *d->__nextchar) == NULL)
726 if (print_errors)
728 #if defined _LIBC && defined USE_IN_LIBIO
729 char *buf;
730 int n;
731 #endif
733 if (argv[d->optind][1] == '-')
735 /* --option */
736 #if defined _LIBC && defined USE_IN_LIBIO
737 n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"),
738 argv[0], d->__nextchar);
739 #else
740 fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
741 argv[0], d->__nextchar);
742 #endif
744 else
746 /* +option or -option */
747 #if defined _LIBC && defined USE_IN_LIBIO
748 n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"),
749 argv[0], argv[d->optind][0], d->__nextchar);
750 #else
751 fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
752 argv[0], argv[d->optind][0], d->__nextchar);
753 #endif
756 #if defined _LIBC && defined USE_IN_LIBIO
757 if (n >= 0)
759 _IO_flockfile (stderr);
761 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
762 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
764 __fxprintf (NULL, "%s", buf);
766 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
767 _IO_funlockfile (stderr);
769 free (buf);
771 #endif
773 d->__nextchar = (char *) "";
774 d->optind++;
775 d->optopt = 0;
776 return '?';
780 /* Look at and handle the next short option-character. */
783 char c = *d->__nextchar++;
784 char *temp = strchr (optstring, c);
786 /* Increment `optind' when we start to process its last character. */
787 if (*d->__nextchar == '\0')
788 ++d->optind;
790 if (temp == NULL || c == ':')
792 if (print_errors)
794 #if defined _LIBC && defined USE_IN_LIBIO
795 char *buf;
796 int n;
797 #endif
799 #if defined _LIBC && defined USE_IN_LIBIO
800 n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"),
801 argv[0], c);
802 #else
803 fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
804 #endif
806 #if defined _LIBC && defined USE_IN_LIBIO
807 if (n >= 0)
809 _IO_flockfile (stderr);
811 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
812 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
814 __fxprintf (NULL, "%s", buf);
816 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
817 _IO_funlockfile (stderr);
819 free (buf);
821 #endif
823 d->optopt = c;
824 return '?';
826 /* Convenience. Treat POSIX -W foo same as long option --foo */
827 if (temp[0] == 'W' && temp[1] == ';')
829 char *nameend;
830 const struct option *p;
831 const struct option *pfound = NULL;
832 int exact = 0;
833 int ambig = 0;
834 int indfound = 0;
835 int option_index;
837 /* This is an option that requires an argument. */
838 if (*d->__nextchar != '\0')
840 d->optarg = d->__nextchar;
841 /* If we end this ARGV-element by taking the rest as an arg,
842 we must advance to the next element now. */
843 d->optind++;
845 else if (d->optind == argc)
847 if (print_errors)
849 #if defined _LIBC && defined USE_IN_LIBIO
850 char *buf;
852 if (__asprintf (&buf,
853 _("%s: option requires an argument -- '%c'\n"),
854 argv[0], c) >= 0)
856 _IO_flockfile (stderr);
858 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
859 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
861 __fxprintf (NULL, "%s", buf);
863 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
864 _IO_funlockfile (stderr);
866 free (buf);
868 #else
869 fprintf (stderr,
870 _("%s: option requires an argument -- '%c'\n"),
871 argv[0], c);
872 #endif
874 d->optopt = c;
875 if (optstring[0] == ':')
876 c = ':';
877 else
878 c = '?';
879 return c;
881 else
882 /* We already incremented `d->optind' once;
883 increment it again when taking next ARGV-elt as argument. */
884 d->optarg = argv[d->optind++];
886 /* optarg is now the argument, see if it's in the
887 table of longopts. */
889 for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
890 nameend++)
891 /* Do nothing. */ ;
893 /* Test all long options for either exact match
894 or abbreviated matches. */
895 for (p = longopts, option_index = 0; p->name; p++, option_index++)
896 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
898 if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
900 /* Exact match found. */
901 pfound = p;
902 indfound = option_index;
903 exact = 1;
904 break;
906 else if (pfound == NULL)
908 /* First nonexact match found. */
909 pfound = p;
910 indfound = option_index;
912 else
913 /* Second or later nonexact match found. */
914 ambig = 1;
916 if (ambig && !exact)
918 if (print_errors)
920 #if defined _LIBC && defined USE_IN_LIBIO
921 char *buf;
923 if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"),
924 argv[0], argv[d->optind]) >= 0)
926 _IO_flockfile (stderr);
928 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
929 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
931 __fxprintf (NULL, "%s", buf);
933 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
934 _IO_funlockfile (stderr);
936 free (buf);
938 #else
939 fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
940 argv[0], argv[d->optind]);
941 #endif
943 d->__nextchar += strlen (d->__nextchar);
944 d->optind++;
945 return '?';
947 if (pfound != NULL)
949 option_index = indfound;
950 if (*nameend)
952 /* Don't test has_arg with >, because some C compilers don't
953 allow it to be used on enums. */
954 if (pfound->has_arg)
955 d->optarg = nameend + 1;
956 else
958 if (print_errors)
960 #if defined _LIBC && defined USE_IN_LIBIO
961 char *buf;
963 if (__asprintf (&buf, _("\
964 %s: option '-W %s' doesn't allow an argument\n"),
965 argv[0], pfound->name) >= 0)
967 _IO_flockfile (stderr);
969 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
970 ((_IO_FILE *) stderr)->_flags2
971 |= _IO_FLAGS2_NOTCANCEL;
973 __fxprintf (NULL, "%s", buf);
975 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
976 _IO_funlockfile (stderr);
978 free (buf);
980 #else
981 fprintf (stderr, _("\
982 %s: option '-W %s' doesn't allow an argument\n"),
983 argv[0], pfound->name);
984 #endif
987 d->__nextchar += strlen (d->__nextchar);
988 return '?';
991 else if (pfound->has_arg == 1)
993 if (d->optind < argc)
994 d->optarg = argv[d->optind++];
995 else
997 if (print_errors)
999 #if defined _LIBC && defined USE_IN_LIBIO
1000 char *buf;
1002 if (__asprintf (&buf, _("\
1003 %s: option '%s' requires an argument\n"),
1004 argv[0], argv[d->optind - 1]) >= 0)
1006 _IO_flockfile (stderr);
1008 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1009 ((_IO_FILE *) stderr)->_flags2
1010 |= _IO_FLAGS2_NOTCANCEL;
1012 __fxprintf (NULL, "%s", buf);
1014 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1015 _IO_funlockfile (stderr);
1017 free (buf);
1019 #else
1020 fprintf (stderr,
1021 _("%s: option '%s' requires an argument\n"),
1022 argv[0], argv[d->optind - 1]);
1023 #endif
1025 d->__nextchar += strlen (d->__nextchar);
1026 return optstring[0] == ':' ? ':' : '?';
1029 d->__nextchar += strlen (d->__nextchar);
1030 if (longind != NULL)
1031 *longind = option_index;
1032 if (pfound->flag)
1034 *(pfound->flag) = pfound->val;
1035 return 0;
1037 return pfound->val;
1039 d->__nextchar = NULL;
1040 return 'W'; /* Let the application handle it. */
1042 if (temp[1] == ':')
1044 if (temp[2] == ':')
1046 /* This is an option that accepts an argument optionally. */
1047 if (*d->__nextchar != '\0')
1049 d->optarg = d->__nextchar;
1050 d->optind++;
1052 else
1053 d->optarg = NULL;
1054 d->__nextchar = NULL;
1056 else
1058 /* This is an option that requires an argument. */
1059 if (*d->__nextchar != '\0')
1061 d->optarg = d->__nextchar;
1062 /* If we end this ARGV-element by taking the rest as an arg,
1063 we must advance to the next element now. */
1064 d->optind++;
1066 else if (d->optind == argc)
1068 if (print_errors)
1070 #if defined _LIBC && defined USE_IN_LIBIO
1071 char *buf;
1073 if (__asprintf (&buf, _("\
1074 %s: option requires an argument -- '%c'\n"),
1075 argv[0], c) >= 0)
1077 _IO_flockfile (stderr);
1079 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1080 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1082 __fxprintf (NULL, "%s", buf);
1084 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1085 _IO_funlockfile (stderr);
1087 free (buf);
1089 #else
1090 fprintf (stderr,
1091 _("%s: option requires an argument -- '%c'\n"),
1092 argv[0], c);
1093 #endif
1095 d->optopt = c;
1096 if (optstring[0] == ':')
1097 c = ':';
1098 else
1099 c = '?';
1101 else
1102 /* We already incremented `optind' once;
1103 increment it again when taking next ARGV-elt as argument. */
1104 d->optarg = argv[d->optind++];
1105 d->__nextchar = NULL;
1108 return c;
1113 _getopt_internal (int argc, char *const *argv, const char *optstring,
1114 const struct option *longopts, int *longind, int long_only)
1116 int result;
1118 getopt_data.optind = optind;
1119 getopt_data.opterr = opterr;
1121 result = _getopt_internal_r (argc, argv, optstring, longopts,
1122 longind, long_only, &getopt_data);
1124 optind = getopt_data.optind;
1125 optarg = getopt_data.optarg;
1126 optopt = getopt_data.optopt;
1128 return result;
1132 getopt (int argc, char *const *argv, const char *optstring)
1134 return _getopt_internal (argc, argv, optstring,
1135 (const struct option *) 0,
1136 (int *) 0,
1140 #endif /* Not ELIDE_CODE. */
1142 #ifdef TEST
1144 /* Compile with -DTEST to make an executable for use in testing
1145 the above definition of `getopt'. */
1148 main (int argc, char **argv)
1150 int c;
1151 int digit_optind = 0;
1153 while (1)
1155 int this_option_optind = optind ? optind : 1;
1157 c = getopt (argc, argv, "abc:d:0123456789");
1158 if (c == -1)
1159 break;
1161 switch (c)
1163 case '0':
1164 case '1':
1165 case '2':
1166 case '3':
1167 case '4':
1168 case '5':
1169 case '6':
1170 case '7':
1171 case '8':
1172 case '9':
1173 if (digit_optind != 0 && digit_optind != this_option_optind)
1174 printf ("digits occur in two different argv-elements.\n");
1175 digit_optind = this_option_optind;
1176 printf ("option %c\n", c);
1177 break;
1179 case 'a':
1180 printf ("option a\n");
1181 break;
1183 case 'b':
1184 printf ("option b\n");
1185 break;
1187 case 'c':
1188 printf ("option c with value '%s'\n", optarg);
1189 break;
1191 case '?':
1192 break;
1194 default:
1195 printf ("?? getopt returned character code 0%o ??\n", c);
1199 if (optind < argc)
1201 printf ("non-option ARGV-elements: ");
1202 while (optind < argc)
1203 printf ("%s ", argv[optind++]);
1204 printf ("\n");
1207 exit (0);
1210 #endif /* TEST */