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 drepper@gnu.org
5 Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001
6 Free Software Foundation, Inc.
7 This file is part of the GNU C Library.
9 The GNU C Library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
14 The GNU C Library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public
20 License along with the GNU C Library; if not, write to the Free
21 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
25 * Modified for uClibc by Manuel Novoa III on 1/5/01.
26 * Modified once again for uClibc by Erik Andersen 8/7/02
33 #ifdef __UCLIBC_HAS_GETTEXT_AWARENESS__
37 libc_hidden_proto(strchr)
38 libc_hidden_proto(strcmp)
39 libc_hidden_proto(strlen)
40 libc_hidden_proto(strncmp)
41 libc_hidden_proto(getenv)
42 libc_hidden_proto(fprintf)
44 #ifdef __UCLIBC_MJN3_ONLY__
45 #warning TODO: Enable gettext awareness.
46 #endif /* __UCLIBC_MJN3_ONLY__ */
51 /* Treat '-W foo' the same as the long option '--foo',
52 * disabled for the moment since it costs about 2k... */
53 #undef SPECIAL_TREATMENT_FOR_W
55 /* This version of `getopt' appears to the caller like standard Unix `getopt'
56 but it behaves differently for the user, since it allows the user
57 to intersperse the options with the other arguments.
59 As `getopt' works, it permutes the elements of ARGV so that,
60 when it is done, all the options precede everything else. Thus
61 all application programs are extended to handle flexible argument order.
63 Setting the environment variable POSIXLY_CORRECT disables permutation.
64 Then the behavior is completely standard.
66 GNU application programs can use a third alternative mode in which
67 they can distinguish the relative order of options and other arguments. */
71 extern int _getopt_internal (int argc, char *const *argv, const char *optstring,
72 const struct option *longopts, int *longind, int long_only) attribute_hidden;
75 /* For communication from `getopt' to the caller.
76 When `getopt' finds an option that takes an argument,
77 the argument value is returned here.
78 Also, when `ordering' is RETURN_IN_ORDER,
79 each non-option ARGV-element is returned here. */
83 /* Index in ARGV of the next element to be scanned.
84 This is used for communication to and from the caller
85 and for communication between successive calls to `getopt'.
87 On entry to `getopt', zero means this is the first call; initialize.
89 When `getopt' returns -1, this is the index of the first of the
90 non-option elements that the caller should itself scan.
92 Otherwise, `optind' communicates from one call to the next
93 how much of ARGV has been scanned so far. */
95 /* 1003.2 says this must be 1 before any call. */
98 /* Callers store zero here to inhibit the error message
99 for unrecognized options. */
103 /* Set to an option character which was unrecognized.
104 This must be initialized on some systems to avoid linking in the
105 system's own getopt implementation. */
109 /* The next char to be scanned in the option-element
110 in which the last option character we returned was found.
111 This allows us to pick up the scan where we left off.
113 If this is zero, or a null string, it means resume the scan
114 by advancing to the next ARGV-element. */
116 static char *nextchar;
118 /* Formerly, initialization of getopt depended on optind==0, which
119 causes problems with re-calling getopt as programs generally don't
122 static int __getopt_initialized;
124 /* Describe how to deal with options that follow non-option ARGV-elements.
126 If the caller did not specify anything,
127 the default is REQUIRE_ORDER if the environment variable
128 POSIXLY_CORRECT is defined, PERMUTE otherwise.
130 REQUIRE_ORDER means don't recognize them as options;
131 stop option processing when the first non-option is seen.
132 This is what Unix does.
133 This mode of operation is selected by either setting the environment
134 variable POSIXLY_CORRECT, or using `+' as the first character
135 of the list of option characters.
137 PERMUTE is the default. We permute the contents of ARGV as we scan,
138 so that eventually all the non-options are at the end. This allows options
139 to be given in any order, even with programs that were not written to
142 RETURN_IN_ORDER is an option available to programs that were written
143 to expect options and other ARGV-elements in any order and that care about
144 the ordering of the two. We describe each non-option ARGV-element
145 as if it were the argument of an option with character code 1.
146 Using `-' as the first character of the list of option characters
147 selects this mode of operation.
149 The special argument `--' forces an end of option-scanning regardless
150 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
151 `--' can cause `getopt' to return -1 with `optind' != ARGC. */
155 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
159 # define my_index strchr
161 /* Handle permutation of arguments. */
163 /* Describe the part of ARGV that contains non-options that have
164 been skipped. `first_nonopt' is the index in ARGV of the first of them;
165 `last_nonopt' is the index after the last of them. */
167 static int first_nonopt;
168 static int last_nonopt;
170 /* Exchange two adjacent subsequences of ARGV.
171 One subsequence is elements [first_nonopt,last_nonopt)
172 which contains all the non-options that have been skipped so far.
173 The other is elements [last_nonopt,optind), which contains all
174 the options processed since those non-options were skipped.
176 `first_nonopt' and `last_nonopt' are relocated so that they describe
177 the new indices of the non-options in ARGV after they are moved. */
179 static void exchange (char **argv)
181 int bottom = first_nonopt;
182 int middle = last_nonopt;
186 /* Exchange the shorter segment with the far end of the longer segment.
187 That puts the shorter segment into the right place.
188 It leaves the longer segment in the right place overall,
189 but it consists of two parts that need to be swapped next. */
191 while (top > middle && middle > bottom)
193 if (top - middle > middle - bottom)
195 /* Bottom segment is the short one. */
196 int len = middle - bottom;
199 /* Swap it with the top part of the top segment. */
200 for (i = 0; i < len; i++)
202 tem = argv[bottom + i];
203 argv[bottom + i] = argv[top - (middle - bottom) + i];
204 argv[top - (middle - bottom) + i] = tem;
206 /* Exclude the moved bottom segment from further swapping. */
211 /* Top segment is the short one. */
212 int len = top - middle;
215 /* Swap it with the bottom part of the bottom segment. */
216 for (i = 0; i < len; i++)
218 tem = argv[bottom + i];
219 argv[bottom + i] = argv[middle + i];
220 argv[middle + i] = tem;
222 /* Exclude the moved top segment from further swapping. */
227 /* Update records for the slots the non-options now occupy. */
229 first_nonopt += (optind - last_nonopt);
230 last_nonopt = optind;
233 /* Initialize the internal data when the first call is made. */
235 static const char *_getopt_initialize (attribute_unused int argc, attribute_unused char *const * argv, const char *optstring)
237 /* Start processing options with ARGV-element 1 (since ARGV-element 0
238 is the program name); the sequence of previously skipped
239 non-option ARGV-elements is empty. */
241 first_nonopt = last_nonopt = optind;
245 /* Determine how to handle the ordering of options and nonoptions. */
247 if (optstring[0] == '-')
249 ordering = RETURN_IN_ORDER;
252 else if (optstring[0] == '+')
254 ordering = REQUIRE_ORDER;
257 else if (getenv ("POSIXLY_CORRECT") != NULL)
258 ordering = REQUIRE_ORDER;
265 /* Scan elements of ARGV (whose length is ARGC) for option characters
268 If an element of ARGV starts with '-', and is not exactly "-" or "--",
269 then it is an option element. The characters of this element
270 (aside from the initial '-') are option characters. If `getopt'
271 is called repeatedly, it returns successively each of the option characters
272 from each of the option elements.
274 If `getopt' finds another option character, it returns that character,
275 updating `optind' and `nextchar' so that the next call to `getopt' can
276 resume the scan with the following option character or ARGV-element.
278 If there are no more option characters, `getopt' returns -1.
279 Then `optind' is the index in ARGV of the first ARGV-element
280 that is not an option. (The ARGV-elements have been permuted
281 so that those that are not options now come last.)
283 OPTSTRING is a string containing the legitimate option characters.
284 If an option character is seen that is not listed in OPTSTRING,
285 return '?' after printing an error message. If you set `opterr' to
286 zero, the error message is suppressed but we still return '?'.
288 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
289 so the following text in the same ARGV-element, or the text of the following
290 ARGV-element, is returned in `optarg'. Two colons mean an option that
291 wants an optional arg; if there is text in the current ARGV-element,
292 it is returned in `optarg', otherwise `optarg' is set to zero.
294 If OPTSTRING starts with `-' or `+', it requests different methods of
295 handling the non-option ARGV-elements.
296 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
298 Long-named options begin with `--' instead of `-'.
299 Their names may be abbreviated as long as the abbreviation is unique
300 or is an exact match for some defined option. If they have an
301 argument, it follows the option name in the same ARGV-element, separated
302 from the option name by a `=', or else the in next ARGV-element.
303 When `getopt' finds a long-named option, it returns 0 if that option's
304 `flag' field is nonzero, the value of the option's `val' field
305 if the `flag' field is zero.
307 The elements of ARGV aren't really const, because we permute them.
308 But we pretend they're const in the prototype to be compatible
311 LONGOPTS is a vector of `struct option' terminated by an
312 element containing a name which is zero.
314 LONGIND returns the index in LONGOPT of the long-named option found.
315 It is only valid when a long-named option has been found by the most
318 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
319 long-named options. */
321 int attribute_hidden _getopt_internal (int argc, char *const *argv, const char *optstring,
322 const struct option *longopts, int *longind, int long_only)
324 int print_errors = opterr;
325 if (optstring[0] == ':')
333 if (optind == 0 || !__getopt_initialized)
336 optind = 1; /* Don't scan ARGV[0], the program name. */
337 optstring = _getopt_initialize (argc, argv, optstring);
338 __getopt_initialized = 1;
341 /* Test whether ARGV[optind] points to a non-option argument.
342 Either it does not have option syntax, or there is an environment flag
343 from the shell indicating it is not an option. The later information
344 is only used when the used in the GNU libc. */
345 #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
347 if (nextchar == NULL || *nextchar == '\0')
349 /* Advance to the next ARGV-element. */
351 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
352 moved back by the user (who may also have changed the arguments). */
353 if (last_nonopt > optind)
354 last_nonopt = optind;
355 if (first_nonopt > optind)
356 first_nonopt = optind;
358 if (ordering == PERMUTE)
360 /* If we have just processed some options following some non-options,
361 exchange them so that the options come first. */
363 if (first_nonopt != last_nonopt && last_nonopt != optind)
364 exchange ((char **) argv);
365 else if (last_nonopt != optind)
366 first_nonopt = optind;
368 /* Skip any additional non-options
369 and extend the range of non-options previously skipped. */
371 while (optind < argc && NONOPTION_P)
373 last_nonopt = optind;
376 /* The special ARGV-element `--' means premature end of options.
377 Skip it like a null option,
378 then exchange with previous non-options as if it were an option,
379 then skip everything else like a non-option. */
381 if (optind != argc && !strcmp (argv[optind], "--"))
385 if (first_nonopt != last_nonopt && last_nonopt != optind)
386 exchange ((char **) argv);
387 else if (first_nonopt == last_nonopt)
388 first_nonopt = optind;
394 /* If we have done all the ARGV-elements, stop the scan
395 and back over any non-options that we skipped and permuted. */
399 /* Set the next-arg-index to point at the non-options
400 that we previously skipped, so the caller will digest them. */
401 if (first_nonopt != last_nonopt)
402 optind = first_nonopt;
406 /* If we have come to a non-option and did not permute it,
407 either stop the scan or describe it to the caller and pass it by. */
411 if (ordering == REQUIRE_ORDER)
413 optarg = argv[optind++];
417 /* We have found another option-ARGV-element.
418 Skip the initial punctuation. */
420 nextchar = (argv[optind] + 1
421 + (longopts != NULL && argv[optind][1] == '-'));
424 /* Decode the current option-ARGV-element. */
426 /* Check whether the ARGV-element is a long option.
428 If long_only and the ARGV-element has the form "-f", where f is
429 a valid short option, don't consider it an abbreviated form of
430 a long option that starts with f. Otherwise there would be no
431 way to give the -f short option.
433 On the other hand, if there's a long option "fubar" and
434 the ARGV-element is "-fu", do consider that an abbreviation of
435 the long option, just like "--fu", and not "-f" with arg "u".
437 This distinction seems to be the most useful approach. */
440 && (argv[optind][1] == '-'
441 || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
444 const struct option *p;
445 const struct option *pfound = NULL;
451 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
454 /* Test all long options for either exact match
455 or abbreviated matches. */
456 for (p = longopts, option_index = 0; p->name; p++, option_index++)
457 if (!strncmp (p->name, nextchar, nameend - nextchar))
459 if ((unsigned int) (nameend - nextchar)
460 == (unsigned int) strlen (p->name))
462 /* Exact match found. */
464 indfound = option_index;
468 else if (pfound == NULL)
470 /* First nonexact match found. */
472 indfound = option_index;
475 || pfound->has_arg != p->has_arg
476 || pfound->flag != p->flag
477 || pfound->val != p->val)
478 /* Second or later nonexact match found. */
486 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
487 argv[0], argv[optind]);
489 nextchar += strlen (nextchar);
497 option_index = indfound;
501 /* Don't test has_arg with >, because some C compilers don't
502 allow it to be used on enums. */
504 optarg = nameend + 1;
510 if (argv[optind - 1][1] == '-')
513 fprintf (stderr, _("\
514 %s: option `--%s' doesn't allow an argument\n"),
515 argv[0], pfound->name);
519 /* +option or -option */
520 fprintf (stderr, _("\
521 %s: option `%c%s' doesn't allow an argument\n"),
522 argv[0], argv[optind - 1][0], pfound->name);
527 nextchar += strlen (nextchar);
529 optopt = pfound->val;
533 else if (pfound->has_arg == 1)
536 optarg = argv[optind++];
542 _("%s: option `%s' requires an argument\n"),
543 argv[0], argv[optind - 1]);
545 nextchar += strlen (nextchar);
546 optopt = pfound->val;
547 return optstring[0] == ':' ? ':' : '?';
550 nextchar += strlen (nextchar);
552 *longind = option_index;
555 *(pfound->flag) = pfound->val;
561 /* Can't find it as a long option. If this is not getopt_long_only,
562 or the option starts with '--' or is not a valid short
563 option, then it's an error.
564 Otherwise interpret it as a short option. */
565 if (!long_only || argv[optind][1] == '-'
566 || my_index (optstring, *nextchar) == NULL)
571 if (argv[optind][1] == '-')
574 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
579 /* +option or -option */
580 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
581 argv[0], argv[optind][0], nextchar);
585 nextchar = (char *) "";
592 /* Look at and handle the next short option-character. */
595 char c = *nextchar++;
596 char *temp = my_index (optstring, c);
598 /* Increment `optind' when we start to process its last character. */
599 if (*nextchar == '\0')
602 if (temp == NULL || c == ':')
606 /* 1003.2 specifies the format of this message. */
607 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
612 #ifdef SPECIAL_TREATMENT_FOR_W
613 /* Convenience. Treat POSIX -W foo same as long option --foo */
614 if (temp[0] == 'W' && temp[1] == ';')
617 const struct option *p;
618 const struct option *pfound = NULL;
624 /* This is an option that requires an argument. */
625 if (*nextchar != '\0')
628 /* If we end this ARGV-element by taking the rest as an arg,
629 we must advance to the next element now. */
632 else if (optind == argc)
636 /* 1003.2 specifies the format of this message. */
637 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
641 if (optstring[0] == ':')
648 /* We already incremented `optind' once;
649 increment it again when taking next ARGV-elt as argument. */
650 optarg = argv[optind++];
652 /* optarg is now the argument, see if it's in the
653 table of longopts. */
655 for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
658 /* Test all long options for either exact match
659 or abbreviated matches. */
660 for (p = longopts, option_index = 0; p->name; p++, option_index++)
661 if (!strncmp (p->name, nextchar, nameend - nextchar))
663 if ((unsigned int) (nameend - nextchar) == strlen (p->name))
665 /* Exact match found. */
667 indfound = option_index;
671 else if (pfound == NULL)
673 /* First nonexact match found. */
675 indfound = option_index;
678 /* Second or later nonexact match found. */
685 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
686 argv[0], argv[optind]);
688 nextchar += strlen (nextchar);
694 option_index = indfound;
697 /* Don't test has_arg with >, because some C compilers don't
698 allow it to be used on enums. */
700 optarg = nameend + 1;
705 fprintf (stderr, _("\
706 %s: option `-W %s' doesn't allow an argument\n"),
707 argv[0], pfound->name);
710 nextchar += strlen (nextchar);
714 else if (pfound->has_arg == 1)
717 optarg = argv[optind++];
723 _("%s: option `%s' requires an argument\n"),
724 argv[0], argv[optind - 1]);
726 nextchar += strlen (nextchar);
727 return optstring[0] == ':' ? ':' : '?';
730 nextchar += strlen (nextchar);
732 *longind = option_index;
735 *(pfound->flag) = pfound->val;
741 return 'W'; /* Let the application handle it. */
748 /* This is an option that accepts an argument optionally. */
749 if (*nextchar != '\0')
760 /* This is an option that requires an argument. */
761 if (*nextchar != '\0')
764 /* If we end this ARGV-element by taking the rest as an arg,
765 we must advance to the next element now. */
768 else if (optind == argc)
772 /* 1003.2 specifies the format of this message. */
774 _("%s: option requires an argument -- %c\n"),
778 if (optstring[0] == ':')
784 /* We already incremented `optind' once;
785 increment it again when taking next ARGV-elt as argument. */
786 optarg = argv[optind++];
794 int getopt (int argc, char *const *argv, const char *optstring)
796 return _getopt_internal (argc, argv, optstring,
797 (const struct option *) 0, (int *) 0, 0);
800 int getopt_long (int argc, char *const *argv, const char *options,
801 const struct option *long_options, int *opt_index)
803 return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
806 /* Like getopt_long, but '-' as well as '--' can indicate a long option.
807 If an option that starts with '-' (not '--') doesn't match a long option,
808 but does match a short option, it is parsed as a short option
811 int getopt_long_only (int argc, char *const *argv, const char *options,
812 const struct option *long_options, int *opt_index)
814 return _getopt_internal (argc, argv, options, long_options, opt_index, 1);