Debian Codegraph @

texk/kpathsea/getopt.c

raw
1 /* Getopt for GNU.
2
3 Copyright 2008-2012 Karl Berry.
4 Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 2000, 2010
5 Free Software Foundation, Inc.
6
7 The original version of this file was part of the GNU C Library.
8 Its master source is NOT part of the C library, however.
9 The master source lives in libc.
10 This version has been modified for use with libkpathsea.
11
12 This library is free software; you can redistribute it and/or
13 modify it under the terms of the GNU Lesser General Public
14 License as published by the Free Software Foundation; either
15 version 2.1 of the License, or (at your option) any later version.
16
17 This library is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 Lesser General Public License for more details.
21
22 You should have received a copy of the GNU Lesser General Public License
23 along with this library; if not, see <http://www.gnu.org/licenses/>. */
24
25
26 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
27 Ditto for AIX 3.2 and <stdlib.h>. */
28 #ifndef _NO_PROTO
29 #define _NO_PROTO
30 #endif
31
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
35 #ifdef HAVE_STRING_H
36 #include <string.h>
37 #endif
38
39 #include <stdio.h>
40
41 /* Comment out all this code if we are using the GNU C Library, and are not
42 actually compiling the library itself. This code is part of the GNU C
43 Library, but also included in many other GNU distributions. Compiling
44 and linking in this code is a waste when using the GNU C library
45 (especially if it is a shared library). Rather than having every GNU
46 program understand `configure --with-gnu-libc' and omit the object files,
47 it is simpler to just do this in the source for each such file. */
48
49 #define GETOPT_INTERFACE_VERSION 2
50 #if !defined (_LIBC) && defined (__GLIBC__) && __GLIBC__ >= 2
51 #include <gnu-versions.h>
52 #if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
53 #define ELIDE_CODE
54 #endif
55 #endif
56
57 #ifndef ELIDE_CODE
58
59
60 /* This needs to come after some library #include
61 to get __GNU_LIBRARY__ defined. */
62 #ifdef __GNU_LIBRARY__
63 /* Don't include stdlib.h for non-GNU C libraries because some of them
64 contain conflicting prototypes for getopt. */
65 #include <stdlib.h>
66 #include <unistd.h>
67 #endif /* GNU C library. */
68
69 #ifdef VMS
70 #include <unixlib.h>
71 #if HAVE_STRING_H - 0
72 #include <string.h>
73 #endif
74 #endif
75
76 #if defined (WIN32) && !defined (__CYGWIN__)
77 /* It's not Unix, really. See? Capital letters. */
78 #include <stdlib.h>
79 #include <windows.h>
80 #undef getpid
81 #define getpid() GetCurrentProcessId()
82 #endif
83
84 #ifndef _
85 /* This is for other GNU distributions with internationalized messages.
86 When compiling libc, the _ macro is predefined. */
87 #ifdef HAVE_LIBINTL_H
88 # include <libintl.h>
89 # define _(msgid) gettext (msgid)
90 #else
91 # define _(msgid) (msgid)
92 #endif
93 #endif
94
95 /* This version of `getopt' appears to the caller like standard Unix `getopt'
96 but it behaves differently for the user, since it allows the user
97 to intersperse the options with the other arguments.
98
99 As `getopt' works, it permutes the elements of ARGV so that,
100 when it is done, all the options precede everything else. Thus
101 all application programs are extended to handle flexible argument order.
102
103 Setting the environment variable POSIXLY_CORRECT disables permutation.
104 Then the behavior is completely standard.
105
106 GNU application programs can use a third alternative mode in which
107 they can distinguish the relative order of options and other arguments. */
108
109 #include "getopt.h"
110
111 /* For communication from `getopt' to the caller.
112 When `getopt' finds an option that takes an argument,
113 the argument value is returned here.
114 Also, when `ordering' is RETURN_IN_ORDER,
115 each non-option ARGV-element is returned here. */
116
117 char *optarg = NULL;
118
119 /* Index in ARGV of the next element to be scanned.
120 This is used for communication to and from the caller
121 and for communication between successive calls to `getopt'.
122
123 On entry to `getopt', zero means this is the first call; initialize.
124
125 When `getopt' returns -1, this is the index of the first of the
126 non-option elements that the caller should itself scan.
127
128 Otherwise, `optind' communicates from one call to the next
129 how much of ARGV has been scanned so far. */
130
131 /* 1003.2 says this must be 1 before any call. */
132 int optind = 1;
133
134 /* Formerly, initialization of getopt depended on optind==0, which
135 causes problems with re-calling getopt as programs generally don't
136 know that. */
137
138 int __getopt_initialized = 0;
139
140 /* The next char to be scanned in the option-element
141 in which the last option character we returned was found.
142 This allows us to pick up the scan where we left off.
143
144 If this is zero, or a null string, it means resume the scan
145 by advancing to the next ARGV-element. */
146
147 static char *nextchar;
148
149 /* Callers store zero here to inhibit the error message
150 for unrecognized options. */
151
152 int opterr = 1;
153
154 /* Set to an option character which was unrecognized.
155 This must be initialized on some systems to avoid linking in the
156 system's own getopt implementation. */
157
158 int optopt = '?';
159
160 /* Describe how to deal with options that follow non-option ARGV-elements.
161
162 If the caller did not specify anything,
163 the default is REQUIRE_ORDER if the environment variable
164 POSIXLY_CORRECT is defined, PERMUTE otherwise.
165
166 REQUIRE_ORDER means don't recognize them as options;
167 stop option processing when the first non-option is seen.
168 This is what Unix does.
169 This mode of operation is selected by either setting the environment
170 variable POSIXLY_CORRECT, or using `+' as the first character
171 of the list of option characters.
172
173 PERMUTE is the default. We permute the contents of ARGV as we scan,
174 so that eventually all the non-options are at the end. This allows options
175 to be given in any order, even with programs that were not written to
176 expect this.
177
178 RETURN_IN_ORDER is an option available to programs that were written
179 to expect options and other ARGV-elements in any order and that care about
180 the ordering of the two. We describe each non-option ARGV-element
181 as if it were the argument of an option with character code 1.
182 Using `-' as the first character of the list of option characters
183 selects this mode of operation.
184
185 The special argument `--' forces an end of option-scanning regardless
186 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
187 `--' can cause `getopt' to return -1 with `optind' != ARGC. */
188
189 static enum
190 {
191 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
192 } ordering;
193
194 /* Value of POSIXLY_CORRECT environment variable. */
195 static char *posixly_correct;
196
197 #if defined(__GNU_LIBRARY__) || defined(WIN32)
198 /* We want to avoid inclusion of string.h with non-GNU libraries
199 because there are many ways it can cause trouble.
200 On some systems, it contains special magic macros that don't work
201 in GCC. */
202 #include <string.h>
203 #define my_index strchr
204 #else
205
206 /* Avoid depending on library functions or files
207 whose names are inconsistent. */
208
209 /* Can no longer have this declaration because of C23 (see c-std.h).
210 <stdlib.h> and <string.h> are almost certainly included already,
211 one way or another, so this whole #else branch of code seems
212 irrelevant nowadays, but we'll go with the minimal change. */
213 /* char *getenv (); */
214
215 static char *my_index(const char *str, int chr)
216 {
217 while (*str)
218 {
219 if (*str == chr)
220 return (char *) str;
221 str++;
222 }
223 return 0;
224 }
225
226 #endif /* not __GNU_LIBRARY__ */
227
228 /* Handle permutation of arguments. */
229
230 /* Describe the part of ARGV that contains non-options that have
231 been skipped. `first_nonopt' is the index in ARGV of the first of them;
232 `last_nonopt' is the index after the last of them. */
233
234 static int first_nonopt;
235 static int last_nonopt;
236
237 #ifdef _LIBC
238 /* Bash 2.0 gives us an environment variable containing flags
239 indicating ARGV elements that should not be considered arguments. */
240
241 static const char *nonoption_flags;
242 static int nonoption_flags_len;
243
244 static int original_argc;
245 static char *const *original_argv;
246
247 /* Make sure the environment variable bash 2.0 puts in the environment
248 is valid for the getopt call we must make sure that the ARGV passed
249 to getopt is that one passed to the process. */
250 static void store_args (int argc, char *const *argv) __attribute__ ((unused));
251 static void
252 store_args (int argc, char *const *argv)
253 {
254 /* XXX This is no good solution. We should rather copy the args so
255 that we can compare them later. But we must not use malloc(3). */
256 original_argc = argc;
257 original_argv = argv;
258 }
259 text_set_element (__libc_subinit, store_args);
260 #endif
261
262 /* Exchange two adjacent subsequences of ARGV.
263 One subsequence is elements [first_nonopt,last_nonopt)
264 which contains all the non-options that have been skipped so far.
265 The other is elements [last_nonopt,optind), which contains all
266 the options processed since those non-options were skipped.
267
268 `first_nonopt' and `last_nonopt' are relocated so that they describe
269 the new indices of the non-options in ARGV after they are moved. */
270
271 static void exchange(char **argv)
272 {
273 int bottom = first_nonopt;
274 int middle = last_nonopt;
275 int top = optind;
276 char *tem;
277
278 /* Exchange the shorter segment with the far end of the longer segment.
279 That puts the shorter segment into the right place.
280 It leaves the longer segment in the right place overall,
281 but it consists of two parts that need to be swapped next. */
282
283 while (top > middle && middle > bottom)
284 {
285 if (top - middle > middle - bottom)
286 {
287 /* Bottom segment is the short one. */
288 int len = middle - bottom;
289 register int i;
290
291 /* Swap it with the top part of the top segment. */
292 for (i = 0; i < len; i++)
293 {
294 tem = argv[bottom + i];
295 argv[bottom + i] = argv[top - (middle - bottom) + i];
296 argv[top - (middle - bottom) + i] = tem;
297 }
298 /* Exclude the moved bottom segment from further swapping. */
299 top -= len;
300 }
301 else
302 {
303 /* Top segment is the short one. */
304 int len = top - middle;
305 register int i;
306
307 /* Swap it with the bottom part of the bottom segment. */
308 for (i = 0; i < len; i++)
309 {
310 tem = argv[bottom + i];
311 argv[bottom + i] = argv[middle + i];
312 argv[middle + i] = tem;
313 }
314 /* Exclude the moved top segment from further swapping. */
315 bottom += len;
316 }
317 }
318
319 /* Update records for the slots the non-options now occupy. */
320
321 first_nonopt += (optind - last_nonopt);
322 last_nonopt = optind;
323 }
324
325 /* Initialize the internal data when the first call is made. */
326
327 static const char *_getopt_initialize(int argc, char *const *argv, const char *optstring)
328 {
329 /* Start processing options with ARGV-element 1 (since ARGV-element 0
330 is the program name); the sequence of previously skipped
331 non-option ARGV-elements is empty. */
332
333 first_nonopt = last_nonopt = optind = 1;
334
335 nextchar = NULL;
336
337 posixly_correct = getenv ("POSIXLY_CORRECT");
338
339 /* Determine how to handle the ordering of options and nonoptions. */
340
341 if (optstring[0] == '-')
342 {
343 ordering = RETURN_IN_ORDER;
344 ++optstring;
345 }
346 else if (optstring[0] == '+')
347 {
348 ordering = REQUIRE_ORDER;
349 ++optstring;
350 }
351 else if (posixly_correct != NULL)
352 ordering = REQUIRE_ORDER;
353 else
354 ordering = PERMUTE;
355
356 #ifdef _LIBC
357 if (posixly_correct == NULL
358 && argc == original_argc && argv == original_argv)
359 {
360 /* Bash 2.0 puts a special variable in the environment for each
361 command it runs, specifying which ARGV elements are the results of
362 file name wildcard expansion and therefore should not be
363 considered as options. */
364 char var[100];
365 sprintf (var, "_%d_GNU_nonoption_argv_flags_", getpid ());
366 nonoption_flags = getenv (var);
367 if (nonoption_flags == NULL)
368 nonoption_flags_len = 0;
369 else
370 nonoption_flags_len = strlen (nonoption_flags);
371 }
372 else
373 nonoption_flags_len = 0;
374 #endif
375
376 return optstring;
377 }
378
379 /* Scan elements of ARGV (whose length is ARGC) for option characters
380 given in OPTSTRING.
381
382 If an element of ARGV starts with '-', and is not exactly "-" or "--",
383 then it is an option element. The characters of this element
384 (aside from the initial '-') are option characters. If `getopt'
385 is called repeatedly, it returns successively each of the option characters
386 from each of the option elements.
387
388 If `getopt' finds another option character, it returns that character,
389 updating `optind' and `nextchar' so that the next call to `getopt' can
390 resume the scan with the following option character or ARGV-element.
391
392 If there are no more option characters, `getopt' returns -1.
393 Then `optind' is the index in ARGV of the first ARGV-element
394 that is not an option. (The ARGV-elements have been permuted
395 so that those that are not options now come last.)
396
397 OPTSTRING is a string containing the legitimate option characters.
398 If an option character is seen that is not listed in OPTSTRING,
399 return '?' after printing an error message. If you set `opterr' to
400 zero, the error message is suppressed but we still return '?'.
401
402 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
403 so the following text in the same ARGV-element, or the text of the following
404 ARGV-element, is returned in `optarg'. Two colons mean an option that
405 wants an optional arg; if there is text in the current ARGV-element,
406 it is returned in `optarg', otherwise `optarg' is set to zero.
407
408 If OPTSTRING starts with `-' or `+', it requests different methods of
409 handling the non-option ARGV-elements.
410 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
411
412 Long-named options begin with `--' instead of `-'.
413 Their names may be abbreviated as long as the abbreviation is unique
414 or is an exact match for some defined option. If they have an
415 argument, it follows the option name in the same ARGV-element, separated
416 from the option name by a `=', or else the in next ARGV-element.
417 When `getopt' finds a long-named option, it returns 0 if that option's
418 `flag' field is nonzero, the value of the option's `val' field
419 if the `flag' field is zero.
420
421 The elements of ARGV aren't really const, because we permute them.
422 But we pretend they're const in the prototype to be compatible
423 with other systems.
424
425 LONGOPTS is a vector of `struct option' terminated by an
426 element containing a name which is zero.
427
428 LONGIND returns the index in LONGOPT of the long-named option found.
429 It is only valid when a long-named option has been found by the most
430 recent call.
431
432 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
433 long-named options. */
434
435 int _getopt_internal(
436 int argc,
437 char *const *argv,
438 const char *optstring,
439 const struct option *longopts,
440 int *longind,
441 int long_only
442 ){
443 optarg = NULL;
444
445 if (!__getopt_initialized || optind == 0)
446 {
447 optstring = _getopt_initialize (argc, argv, optstring);
448 optind = 1; /* Don't scan ARGV[0], the program name. */
449 __getopt_initialized = 1;
450 }
451
452 /* Test whether ARGV[optind] points to a non-option argument.
453 Either it does not have option syntax, or there is an environment flag
454 from the shell indicating it is not an option. The later information
455 is only used when the used in the GNU libc. */
456 #ifdef _LIBC
457 #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
458 || (optind < nonoption_flags_len \
459 && nonoption_flags[optind] == '1'))
460 #else
461 #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
462 #endif
463
464 if (nextchar == NULL || *nextchar == '\0')
465 {
466 /* Advance to the next ARGV-element. */
467
468 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
469 moved back by the user (who may also have changed the arguments). */
470 if (last_nonopt > optind)
471 last_nonopt = optind;
472 if (first_nonopt > optind)
473 first_nonopt = optind;
474
475 if (ordering == PERMUTE)
476 {
477 /* If we have just processed some options following some non-options,
478 exchange them so that the options come first. */
479
480 if (first_nonopt != last_nonopt && last_nonopt != optind)
481 exchange ((char **) argv);
482 else if (last_nonopt != optind)
483 first_nonopt = optind;
484
485 /* Skip any additional non-options
486 and extend the range of non-options previously skipped. */
487
488 while (optind < argc && NONOPTION_P)
489 optind++;
490 last_nonopt = optind;
491 }
492
493 /* The special ARGV-element `--' means premature end of options.
494 Skip it like a null option,
495 then exchange with previous non-options as if it were an option,
496 then skip everything else like a non-option. */
497
498 if (optind != argc && !strcmp (argv[optind], "--"))
499 {
500 optind++;
501
502 if (first_nonopt != last_nonopt && last_nonopt != optind)
503 exchange ((char **) argv);
504 else if (first_nonopt == last_nonopt)
505 first_nonopt = optind;
506 last_nonopt = argc;
507
508 optind = argc;
509 }
510
511 /* If we have done all the ARGV-elements, stop the scan
512 and back over any non-options that we skipped and permuted. */
513
514 if (optind == argc)
515 {
516 /* Set the next-arg-index to point at the non-options
517 that we previously skipped, so the caller will digest them. */
518 if (first_nonopt != last_nonopt)
519 optind = first_nonopt;
520 return -1;
521 }
522
523 /* If we have come to a non-option and did not permute it,
524 either stop the scan or describe it to the caller and pass it by. */
525
526 if (NONOPTION_P)
527 {
528 if (ordering == REQUIRE_ORDER)
529 return -1;
530 optarg = argv[optind++];
531 return 1;
532 }
533
534 /* We have found another option-ARGV-element.
535 Skip the initial punctuation. */
536
537 nextchar = (argv[optind] + 1
538 + (longopts != NULL && argv[optind][1] == '-'));
539 }
540
541 /* Decode the current option-ARGV-element. */
542
543 /* Check whether the ARGV-element is a long option.
544
545 If long_only and the ARGV-element has the form "-f", where f is
546 a valid short option, don't consider it an abbreviated form of
547 a long option that starts with f. Otherwise there would be no
548 way to give the -f short option.
549
550 On the other hand, if there's a long option "fubar" and
551 the ARGV-element is "-fu", do consider that an abbreviation of
552 the long option, just like "--fu", and not "-f" with arg "u".
553
554 This distinction seems to be the most useful approach. */
555
556 if (longopts != NULL
557 && (argv[optind][1] == '-'
558 || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
559 {
560 char *nameend;
561 const struct option *p;
562 const struct option *pfound = NULL;
563 int exact = 0;
564 int ambig = 0;
565 int indfound = -1;
566 int option_index;
567
568 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
569 /* Do nothing. */ ;
570
571 /* Test all long options for either exact match
572 or abbreviated matches. */
573 for (p = longopts, option_index = 0; p->name; p++, option_index++)
574 if (!strncmp (p->name, nextchar, nameend - nextchar))
575 {
576 if ((unsigned int) (nameend - nextchar)
577 == (unsigned int) strlen (p->name))
578 {
579 /* Exact match found. */
580 pfound = p;
581 indfound = option_index;
582 exact = 1;
583 break;
584 }
585 else if (pfound == NULL)
586 {
587 /* First nonexact match found. */
588 pfound = p;
589 indfound = option_index;
590 }
591 else
592 /* Second or later nonexact match found. */
593 ambig = 1;
594 }
595
596 if (ambig && !exact)
597 {
598 if (opterr)
599 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
600 argv[0], argv[optind]);
601 nextchar += strlen (nextchar);
602 optind++;
603 optopt = 0;
604 return '?';
605 }
606
607 if (pfound != NULL)
608 {
609 option_index = indfound;
610 optind++;
611 if (*nameend)
612 {
613 /* Don't test has_arg with >, because some C compilers don't
614 allow it to be used on enums. */
615 if (pfound->has_arg)
616 optarg = nameend + 1;
617 else
618 {
619 if (opterr)
620 {
621 if (argv[optind - 1][1] == '-')
622 /* --option */
623 fprintf (stderr,
624 _("%s: option `--%s' doesn't allow an argument\n"),
625 argv[0], pfound->name);
626 else
627 /* +option or -option */
628 fprintf (stderr,
629 _("%s: option `%c%s' doesn't allow an argument\n"),
630 argv[0], argv[optind - 1][0], pfound->name);
631 }
632
633 nextchar += strlen (nextchar);
634
635 optopt = pfound->val;
636 return '?';
637 }
638 }
639 else if (pfound->has_arg == 1)
640 {
641 if (optind < argc)
642 optarg = argv[optind++];
643 else
644 {
645 if (opterr)
646 fprintf (stderr,
647 _("%s: option `%s' requires an argument\n"),
648 argv[0], argv[optind - 1]);
649 nextchar += strlen (nextchar);
650 optopt = pfound->val;
651 return optstring[0] == ':' ? ':' : '?';
652 }
653 }
654 nextchar += strlen (nextchar);
655 if (longind != NULL)
656 *longind = option_index;
657 if (pfound->flag)
658 {
659 *(pfound->flag) = pfound->val;
660 return 0;
661 }
662 return pfound->val;
663 }
664
665 /* Can't find it as a long option. If this is not getopt_long_only,
666 or the option starts with '--' or is not a valid short
667 option, then it's an error.
668 Otherwise interpret it as a short option. */
669 if (!long_only || argv[optind][1] == '-'
670 || my_index (optstring, *nextchar) == NULL)
671 {
672 if (opterr)
673 {
674 if (argv[optind][1] == '-')
675 /* --option */
676 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
677 argv[0], nextchar);
678 else
679 /* +option or -option */
680 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
681 argv[0], argv[optind][0], nextchar);
682 }
683 nextchar = (char *) "";
684 optind++;
685 optopt = 0;
686 return '?';
687 }
688 }
689
690 /* Look at and handle the next short option-character. */
691
692 {
693 char c = *nextchar++;
694 char *temp = my_index (optstring, c);
695
696 /* Increment `optind' when we start to process its last character. */
697 if (*nextchar == '\0')
698 ++optind;
699
700 if (temp == NULL || c == ':')
701 {
702 if (opterr)
703 {
704 if (posixly_correct)
705 /* 1003.2 specifies the format of this message. */
706 fprintf (stderr, _("%s: illegal option -- %c\n"),
707 argv[0], c);
708 else
709 fprintf (stderr, _("%s: invalid option -- %c\n"),
710 argv[0], c);
711 }
712 optopt = c;
713 return '?';
714 }
715 /* Convenience. Treat POSIX -W foo same as long option --foo */
716 if (temp[0] == 'W' && temp[1] == ';')
717 {
718 char *nameend;
719 const struct option *p;
720 const struct option *pfound = NULL;
721 int exact = 0;
722 int ambig = 0;
723 int indfound = 0;
724 int option_index;
725
726 /* This is an option that requires an argument. */
727 if (*nextchar != '\0')
728 {
729 optarg = nextchar;
730 /* If we end this ARGV-element by taking the rest as an arg,
731 we must advance to the next element now. */
732 optind++;
733 }
734 else if (optind == argc)
735 {
736 if (opterr)
737 {
738 /* 1003.2 specifies the format of this message. */
739 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
740 argv[0], c);
741 }
742 optopt = c;
743 if (optstring[0] == ':')
744 c = ':';
745 else
746 c = '?';
747 return c;
748 }
749 else
750 /* We already incremented `optind' once;
751 increment it again when taking next ARGV-elt as argument. */
752 optarg = argv[optind++];
753
754 /* optarg is now the argument, see if it's in the
755 table of longopts. */
756
757 for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
758 /* Do nothing. */ ;
759
760 /* Test all long options for either exact match
761 or abbreviated matches. */
762 for (p = longopts, option_index = 0; p->name; p++, option_index++)
763 if (!strncmp (p->name, nextchar, nameend - nextchar))
764 {
765 if ((unsigned int) (nameend - nextchar) == strlen (p->name))
766 {
767 /* Exact match found. */
768 pfound = p;
769 indfound = option_index;
770 exact = 1;
771 break;
772 }
773 else if (pfound == NULL)
774 {
775 /* First nonexact match found. */
776 pfound = p;
777 indfound = option_index;
778 }
779 else
780 /* Second or later nonexact match found. */
781 ambig = 1;
782 }
783 if (ambig && !exact)
784 {
785 if (opterr)
786 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
787 argv[0], argv[optind]);
788 nextchar += strlen (nextchar);
789 optind++;
790 return '?';
791 }
792 if (pfound != NULL)
793 {
794 option_index = indfound;
795 if (*nameend)
796 {
797 /* Don't test has_arg with >, because some C compilers don't
798 allow it to be used on enums. */
799 if (pfound->has_arg)
800 optarg = nameend + 1;
801 else
802 {
803 if (opterr)
804 fprintf (stderr, _("\
805 %s: option `-W %s' doesn't allow an argument\n"),
806 argv[0], pfound->name);
807
808 nextchar += strlen (nextchar);
809 return '?';
810 }
811 }
812 else if (pfound->has_arg == 1)
813 {
814 if (optind < argc)
815 optarg = argv[optind++];
816 else
817 {
818 if (opterr)
819 fprintf (stderr,
820 _("%s: option `%s' requires an argument\n"),
821 argv[0], argv[optind - 1]);
822 nextchar += strlen (nextchar);
823 return optstring[0] == ':' ? ':' : '?';
824 }
825 }
826 nextchar += strlen (nextchar);
827 if (longind != NULL)
828 *longind = option_index;
829 if (pfound->flag)
830 {
831 *(pfound->flag) = pfound->val;
832 return 0;
833 }
834 return pfound->val;
835 }
836 nextchar = NULL;
837 return 'W'; /* Let the application handle it. */
838 }
839 if (temp[1] == ':')
840 {
841 if (temp[2] == ':')
842 {
843 /* This is an option that accepts an argument optionally. */
844 if (*nextchar != '\0')
845 {
846 optarg = nextchar;
847 optind++;
848 }
849 else
850 optarg = NULL;
851 nextchar = NULL;
852 }
853 else
854 {
855 /* This is an option that requires an argument. */
856 if (*nextchar != '\0')
857 {
858 optarg = nextchar;
859 /* If we end this ARGV-element by taking the rest as an arg,
860 we must advance to the next element now. */
861 optind++;
862 }
863 else if (optind == argc)
864 {
865 if (opterr)
866 {
867 /* 1003.2 specifies the format of this message. */
868 fprintf (stderr,
869 _("%s: option requires an argument -- %c\n"),
870 argv[0], c);
871 }
872 optopt = c;
873 if (optstring[0] == ':')
874 c = ':';
875 else
876 c = '?';
877 }
878 else
879 /* We already incremented `optind' once;
880 increment it again when taking next ARGV-elt as argument. */
881 optarg = argv[optind++];
882 nextchar = NULL;
883 }
884 }
885 return c;
886 }
887 }
888
889 int getopt(int argc, char *const *argv, const char *optstring)
890 {
891 return _getopt_internal (argc, argv, optstring,
892 (const struct option *) 0,
893 (int *) 0,
894 0);
895 }
896
897 #endif /* Not ELIDE_CODE. */
898
899 #ifdef TEST
900
901 /* Compile with -DTEST to make an executable for use in testing
902 the above definition of `getopt'. */
903
904 int main(int argc, char **argv)
905 {
906 int c;
907 int digit_optind = 0;
908
909 while (1)
910 {
911 int this_option_optind = optind ? optind : 1;
912
913 c = getopt (argc, argv, "abc:d:0123456789");
914 if (c == -1)
915 break;
916
917 switch (c)
918 {
919 case '0':
920 case '1':
921 case '2':
922 case '3':
923 case '4':
924 case '5':
925 case '6':
926 case '7':
927 case '8':
928 case '9':
929 if (digit_optind != 0 && digit_optind != this_option_optind)
930 printf ("digits occur in two different argv-elements.\n");
931 digit_optind = this_option_optind;
932 printf ("option %c\n", c);
933 break;
934
935 case 'a':
936 printf ("option a\n");
937 break;
938
939 case 'b':
940 printf ("option b\n");
941 break;
942
943 case 'c':
944 printf ("option c with value `%s'\n", optarg);
945 break;
946
947 case '?':
948 break;
949
950 default:
951 printf ("?? getopt returned character code 0%o ??\n", c);
952 }
953 }
954
955 if (optind < argc)
956 {
957 printf ("non-option ARGV-elements: ");
958 while (optind < argc)
959 printf ("%s ", argv[optind++]);
960 printf ("\n");
961 }
962
963 exit (0);
964 }
965
966 #endif /* TEST */