Another round in fixing getopt problems. Hopefully the last one!
[s-roff.git] / src / libs / libgroff / getopt.c
blobbcb81c83fe25da1e9c01b0a6347f5ce836a68960
1 /* Getopt for GNU.
2 NOTE: getopt is now part of the C library, so if you don't know what
3 "Keep this file name-space clean" means, talk to drepper@gnu.org
4 before changing it!
5 Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001,2002,2003,2004
6 Free Software Foundation, Inc.
7 This file is part of the GNU C Library.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License along
20 with this program; if not, write to the Free Software Foundation,
21 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
23 /* 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 /* This needs to come after some library #include
36 to get __GNU_LIBRARY__ defined. */
37 #ifdef __GNU_LIBRARY__
38 /* Don't include stdlib.h for non-GNU C libraries because some of them
39 contain conflicting prototypes for getopt. */
40 # include <stdlib.h>
41 # include <unistd.h>
42 #endif /* GNU C library. */
44 #include <string.h>
46 #ifdef VMS
47 # include <unixlib.h>
48 #endif
50 #ifdef _LIBC
51 # include <libintl.h>
52 #else
53 # include "gettext.h"
54 # define _(msgid) gettext (msgid)
55 #endif
57 #if defined _LIBC && defined USE_IN_LIBIO
58 # include <wchar.h>
59 #endif
61 #ifndef attribute_hidden
62 # define attribute_hidden
63 #endif
65 /* Unlike standard Unix `getopt', functions like `getopt_long'
66 let the user intersperse the options with the other arguments.
68 As `getopt_long' works, it permutes the elements of ARGV so that,
69 when it is done, all the options precede everything else. Thus
70 all application programs are extended to handle flexible argument order.
72 Using `getopt' or setting the environment variable POSIXLY_CORRECT
73 disables permutation.
74 Then the application's behavior is completely standard.
76 GNU application programs can use a third alternative mode in which
77 they can distinguish the relative order of options and other arguments. */
79 #include "getopt.h"
80 #include "getopt_int.h"
82 /* For communication from `getopt' to the caller.
83 When `getopt' finds an option that takes an argument,
84 the argument value is returned here.
85 Also, when `ordering' is RETURN_IN_ORDER,
86 each non-option ARGV-element is returned here. */
88 char *optarg;
90 /* Index in ARGV of the next element to be scanned.
91 This is used for communication to and from the caller
92 and for communication between successive calls to `getopt'.
94 On entry to `getopt', zero means this is the first call; initialize.
96 When `getopt' returns -1, this is the index of the first of the
97 non-option elements that the caller should itself scan.
99 Otherwise, `optind' communicates from one call to the next
100 how much of ARGV has been scanned so far. */
102 /* 1003.2 says this must be 1 before any call. */
103 int optind = 1;
105 /* Callers store zero here to inhibit the error message
106 for unrecognized options. */
108 int opterr = 1;
110 /* Set to an option character which was unrecognized.
111 This must be initialized on some systems to avoid linking in the
112 system's own getopt implementation. */
114 int optopt = '?';
116 /* Keep a global copy of all internal members of getopt_data. */
118 static struct _getopt_data getopt_data;
121 #ifndef __GNU_LIBRARY__
123 /* Avoid depending on library functions or files
124 whose names are inconsistent. */
126 #ifndef getenv
127 extern char *getenv ();
128 #endif
130 #endif /* not __GNU_LIBRARY__ */
132 #ifdef _LIBC
133 /* Stored original parameters.
134 XXX This is no good solution. We should rather copy the args so
135 that we can compare them later. But we must not use malloc(3). */
136 extern int __libc_argc;
137 extern char **__libc_argv;
139 /* Bash 2.0 gives us an environment variable containing flags
140 indicating ARGV elements that should not be considered arguments. */
142 # ifdef USE_NONOPTION_FLAGS
143 /* Defined in getopt_init.c */
144 extern char *__getopt_nonoption_flags;
145 # endif
147 # ifdef USE_NONOPTION_FLAGS
148 # define SWAP_FLAGS(ch1, ch2) \
149 if (d->__nonoption_flags_len > 0) \
151 char __tmp = __getopt_nonoption_flags[ch1]; \
152 __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
153 __getopt_nonoption_flags[ch2] = __tmp; \
155 # else
156 # define SWAP_FLAGS(ch1, ch2)
157 # endif
158 #else /* !_LIBC */
159 # define SWAP_FLAGS(ch1, ch2)
160 #endif /* _LIBC */
162 /* Exchange two adjacent subsequences of ARGV.
163 One subsequence is elements [first_nonopt,last_nonopt)
164 which contains all the non-options that have been skipped so far.
165 The other is elements [last_nonopt,optind), which contains all
166 the options processed since those non-options were skipped.
168 `first_nonopt' and `last_nonopt' are relocated so that they describe
169 the new indices of the non-options in ARGV after they are moved. */
171 static void
172 exchange (char **argv, struct _getopt_data *d)
174 int bottom = d->__first_nonopt;
175 int middle = d->__last_nonopt;
176 int top = d->optind;
177 char *tem;
179 /* Exchange the shorter segment with the far end of the longer segment.
180 That puts the shorter segment into the right place.
181 It leaves the longer segment in the right place overall,
182 but it consists of two parts that need to be swapped next. */
184 #if defined _LIBC && defined USE_NONOPTION_FLAGS
185 /* First make sure the handling of the `__getopt_nonoption_flags'
186 string can work normally. Our top argument must be in the range
187 of the string. */
188 if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
190 /* We must extend the array. The user plays games with us and
191 presents new arguments. */
192 char *new_str = malloc (top + 1);
193 if (new_str == NULL)
194 d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
195 else
197 memset (__mempcpy (new_str, __getopt_nonoption_flags,
198 d->__nonoption_flags_max_len),
199 '\0', top + 1 - d->__nonoption_flags_max_len);
200 d->__nonoption_flags_max_len = top + 1;
201 __getopt_nonoption_flags = new_str;
204 #endif
206 while (top > middle && middle > bottom)
208 if (top - middle > middle - bottom)
210 /* Bottom segment is the short one. */
211 int len = middle - bottom;
212 register int i;
214 /* Swap it with the top part of the top segment. */
215 for (i = 0; i < len; i++)
217 tem = argv[bottom + i];
218 argv[bottom + i] = argv[top - (middle - bottom) + i];
219 argv[top - (middle - bottom) + i] = tem;
220 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
222 /* Exclude the moved bottom segment from further swapping. */
223 top -= len;
225 else
227 /* Top segment is the short one. */
228 int len = top - middle;
229 register int i;
231 /* Swap it with the bottom part of the bottom segment. */
232 for (i = 0; i < len; i++)
234 tem = argv[bottom + i];
235 argv[bottom + i] = argv[middle + i];
236 argv[middle + i] = tem;
237 SWAP_FLAGS (bottom + i, middle + i);
239 /* Exclude the moved top segment from further swapping. */
240 bottom += len;
244 /* Update records for the slots the non-options now occupy. */
246 d->__first_nonopt += (d->optind - d->__last_nonopt);
247 d->__last_nonopt = d->optind;
250 /* Initialize the internal data when the first call is made. */
252 static const char *
253 _getopt_initialize (int argc, char **argv, const char *optstring,
254 int posixly_correct, struct _getopt_data *d)
256 /* Start processing options with ARGV-element 1 (since ARGV-element 0
257 is the program name); the sequence of previously skipped
258 non-option ARGV-elements is empty. */
260 d->__first_nonopt = d->__last_nonopt = d->optind;
262 d->__nextchar = NULL;
264 d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT");
266 /* Determine how to handle the ordering of options and nonoptions. */
268 if (optstring[0] == '-')
270 d->__ordering = RETURN_IN_ORDER;
271 ++optstring;
273 else if (optstring[0] == '+')
275 d->__ordering = REQUIRE_ORDER;
276 ++optstring;
278 else if (d->__posixly_correct)
279 d->__ordering = REQUIRE_ORDER;
280 else
281 d->__ordering = PERMUTE;
283 #if defined _LIBC && defined USE_NONOPTION_FLAGS
284 if (!d->__posixly_correct
285 && argc == __libc_argc && argv == __libc_argv)
287 if (d->__nonoption_flags_max_len == 0)
289 if (__getopt_nonoption_flags == NULL
290 || __getopt_nonoption_flags[0] == '\0')
291 d->__nonoption_flags_max_len = -1;
292 else
294 const char *orig_str = __getopt_nonoption_flags;
295 int len = d->__nonoption_flags_max_len = strlen (orig_str);
296 if (d->__nonoption_flags_max_len < argc)
297 d->__nonoption_flags_max_len = argc;
298 __getopt_nonoption_flags =
299 (char *) malloc (d->__nonoption_flags_max_len);
300 if (__getopt_nonoption_flags == NULL)
301 d->__nonoption_flags_max_len = -1;
302 else
303 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
304 '\0', d->__nonoption_flags_max_len - len);
307 d->__nonoption_flags_len = d->__nonoption_flags_max_len;
309 else
310 d->__nonoption_flags_len = 0;
311 #endif
313 return optstring;
316 /* Scan elements of ARGV (whose length is ARGC) for option characters
317 given in OPTSTRING.
319 If an element of ARGV starts with '-', and is not exactly "-" or "--",
320 then it is an option element. The characters of this element
321 (aside from the initial '-') are option characters. If `getopt'
322 is called repeatedly, it returns successively each of the option characters
323 from each of the option elements.
325 If `getopt' finds another option character, it returns that character,
326 updating `optind' and `nextchar' so that the next call to `getopt' can
327 resume the scan with the following option character or ARGV-element.
329 If there are no more option characters, `getopt' returns -1.
330 Then `optind' is the index in ARGV of the first ARGV-element
331 that is not an option. (The ARGV-elements have been permuted
332 so that those that are not options now come last.)
334 OPTSTRING is a string containing the legitimate option characters.
335 If an option character is seen that is not listed in OPTSTRING,
336 return '?' after printing an error message. If you set `opterr' to
337 zero, the error message is suppressed but we still return '?'.
339 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
340 so the following text in the same ARGV-element, or the text of the following
341 ARGV-element, is returned in `optarg'. Two colons mean an option that
342 wants an optional arg; if there is text in the current ARGV-element,
343 it is returned in `optarg', otherwise `optarg' is set to zero.
345 If OPTSTRING starts with `-' or `+', it requests different methods of
346 handling the non-option ARGV-elements.
347 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
349 Long-named options begin with `--' instead of `-'.
350 Their names may be abbreviated as long as the abbreviation is unique
351 or is an exact match for some defined option. If they have an
352 argument, it follows the option name in the same ARGV-element, separated
353 from the option name by a `=', or else the in next ARGV-element.
354 When `getopt' finds a long-named option, it returns 0 if that option's
355 `flag' field is nonzero, the value of the option's `val' field
356 if the `flag' field is zero.
358 LONGOPTS is a vector of `struct option' terminated by an
359 element containing a name which is zero.
361 LONGIND returns the index in LONGOPT of the long-named option found.
362 It is only valid when a long-named option has been found by the most
363 recent call.
365 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
366 long-named options.
368 If POSIXLY_CORRECT is nonzero, behave as if the POSIXLY_CORRECT
369 environment variable were set. */
372 _getopt_internal_r (int argc, char **argv, const char *optstring,
373 const struct option *longopts, int *longind,
374 int long_only, int posixly_correct, struct _getopt_data *d)
376 int print_errors = d->opterr;
377 if (optstring[0] == ':')
378 print_errors = 0;
380 if (argc < 1)
381 return -1;
383 d->optarg = NULL;
385 if (d->optind == 0 || !d->__initialized)
387 if (d->optind == 0)
388 d->optind = 1; /* Don't scan ARGV[0], the program name. */
389 optstring = _getopt_initialize (argc, argv, optstring,
390 posixly_correct, d);
391 d->__initialized = 1;
394 /* Test whether ARGV[optind] points to a non-option argument.
395 Either it does not have option syntax, or there is an environment flag
396 from the shell indicating it is not an option. The later information
397 is only used when the used in the GNU libc. */
398 #if defined _LIBC && defined USE_NONOPTION_FLAGS
399 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
400 || (d->optind < d->__nonoption_flags_len \
401 && __getopt_nonoption_flags[d->optind] == '1'))
402 #else
403 # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
404 #endif
406 if (d->__nextchar == NULL || *d->__nextchar == '\0')
408 /* Advance to the next ARGV-element. */
410 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
411 moved back by the user (who may also have changed the arguments). */
412 if (d->__last_nonopt > d->optind)
413 d->__last_nonopt = d->optind;
414 if (d->__first_nonopt > d->optind)
415 d->__first_nonopt = d->optind;
417 if (d->__ordering == PERMUTE)
419 /* If we have just processed some options following some non-options,
420 exchange them so that the options come first. */
422 if (d->__first_nonopt != d->__last_nonopt
423 && d->__last_nonopt != d->optind)
424 exchange ((char **) argv, d);
425 else if (d->__last_nonopt != d->optind)
426 d->__first_nonopt = d->optind;
428 /* Skip any additional non-options
429 and extend the range of non-options previously skipped. */
431 while (d->optind < argc && NONOPTION_P)
432 d->optind++;
433 d->__last_nonopt = d->optind;
436 /* The special ARGV-element `--' means premature end of options.
437 Skip it like a null option,
438 then exchange with previous non-options as if it were an option,
439 then skip everything else like a non-option. */
441 if (d->optind != argc && !strcmp (argv[d->optind], "--"))
443 d->optind++;
445 if (d->__first_nonopt != d->__last_nonopt
446 && d->__last_nonopt != d->optind)
447 exchange ((char **) argv, d);
448 else if (d->__first_nonopt == d->__last_nonopt)
449 d->__first_nonopt = d->optind;
450 d->__last_nonopt = argc;
452 d->optind = argc;
455 /* If we have done all the ARGV-elements, stop the scan
456 and back over any non-options that we skipped and permuted. */
458 if (d->optind == argc)
460 /* Set the next-arg-index to point at the non-options
461 that we previously skipped, so the caller will digest them. */
462 if (d->__first_nonopt != d->__last_nonopt)
463 d->optind = d->__first_nonopt;
464 return -1;
467 /* If we have come to a non-option and did not permute it,
468 either stop the scan or describe it to the caller and pass it by. */
470 if (NONOPTION_P)
472 if (d->__ordering == REQUIRE_ORDER)
473 return -1;
474 d->optarg = argv[d->optind++];
475 return 1;
478 /* We have found another option-ARGV-element.
479 Skip the initial punctuation. */
481 d->__nextchar = (argv[d->optind] + 1
482 + (longopts != NULL && argv[d->optind][1] == '-'));
485 /* Decode the current option-ARGV-element. */
487 /* Check whether the ARGV-element is a long option.
489 If long_only and the ARGV-element has the form "-f", where f is
490 a valid short option, don't consider it an abbreviated form of
491 a long option that starts with f. Otherwise there would be no
492 way to give the -f short option.
494 On the other hand, if there's a long option "fubar" and
495 the ARGV-element is "-fu", do consider that an abbreviation of
496 the long option, just like "--fu", and not "-f" with arg "u".
498 This distinction seems to be the most useful approach. */
500 if (longopts != NULL
501 && (argv[d->optind][1] == '-'
502 || (long_only && (argv[d->optind][2]
503 || !strchr (optstring, argv[d->optind][1])))))
505 char *nameend;
506 const struct option *p;
507 const struct option *pfound = NULL;
508 int exact = 0;
509 int ambig = 0;
510 int indfound = -1;
511 int option_index;
513 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
514 /* Do nothing. */ ;
516 /* Test all long options for either exact match
517 or abbreviated matches. */
518 for (p = longopts, option_index = 0; p->name; p++, option_index++)
519 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
521 if ((unsigned int) (nameend - d->__nextchar)
522 == (unsigned int) strlen (p->name))
524 /* Exact match found. */
525 pfound = p;
526 indfound = option_index;
527 exact = 1;
528 break;
530 else if (pfound == NULL)
532 /* First nonexact match found. */
533 pfound = p;
534 indfound = option_index;
536 else if (long_only
537 || pfound->has_arg != p->has_arg
538 || pfound->flag != p->flag
539 || pfound->val != p->val)
540 /* Second or later nonexact match found. */
541 ambig = 1;
544 if (ambig && !exact)
546 if (print_errors)
548 #if defined _LIBC && defined USE_IN_LIBIO
549 char *buf;
551 if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
552 argv[0], argv[d->optind]) >= 0)
554 _IO_flockfile (stderr);
556 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
557 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
559 if (_IO_fwide (stderr, 0) > 0)
560 __fwprintf (stderr, L"%s", buf);
561 else
562 fputs (buf, stderr);
564 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
565 _IO_funlockfile (stderr);
567 free (buf);
569 #else
570 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
571 argv[0], argv[d->optind]);
572 #endif
574 d->__nextchar += strlen (d->__nextchar);
575 d->optind++;
576 d->optopt = 0;
577 return '?';
580 if (pfound != NULL)
582 option_index = indfound;
583 d->optind++;
584 if (*nameend)
586 /* Don't test has_arg with >, because some C compilers don't
587 allow it to be used on enums. */
588 if (pfound->has_arg)
589 d->optarg = nameend + 1;
590 else
592 if (print_errors)
594 #if defined _LIBC && defined USE_IN_LIBIO
595 char *buf;
596 int n;
597 #endif
599 if (argv[d->optind - 1][1] == '-')
601 /* --option */
602 #if defined _LIBC && defined USE_IN_LIBIO
603 n = __asprintf (&buf, _("\
604 %s: option `--%s' doesn't allow an argument\n"),
605 argv[0], pfound->name);
606 #else
607 fprintf (stderr, _("\
608 %s: option `--%s' doesn't allow an argument\n"),
609 argv[0], pfound->name);
610 #endif
612 else
614 /* +option or -option */
615 #if defined _LIBC && defined USE_IN_LIBIO
616 n = __asprintf (&buf, _("\
617 %s: option `%c%s' doesn't allow an argument\n"),
618 argv[0], argv[d->optind - 1][0],
619 pfound->name);
620 #else
621 fprintf (stderr, _("\
622 %s: option `%c%s' doesn't allow an argument\n"),
623 argv[0], argv[d->optind - 1][0],
624 pfound->name);
625 #endif
628 #if defined _LIBC && defined USE_IN_LIBIO
629 if (n >= 0)
631 _IO_flockfile (stderr);
633 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
634 ((_IO_FILE *) stderr)->_flags2
635 |= _IO_FLAGS2_NOTCANCEL;
637 if (_IO_fwide (stderr, 0) > 0)
638 __fwprintf (stderr, L"%s", buf);
639 else
640 fputs (buf, stderr);
642 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
643 _IO_funlockfile (stderr);
645 free (buf);
647 #endif
650 d->__nextchar += strlen (d->__nextchar);
652 d->optopt = pfound->val;
653 return '?';
656 else if (pfound->has_arg == 1)
658 if (d->optind < argc)
659 d->optarg = argv[d->optind++];
660 else
662 if (print_errors)
664 #if defined _LIBC && defined USE_IN_LIBIO
665 char *buf;
667 if (__asprintf (&buf, _("\
668 %s: option `%s' requires an argument\n"),
669 argv[0], argv[d->optind - 1]) >= 0)
671 _IO_flockfile (stderr);
673 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
674 ((_IO_FILE *) stderr)->_flags2
675 |= _IO_FLAGS2_NOTCANCEL;
677 if (_IO_fwide (stderr, 0) > 0)
678 __fwprintf (stderr, L"%s", buf);
679 else
680 fputs (buf, stderr);
682 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
683 _IO_funlockfile (stderr);
685 free (buf);
687 #else
688 fprintf (stderr,
689 _("%s: option `%s' requires an argument\n"),
690 argv[0], argv[d->optind - 1]);
691 #endif
693 d->__nextchar += strlen (d->__nextchar);
694 d->optopt = pfound->val;
695 return optstring[0] == ':' ? ':' : '?';
698 d->__nextchar += strlen (d->__nextchar);
699 if (longind != NULL)
700 *longind = option_index;
701 if (pfound->flag)
703 *(pfound->flag) = pfound->val;
704 return 0;
706 return pfound->val;
709 /* Can't find it as a long option. If this is not getopt_long_only,
710 or the option starts with '--' or is not a valid short
711 option, then it's an error.
712 Otherwise interpret it as a short option. */
713 if (!long_only || argv[d->optind][1] == '-'
714 || strchr (optstring, *d->__nextchar) == NULL)
716 if (print_errors)
718 #if defined _LIBC && defined USE_IN_LIBIO
719 char *buf;
720 int n;
721 #endif
723 if (argv[d->optind][1] == '-')
725 /* --option */
726 #if defined _LIBC && defined USE_IN_LIBIO
727 n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
728 argv[0], d->__nextchar);
729 #else
730 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
731 argv[0], d->__nextchar);
732 #endif
734 else
736 /* +option or -option */
737 #if defined _LIBC && defined USE_IN_LIBIO
738 n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
739 argv[0], argv[d->optind][0], d->__nextchar);
740 #else
741 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
742 argv[0], argv[d->optind][0], d->__nextchar);
743 #endif
746 #if defined _LIBC && defined USE_IN_LIBIO
747 if (n >= 0)
749 _IO_flockfile (stderr);
751 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
752 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
754 if (_IO_fwide (stderr, 0) > 0)
755 __fwprintf (stderr, L"%s", buf);
756 else
757 fputs (buf, stderr);
759 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
760 _IO_funlockfile (stderr);
762 free (buf);
764 #endif
766 d->__nextchar = (char *) "";
767 d->optind++;
768 d->optopt = 0;
769 return '?';
773 /* Look at and handle the next short option-character. */
776 char c = *d->__nextchar++;
777 char *temp = strchr (optstring, c);
779 /* Increment `optind' when we start to process its last character. */
780 if (*d->__nextchar == '\0')
781 ++d->optind;
783 if (temp == NULL || c == ':')
785 if (print_errors)
787 #if defined _LIBC && defined USE_IN_LIBIO
788 char *buf;
789 int n;
790 #endif
792 if (d->__posixly_correct)
794 /* 1003.2 specifies the format of this message. */
795 #if defined _LIBC && defined USE_IN_LIBIO
796 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
797 argv[0], c);
798 #else
799 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
800 #endif
802 else
804 #if defined _LIBC && defined USE_IN_LIBIO
805 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
806 argv[0], c);
807 #else
808 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
809 #endif
812 #if defined _LIBC && defined USE_IN_LIBIO
813 if (n >= 0)
815 _IO_flockfile (stderr);
817 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
818 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
820 if (_IO_fwide (stderr, 0) > 0)
821 __fwprintf (stderr, L"%s", buf);
822 else
823 fputs (buf, stderr);
825 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
826 _IO_funlockfile (stderr);
828 free (buf);
830 #endif
832 d->optopt = c;
833 return '?';
835 /* Convenience. Treat POSIX -W foo same as long option --foo */
836 if (temp[0] == 'W' && temp[1] == ';')
838 char *nameend;
839 const struct option *p;
840 const struct option *pfound = NULL;
841 int exact = 0;
842 int ambig = 0;
843 int indfound = 0;
844 int option_index;
846 /* This is an option that requires an argument. */
847 if (*d->__nextchar != '\0')
849 d->optarg = d->__nextchar;
850 /* If we end this ARGV-element by taking the rest as an arg,
851 we must advance to the next element now. */
852 d->optind++;
854 else if (d->optind == argc)
856 if (print_errors)
858 /* 1003.2 specifies the format of this message. */
859 #if defined _LIBC && defined USE_IN_LIBIO
860 char *buf;
862 if (__asprintf (&buf,
863 _("%s: option requires an argument -- %c\n"),
864 argv[0], c) >= 0)
866 _IO_flockfile (stderr);
868 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
869 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
871 if (_IO_fwide (stderr, 0) > 0)
872 __fwprintf (stderr, L"%s", buf);
873 else
874 fputs (buf, stderr);
876 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
877 _IO_funlockfile (stderr);
879 free (buf);
881 #else
882 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
883 argv[0], c);
884 #endif
886 d->optopt = c;
887 if (optstring[0] == ':')
888 c = ':';
889 else
890 c = '?';
891 return c;
893 else
894 /* We already incremented `d->optind' once;
895 increment it again when taking next ARGV-elt as argument. */
896 d->optarg = argv[d->optind++];
898 /* optarg is now the argument, see if it's in the
899 table of longopts. */
901 for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
902 nameend++)
903 /* Do nothing. */ ;
905 /* Test all long options for either exact match
906 or abbreviated matches. */
907 for (p = longopts, option_index = 0; p->name; p++, option_index++)
908 if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
910 if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
912 /* Exact match found. */
913 pfound = p;
914 indfound = option_index;
915 exact = 1;
916 break;
918 else if (pfound == NULL)
920 /* First nonexact match found. */
921 pfound = p;
922 indfound = option_index;
924 else
925 /* Second or later nonexact match found. */
926 ambig = 1;
928 if (ambig && !exact)
930 if (print_errors)
932 #if defined _LIBC && defined USE_IN_LIBIO
933 char *buf;
935 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
936 argv[0], argv[d->optind]) >= 0)
938 _IO_flockfile (stderr);
940 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
941 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
943 if (_IO_fwide (stderr, 0) > 0)
944 __fwprintf (stderr, L"%s", buf);
945 else
946 fputs (buf, stderr);
948 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
949 _IO_funlockfile (stderr);
951 free (buf);
953 #else
954 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
955 argv[0], argv[d->optind]);
956 #endif
958 d->__nextchar += strlen (d->__nextchar);
959 d->optind++;
960 return '?';
962 if (pfound != NULL)
964 option_index = indfound;
965 if (*nameend)
967 /* Don't test has_arg with >, because some C compilers don't
968 allow it to be used on enums. */
969 if (pfound->has_arg)
970 d->optarg = nameend + 1;
971 else
973 if (print_errors)
975 #if defined _LIBC && defined USE_IN_LIBIO
976 char *buf;
978 if (__asprintf (&buf, _("\
979 %s: option `-W %s' doesn't allow an argument\n"),
980 argv[0], pfound->name) >= 0)
982 _IO_flockfile (stderr);
984 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
985 ((_IO_FILE *) stderr)->_flags2
986 |= _IO_FLAGS2_NOTCANCEL;
988 if (_IO_fwide (stderr, 0) > 0)
989 __fwprintf (stderr, L"%s", buf);
990 else
991 fputs (buf, stderr);
993 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
994 _IO_funlockfile (stderr);
996 free (buf);
998 #else
999 fprintf (stderr, _("\
1000 %s: option `-W %s' doesn't allow an argument\n"),
1001 argv[0], pfound->name);
1002 #endif
1005 d->__nextchar += strlen (d->__nextchar);
1006 return '?';
1009 else if (pfound->has_arg == 1)
1011 if (d->optind < argc)
1012 d->optarg = argv[d->optind++];
1013 else
1015 if (print_errors)
1017 #if defined _LIBC && defined USE_IN_LIBIO
1018 char *buf;
1020 if (__asprintf (&buf, _("\
1021 %s: option `%s' requires an argument\n"),
1022 argv[0], argv[d->optind - 1]) >= 0)
1024 _IO_flockfile (stderr);
1026 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1027 ((_IO_FILE *) stderr)->_flags2
1028 |= _IO_FLAGS2_NOTCANCEL;
1030 if (_IO_fwide (stderr, 0) > 0)
1031 __fwprintf (stderr, L"%s", buf);
1032 else
1033 fputs (buf, stderr);
1035 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1036 _IO_funlockfile (stderr);
1038 free (buf);
1040 #else
1041 fprintf (stderr,
1042 _("%s: option `%s' requires an argument\n"),
1043 argv[0], argv[d->optind - 1]);
1044 #endif
1046 d->__nextchar += strlen (d->__nextchar);
1047 return optstring[0] == ':' ? ':' : '?';
1050 d->__nextchar += strlen (d->__nextchar);
1051 if (longind != NULL)
1052 *longind = option_index;
1053 if (pfound->flag)
1055 *(pfound->flag) = pfound->val;
1056 return 0;
1058 return pfound->val;
1060 d->__nextchar = NULL;
1061 return 'W'; /* Let the application handle it. */
1063 if (temp[1] == ':')
1065 if (temp[2] == ':')
1067 /* This is an option that accepts an argument optionally. */
1068 if (*d->__nextchar != '\0')
1070 d->optarg = d->__nextchar;
1071 d->optind++;
1073 else
1074 d->optarg = NULL;
1075 d->__nextchar = NULL;
1077 else
1079 /* This is an option that requires an argument. */
1080 if (*d->__nextchar != '\0')
1082 d->optarg = d->__nextchar;
1083 /* If we end this ARGV-element by taking the rest as an arg,
1084 we must advance to the next element now. */
1085 d->optind++;
1087 else if (d->optind == argc)
1089 if (print_errors)
1091 /* 1003.2 specifies the format of this message. */
1092 #if defined _LIBC && defined USE_IN_LIBIO
1093 char *buf;
1095 if (__asprintf (&buf, _("\
1096 %s: option requires an argument -- %c\n"),
1097 argv[0], c) >= 0)
1099 _IO_flockfile (stderr);
1101 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
1102 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
1104 if (_IO_fwide (stderr, 0) > 0)
1105 __fwprintf (stderr, L"%s", buf);
1106 else
1107 fputs (buf, stderr);
1109 ((_IO_FILE *) stderr)->_flags2 = old_flags2;
1110 _IO_funlockfile (stderr);
1112 free (buf);
1114 #else
1115 fprintf (stderr,
1116 _("%s: option requires an argument -- %c\n"),
1117 argv[0], c);
1118 #endif
1120 d->optopt = c;
1121 if (optstring[0] == ':')
1122 c = ':';
1123 else
1124 c = '?';
1126 else
1127 /* We already incremented `optind' once;
1128 increment it again when taking next ARGV-elt as argument. */
1129 d->optarg = argv[d->optind++];
1130 d->__nextchar = NULL;
1133 return c;
1138 _getopt_internal (int argc, char **argv, const char *optstring,
1139 const struct option *longopts, int *longind,
1140 int long_only, int posixly_correct)
1142 int result;
1144 getopt_data.optind = optind;
1145 getopt_data.opterr = opterr;
1147 result = _getopt_internal_r (argc, argv, optstring, longopts, longind,
1148 long_only, posixly_correct, &getopt_data);
1150 optind = getopt_data.optind;
1151 optarg = getopt_data.optarg;
1152 optopt = getopt_data.optopt;
1154 return result;
1157 /* glibc gets a LSB-compliant getopt.
1158 Standalone applications get a POSIX-compliant getopt. */
1159 #if _LIBC
1160 enum { POSIXLY_CORRECT = 0 };
1161 #else
1162 enum { POSIXLY_CORRECT = 1 };
1163 #endif
1166 getopt (int argc, char *const *argv, const char *optstring)
1168 return _getopt_internal (argc, (char **) argv, optstring, NULL, NULL, 0,
1169 POSIXLY_CORRECT);
1173 #ifdef TEST
1175 /* Compile with -DTEST to make an executable for use in testing
1176 the above definition of `getopt'. */
1179 main (int argc, char **argv)
1181 int c;
1182 int digit_optind = 0;
1184 while (1)
1186 int this_option_optind = optind ? optind : 1;
1188 c = getopt (argc, argv, "abc:d:0123456789");
1189 if (c == -1)
1190 break;
1192 switch (c)
1194 case '0':
1195 case '1':
1196 case '2':
1197 case '3':
1198 case '4':
1199 case '5':
1200 case '6':
1201 case '7':
1202 case '8':
1203 case '9':
1204 if (digit_optind != 0 && digit_optind != this_option_optind)
1205 printf ("digits occur in two different argv-elements.\n");
1206 digit_optind = this_option_optind;
1207 printf ("option %c\n", c);
1208 break;
1210 case 'a':
1211 printf ("option a\n");
1212 break;
1214 case 'b':
1215 printf ("option b\n");
1216 break;
1218 case 'c':
1219 printf ("option c with value `%s'\n", optarg);
1220 break;
1222 case '?':
1223 break;
1225 default:
1226 printf ("?? getopt returned character code 0%o ??\n", c);
1230 if (optind < argc)
1232 printf ("non-option ARGV-elements: ");
1233 while (optind < argc)
1234 printf ("%s ", argv[optind++]);
1235 printf ("\n");
1238 exit (0);
1241 #endif /* TEST */