Debian Codegraph @

subprojects/gperf/lib/getopt.c

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