]>
git.proxmox.com Git - mirror_smartmontools-debian.git/blob - getopt/getopt.c
2 Copyright (C) 1987-2018 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 <http://www.gnu.org/licenses/>. */
20 #if !defined(_LIBC) && !defined(_GETOPT_STANDALONE)
29 #ifndef _GETOPT_STANDALONE
34 /* When used as part of glibc, error printing must be done differently
35 for standards compliance. getopt is not a cancellation point, so
36 it must not call functions that are, and it is specified by an
37 older standard than stdio locking, so it must not refer to
38 functions in the "user namespace" related to stdio locking.
39 Finally, it must use glibc's internal message translation so that
40 the messages are looked up in the proper text domain. */
42 # define fprintf __fxprintf_nocancel
43 # define flockfile(fp) _IO_flockfile (fp)
44 # define funlockfile(fp) _IO_funlockfile (fp)
46 #ifndef _GETOPT_STANDALONE
48 # define _(msgid) gettext (msgid)
50 # define _(msgid) (msgid)
52 /* When used standalone, flockfile and funlockfile might not be
54 # ifndef _POSIX_THREAD_SAFE_FUNCTIONS
55 # define flockfile(fp) /* nop */
56 # define funlockfile(fp) /* nop */
58 /* When used standalone, do not attempt to use alloca. */
59 # define __libc_use_alloca(size) 0
61 # define alloca(size) (abort (), (void *)0)
64 /* This implementation of 'getopt' has three modes for handling
65 options interspersed with non-option arguments. It can stop
66 scanning for options at the first non-option argument encountered,
67 as POSIX specifies. It can continue scanning for options after the
68 first non-option argument, but permute 'argv' as it goes so that,
69 after 'getopt' is done, all the options precede all the non-option
70 arguments and 'optind' points to the first non-option argument.
71 Or, it can report non-option arguments as if they were arguments to
72 the option character '\x01'.
74 The default behavior of 'getopt_long' is to permute the argument list.
75 When this implementation is used standalone, the default behavior of
76 'getopt' is to stop at the first non-option argument, but when it is
77 used as part of GNU libc it also permutes the argument list. In both
78 cases, setting the environment variable POSIXLY_CORRECT to any value
81 If the first character of the OPTSTRING argument to 'getopt' or
82 'getopt_long' is '+', both functions will stop at the first
83 non-option argument. If it is '-', both functions will report
84 non-option arguments as arguments to the option character '\x01'. */
86 #include "getopt_int.h"
88 /* For communication from 'getopt' to the caller.
89 When 'getopt' finds an option that takes an argument,
90 the argument value is returned here.
91 Also, when 'ordering' is RETURN_IN_ORDER,
92 each non-option ARGV-element is returned here. */
96 /* Index in ARGV of the next element to be scanned.
97 This is used for communication to and from the caller
98 and for communication between successive calls to 'getopt'.
100 On entry to 'getopt', zero means this is the first call; initialize.
102 When 'getopt' returns -1, this is the index of the first of the
103 non-option elements that the caller should itself scan.
105 Otherwise, 'optind' communicates from one call to the next
106 how much of ARGV has been scanned so far. */
108 /* 1003.2 says this must be 1 before any call. */
111 /* Callers store zero here to inhibit the error message
112 for unrecognized options. */
116 /* Set to an option character which was unrecognized.
117 This must be initialized on some systems to avoid linking in the
118 system's own getopt implementation. */
122 /* Keep a global copy of all internal members of getopt_data. */
124 static struct _getopt_data getopt_data
;
126 /* Exchange two adjacent subsequences of ARGV.
127 One subsequence is elements [first_nonopt,last_nonopt)
128 which contains all the non-options that have been skipped so far.
129 The other is elements [last_nonopt,optind), which contains all
130 the options processed since those non-options were skipped.
132 'first_nonopt' and 'last_nonopt' are relocated so that they describe
133 the new indices of the non-options in ARGV after they are moved. */
136 exchange (char **argv
, struct _getopt_data
*d
)
138 int bottom
= d
->__first_nonopt
;
139 int middle
= d
->__last_nonopt
;
143 /* Exchange the shorter segment with the far end of the longer segment.
144 That puts the shorter segment into the right place.
145 It leaves the longer segment in the right place overall,
146 but it consists of two parts that need to be swapped next. */
148 while (top
> middle
&& middle
> bottom
)
150 if (top
- middle
> middle
- bottom
)
152 /* Bottom segment is the short one. */
153 int len
= middle
- bottom
;
156 /* Swap it with the top part of the top segment. */
157 for (i
= 0; i
< len
; i
++)
159 tem
= argv
[bottom
+ i
];
160 argv
[bottom
+ i
] = argv
[top
- (middle
- bottom
) + i
];
161 argv
[top
- (middle
- bottom
) + i
] = tem
;
163 /* Exclude the moved bottom segment from further swapping. */
168 /* Top segment is the short one. */
169 int len
= top
- middle
;
172 /* Swap it with the bottom part of the bottom segment. */
173 for (i
= 0; i
< len
; i
++)
175 tem
= argv
[bottom
+ i
];
176 argv
[bottom
+ i
] = argv
[middle
+ i
];
177 argv
[middle
+ i
] = tem
;
179 /* Exclude the moved top segment from further swapping. */
184 /* Update records for the slots the non-options now occupy. */
186 d
->__first_nonopt
+= (d
->optind
- d
->__last_nonopt
);
187 d
->__last_nonopt
= d
->optind
;
190 /* Process the argument starting with d->__nextchar as a long option.
191 d->optind should *not* have been advanced over this argument.
193 If the value returned is -1, it was not actually a long option, the
194 state is unchanged, and the argument should be processed as a set
195 of short options (this can only happen when long_only is true).
196 Otherwise, the option (and its argument, if any) have been consumed
197 and the return value is the value to return from _getopt_internal_r. */
199 process_long_option (int argc
, char **argv
, const char *optstring
,
200 const struct option
*longopts
, int *longind
,
201 int long_only
, struct _getopt_data
*d
,
202 int print_errors
, const char *prefix
)
206 const struct option
*p
;
207 const struct option
*pfound
= NULL
;
211 for (nameend
= d
->__nextchar
; *nameend
&& *nameend
!= '='; nameend
++)
213 namelen
= nameend
- d
->__nextchar
;
215 /* First look for an exact match, counting the options as a side
217 for (p
= longopts
, n_options
= 0; p
->name
; p
++, n_options
++)
218 if (!strncmp (p
->name
, d
->__nextchar
, namelen
)
219 && namelen
== strlen (p
->name
))
221 /* Exact match found. */
223 option_index
= n_options
;
229 /* Didn't find an exact match, so look for abbreviations. */
230 unsigned char *ambig_set
= NULL
;
231 int ambig_malloced
= 0;
232 int ambig_fallback
= 0;
235 for (p
= longopts
, option_index
= 0; p
->name
; p
++, option_index
++)
236 if (!strncmp (p
->name
, d
->__nextchar
, namelen
))
240 /* First nonexact match found. */
242 indfound
= option_index
;
245 || pfound
->has_arg
!= p
->has_arg
246 || pfound
->flag
!= p
->flag
247 || pfound
->val
!= p
->val
)
249 /* Second or later nonexact match found. */
253 /* Don't waste effort tracking the ambig set if
254 we're not going to print it anyway. */
258 if (__libc_use_alloca (n_options
))
259 ambig_set
= alloca (n_options
);
260 else if ((ambig_set
= malloc (n_options
)) == NULL
)
261 /* Fall back to simpler error message. */
268 memset (ambig_set
, 0, n_options
);
269 ambig_set
[indfound
] = 1;
273 ambig_set
[option_index
] = 1;
278 if (ambig_set
|| ambig_fallback
)
283 fprintf (stderr
, _("%s: option '%s%s' is ambiguous\n"),
284 argv
[0], prefix
, d
->__nextchar
);
289 _("%s: option '%s%s' is ambiguous; possibilities:"),
290 argv
[0], prefix
, d
->__nextchar
);
292 for (option_index
= 0; option_index
< n_options
; option_index
++)
293 if (ambig_set
[option_index
])
294 fprintf (stderr
, " '%s%s'",
295 prefix
, longopts
[option_index
].name
);
297 /* This must use 'fprintf' even though it's only
298 printing a single character, so that it goes through
299 __fxprintf_nocancel when compiled as part of glibc. */
300 fprintf (stderr
, "\n");
301 funlockfile (stderr
);
306 d
->__nextchar
+= strlen (d
->__nextchar
);
312 option_index
= indfound
;
317 /* Can't find it as a long option. If this is not getopt_long_only,
318 or the option starts with '--' or is not a valid short option,
319 then it's an error. */
320 if (!long_only
|| argv
[d
->optind
][1] == '-'
321 || strchr (optstring
, *d
->__nextchar
) == NULL
)
324 fprintf (stderr
, _("%s: unrecognized option '%s%s'\n"),
325 argv
[0], prefix
, d
->__nextchar
);
327 d
->__nextchar
= NULL
;
333 /* Otherwise interpret it as a short option. */
337 /* We have found a matching long option. Consume it. */
339 d
->__nextchar
= NULL
;
342 /* Don't test has_arg with >, because some C compilers don't
343 allow it to be used on enums. */
345 d
->optarg
= nameend
+ 1;
350 _("%s: option '%s%s' doesn't allow an argument\n"),
351 argv
[0], prefix
, pfound
->name
);
353 d
->optopt
= pfound
->val
;
357 else if (pfound
->has_arg
== 1)
359 if (d
->optind
< argc
)
360 d
->optarg
= argv
[d
->optind
++];
365 _("%s: option '%s%s' requires an argument\n"),
366 argv
[0], prefix
, pfound
->name
);
368 d
->optopt
= pfound
->val
;
369 return optstring
[0] == ':' ? ':' : '?';
374 *longind
= option_index
;
377 *(pfound
->flag
) = pfound
->val
;
385 # define _GL_UNUSED __attribute__((__unused__))
391 /* Initialize internal data upon the first call to getopt. */
394 _getopt_initialize (int argc _GL_UNUSED
,
395 char **argv _GL_UNUSED
, const char *optstring
,
396 struct _getopt_data
*d
, int posixly_correct
)
398 /* Start processing options with ARGV-element 1 (since ARGV-element 0
399 is the program name); the sequence of previously skipped
400 non-option ARGV-elements is empty. */
404 d
->__first_nonopt
= d
->__last_nonopt
= d
->optind
;
405 d
->__nextchar
= NULL
;
407 /* Determine how to handle the ordering of options and nonoptions. */
408 if (optstring
[0] == '-')
410 d
->__ordering
= RETURN_IN_ORDER
;
413 else if (optstring
[0] == '+')
415 d
->__ordering
= REQUIRE_ORDER
;
418 else if (posixly_correct
|| !!getenv ("POSIXLY_CORRECT"))
419 d
->__ordering
= REQUIRE_ORDER
;
421 d
->__ordering
= PERMUTE
;
423 d
->__initialized
= 1;
427 /* Scan elements of ARGV (whose length is ARGC) for option characters
430 If an element of ARGV starts with '-', and is not exactly "-" or "--",
431 then it is an option element. The characters of this element
432 (aside from the initial '-') are option characters. If 'getopt'
433 is called repeatedly, it returns successively each of the option characters
434 from each of the option elements.
436 If 'getopt' finds another option character, it returns that character,
437 updating 'optind' and 'nextchar' so that the next call to 'getopt' can
438 resume the scan with the following option character or ARGV-element.
440 If there are no more option characters, 'getopt' returns -1.
441 Then 'optind' is the index in ARGV of the first ARGV-element
442 that is not an option. (The ARGV-elements have been permuted
443 so that those that are not options now come last.)
445 OPTSTRING is a string containing the legitimate option characters.
446 If an option character is seen that is not listed in OPTSTRING,
447 return '?' after printing an error message. If you set 'opterr' to
448 zero, the error message is suppressed but we still return '?'.
450 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
451 so the following text in the same ARGV-element, or the text of the following
452 ARGV-element, is returned in 'optarg'. Two colons mean an option that
453 wants an optional arg; if there is text in the current ARGV-element,
454 it is returned in 'optarg', otherwise 'optarg' is set to zero.
456 If OPTSTRING starts with '-' or '+', it requests different methods of
457 handling the non-option ARGV-elements.
458 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
460 Long-named options begin with '--' instead of '-'.
461 Their names may be abbreviated as long as the abbreviation is unique
462 or is an exact match for some defined option. If they have an
463 argument, it follows the option name in the same ARGV-element, separated
464 from the option name by a '=', or else the in next ARGV-element.
465 When 'getopt' finds a long-named option, it returns 0 if that option's
466 'flag' field is nonzero, the value of the option's 'val' field
467 if the 'flag' field is zero.
469 The elements of ARGV aren't really const, because we permute them.
470 But we pretend they're const in the prototype to be compatible
473 LONGOPTS is a vector of 'struct option' terminated by an
474 element containing a name which is zero.
476 LONGIND returns the index in LONGOPT of the long-named option found.
477 It is only valid when a long-named option has been found by the most
480 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
481 long-named options. */
484 _getopt_internal_r (int argc
, char **argv
, const char *optstring
,
485 const struct option
*longopts
, int *longind
,
486 int long_only
, struct _getopt_data
*d
, int posixly_correct
)
488 int print_errors
= d
->opterr
;
495 if (d
->optind
== 0 || !d
->__initialized
)
496 optstring
= _getopt_initialize (argc
, argv
, optstring
, d
, posixly_correct
);
497 else if (optstring
[0] == '-' || optstring
[0] == '+')
500 if (optstring
[0] == ':')
503 /* Test whether ARGV[optind] points to a non-option argument. */
504 #define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
506 if (d
->__nextchar
== NULL
|| *d
->__nextchar
== '\0')
508 /* Advance to the next ARGV-element. */
510 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
511 moved back by the user (who may also have changed the arguments). */
512 if (d
->__last_nonopt
> d
->optind
)
513 d
->__last_nonopt
= d
->optind
;
514 if (d
->__first_nonopt
> d
->optind
)
515 d
->__first_nonopt
= d
->optind
;
517 if (d
->__ordering
== PERMUTE
)
519 /* If we have just processed some options following some non-options,
520 exchange them so that the options come first. */
522 if (d
->__first_nonopt
!= d
->__last_nonopt
523 && d
->__last_nonopt
!= d
->optind
)
525 else if (d
->__last_nonopt
!= d
->optind
)
526 d
->__first_nonopt
= d
->optind
;
528 /* Skip any additional non-options
529 and extend the range of non-options previously skipped. */
531 while (d
->optind
< argc
&& NONOPTION_P
)
533 d
->__last_nonopt
= d
->optind
;
536 /* The special ARGV-element '--' means premature end of options.
537 Skip it like a null option,
538 then exchange with previous non-options as if it were an option,
539 then skip everything else like a non-option. */
541 if (d
->optind
!= argc
&& !strcmp (argv
[d
->optind
], "--"))
545 if (d
->__first_nonopt
!= d
->__last_nonopt
546 && d
->__last_nonopt
!= d
->optind
)
548 else if (d
->__first_nonopt
== d
->__last_nonopt
)
549 d
->__first_nonopt
= d
->optind
;
550 d
->__last_nonopt
= argc
;
555 /* If we have done all the ARGV-elements, stop the scan
556 and back over any non-options that we skipped and permuted. */
558 if (d
->optind
== argc
)
560 /* Set the next-arg-index to point at the non-options
561 that we previously skipped, so the caller will digest them. */
562 if (d
->__first_nonopt
!= d
->__last_nonopt
)
563 d
->optind
= d
->__first_nonopt
;
567 /* If we have come to a non-option and did not permute it,
568 either stop the scan or describe it to the caller and pass it by. */
572 if (d
->__ordering
== REQUIRE_ORDER
)
574 d
->optarg
= argv
[d
->optind
++];
578 /* We have found another option-ARGV-element.
579 Check whether it might be a long option. */
582 if (argv
[d
->optind
][1] == '-')
584 /* "--foo" is always a long option. The special option
585 "--" was handled above. */
586 d
->__nextchar
= argv
[d
->optind
] + 2;
587 return process_long_option (argc
, argv
, optstring
, longopts
,
588 longind
, long_only
, d
,
592 /* If long_only and the ARGV-element has the form "-f",
593 where f is a valid short option, don't consider it an
594 abbreviated form of a long option that starts with f.
595 Otherwise there would be no way to give the -f short
598 On the other hand, if there's a long option "fubar" and
599 the ARGV-element is "-fu", do consider that an
600 abbreviation of the long option, just like "--fu", and
601 not "-f" with arg "u".
603 This distinction seems to be the most useful approach. */
604 if (long_only
&& (argv
[d
->optind
][2]
605 || !strchr (optstring
, argv
[d
->optind
][1])))
608 d
->__nextchar
= argv
[d
->optind
] + 1;
609 code
= process_long_option (argc
, argv
, optstring
, longopts
,
610 longind
, long_only
, d
,
617 /* It is not a long option. Skip the initial punctuation. */
618 d
->__nextchar
= argv
[d
->optind
] + 1;
621 /* Look at and handle the next short option-character. */
624 char c
= *d
->__nextchar
++;
625 const char *temp
= strchr (optstring
, c
);
627 /* Increment 'optind' when we start to process its last character. */
628 if (*d
->__nextchar
== '\0')
631 if (temp
== NULL
|| c
== ':' || c
== ';')
634 fprintf (stderr
, _("%s: invalid option -- '%c'\n"), argv
[0], c
);
639 /* Convenience. Treat POSIX -W foo same as long option --foo */
640 if (temp
[0] == 'W' && temp
[1] == ';' && longopts
!= NULL
)
642 /* This is an option that requires an argument. */
643 if (*d
->__nextchar
!= '\0')
644 d
->optarg
= d
->__nextchar
;
645 else if (d
->optind
== argc
)
649 _("%s: option requires an argument -- '%c'\n"),
653 if (optstring
[0] == ':')
660 d
->optarg
= argv
[d
->optind
];
662 d
->__nextchar
= d
->optarg
;
664 return process_long_option (argc
, argv
, optstring
, longopts
, longind
,
665 0 /* long_only */, d
, print_errors
, "-W ");
671 /* This is an option that accepts an argument optionally. */
672 if (*d
->__nextchar
!= '\0')
674 d
->optarg
= d
->__nextchar
;
679 d
->__nextchar
= NULL
;
683 /* This is an option that requires an argument. */
684 if (*d
->__nextchar
!= '\0')
686 d
->optarg
= d
->__nextchar
;
687 /* If we end this ARGV-element by taking the rest as an arg,
688 we must advance to the next element now. */
691 else if (d
->optind
== argc
)
695 _("%s: option requires an argument -- '%c'\n"),
699 if (optstring
[0] == ':')
705 /* We already incremented 'optind' once;
706 increment it again when taking next ARGV-elt as argument. */
707 d
->optarg
= argv
[d
->optind
++];
708 d
->__nextchar
= NULL
;
716 _getopt_internal (int argc
, char **argv
, const char *optstring
,
717 const struct option
*longopts
, int *longind
, int long_only
,
722 getopt_data
.optind
= optind
;
723 getopt_data
.opterr
= opterr
;
725 result
= _getopt_internal_r (argc
, argv
, optstring
, longopts
,
726 longind
, long_only
, &getopt_data
,
729 optind
= getopt_data
.optind
;
730 optarg
= getopt_data
.optarg
;
731 optopt
= getopt_data
.optopt
;
736 /* glibc gets a LSB-compliant getopt and a POSIX-complaint __posix_getopt.
737 Standalone applications just get a POSIX-compliant getopt.
738 POSIX and LSB both require these functions to take 'char *const *argv'
739 even though this is incorrect (because of the permutation). */
740 #define GETOPT_ENTRY(NAME, POSIXLY_CORRECT) \
742 NAME (int argc, char *const *argv, const char *optstring) \
744 return _getopt_internal (argc, (char **)argv, optstring, \
745 0, 0, 0, POSIXLY_CORRECT); \
749 GETOPT_ENTRY(getopt
, 0)
750 GETOPT_ENTRY(__posix_getopt
, 1)
752 GETOPT_ENTRY(getopt
, 1)
758 /* Compile with -DTEST to make an executable for use in testing
759 the above definition of 'getopt'. */
762 main (int argc
, char **argv
)
765 int digit_optind
= 0;
769 int this_option_optind
= optind
? optind
: 1;
771 c
= getopt (argc
, argv
, "abc:d:0123456789");
787 if (digit_optind
!= 0 && digit_optind
!= this_option_optind
)
788 printf ("digits occur in two different argv-elements.\n");
789 digit_optind
= this_option_optind
;
790 printf ("option %c\n", c
);
794 printf ("option a\n");
798 printf ("option b\n");
802 printf ("option c with value '%s'\n", optarg
);
809 printf ("?? getopt returned character code 0%o ??\n", c
);
815 printf ("non-option ARGV-elements: ");
816 while (optind
< argc
)
817 printf ("%s ", argv
[optind
++]);