* lisp/generic-x.el (etc-fstab-generic-mode): Add ext4, sysfs keywords.
[emacs.git] / lib / getopt.c
blobc8b301363f1f4b664b6ed2dd4e3c82a841734890
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, 2006, 2008-2011 Free Software
6 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 General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) 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 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #ifndef _LIBC
23 # include <config.h>
24 #endif
26 #include "getopt.h"
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
33 #ifdef _LIBC
34 # include <libintl.h>
35 #else
36 # include "gettext.h"
37 # define _(msgid) gettext (msgid)
38 #endif
40 #if defined _LIBC && defined USE_IN_LIBIO
41 # include <wchar.h>
42 #endif
44 /* This version of `getopt' appears to the caller like standard Unix `getopt'
45 but it behaves differently for the user, since it allows the user
46 to intersperse the options with the other arguments.
48 As `getopt_long' works, it permutes the elements of ARGV so that,
49 when it is done, all the options precede everything else. Thus
50 all application programs are extended to handle flexible argument order.
52 Using `getopt' or setting the environment variable POSIXLY_CORRECT
53 disables permutation.
54 Then the behavior is completely standard.
56 GNU application programs can use a third alternative mode in which
57 they can distinguish the relative order of options and other arguments. */
59 #include "getopt_int.h"
61 /* For communication from `getopt' to the caller.
62 When `getopt' finds an option that takes an argument,
63 the argument value is returned here.
64 Also, when `ordering' is RETURN_IN_ORDER,
65 each non-option ARGV-element is returned here. */
67 char *optarg;
69 /* Index in ARGV of the next element to be scanned.
70 This is used for communication to and from the caller
71 and for communication between successive calls to `getopt'.
73 On entry to `getopt', zero means this is the first call; initialize.
75 When `getopt' returns -1, this is the index of the first of the
76 non-option elements that the caller should itself scan.
78 Otherwise, `optind' communicates from one call to the next
79 how much of ARGV has been scanned so far. */
81 /* 1003.2 says this must be 1 before any call. */
82 int optind = 1;
84 /* Callers store zero here to inhibit the error message
85 for unrecognized options. */
87 int opterr = 1;
89 /* Set to an option character which was unrecognized.
90 This must be initialized on some systems to avoid linking in the
91 system's own getopt implementation. */
93 int optopt = '?';
95 /* Keep a global copy of all internal members of getopt_data. */
97 static struct _getopt_data getopt_data;
100 #if defined HAVE_DECL_GETENV && !HAVE_DECL_GETENV
101 extern char *getenv ();
102 #endif
104 #ifdef _LIBC
105 /* Stored original parameters.
106 XXX This is no good solution. We should rather copy the args so
107 that we can compare them later. But we must not use malloc(3). */
108 extern int __libc_argc;
109 extern char **__libc_argv;
111 /* Bash 2.0 gives us an environment variable containing flags
112 indicating ARGV elements that should not be considered arguments. */
114 # ifdef USE_NONOPTION_FLAGS
115 /* Defined in getopt_init.c */
116 extern char *__getopt_nonoption_flags;
117 # endif
119 # ifdef USE_NONOPTION_FLAGS
120 # define SWAP_FLAGS(ch1, ch2) \
121 if (d->__nonoption_flags_len > 0) \
123 char __tmp = __getopt_nonoption_flags[ch1]; \
124 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
125 __getopt_nonoption_flags[ch2] = __tmp; \
127 # else
128 # define SWAP_FLAGS(ch1, ch2)
129 # endif
130 #else /* !_LIBC */
131 # define SWAP_FLAGS(ch1, ch2)
132 #endif /* _LIBC */
134 /* Exchange two adjacent subsequences of ARGV.
135 One subsequence is elements [first_nonopt,last_nonopt)
136 which contains all the non-options that have been skipped so far.
137 The other is elements [last_nonopt,optind), which contains all
138 the options processed since those non-options were skipped.
140 `first_nonopt' and `last_nonopt' are relocated so that they describe
141 the new indices of the non-options in ARGV after they are moved. */
143 static void
144 exchange (char **argv, struct _getopt_data *d)
146 int bottom = d->__first_nonopt;
147 int middle = d->__last_nonopt;
148 int top = d->optind;
149 char *tem;
151 /* Exchange the shorter segment with the far end of the longer segment.
152 That puts the shorter segment into the right place.
153 It leaves the longer segment in the right place overall,
154 but it consists of two parts that need to be swapped next. */
156 #if defined _LIBC && defined USE_NONOPTION_FLAGS
157 /* First make sure the handling of the `__getopt_nonoption_flags'
158 string can work normally. Our top argument must be in the range
159 of the string. */
160 if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
162 /* We must extend the array. The user plays games with us and
163 presents new arguments. */
164 char *new_str = malloc (top + 1);
165 if (new_str == NULL)
166 d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
167 else
169 memset (__mempcpy (new_str, __getopt_nonoption_flags,
170 d->__nonoption_flags_max_len),
171 '\0', top + 1 - d->__nonoption_flags_max_len);
172 d->__nonoption_flags_max_len = top + 1;
173 __getopt_nonoption_flags = new_str;
176 #endif
178 while (top > middle && middle > bottom)
180 if (top - middle > middle - bottom)
182 /* Bottom segment is the short one. */
183 int len = middle - bottom;
184 register int i;
186 /* Swap it with the top part of the top segment. */
187 for (i = 0; i < len; i++)
189 tem = argv[bottom + i];
190 argv[bottom + i] = argv[top - (middle - bottom) + i];
191 argv[top - (middle - bottom) + i] = tem;
192 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
194 /* Exclude the moved bottom segment from further swapping. */
195 top -= len;
197 else
199 /* Top segment is the short one. */
200 int len = top - middle;
201 register int i;
203 /* Swap it with the bottom part of the bottom segment. */
204 for (i = 0; i < len; i++)
206 tem = argv[bottom + i];
207 argv[bottom + i] = argv[middle + i];
208 argv[middle + i] = tem;
209 SWAP_FLAGS (bottom + i, middle + i);
211 /* Exclude the moved top segment from further swapping. */
212 bottom += len;
216 /* Update records for the slots the non-options now occupy. */
218 d->__first_nonopt += (d->optind - d->__last_nonopt);
219 d->__last_nonopt = d->optind;
222 /* Initialize the internal data when the first call is made. */
224 static const char *
225 _getopt_initialize (int argc _GL_UNUSED,
226 char **argv _GL_UNUSED, const char *optstring,
227 struct _getopt_data *d, int posixly_correct)
229 /* Start processing options with ARGV-element 1 (since ARGV-element 0
230 is the program name); the sequence of previously skipped
231 non-option ARGV-elements is empty. */
233 d->__first_nonopt = d->__last_nonopt = d->optind;
235 d->__nextchar = NULL;
237 d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT");
239 /* Determine how to handle the ordering of options and nonoptions. */
241 if (optstring[0] == '-')
243 d->__ordering = RETURN_IN_ORDER;
244 ++optstring;
246 else if (optstring[0] == '+')
248 d->__ordering = REQUIRE_ORDER;
249 ++optstring;
251 else if (d->__posixly_correct)
252 d->__ordering = REQUIRE_ORDER;
253 else
254 d->__ordering = PERMUTE;
256 #if defined _LIBC && defined USE_NONOPTION_FLAGS
257 if (!d->__posixly_correct
258 && argc == __libc_argc && argv == __libc_argv)
260 if (d->__nonoption_flags_max_len == 0)
262 if (__getopt_nonoption_flags == NULL
263 || __getopt_nonoption_flags[0] == '\0')
264 d->__nonoption_flags_max_len = -1;
265 else
267 const char *orig_str = __getopt_nonoption_flags;
268 int len = d->__nonoption_flags_max_len = strlen (orig_str);
269 if (d->__nonoption_flags_max_len < argc)
270 d->__nonoption_flags_max_len = argc;
271 __getopt_nonoption_flags =
272 (char *) malloc (d->__nonoption_flags_max_len);
273 if (__getopt_nonoption_flags == NULL)
274 d->__nonoption_flags_max_len = -1;
275 else
276 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
277 '\0', d->__nonoption_flags_max_len - len);
280 d->__nonoption_flags_len = d->__nonoption_flags_max_len;
282 else
283 d->__nonoption_flags_len = 0;
284 #endif
286 return optstring;
289 /* Scan elements of ARGV (whose length is ARGC) for option characters
290 given in OPTSTRING.
292 If an element of ARGV starts with '-', and is not exactly "-" or "--",
293 then it is an option element. The characters of this element
294 (aside from the initial '-') are option characters. If `getopt'
295 is called repeatedly, it returns successively each of the option characters
296 from each of the option elements.
298 If `getopt' finds another option character, it returns that character,
299 updating `optind' and `nextchar' so that the next call to `getopt' can
300 resume the scan with the following option character or ARGV-element.
302 If there are no more option characters, `getopt' returns -1.
303 Then `optind' is the index in ARGV of the first ARGV-element
304 that is not an option. (The ARGV-elements have been permuted
305 so that those that are not options now come last.)
307 OPTSTRING is a string containing the legitimate option characters.
308 If an option character is seen that is not listed in OPTSTRING,
309 return '?' after printing an error message. If you set `opterr' to
310 zero, the error message is suppressed but we still return '?'.
312 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
313 so the following text in the same ARGV-element, or the text of the following
314 ARGV-element, is returned in `optarg'. Two colons mean an option that
315 wants an optional arg; if there is text in the current ARGV-element,
316 it is returned in `optarg', otherwise `optarg' is set to zero.
318 If OPTSTRING starts with `-' or `+', it requests different methods of
319 handling the non-option ARGV-elements.
320 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
322 Long-named options begin with `--' instead of `-'.
323 Their names may be abbreviated as long as the abbreviation is unique
324 or is an exact match for some defined option. If they have an
325 argument, it follows the option name in the same ARGV-element, separated
326 from the option name by a `=', or else the in next ARGV-element.
327 When `getopt' finds a long-named option, it returns 0 if that option's
328 `flag' field is nonzero, the value of the option's `val' field
329 if the `flag' field is zero.
331 The elements of ARGV aren't really const, because we permute them.
332 But we pretend they're const in the prototype to be compatible
333 with other systems.
335 LONGOPTS is a vector of `struct option' terminated by an
336 element containing a name which is zero.
338 LONGIND returns the index in LONGOPT of the long-named option found.
339 It is only valid when a long-named option has been found by the most
340 recent call.
342 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
343 long-named options. */
346 _getopt_internal_r (int argc, char **argv, const char *optstring,
347 const struct option *longopts, int *longind,
348 int long_only, struct _getopt_data *d, int posixly_correct)
350 int print_errors = d->opterr;
352 if (argc < 1)
353 return -1;
355 d->optarg = NULL;
357 if (d->optind == 0 || !d->__initialized)
359 if (d->optind == 0)
360 d->optind = 1; /* Don't scan ARGV[0], the program name. */
361 optstring = _getopt_initialize (argc, argv, optstring, d,
362 posixly_correct);
363 d->__initialized = 1;
365 else if (optstring[0] == '-' || optstring[0] == '+')
366 optstring++;
367 if (optstring[0] == ':')
368 print_errors = 0;
370 /* Test whether ARGV[optind] points to a non-option argument.
371 Either it does not have option syntax, or there is an environment flag
372 from the shell indicating it is not an option. The later information
373 is only used when the used in the GNU libc. */
374 #if defined _LIBC && defined USE_NONOPTION_FLAGS
375 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
376 || (d->optind < d->__nonoption_flags_len \
377 && __getopt_nonoption_flags[d->optind] == '1'))
378 #else
379 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
380 #endif
382 if (d->__nextchar == NULL || *d->__nextchar == '\0')
384 /* Advance to the next ARGV-element. */
386 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
387 moved back by the user (who may also have changed the arguments). */
388 if (d->__last_nonopt > d->optind)
389 d->__last_nonopt = d->optind;
390 if (d->__first_nonopt > d->optind)
391 d->__first_nonopt = d->optind;
393 if (d->__ordering == PERMUTE)
395 /* If we have just processed some options following some non-options,
396 exchange them so that the options come first. */
398 if (d->__first_nonopt != d->__last_nonopt
399 && d->__last_nonopt != d->optind)
400 exchange ((char **) argv, d);
401 else if (d->__last_nonopt != d->optind)
402 d->__first_nonopt = d->optind;
404 /* Skip any additional non-options
405 and extend the range of non-options previously skipped. */
407 while (d->optind < argc && NONOPTION_P)
408 d->optind++;
409 d->__last_nonopt = d->optind;
412 /* The special ARGV-element `--' means premature end of options.
413 Skip it like a null option,
414 then exchange with previous non-options as if it were an option,
415 then skip everything else like a non-option. */
417 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
419 d->optind++;
421 if (d->__first_nonopt != d->__last_nonopt
422 && d->__last_nonopt != d->optind)
423 exchange ((char **) argv, d);
424 else if (d->__first_nonopt == d->__last_nonopt)
425 d->__first_nonopt = d->optind;
426 d->__last_nonopt = argc;
428 d->optind = argc;
431 /* If we have done all the ARGV-elements, stop the scan
432 and back over any non-options that we skipped and permuted. */
434 if (d->optind == argc)
436 /* Set the next-arg-index to point at the non-options
437 that we previously skipped, so the caller will digest them. */
438 if (d->__first_nonopt != d->__last_nonopt)
439 d->optind = d->__first_nonopt;
440 return -1;
443 /* If we have come to a non-option and did not permute it,
444 either stop the scan or describe it to the caller and pass it by. */
446 if (NONOPTION_P)
448 if (d->__ordering == REQUIRE_ORDER)
449 return -1;
450 d->optarg = argv[d->optind++];
451 return 1;
454 /* We have found another option-ARGV-element.
455 Skip the initial punctuation. */
457 d->__nextchar = (argv[d->optind] + 1
458 + (longopts != NULL && argv[d->optind][1] == '-'));
461 /* Decode the current option-ARGV-element. */
463 /* Check whether the ARGV-element is a long option.
465 If long_only and the ARGV-element has the form "-f", where f is
466 a valid short option, don't consider it an abbreviated form of
467 a long option that starts with f. Otherwise there would be no
468 way to give the -f short option.
470 On the other hand, if there's a long option "fubar" and
471 the ARGV-element is "-fu", do consider that an abbreviation of
472 the long option, just like "--fu", and not "-f" with arg "u".
474 This distinction seems to be the most useful approach. */
476 if (longopts != NULL
477 && (argv[d->optind][1] == '-'
478 || (long_only && (argv[d->optind][2]
479 || !strchr (optstring, argv[d->optind][1])))))
481 char *nameend;
482 const struct option *p;
483 const struct option *pfound = NULL;
484 int exact = 0;
485 int ambig = 0;
486 int indfound = -1;
487 int option_index;
489 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
490 /* Do nothing. */ ;
492 /* Test all long options for either exact match
493 or abbreviated matches. */
494 for (p = longopts, option_index = 0; p->name; p++, option_index++)
495 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
497 if ((unsigned int) (nameend - d->__nextchar)
498 == (unsigned int) strlen (p->name))
500 /* Exact match found. */
501 pfound = p;
502 indfound = option_index;
503 exact = 1;
504 break;
506 else if (pfound == NULL)
508 /* First nonexact match found. */
509 pfound = p;
510 indfound = option_index;
512 else if (long_only
513 || pfound->has_arg != p->has_arg
514 || pfound->flag != p->flag
515 || pfound->val != p->val)
516 /* Second or later nonexact match found. */
517 ambig = 1;
520 if (ambig && !exact)
522 if (print_errors)
524 #if defined _LIBC && defined USE_IN_LIBIO
525 char *buf;
527 if (__asprintf (&buf, _("%s: option '%s' is ambiguous\n"),
528 argv[0], argv[d->optind]) >= 0)
530 _IO_flockfile (stderr);
532 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
533 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
535 __fxprintf (NULL, "%s", buf);
537 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
538 _IO_funlockfile (stderr);
540 free (buf);
542 #else
543 fprintf (stderr, _("%s: option '%s' is ambiguous\n"),
544 argv[0], argv[d->optind]);
545 #endif
547 d->__nextchar += strlen (d->__nextchar);
548 d->optind++;
549 d->optopt = 0;
550 return '?';
553 if (pfound != NULL)
555 option_index = indfound;
556 d->optind++;
557 if (*nameend)
559 /* Don't test has_arg with >, because some C compilers don't
560 allow it to be used on enums. */
561 if (pfound->has_arg)
562 d->optarg = nameend + 1;
563 else
565 if (print_errors)
567 #if defined _LIBC && defined USE_IN_LIBIO
568 char *buf;
569 int n;
570 #endif
572 if (argv[d->optind - 1][1] == '-')
574 /* --option */
575 #if defined _LIBC && defined USE_IN_LIBIO
576 n = __asprintf (&buf, _("\
577 %s: option '--%s' doesn't allow an argument\n"),
578 argv[0], pfound->name);
579 #else
580 fprintf (stderr, _("\
581 %s: option '--%s' doesn't allow an argument\n"),
582 argv[0], pfound->name);
583 #endif
585 else
587 /* +option or -option */
588 #if defined _LIBC && defined USE_IN_LIBIO
589 n = __asprintf (&buf, _("\
590 %s: option '%c%s' doesn't allow an argument\n"),
591 argv[0], argv[d->optind - 1][0],
592 pfound->name);
593 #else
594 fprintf (stderr, _("\
595 %s: option '%c%s' doesn't allow an argument\n"),
596 argv[0], argv[d->optind - 1][0],
597 pfound->name);
598 #endif
601 #if defined _LIBC && defined USE_IN_LIBIO
602 if (n >= 0)
604 _IO_flockfile (stderr);
606 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
607 ((_IO_FILE *) stderr)->_flags2
608 |= _IO_FLAGS2_NOTCANCEL;
610 __fxprintf (NULL, "%s", buf);
612 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
613 _IO_funlockfile (stderr);
615 free (buf);
617 #endif
620 d->__nextchar += strlen (d->__nextchar);
622 d->optopt = pfound->val;
623 return '?';
626 else if (pfound->has_arg == 1)
628 if (d->optind < argc)
629 d->optarg = argv[d->optind++];
630 else
632 if (print_errors)
634 #if defined _LIBC && defined USE_IN_LIBIO
635 char *buf;
637 if (__asprintf (&buf, _("\
638 %s: option '--%s' requires an argument\n"),
639 argv[0], pfound->name) >= 0)
641 _IO_flockfile (stderr);
643 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
644 ((_IO_FILE *) stderr)->_flags2
645 |= _IO_FLAGS2_NOTCANCEL;
647 __fxprintf (NULL, "%s", buf);
649 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
650 _IO_funlockfile (stderr);
652 free (buf);
654 #else
655 fprintf (stderr,
656 _("%s: option '--%s' requires an argument\n"),
657 argv[0], pfound->name);
658 #endif
660 d->__nextchar += strlen (d->__nextchar);
661 d->optopt = pfound->val;
662 return optstring[0] == ':' ? ':' : '?';
665 d->__nextchar += strlen (d->__nextchar);
666 if (longind != NULL)
667 *longind = option_index;
668 if (pfound->flag)
670 *(pfound->flag) = pfound->val;
671 return 0;
673 return pfound->val;
676 /* Can't find it as a long option. If this is not getopt_long_only,
677 or the option starts with '--' or is not a valid short
678 option, then it's an error.
679 Otherwise interpret it as a short option. */
680 if (!long_only || argv[d->optind][1] == '-'
681 || strchr (optstring, *d->__nextchar) == NULL)
683 if (print_errors)
685 #if defined _LIBC && defined USE_IN_LIBIO
686 char *buf;
687 int n;
688 #endif
690 if (argv[d->optind][1] == '-')
692 /* --option */
693 #if defined _LIBC && defined USE_IN_LIBIO
694 n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"),
695 argv[0], d->__nextchar);
696 #else
697 fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
698 argv[0], d->__nextchar);
699 #endif
701 else
703 /* +option or -option */
704 #if defined _LIBC && defined USE_IN_LIBIO
705 n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"),
706 argv[0], argv[d->optind][0], d->__nextchar);
707 #else
708 fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
709 argv[0], argv[d->optind][0], d->__nextchar);
710 #endif
713 #if defined _LIBC && defined USE_IN_LIBIO
714 if (n >= 0)
716 _IO_flockfile (stderr);
718 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
719 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
721 __fxprintf (NULL, "%s", buf);
723 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
724 _IO_funlockfile (stderr);
726 free (buf);
728 #endif
730 d->__nextchar = (char *) "";
731 d->optind++;
732 d->optopt = 0;
733 return '?';
737 /* Look at and handle the next short option-character. */
740 char c = *d->__nextchar++;
741 const char *temp = strchr (optstring, c);
743 /* Increment `optind' when we start to process its last character. */
744 if (*d->__nextchar == '\0')
745 ++d->optind;
747 if (temp == NULL || c == ':' || c == ';')
749 if (print_errors)
751 #if defined _LIBC && defined USE_IN_LIBIO
752 char *buf;
753 int n;
754 #endif
756 #if defined _LIBC && defined USE_IN_LIBIO
757 n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"),
758 argv[0], c);
759 #else
760 fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
761 #endif
763 #if defined _LIBC && defined USE_IN_LIBIO
764 if (n >= 0)
766 _IO_flockfile (stderr);
768 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
769 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
771 __fxprintf (NULL, "%s", buf);
773 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
774 _IO_funlockfile (stderr);
776 free (buf);
778 #endif
780 d->optopt = c;
781 return '?';
783 /* Convenience. Treat POSIX -W foo same as long option --foo */
784 if (temp[0] == 'W' && temp[1] == ';')
786 char *nameend;
787 const struct option *p;
788 const struct option *pfound = NULL;
789 int exact = 0;
790 int ambig = 0;
791 int indfound = 0;
792 int option_index;
794 /* This is an option that requires an argument. */
795 if (*d->__nextchar != '\0')
797 d->optarg = d->__nextchar;
798 /* If we end this ARGV-element by taking the rest as an arg,
799 we must advance to the next element now. */
800 d->optind++;
802 else if (d->optind == argc)
804 if (print_errors)
806 #if defined _LIBC && defined USE_IN_LIBIO
807 char *buf;
809 if (__asprintf (&buf,
810 _("%s: option requires an argument -- '%c'\n"),
811 argv[0], c) >= 0)
813 _IO_flockfile (stderr);
815 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
816 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
818 __fxprintf (NULL, "%s", buf);
820 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
821 _IO_funlockfile (stderr);
823 free (buf);
825 #else
826 fprintf (stderr,
827 _("%s: option requires an argument -- '%c'\n"),
828 argv[0], c);
829 #endif
831 d->optopt = c;
832 if (optstring[0] == ':')
833 c = ':';
834 else
835 c = '?';
836 return c;
838 else
839 /* We already incremented `d->optind' once;
840 increment it again when taking next ARGV-elt as argument. */
841 d->optarg = argv[d->optind++];
843 /* optarg is now the argument, see if it's in the
844 table of longopts. */
846 for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
847 nameend++)
848 /* Do nothing. */ ;
850 /* Test all long options for either exact match
851 or abbreviated matches. */
852 for (p = longopts, option_index = 0; p->name; p++, option_index++)
853 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
855 if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
857 /* Exact match found. */
858 pfound = p;
859 indfound = option_index;
860 exact = 1;
861 break;
863 else if (pfound == NULL)
865 /* First nonexact match found. */
866 pfound = p;
867 indfound = option_index;
869 else if (long_only
870 || pfound->has_arg != p->has_arg
871 || pfound->flag != p->flag
872 || pfound->val != p->val)
873 /* Second or later nonexact match found. */
874 ambig = 1;
876 if (ambig && !exact)
878 if (print_errors)
880 #if defined _LIBC && defined USE_IN_LIBIO
881 char *buf;
883 if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"),
884 argv[0], d->optarg) >= 0)
886 _IO_flockfile (stderr);
888 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
889 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
891 __fxprintf (NULL, "%s", buf);
893 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
894 _IO_funlockfile (stderr);
896 free (buf);
898 #else
899 fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
900 argv[0], d->optarg);
901 #endif
903 d->__nextchar += strlen (d->__nextchar);
904 d->optind++;
905 return '?';
907 if (pfound != NULL)
909 option_index = indfound;
910 if (*nameend)
912 /* Don't test has_arg with >, because some C compilers don't
913 allow it to be used on enums. */
914 if (pfound->has_arg)
915 d->optarg = nameend + 1;
916 else
918 if (print_errors)
920 #if defined _LIBC && defined USE_IN_LIBIO
921 char *buf;
923 if (__asprintf (&buf, _("\
924 %s: option '-W %s' doesn't allow an argument\n"),
925 argv[0], pfound->name) >= 0)
927 _IO_flockfile (stderr);
929 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
930 ((_IO_FILE *) stderr)->_flags2
931 |= _IO_FLAGS2_NOTCANCEL;
933 __fxprintf (NULL, "%s", buf);
935 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
936 _IO_funlockfile (stderr);
938 free (buf);
940 #else
941 fprintf (stderr, _("\
942 %s: option '-W %s' doesn't allow an argument\n"),
943 argv[0], pfound->name);
944 #endif
947 d->__nextchar += strlen (d->__nextchar);
948 return '?';
951 else if (pfound->has_arg == 1)
953 if (d->optind < argc)
954 d->optarg = argv[d->optind++];
955 else
957 if (print_errors)
959 #if defined _LIBC && defined USE_IN_LIBIO
960 char *buf;
962 if (__asprintf (&buf, _("\
963 %s: option '-W %s' requires an argument\n"),
964 argv[0], pfound->name) >= 0)
966 _IO_flockfile (stderr);
968 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
969 ((_IO_FILE *) stderr)->_flags2
970 |= _IO_FLAGS2_NOTCANCEL;
972 __fxprintf (NULL, "%s", buf);
974 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
975 _IO_funlockfile (stderr);
977 free (buf);
979 #else
980 fprintf (stderr, _("\
981 %s: option '-W %s' requires an argument\n"),
982 argv[0], pfound->name);
983 #endif
985 d->__nextchar += strlen (d->__nextchar);
986 return optstring[0] == ':' ? ':' : '?';
989 else
990 d->optarg = NULL;
991 d->__nextchar += strlen (d->__nextchar);
992 if (longind != NULL)
993 *longind = option_index;
994 if (pfound->flag)
996 *(pfound->flag) = pfound->val;
997 return 0;
999 return pfound->val;
1001 d->__nextchar = NULL;
1002 return 'W'; /* Let the application handle it. */
1004 if (temp[1] == ':')
1006 if (temp[2] == ':')
1008 /* This is an option that accepts an argument optionally. */
1009 if (*d->__nextchar != '\0')
1011 d->optarg = d->__nextchar;
1012 d->optind++;
1014 else
1015 d->optarg = NULL;
1016 d->__nextchar = NULL;
1018 else
1020 /* This is an option that requires an argument. */
1021 if (*d->__nextchar != '\0')
1023 d->optarg = d->__nextchar;
1024 /* If we end this ARGV-element by taking the rest as an arg,
1025 we must advance to the next element now. */
1026 d->optind++;
1028 else if (d->optind == argc)
1030 if (print_errors)
1032 #if defined _LIBC && defined USE_IN_LIBIO
1033 char *buf;
1035 if (__asprintf (&buf, _("\
1036 %s: option requires an argument -- '%c'\n"),
1037 argv[0], c) >= 0)
1039 _IO_flockfile (stderr);
1041 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1042 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1044 __fxprintf (NULL, "%s", buf);
1046 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1047 _IO_funlockfile (stderr);
1049 free (buf);
1051 #else
1052 fprintf (stderr,
1053 _("%s: option requires an argument -- '%c'\n"),
1054 argv[0], c);
1055 #endif
1057 d->optopt = c;
1058 if (optstring[0] == ':')
1059 c = ':';
1060 else
1061 c = '?';
1063 else
1064 /* We already incremented `optind' once;
1065 increment it again when taking next ARGV-elt as argument. */
1066 d->optarg = argv[d->optind++];
1067 d->__nextchar = NULL;
1070 return c;
1075 _getopt_internal (int argc, char **argv, const char *optstring,
1076 const struct option *longopts, int *longind, int long_only,
1077 int posixly_correct)
1079 int result;
1081 getopt_data.optind = optind;
1082 getopt_data.opterr = opterr;
1084 result = _getopt_internal_r (argc, argv, optstring, longopts,
1085 longind, long_only, &getopt_data,
1086 posixly_correct);
1088 optind = getopt_data.optind;
1089 optarg = getopt_data.optarg;
1090 optopt = getopt_data.optopt;
1092 return result;
1095 /* glibc gets a LSB-compliant getopt.
1096 Standalone applications get a POSIX-compliant getopt. */
1097 #if _LIBC
1098 enum { POSIXLY_CORRECT = 0 };
1099 #else
1100 enum { POSIXLY_CORRECT = 1 };
1101 #endif
1104 getopt (int argc, char *const *argv, const char *optstring)
1106 return _getopt_internal (argc, (char **) argv, optstring,
1107 (const struct option *) 0,
1108 (int *) 0,
1109 0, POSIXLY_CORRECT);
1112 #ifdef _LIBC
1114 __posix_getopt (int argc, char *const *argv, const char *optstring)
1116 return _getopt_internal (argc, argv, optstring,
1117 (const struct option *) 0,
1118 (int *) 0,
1119 0, 1);
1121 #endif
1124 #ifdef TEST
1126 /* Compile with -DTEST to make an executable for use in testing
1127 the above definition of `getopt'. */
1130 main (int argc, char **argv)
1132 int c;
1133 int digit_optind = 0;
1135 while (1)
1137 int this_option_optind = optind ? optind : 1;
1139 c = getopt (argc, argv, "abc:d:0123456789");
1140 if (c == -1)
1141 break;
1143 switch (c)
1145 case '0':
1146 case '1':
1147 case '2':
1148 case '3':
1149 case '4':
1150 case '5':
1151 case '6':
1152 case '7':
1153 case '8':
1154 case '9':
1155 if (digit_optind != 0 && digit_optind != this_option_optind)
1156 printf ("digits occur in two different argv-elements.\n");
1157 digit_optind = this_option_optind;
1158 printf ("option %c\n", c);
1159 break;
1161 case 'a':
1162 printf ("option a\n");
1163 break;
1165 case 'b':
1166 printf ("option b\n");
1167 break;
1169 case 'c':
1170 printf ("option c with value '%s'\n", optarg);
1171 break;
1173 case '?':
1174 break;
1176 default:
1177 printf ("?? getopt returned character code 0%o ??\n", c);
1181 if (optind < argc)
1183 printf ("non-option ARGV-elements: ");
1184 while (optind < argc)
1185 printf ("%s ", argv[optind++]);
1186 printf ("\n");
1189 exit (0);
1192 #endif /* TEST */