2 Copyright (C) 1987-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library and is also part of gnulib.
4 Patches to this file should be submitted to both projects.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
36 /* When used as part of glibc, error printing must be done differently
37 for standards compliance. getopt is not a cancellation point, so
38 it must not call functions that are, and it is specified by an
39 older standard than stdio locking, so it must not refer to
40 functions in the "user namespace" related to stdio locking.
41 Finally, it must use glibc's internal message translation so that
42 the messages are looked up in the proper text domain. */
44 # define fprintf __fxprintf_nocancel
45 # define flockfile(fp) _IO_flockfile (fp)
46 # define funlockfile(fp) _IO_funlockfile (fp)
48 /* Completely disable NLS for getopt. We won't include translations for it
49 anyway. If the system lacks getopt_long, missing translations probably
51 //# include "gettext.h"
52 //# define _(msgid) gettext (msgid)
53 #define _(msgid) (msgid)
54 /* When used standalone, flockfile and funlockfile might not be
56 # if (!defined _POSIX_THREAD_SAFE_FUNCTIONS \
57 || (defined _WIN32 && ! defined __CYGWIN__))
58 # define flockfile(fp) /* nop */
59 # define funlockfile(fp) /* nop */
61 /* When used standalone, do not attempt to use alloca. */
62 # define __libc_use_alloca(size) 0
64 # define alloca(size) (abort (), (void *)0)
67 /* This implementation of 'getopt' has three modes for handling
68 options interspersed with non-option arguments. It can stop
69 scanning for options at the first non-option argument encountered,
70 as POSIX specifies. It can continue scanning for options after the
71 first non-option argument, but permute 'argv' as it goes so that,
72 after 'getopt' is done, all the options precede all the non-option
73 arguments and 'optind' points to the first non-option argument.
74 Or, it can report non-option arguments as if they were arguments to
75 the option character '\x01'.
77 The default behavior of 'getopt_long' is to permute the argument list.
78 When this implementation is used standalone, the default behavior of
79 'getopt' is to stop at the first non-option argument, but when it is
80 used as part of GNU libc it also permutes the argument list. In both
81 cases, setting the environment variable POSIXLY_CORRECT to any value
84 If the first character of the OPTSTRING argument to 'getopt' or
85 'getopt_long' is '+', both functions will stop at the first
86 non-option argument. If it is '-', both functions will report
87 non-option arguments as arguments to the option character '\x01'. */
89 #include "getopt_int.h"
91 /* For communication from 'getopt' to the caller.
92 When 'getopt' finds an option that takes an argument,
93 the argument value is returned here.
94 Also, when 'ordering' is RETURN_IN_ORDER,
95 each non-option ARGV-element is returned here. */
99 /* Index in ARGV of the next element to be scanned.
100 This is used for communication to and from the caller
101 and for communication between successive calls to 'getopt'.
103 On entry to 'getopt', zero means this is the first call; initialize.
105 When 'getopt' returns -1, this is the index of the first of the
106 non-option elements that the caller should itself scan.
108 Otherwise, 'optind' communicates from one call to the next
109 how much of ARGV has been scanned so far. */
111 /* 1003.2 says this must be 1 before any call. */
114 /* Callers store zero here to inhibit the error message
115 for unrecognized options. */
119 /* Set to an option character which was unrecognized.
120 This must be initialized on some systems to avoid linking in the
121 system's own getopt implementation. */
125 /* Keep a global copy of all internal members of getopt_data. */
127 static struct _getopt_data getopt_data
;
129 /* Exchange two adjacent subsequences of ARGV.
130 One subsequence is elements [first_nonopt,last_nonopt)
131 which contains all the non-options that have been skipped so far.
132 The other is elements [last_nonopt,optind), which contains all
133 the options processed since those non-options were skipped.
135 'first_nonopt' and 'last_nonopt' are relocated so that they describe
136 the new indices of the non-options in ARGV after they are moved. */
139 exchange (char **argv
, struct _getopt_data
*d
)
141 int bottom
= d
->__first_nonopt
;
142 int middle
= d
->__last_nonopt
;
146 /* Exchange the shorter segment with the far end of the longer segment.
147 That puts the shorter segment into the right place.
148 It leaves the longer segment in the right place overall,
149 but it consists of two parts that need to be swapped next. */
151 while (top
> middle
&& middle
> bottom
)
153 if (top
- middle
> middle
- bottom
)
155 /* Bottom segment is the short one. */
156 int len
= middle
- bottom
;
159 /* Swap it with the top part of the top segment. */
160 for (i
= 0; i
< len
; i
++)
162 tem
= argv
[bottom
+ i
];
163 argv
[bottom
+ i
] = argv
[top
- (middle
- bottom
) + i
];
164 argv
[top
- (middle
- bottom
) + i
] = tem
;
166 /* Exclude the moved bottom segment from further swapping. */
171 /* Top segment is the short one. */
172 int len
= top
- middle
;
175 /* Swap it with the bottom part of the bottom segment. */
176 for (i
= 0; i
< len
; i
++)
178 tem
= argv
[bottom
+ i
];
179 argv
[bottom
+ i
] = argv
[middle
+ i
];
180 argv
[middle
+ i
] = tem
;
182 /* Exclude the moved top segment from further swapping. */
187 /* Update records for the slots the non-options now occupy. */
189 d
->__first_nonopt
+= (d
->optind
- d
->__last_nonopt
);
190 d
->__last_nonopt
= d
->optind
;
193 /* Process the argument starting with d->__nextchar as a long option.
194 d->optind should *not* have been advanced over this argument.
196 If the value returned is -1, it was not actually a long option, the
197 state is unchanged, and the argument should be processed as a set
198 of short options (this can only happen when long_only is true).
199 Otherwise, the option (and its argument, if any) have been consumed
200 and the return value is the value to return from _getopt_internal_r. */
202 process_long_option (int argc
, char **argv
, const char *optstring
,
203 const struct option
*longopts
, int *longind
,
204 int long_only
, struct _getopt_data
*d
,
205 int print_errors
, const char *prefix
)
209 const struct option
*p
;
210 const struct option
*pfound
= NULL
;
214 for (nameend
= d
->__nextchar
; *nameend
&& *nameend
!= '='; nameend
++)
216 namelen
= (size_t)(nameend
- d
->__nextchar
);
218 /* First look for an exact match, counting the options as a side
220 for (p
= longopts
, n_options
= 0; p
->name
; p
++, n_options
++)
221 if (!strncmp (p
->name
, d
->__nextchar
, namelen
)
222 && namelen
== strlen (p
->name
))
224 /* Exact match found. */
226 option_index
= n_options
;
232 /* Didn't find an exact match, so look for abbreviations. */
233 unsigned char *ambig_set
= NULL
;
234 int ambig_malloced
= 0;
235 int ambig_fallback
= 0;
238 for (p
= longopts
, option_index
= 0; p
->name
; p
++, option_index
++)
239 if (!strncmp (p
->name
, d
->__nextchar
, namelen
))
243 /* First nonexact match found. */
245 indfound
= option_index
;
248 || pfound
->has_arg
!= p
->has_arg
249 || pfound
->flag
!= p
->flag
250 || pfound
->val
!= p
->val
)
252 /* Second or later nonexact match found. */
256 /* Don't waste effort tracking the ambig set if
257 we're not going to print it anyway. */
261 if (__libc_use_alloca (n_options
))
262 ambig_set
= alloca (n_options
);
263 else if ((ambig_set
= malloc ((size_t)n_options
)) == NULL
)
264 /* Fall back to simpler error message. */
271 memset (ambig_set
, 0, (size_t)n_options
);
272 ambig_set
[indfound
] = 1;
276 ambig_set
[option_index
] = 1;
281 if (ambig_set
|| ambig_fallback
)
286 fprintf (stderr
, _("%s: option '%s%s' is ambiguous\n"),
287 argv
[0], prefix
, d
->__nextchar
);
292 _("%s: option '%s%s' is ambiguous; possibilities:"),
293 argv
[0], prefix
, d
->__nextchar
);
295 for (option_index
= 0; option_index
< n_options
; option_index
++)
296 if (ambig_set
[option_index
])
297 fprintf (stderr
, " '%s%s'",
298 prefix
, longopts
[option_index
].name
);
300 /* This must use 'fprintf' even though it's only
301 printing a single character, so that it goes through
302 __fxprintf_nocancel when compiled as part of glibc. */
303 fprintf (stderr
, "\n");
304 funlockfile (stderr
);
309 d
->__nextchar
+= strlen (d
->__nextchar
);
315 option_index
= indfound
;
320 /* Can't find it as a long option. If this is not getopt_long_only,
321 or the option starts with '--' or is not a valid short option,
322 then it's an error. */
323 if (!long_only
|| argv
[d
->optind
][1] == '-'
324 || strchr (optstring
, *d
->__nextchar
) == NULL
)
327 fprintf (stderr
, _("%s: unrecognized option '%s%s'\n"),
328 argv
[0], prefix
, d
->__nextchar
);
330 d
->__nextchar
= NULL
;
336 /* Otherwise interpret it as a short option. */
340 /* We have found a matching long option. Consume it. */
342 d
->__nextchar
= NULL
;
345 /* Don't test has_arg with >, because some C compilers don't
346 allow it to be used on enums. */
348 d
->optarg
= nameend
+ 1;
353 _("%s: option '%s%s' doesn't allow an argument\n"),
354 argv
[0], prefix
, pfound
->name
);
356 d
->optopt
= pfound
->val
;
360 else if (pfound
->has_arg
== 1)
362 if (d
->optind
< argc
)
363 d
->optarg
= argv
[d
->optind
++];
368 _("%s: option '%s%s' requires an argument\n"),
369 argv
[0], prefix
, pfound
->name
);
371 d
->optopt
= pfound
->val
;
372 return optstring
[0] == ':' ? ':' : '?';
377 *longind
= option_index
;
380 *(pfound
->flag
) = pfound
->val
;
386 /* Initialize internal data upon the first call to getopt. */
389 _getopt_initialize (int argc
,
390 char **argv
, const char *optstring
,
391 struct _getopt_data
*d
, int posixly_correct
)
395 /* Start processing options with ARGV-element 1 (since ARGV-element 0
396 is the program name); the sequence of previously skipped
397 non-option ARGV-elements is empty. */
401 d
->__first_nonopt
= d
->__last_nonopt
= d
->optind
;
402 d
->__nextchar
= NULL
;
404 /* Determine how to handle the ordering of options and nonoptions. */
405 if (optstring
[0] == '-')
407 d
->__ordering
= RETURN_IN_ORDER
;
410 else if (optstring
[0] == '+')
412 d
->__ordering
= REQUIRE_ORDER
;
415 else if (posixly_correct
|| !!getenv ("POSIXLY_CORRECT"))
416 d
->__ordering
= REQUIRE_ORDER
;
418 d
->__ordering
= PERMUTE
;
420 d
->__initialized
= 1;
424 /* Scan elements of ARGV (whose length is ARGC) for option characters
427 If an element of ARGV starts with '-', and is not exactly "-" or "--",
428 then it is an option element. The characters of this element
429 (aside from the initial '-') are option characters. If 'getopt'
430 is called repeatedly, it returns successively each of the option characters
431 from each of the option elements.
433 If 'getopt' finds another option character, it returns that character,
434 updating 'optind' and 'nextchar' so that the next call to 'getopt' can
435 resume the scan with the following option character or ARGV-element.
437 If there are no more option characters, 'getopt' returns -1.
438 Then 'optind' is the index in ARGV of the first ARGV-element
439 that is not an option. (The ARGV-elements have been permuted
440 so that those that are not options now come last.)
442 OPTSTRING is a string containing the legitimate option characters.
443 If an option character is seen that is not listed in OPTSTRING,
444 return '?' after printing an error message. If you set 'opterr' to
445 zero, the error message is suppressed but we still return '?'.
447 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
448 so the following text in the same ARGV-element, or the text of the following
449 ARGV-element, is returned in 'optarg'. Two colons mean an option that
450 wants an optional arg; if there is text in the current ARGV-element,
451 it is returned in 'optarg', otherwise 'optarg' is set to zero.
453 If OPTSTRING starts with '-' or '+', it requests different methods of
454 handling the non-option ARGV-elements.
455 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
457 Long-named options begin with '--' instead of '-'.
458 Their names may be abbreviated as long as the abbreviation is unique
459 or is an exact match for some defined option. If they have an
460 argument, it follows the option name in the same ARGV-element, separated
461 from the option name by a '=', or else the in next ARGV-element.
462 When 'getopt' finds a long-named option, it returns 0 if that option's
463 'flag' field is nonzero, the value of the option's 'val' field
464 if the 'flag' field is zero.
466 The elements of ARGV aren't really const, because we permute them.
467 But we pretend they're const in the prototype to be compatible
470 LONGOPTS is a vector of 'struct option' terminated by an
471 element containing a name which is zero.
473 LONGIND returns the index in LONGOPT of the long-named option found.
474 It is only valid when a long-named option has been found by the most
477 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
478 long-named options. */
481 _getopt_internal_r (int argc
, char **argv
, const char *optstring
,
482 const struct option
*longopts
, int *longind
,
483 int long_only
, struct _getopt_data
*d
, int posixly_correct
)
485 int print_errors
= d
->opterr
;
492 if (d
->optind
== 0 || !d
->__initialized
)
493 optstring
= _getopt_initialize (argc
, argv
, optstring
, d
, posixly_correct
);
494 else if (optstring
[0] == '-' || optstring
[0] == '+')
497 if (optstring
[0] == ':')
500 /* Test whether ARGV[optind] points to a non-option argument. */
501 #define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
503 if (d
->__nextchar
== NULL
|| *d
->__nextchar
== '\0')
505 /* Advance to the next ARGV-element. */
507 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
508 moved back by the user (who may also have changed the arguments). */
509 if (d
->__last_nonopt
> d
->optind
)
510 d
->__last_nonopt
= d
->optind
;
511 if (d
->__first_nonopt
> d
->optind
)
512 d
->__first_nonopt
= d
->optind
;
514 if (d
->__ordering
== PERMUTE
)
516 /* If we have just processed some options following some non-options,
517 exchange them so that the options come first. */
519 if (d
->__first_nonopt
!= d
->__last_nonopt
520 && d
->__last_nonopt
!= d
->optind
)
522 else if (d
->__last_nonopt
!= d
->optind
)
523 d
->__first_nonopt
= d
->optind
;
525 /* Skip any additional non-options
526 and extend the range of non-options previously skipped. */
528 while (d
->optind
< argc
&& NONOPTION_P
)
530 d
->__last_nonopt
= d
->optind
;
533 /* The special ARGV-element '--' means premature end of options.
534 Skip it like a null option,
535 then exchange with previous non-options as if it were an option,
536 then skip everything else like a non-option. */
538 if (d
->optind
!= argc
&& !strcmp (argv
[d
->optind
], "--"))
542 if (d
->__first_nonopt
!= d
->__last_nonopt
543 && d
->__last_nonopt
!= d
->optind
)
545 else if (d
->__first_nonopt
== d
->__last_nonopt
)
546 d
->__first_nonopt
= d
->optind
;
547 d
->__last_nonopt
= argc
;
552 /* If we have done all the ARGV-elements, stop the scan
553 and back over any non-options that we skipped and permuted. */
555 if (d
->optind
== argc
)
557 /* Set the next-arg-index to point at the non-options
558 that we previously skipped, so the caller will digest them. */
559 if (d
->__first_nonopt
!= d
->__last_nonopt
)
560 d
->optind
= d
->__first_nonopt
;
564 /* If we have come to a non-option and did not permute it,
565 either stop the scan or describe it to the caller and pass it by. */
569 if (d
->__ordering
== REQUIRE_ORDER
)
571 d
->optarg
= argv
[d
->optind
++];
575 /* We have found another option-ARGV-element.
576 Check whether it might be a long option. */
579 if (argv
[d
->optind
][1] == '-')
581 /* "--foo" is always a long option. The special option
582 "--" was handled above. */
583 d
->__nextchar
= argv
[d
->optind
] + 2;
584 return process_long_option (argc
, argv
, optstring
, longopts
,
585 longind
, long_only
, d
,
589 /* If long_only and the ARGV-element has the form "-f",
590 where f is a valid short option, don't consider it an
591 abbreviated form of a long option that starts with f.
592 Otherwise there would be no way to give the -f short
595 On the other hand, if there's a long option "fubar" and
596 the ARGV-element is "-fu", do consider that an
597 abbreviation of the long option, just like "--fu", and
598 not "-f" with arg "u".
600 This distinction seems to be the most useful approach. */
601 if (long_only
&& (argv
[d
->optind
][2]
602 || !strchr (optstring
, argv
[d
->optind
][1])))
605 d
->__nextchar
= argv
[d
->optind
] + 1;
606 code
= process_long_option (argc
, argv
, optstring
, longopts
,
607 longind
, long_only
, d
,
614 /* It is not a long option. Skip the initial punctuation. */
615 d
->__nextchar
= argv
[d
->optind
] + 1;
618 /* Look at and handle the next short option-character. */
621 char c
= *d
->__nextchar
++;
622 const char *temp
= strchr (optstring
, c
);
624 /* Increment 'optind' when we start to process its last character. */
625 if (*d
->__nextchar
== '\0')
628 if (temp
== NULL
|| c
== ':' || c
== ';')
631 fprintf (stderr
, _("%s: invalid option -- '%c'\n"), argv
[0], c
);
636 /* Convenience. Treat POSIX -W foo same as long option --foo */
637 if (temp
[0] == 'W' && temp
[1] == ';' && longopts
!= NULL
)
639 /* This is an option that requires an argument. */
640 if (*d
->__nextchar
!= '\0')
641 d
->optarg
= d
->__nextchar
;
642 else if (d
->optind
== argc
)
646 _("%s: option requires an argument -- '%c'\n"),
650 if (optstring
[0] == ':')
657 d
->optarg
= argv
[d
->optind
];
659 d
->__nextchar
= d
->optarg
;
661 return process_long_option (argc
, argv
, optstring
, longopts
, longind
,
662 0 /* long_only */, d
, print_errors
, "-W ");
668 /* This is an option that accepts an argument optionally. */
669 if (*d
->__nextchar
!= '\0')
671 d
->optarg
= d
->__nextchar
;
676 d
->__nextchar
= NULL
;
680 /* This is an option that requires an argument. */
681 if (*d
->__nextchar
!= '\0')
683 d
->optarg
= d
->__nextchar
;
684 /* If we end this ARGV-element by taking the rest as an arg,
685 we must advance to the next element now. */
688 else if (d
->optind
== argc
)
692 _("%s: option requires an argument -- '%c'\n"),
696 if (optstring
[0] == ':')
702 /* We already incremented 'optind' once;
703 increment it again when taking next ARGV-elt as argument. */
704 d
->optarg
= argv
[d
->optind
++];
705 d
->__nextchar
= NULL
;
713 _getopt_internal (int argc
, char **argv
, const char *optstring
,
714 const struct option
*longopts
, int *longind
, int long_only
,
719 getopt_data
.optind
= optind
;
720 getopt_data
.opterr
= opterr
;
722 result
= _getopt_internal_r (argc
, argv
, optstring
, longopts
,
723 longind
, long_only
, &getopt_data
,
726 optind
= getopt_data
.optind
;
727 optarg
= getopt_data
.optarg
;
728 optopt
= getopt_data
.optopt
;
733 /* glibc gets a LSB-compliant getopt and a POSIX-complaint __posix_getopt.
734 Standalone applications just get a POSIX-compliant getopt.
735 POSIX and LSB both require these functions to take 'char *const *argv'
736 even though this is incorrect (because of the permutation). */
737 #define GETOPT_ENTRY(NAME, POSIXLY_CORRECT) \
739 NAME (int argc, char *const *argv, const char *optstring) \
741 return _getopt_internal (argc, (char **)argv, optstring, \
742 0, 0, 0, POSIXLY_CORRECT); \
746 GETOPT_ENTRY(getopt
, 0)
747 GETOPT_ENTRY(__posix_getopt
, 1)
749 GETOPT_ENTRY(getopt
, 1)
755 /* Compile with -DTEST to make an executable for use in testing
756 the above definition of 'getopt'. */
759 main (int argc
, char **argv
)
762 int digit_optind
= 0;
766 int this_option_optind
= optind
? optind
: 1;
768 c
= getopt (argc
, argv
, "abc:d:0123456789");
784 if (digit_optind
!= 0 && digit_optind
!= this_option_optind
)
785 printf ("digits occur in two different argv-elements.\n");
786 digit_optind
= this_option_optind
;
787 printf ("option %c\n", c
);
791 printf ("option a\n");
795 printf ("option b\n");
799 printf ("option c with value '%s'\n", optarg
);
806 printf ("?? getopt returned character code 0%o ??\n", c
);
812 printf ("non-option ARGV-elements: ");
813 while (optind
< argc
)
814 printf ("%s ", argv
[optind
++]);