Debian Codegraph @

src/getopt.c

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