1 /* $OpenBSD: getopt_long.c,v 1.22 2006/10/04 21:29:04 jmc Exp $ */
2 /* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
5 * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 * Sponsored in part by the Defense Advanced Research Projects
20 * Agency (DARPA) and Air Force Research Laboratory, Air Force
21 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
24 * Copyright (c) 2000 The NetBSD Foundation, Inc.
25 * All rights reserved.
27 * This code is derived from software contributed to The NetBSD Foundation
28 * by Dieter Baron and Thomas Klausner.
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
39 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
40 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
41 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
43 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
47 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49 * POSSIBILITY OF SUCH DAMAGE.
53 #if defined(LIBC_SCCS) && !defined(lint)
54 static char *rcsid = "$OpenBSD: getopt_long.c,v 1.16 2004/02/04 18:17:25 millert Exp $";
55 #endif /* LIBC_SCCS and not lint */
57 #include <sys/cdefs.h>
58 __FBSDID("$FreeBSD$");
66 #define GNU_COMPATIBLE /* Be more compatible, configure's use us! */
68 #if 0 /* we prefer to keep our getopt(3) */
69 #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
73 int opterr = 1; /* if error message should be printed */
74 int optind = 1; /* index into parent argv vector */
75 int optopt = '?'; /* character checked for validity */
76 int optreset; /* reset getopt */
77 char *optarg; /* argument associated with option */
80 #define PRINT_ERROR ((opterr) && (*options != ':'))
82 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
83 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
84 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
87 #define BADCH (int)'?'
88 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
89 #define INORDER (int)1
94 #define NO_PREFIX (-1)
100 static int getopt_internal(int, char * const *, const char *,
101 const struct option *, int *, int);
102 static int parse_long_options(char * const *, const char *,
103 const struct option *, int *, int, int);
104 static int gcd(int, int);
105 static void permute_args(int, int, int, char * const *);
107 static char *place = EMSG; /* option letter processing */
109 /* XXX: set optreset to 1 rather than these two */
110 static int nonopt_start = -1; /* first non option argument (for permute) */
111 static int nonopt_end = -1; /* first option after non options (for permute) */
114 static const char recargchar[] = "option requires an argument -- %c";
115 static const char illoptchar[] = "illegal option -- %c"; /* From P1003.2 */
116 #ifdef GNU_COMPATIBLE
117 static int dash_prefix = NO_PREFIX;
118 static const char gnuoptchar[] = "invalid option -- %c";
120 static const char recargstring[] = "option `%s%s' requires an argument";
121 static const char ambig[] = "option `%s%.*s' is ambiguous";
122 static const char noarg[] = "option `%s%.*s' doesn't allow an argument";
123 static const char illoptstring[] = "unrecognized option `%s%s'";
125 static const char recargstring[] = "option requires an argument -- %s";
126 static const char ambig[] = "ambiguous option -- %.*s";
127 static const char noarg[] = "option doesn't take an argument -- %.*s";
128 static const char illoptstring[] = "unknown option -- %s";
132 * Compute the greatest common divisor of a and b.
150 * Exchange the block from nonopt_start to nonopt_end with the block
151 * from nonopt_end to opt_end (keeping the same order of arguments
155 permute_args(int panonopt_start, int panonopt_end, int opt_end,
158 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
162 * compute lengths of blocks and number and size of cycles
164 nnonopts = panonopt_end - panonopt_start;
165 nopts = opt_end - panonopt_end;
166 ncycle = gcd(nnonopts, nopts);
167 cyclelen = (opt_end - panonopt_start) / ncycle;
169 for (i = 0; i < ncycle; i++) {
170 cstart = panonopt_end+i;
172 for (j = 0; j < cyclelen; j++) {
173 if (pos >= panonopt_end)
178 /* LINTED const cast */
179 ((char **) nargv)[pos] = nargv[cstart];
180 /* LINTED const cast */
181 ((char **)nargv)[cstart] = swap;
187 * parse_long_options --
188 * Parse long options in argc/argv argument vector.
189 * Returns -1 if short_too is set and the option does not match long_options.
192 parse_long_options(char * const *nargv, const char *options,
193 const struct option *long_options, int *idx, int short_too, int flags)
195 char *current_argv, *has_equal;
196 #ifdef GNU_COMPATIBLE
199 size_t current_argv_len;
200 int i, match, exact_match, second_partial_match;
202 current_argv = place;
203 #ifdef GNU_COMPATIBLE
204 switch (dash_prefix) {
212 current_dash = "-W ";
221 second_partial_match = 0;
225 if ((has_equal = strchr(current_argv, '=')) != NULL) {
226 /* argument found (--option=arg) */
227 current_argv_len = has_equal - current_argv;
230 current_argv_len = strlen(current_argv);
232 for (i = 0; long_options[i].name; i++) {
233 /* find matching long option */
234 if (strncmp(current_argv, long_options[i].name,
238 if (strlen(long_options[i].name) == current_argv_len) {
245 * If this is a known short option, don't allow
246 * a partial match of a single character.
248 if (short_too && current_argv_len == 1)
251 if (match == -1) /* first partial match */
253 else if ((flags & FLAG_LONGONLY) ||
254 long_options[i].has_arg !=
255 long_options[match].has_arg ||
256 long_options[i].flag != long_options[match].flag ||
257 long_options[i].val != long_options[match].val)
258 second_partial_match = 1;
260 if (!exact_match && second_partial_match) {
261 /* ambiguous abbreviation */
264 #ifdef GNU_COMPATIBLE
267 (int)current_argv_len,
272 if (match != -1) { /* option found */
273 if (long_options[match].has_arg == no_argument
277 #ifdef GNU_COMPATIBLE
280 (int)current_argv_len,
283 * XXX: GNU sets optopt to val regardless of flag
285 if (long_options[match].flag == NULL)
286 optopt = long_options[match].val;
289 #ifdef GNU_COMPATIBLE
295 if (long_options[match].has_arg == required_argument ||
296 long_options[match].has_arg == optional_argument) {
299 else if (long_options[match].has_arg ==
302 * optional argument doesn't use next nargv
304 optarg = nargv[optind++];
307 if ((long_options[match].has_arg == required_argument)
308 && (optarg == NULL)) {
310 * Missing argument; leading ':' indicates no error
311 * should be generated.
315 #ifdef GNU_COMPATIBLE
320 * XXX: GNU sets optopt to val regardless of flag
322 if (long_options[match].flag == NULL)
323 optopt = long_options[match].val;
329 } else { /* unknown option */
336 #ifdef GNU_COMPATIBLE
345 if (long_options[match].flag) {
346 *long_options[match].flag = long_options[match].val;
349 return (long_options[match].val);
354 * Parse argc/argv argument vector. Called by user level routines.
357 getopt_internal(int nargc, char * const *nargv, const char *options,
358 const struct option *long_options, int *idx, int flags)
360 char *oli; /* option letter list index */
361 int optchar, short_too;
362 int posixly_correct; /* no static, can be changed on the fly */
368 * Disable GNU extensions if POSIXLY_CORRECT is set or options
369 * string begins with a '+'.
371 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
372 #ifdef GNU_COMPATIBLE
374 flags |= FLAG_ALLARGS;
375 else if (posixly_correct || *options == '+')
376 flags &= ~FLAG_PERMUTE;
378 if (posixly_correct || *options == '+')
379 flags &= ~FLAG_PERMUTE;
380 else if (*options == '-')
381 flags |= FLAG_ALLARGS;
383 if (*options == '+' || *options == '-')
387 * XXX Some GNU programs (like cvs) set optind to 0 instead of
388 * XXX using optreset. Work around this braindamage.
391 optind = optreset = 1;
395 nonopt_start = nonopt_end = -1;
397 if (optreset || !*place) { /* update scanning pointer */
399 if (optind >= nargc) { /* end of argument vector */
401 if (nonopt_end != -1) {
402 /* do permutation, if we have to */
403 permute_args(nonopt_start, nonopt_end,
405 optind -= nonopt_end - nonopt_start;
407 else if (nonopt_start != -1) {
409 * If we skipped non-options, set optind
410 * to the first of them.
412 optind = nonopt_start;
414 nonopt_start = nonopt_end = -1;
417 if (*(place = nargv[optind]) != '-' ||
418 #ifdef GNU_COMPATIBLE
421 (place[1] == '\0' && strchr(options, '-') == NULL)) {
423 place = EMSG; /* found non-option */
424 if (flags & FLAG_ALLARGS) {
427 * return non-option as argument to option 1
429 optarg = nargv[optind++];
432 if (!(flags & FLAG_PERMUTE)) {
434 * If no permutation wanted, stop parsing
435 * at first non-option.
440 if (nonopt_start == -1)
441 nonopt_start = optind;
442 else if (nonopt_end != -1) {
443 permute_args(nonopt_start, nonopt_end,
445 nonopt_start = optind -
446 (nonopt_end - nonopt_start);
450 /* process next argument */
453 if (nonopt_start != -1 && nonopt_end == -1)
457 * If we have "-" do nothing, if "--" we are done.
459 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
463 * We found an option (--), so if we skipped
464 * non-options, we have to permute.
466 if (nonopt_end != -1) {
467 permute_args(nonopt_start, nonopt_end,
469 optind -= nonopt_end - nonopt_start;
471 nonopt_start = nonopt_end = -1;
477 * Check long options if:
478 * 1) we were passed some
479 * 2) the arg is not just "-"
480 * 3) either the arg starts with -- we are getopt_long_only()
482 if (long_options != NULL && place != nargv[optind] &&
483 (*place == '-' || (flags & FLAG_LONGONLY))) {
485 #ifdef GNU_COMPATIBLE
486 dash_prefix = D_PREFIX;
489 place++; /* --foo long option */
490 #ifdef GNU_COMPATIBLE
491 dash_prefix = DD_PREFIX;
493 } else if (*place != ':' && strchr(options, *place) != NULL)
494 short_too = 1; /* could be short option too */
496 optchar = parse_long_options(nargv, options, long_options,
497 idx, short_too, flags);
504 if ((optchar = (int)*place++) == (int)':' ||
505 (optchar == (int)'-' && *place != '\0') ||
506 (oli = strchr(options, optchar)) == NULL) {
508 * If the user specified "-" and '-' isn't listed in
509 * options, return -1 (non-option) as per POSIX.
510 * Otherwise, it is an unknown option character (or ':').
512 if (optchar == (int)'-' && *place == '\0')
516 #ifdef GNU_COMPATIBLE
518 warnx(posixly_correct ? illoptchar : gnuoptchar,
522 warnx(illoptchar, optchar);
527 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
529 if (*place) /* no space */
531 else if (++optind >= nargc) { /* no arg */
534 warnx(recargchar, optchar);
537 } else /* white space */
538 place = nargv[optind];
539 #ifdef GNU_COMPATIBLE
540 dash_prefix = W_PREFIX;
542 optchar = parse_long_options(nargv, options, long_options,
547 if (*++oli != ':') { /* doesn't take argument */
550 } else { /* takes (optional) argument */
552 if (*place) /* no white space */
554 else if (oli[1] != ':') { /* arg not optional */
555 if (++optind >= nargc) { /* no arg */
558 warnx(recargchar, optchar);
562 optarg = nargv[optind];
567 /* dump back option letter */
571 #ifdef REPLACE_GETOPT
574 * Parse argc/argv argument vector.
576 * [eventually this will replace the BSD getopt]
579 getopt(int nargc, char * const *nargv, const char *options)
583 * We don't pass FLAG_PERMUTE to getopt_internal() since
584 * the BSD getopt(3) (unlike GNU) has never done this.
586 * Furthermore, since many privileged programs call getopt()
587 * before dropping privileges it makes sense to keep things
588 * as simple (and bug-free) as possible.
590 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
592 #endif /* REPLACE_GETOPT */
596 * Parse argc/argv argument vector.
599 getopt_long(int nargc, char * const *nargv, const char *options,
600 const struct option *long_options, int *idx)
603 return (getopt_internal(nargc, nargv, options, long_options, idx,
608 * getopt_long_only --
609 * Parse argc/argv argument vector.
612 getopt_long_only(int nargc, char * const *nargv, const char *options,
613 const struct option *long_options, int *idx)
616 return (getopt_internal(nargc, nargv, options, long_options, idx,
617 FLAG_PERMUTE|FLAG_LONGONLY));