liblzma: Omit CRC tables when not needed with ARM64 optimizations.
[xz.git] / lib / getopt.c
blob5941f6fdde2a1a3166353cb0e11033dd2d363bda
1 /* Getopt for GNU.
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/>. */
20 #ifndef _LIBC
21 # ifdef HAVE_CONFIG_H
22 # include <config.h>
23 # endif
24 #endif
26 #include "getopt.h"
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #ifndef _MSC_VER
32 # include <unistd.h>
33 #endif
35 #ifdef _LIBC
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. */
43 # include <libintl.h>
44 # define fprintf __fxprintf_nocancel
45 # define flockfile(fp) _IO_flockfile (fp)
46 # define funlockfile(fp) _IO_funlockfile (fp)
47 #else
48 /* Completely disable NLS for getopt. We won't include translations for it
49 anyway. If the system lacks getopt_long, missing translations probably
50 aren't a problem. */
51 //# include "gettext.h"
52 //# define _(msgid) gettext (msgid)
53 #define _(msgid) (msgid)
54 /* When used standalone, flockfile and funlockfile might not be
55 available. */
56 # if (!defined _POSIX_THREAD_SAFE_FUNCTIONS \
57 || (defined _WIN32 && ! defined __CYGWIN__))
58 # define flockfile(fp) /* nop */
59 # define funlockfile(fp) /* nop */
60 # endif
61 /* When used standalone, do not attempt to use alloca. */
62 # define __libc_use_alloca(size) 0
63 # undef alloca
64 # define alloca(size) (abort (), (void *)0)
65 #endif
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
82 disables permutation.
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. */
97 char *optarg;
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. */
112 int optind = 1;
114 /* Callers store zero here to inhibit the error message
115 for unrecognized options. */
117 int opterr = 1;
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. */
123 int optopt = '?';
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. */
138 static void
139 exchange (char **argv, struct _getopt_data *d)
141 int bottom = d->__first_nonopt;
142 int middle = d->__last_nonopt;
143 int top = d->optind;
144 char *tem;
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;
157 int i;
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. */
167 top -= len;
169 else
171 /* Top segment is the short one. */
172 int len = top - middle;
173 int i;
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. */
183 bottom += len;
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. */
201 static int
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)
207 char *nameend;
208 size_t namelen;
209 const struct option *p;
210 const struct option *pfound = NULL;
211 int n_options;
212 int option_index;
214 for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
215 /* Do nothing. */ ;
216 namelen = (size_t)(nameend - d->__nextchar);
218 /* First look for an exact match, counting the options as a side
219 effect. */
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. */
225 pfound = p;
226 option_index = n_options;
227 break;
230 if (pfound == NULL)
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;
236 int indfound = -1;
238 for (p = longopts, option_index = 0; p->name; p++, option_index++)
239 if (!strncmp (p->name, d->__nextchar, namelen))
241 if (pfound == NULL)
243 /* First nonexact match found. */
244 pfound = p;
245 indfound = option_index;
247 else if (long_only
248 || pfound->has_arg != p->has_arg
249 || pfound->flag != p->flag
250 || pfound->val != p->val)
252 /* Second or later nonexact match found. */
253 if (!ambig_fallback)
255 if (!print_errors)
256 /* Don't waste effort tracking the ambig set if
257 we're not going to print it anyway. */
258 ambig_fallback = 1;
259 else if (!ambig_set)
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. */
265 ambig_fallback = 1;
266 else
267 ambig_malloced = 1;
269 if (ambig_set)
271 memset (ambig_set, 0, (size_t)n_options);
272 ambig_set[indfound] = 1;
275 if (ambig_set)
276 ambig_set[option_index] = 1;
281 if (ambig_set || ambig_fallback)
283 if (print_errors)
285 if (ambig_fallback)
286 fprintf (stderr, _("%s: option '%s%s' is ambiguous\n"),
287 argv[0], prefix, d->__nextchar);
288 else
290 flockfile (stderr);
291 fprintf (stderr,
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);
307 if (ambig_malloced)
308 free (ambig_set);
309 d->__nextchar += strlen (d->__nextchar);
310 d->optind++;
311 d->optopt = 0;
312 return '?';
315 option_index = indfound;
318 if (pfound == NULL)
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)
326 if (print_errors)
327 fprintf (stderr, _("%s: unrecognized option '%s%s'\n"),
328 argv[0], prefix, d->__nextchar);
330 d->__nextchar = NULL;
331 d->optind++;
332 d->optopt = 0;
333 return '?';
336 /* Otherwise interpret it as a short option. */
337 return -1;
340 /* We have found a matching long option. Consume it. */
341 d->optind++;
342 d->__nextchar = NULL;
343 if (*nameend)
345 /* Don't test has_arg with >, because some C compilers don't
346 allow it to be used on enums. */
347 if (pfound->has_arg)
348 d->optarg = nameend + 1;
349 else
351 if (print_errors)
352 fprintf (stderr,
353 _("%s: option '%s%s' doesn't allow an argument\n"),
354 argv[0], prefix, pfound->name);
356 d->optopt = pfound->val;
357 return '?';
360 else if (pfound->has_arg == 1)
362 if (d->optind < argc)
363 d->optarg = argv[d->optind++];
364 else
366 if (print_errors)
367 fprintf (stderr,
368 _("%s: option '%s%s' requires an argument\n"),
369 argv[0], prefix, pfound->name);
371 d->optopt = pfound->val;
372 return optstring[0] == ':' ? ':' : '?';
376 if (longind != NULL)
377 *longind = option_index;
378 if (pfound->flag)
380 *(pfound->flag) = pfound->val;
381 return 0;
383 return pfound->val;
386 /* Initialize internal data upon the first call to getopt. */
388 static const char *
389 _getopt_initialize (int argc,
390 char **argv, const char *optstring,
391 struct _getopt_data *d, int posixly_correct)
393 (void)argc;
394 (void)argv;
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. */
398 if (d->optind == 0)
399 d->optind = 1;
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;
408 ++optstring;
410 else if (optstring[0] == '+')
412 d->__ordering = REQUIRE_ORDER;
413 ++optstring;
415 else if (posixly_correct || !!getenv ("POSIXLY_CORRECT"))
416 d->__ordering = REQUIRE_ORDER;
417 else
418 d->__ordering = PERMUTE;
420 d->__initialized = 1;
421 return optstring;
424 /* Scan elements of ARGV (whose length is ARGC) for option characters
425 given in OPTSTRING.
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
468 with other systems.
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
475 recent call.
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;
487 if (argc < 1)
488 return -1;
490 d->optarg = NULL;
492 if (d->optind == 0 || !d->__initialized)
493 optstring = _getopt_initialize (argc, argv, optstring, d, posixly_correct);
494 else if (optstring[0] == '-' || optstring[0] == '+')
495 optstring++;
497 if (optstring[0] == ':')
498 print_errors = 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)
521 exchange (argv, d);
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)
529 d->optind++;
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], "--"))
540 d->optind++;
542 if (d->__first_nonopt != d->__last_nonopt
543 && d->__last_nonopt != d->optind)
544 exchange (argv, d);
545 else if (d->__first_nonopt == d->__last_nonopt)
546 d->__first_nonopt = d->optind;
547 d->__last_nonopt = argc;
549 d->optind = 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;
561 return -1;
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. */
567 if (NONOPTION_P)
569 if (d->__ordering == REQUIRE_ORDER)
570 return -1;
571 d->optarg = argv[d->optind++];
572 return 1;
575 /* We have found another option-ARGV-element.
576 Check whether it might be a long option. */
577 if (longopts)
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,
586 print_errors, "--");
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
593 option.
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])))
604 int code;
605 d->__nextchar = argv[d->optind] + 1;
606 code = process_long_option (argc, argv, optstring, longopts,
607 longind, long_only, d,
608 print_errors, "-");
609 if (code != -1)
610 return code;
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')
626 ++d->optind;
628 if (temp == NULL || c == ':' || c == ';')
630 if (print_errors)
631 fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
632 d->optopt = c;
633 return '?';
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)
644 if (print_errors)
645 fprintf (stderr,
646 _("%s: option requires an argument -- '%c'\n"),
647 argv[0], c);
649 d->optopt = c;
650 if (optstring[0] == ':')
651 c = ':';
652 else
653 c = '?';
654 return c;
656 else
657 d->optarg = argv[d->optind];
659 d->__nextchar = d->optarg;
660 d->optarg = NULL;
661 return process_long_option (argc, argv, optstring, longopts, longind,
662 0 /* long_only */, d, print_errors, "-W ");
664 if (temp[1] == ':')
666 if (temp[2] == ':')
668 /* This is an option that accepts an argument optionally. */
669 if (*d->__nextchar != '\0')
671 d->optarg = d->__nextchar;
672 d->optind++;
674 else
675 d->optarg = NULL;
676 d->__nextchar = NULL;
678 else
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. */
686 d->optind++;
688 else if (d->optind == argc)
690 if (print_errors)
691 fprintf (stderr,
692 _("%s: option requires an argument -- '%c'\n"),
693 argv[0], c);
695 d->optopt = c;
696 if (optstring[0] == ':')
697 c = ':';
698 else
699 c = '?';
701 else
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;
708 return c;
713 _getopt_internal (int argc, char **argv, const char *optstring,
714 const struct option *longopts, int *longind, int long_only,
715 int posixly_correct)
717 int result;
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,
724 posixly_correct);
726 optind = getopt_data.optind;
727 optarg = getopt_data.optarg;
728 optopt = getopt_data.optopt;
730 return result;
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) \
738 int \
739 NAME (int argc, char *const *argv, const char *optstring) \
741 return _getopt_internal (argc, (char **)argv, optstring, \
742 0, 0, 0, POSIXLY_CORRECT); \
745 #ifdef _LIBC
746 GETOPT_ENTRY(getopt, 0)
747 GETOPT_ENTRY(__posix_getopt, 1)
748 #else
749 GETOPT_ENTRY(getopt, 1)
750 #endif
753 #ifdef TEST
755 /* Compile with -DTEST to make an executable for use in testing
756 the above definition of 'getopt'. */
759 main (int argc, char **argv)
761 int c;
762 int digit_optind = 0;
764 while (1)
766 int this_option_optind = optind ? optind : 1;
768 c = getopt (argc, argv, "abc:d:0123456789");
769 if (c == -1)
770 break;
772 switch (c)
774 case '0':
775 case '1':
776 case '2':
777 case '3':
778 case '4':
779 case '5':
780 case '6':
781 case '7':
782 case '8':
783 case '9':
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);
788 break;
790 case 'a':
791 printf ("option a\n");
792 break;
794 case 'b':
795 printf ("option b\n");
796 break;
798 case 'c':
799 printf ("option c with value '%s'\n", optarg);
800 break;
802 case '?':
803 break;
805 default:
806 printf ("?? getopt returned character code 0%o ??\n", c);
810 if (optind < argc)
812 printf ("non-option ARGV-elements: ");
813 while (optind < argc)
814 printf ("%s ", argv[optind++]);
815 printf ("\n");
818 exit (0);
821 #endif /* TEST */