1 /* $OpenBSD: getopt_long.c,v 1.21 2006/09/22 17:22:05 millert 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.
38 * 3. All advertising materials mentioning features or use of this software
39 * must display the following acknowledgement:
40 * This product includes software developed by the NetBSD
41 * Foundation, Inc. and its contributors.
42 * 4. Neither the name of The NetBSD Foundation nor the names of its
43 * contributors may be used to endorse or promote products derived
44 * from this software without specific prior written permission.
46 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
47 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
48 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
49 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
50 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
56 * POSSIBILITY OF SUCH DAMAGE.
58 * $FreeBSD: src/lib/libc/stdlib/getopt_long.c,v 1.15 2006/09/23 14:48:31 ache Exp $
59 * $DragonFly: src/lib/libc/stdlib/getopt_long.c,v 1.14 2005/11/20 12:37:48 swildner Exp $
68 #define GNU_COMPATIBLE /* Be more compatible, configure's use us! */
70 #if 0 /* we prefer to keep our getopt(3) */
71 #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
75 int opterr
= 1; /* if error message should be printed */
76 int optind
= 1; /* index into parent argv vector */
77 int optopt
= '?'; /* character checked for validity */
78 int optreset
; /* reset getopt */
79 char *optarg
; /* argument associated with option */
82 #define PRINT_ERROR ((opterr) && (*options != ':'))
84 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
85 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
86 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
89 #define BADCH (int)'?'
90 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
91 #define INORDER (int)1
96 #define NO_PREFIX (-1)
102 static int getopt_internal(int, char * const *, const char *,
103 const struct option
*, int *, int);
104 static int parse_long_options(char * const *, const char *,
105 const struct option
*, int *, int, int);
106 static int gcd(int, int);
107 static void permute_args(int, int, int, char * const *);
109 static char *place
= EMSG
; /* option letter processing */
111 /* XXX: set optreset to 1 rather than these two */
112 static int nonopt_start
= -1; /* first non option argument (for permute) */
113 static int nonopt_end
= -1; /* first option after non options (for permute) */
116 static const char recargchar
[] = "option requires an argument -- %c";
117 static const char illoptchar
[] = "illegal option -- %c"; /* From P1003.2 */
118 #ifdef GNU_COMPATIBLE
119 static int dash_prefix
= NO_PREFIX
;
120 static const char gnuoptchar
[] = "invalid option -- %c";
122 static const char recargstring
[] = "option `%s%s' requires an argument";
123 static const char ambig
[] = "option `%s%.*s' is ambiguous";
124 static const char noarg
[] = "option `%s%.*s' doesn't allow an argument";
125 static const char illoptstring
[] = "unrecognized option `%s%s'";
127 static const char recargstring
[] = "option requires an argument -- %s";
128 static const char ambig
[] = "ambiguous option -- %.*s";
129 static const char noarg
[] = "option doesn't take an argument -- %.*s";
130 static const char illoptstring
[] = "unknown option -- %s";
134 * Compute the greatest common divisor of a and b.
152 * Exchange the block from nonopt_start to nonopt_end with the block
153 * from nonopt_end to opt_end (keeping the same order of arguments
157 permute_args(int panonopt_start
, int panonopt_end
, int opt_end
,
160 int cstart
, cyclelen
, i
, j
, ncycle
, nnonopts
, nopts
, pos
;
164 * compute lengths of blocks and number and size of cycles
166 nnonopts
= panonopt_end
- panonopt_start
;
167 nopts
= opt_end
- panonopt_end
;
168 ncycle
= gcd(nnonopts
, nopts
);
169 cyclelen
= (opt_end
- panonopt_start
) / ncycle
;
171 for (i
= 0; i
< ncycle
; i
++) {
172 cstart
= panonopt_end
+i
;
174 for (j
= 0; j
< cyclelen
; j
++) {
175 if (pos
>= panonopt_end
)
180 /* LINTED const cast */
181 (__DECONST(char **, nargv
))[pos
] = nargv
[cstart
];
182 /* LINTED const cast */
183 (__DECONST(char **, nargv
))[cstart
] = swap
;
189 * parse_long_options --
190 * Parse long options in argc/argv argument vector.
191 * Returns -1 if short_too is set and the option does not match long_options.
194 parse_long_options(char * const *nargv
, const char *options
,
195 const struct option
*long_options
, int *idx
, int short_too
, int flags
)
197 char *current_argv
, *has_equal
;
198 #ifdef GNU_COMPATIBLE
201 size_t current_argv_len
;
202 int i
, match
, exact_match
, second_partial_match
;
204 current_argv
= place
;
205 #ifdef GNU_COMPATIBLE
206 switch (dash_prefix
) {
214 current_dash
= "-W ";
223 second_partial_match
= 0;
227 if ((has_equal
= strchr(current_argv
, '=')) != NULL
) {
228 /* argument found (--option=arg) */
229 current_argv_len
= has_equal
- current_argv
;
232 current_argv_len
= strlen(current_argv
);
234 for (i
= 0; long_options
[i
].name
; i
++) {
235 /* find matching long option */
236 if (strncmp(current_argv
, long_options
[i
].name
,
240 if (strlen(long_options
[i
].name
) == current_argv_len
) {
247 * If this is a known short option, don't allow
248 * a partial match of a single character.
250 if (short_too
&& current_argv_len
== 1)
253 if (match
== -1) /* first partial match */
255 else if ((flags
& FLAG_LONGONLY
) ||
256 long_options
[i
].has_arg
!=
257 long_options
[match
].has_arg
||
258 long_options
[i
].flag
!= long_options
[match
].flag
||
259 long_options
[i
].val
!= long_options
[match
].val
)
260 second_partial_match
= 1;
262 if (!exact_match
&& second_partial_match
) {
263 /* ambiguous abbreviation */
266 #ifdef GNU_COMPATIBLE
269 (int)current_argv_len
,
274 if (match
!= -1) { /* option found */
275 if (long_options
[match
].has_arg
== no_argument
279 #ifdef GNU_COMPATIBLE
282 (int)current_argv_len
,
285 * XXX: GNU sets optopt to val regardless of flag
287 if (long_options
[match
].flag
== NULL
)
288 optopt
= long_options
[match
].val
;
291 #ifdef GNU_COMPATIBLE
297 if (long_options
[match
].has_arg
== required_argument
||
298 long_options
[match
].has_arg
== optional_argument
) {
301 else if (long_options
[match
].has_arg
==
304 * optional argument doesn't use next nargv
306 optarg
= nargv
[optind
++];
309 if ((long_options
[match
].has_arg
== required_argument
)
310 && (optarg
== NULL
)) {
312 * Missing argument; leading ':' indicates no error
313 * should be generated.
317 #ifdef GNU_COMPATIBLE
322 * XXX: GNU sets optopt to val regardless of flag
324 if (long_options
[match
].flag
== NULL
)
325 optopt
= long_options
[match
].val
;
331 } else { /* unknown option */
338 #ifdef GNU_COMPATIBLE
347 if (long_options
[match
].flag
) {
348 *long_options
[match
].flag
= long_options
[match
].val
;
351 return (long_options
[match
].val
);
356 * Parse argc/argv argument vector. Called by user level routines.
359 getopt_internal(int nargc
, char * const *nargv
, const char *options
,
360 const struct option
*long_options
, int *idx
, int flags
)
362 char *oli
; /* option letter list index */
363 int optchar
, short_too
;
364 int posixly_correct
; /* no static, can be changed on the fly */
370 * Disable GNU extensions if POSIXLY_CORRECT is set or options
371 * string begins with a '+'.
373 posixly_correct
= (getenv("POSIXLY_CORRECT") != NULL
);
374 #ifdef GNU_COMPATIBLE
376 flags
|= FLAG_ALLARGS
;
377 else if (posixly_correct
|| *options
== '+')
378 flags
&= ~FLAG_PERMUTE
;
380 if (posixly_correct
|| *options
== '+')
381 flags
&= ~FLAG_PERMUTE
;
382 else if (*options
== '-')
383 flags
|= FLAG_ALLARGS
;
385 if (*options
== '+' || *options
== '-')
389 * XXX Some GNU programs (like cvs) set optind to 0 instead of
390 * XXX using optreset. Work around this braindamage.
393 optind
= optreset
= 1;
397 nonopt_start
= nonopt_end
= -1;
399 if (optreset
|| !*place
) { /* update scanning pointer */
401 if (optind
>= nargc
) { /* end of argument vector */
403 if (nonopt_end
!= -1) {
404 /* do permutation, if we have to */
405 permute_args(nonopt_start
, nonopt_end
,
407 optind
-= nonopt_end
- nonopt_start
;
409 else if (nonopt_start
!= -1) {
411 * If we skipped non-options, set optind
412 * to the first of them.
414 optind
= nonopt_start
;
416 nonopt_start
= nonopt_end
= -1;
419 if (*(place
= nargv
[optind
]) != '-' ||
420 #ifdef GNU_COMPATIBLE
423 (place
[1] == '\0' && strchr(options
, '-') == NULL
)) {
425 place
= EMSG
; /* found non-option */
426 if (flags
& FLAG_ALLARGS
) {
429 * return non-option as argument to option 1
431 optarg
= nargv
[optind
++];
434 if (!(flags
& FLAG_PERMUTE
)) {
436 * If no permutation wanted, stop parsing
437 * at first non-option.
442 if (nonopt_start
== -1)
443 nonopt_start
= optind
;
444 else if (nonopt_end
!= -1) {
445 permute_args(nonopt_start
, nonopt_end
,
447 nonopt_start
= optind
-
448 (nonopt_end
- nonopt_start
);
452 /* process next argument */
455 if (nonopt_start
!= -1 && nonopt_end
== -1)
459 * If we have "-" do nothing, if "--" we are done.
461 if (place
[1] != '\0' && *++place
== '-' && place
[1] == '\0') {
465 * We found an option (--), so if we skipped
466 * non-options, we have to permute.
468 if (nonopt_end
!= -1) {
469 permute_args(nonopt_start
, nonopt_end
,
471 optind
-= nonopt_end
- nonopt_start
;
473 nonopt_start
= nonopt_end
= -1;
479 * Check long options if:
480 * 1) we were passed some
481 * 2) the arg is not just "-"
482 * 3) either the arg starts with -- we are getopt_long_only()
484 if (long_options
!= NULL
&& place
!= nargv
[optind
] &&
485 (*place
== '-' || (flags
& FLAG_LONGONLY
))) {
487 #ifdef GNU_COMPATIBLE
488 dash_prefix
= D_PREFIX
;
491 place
++; /* --foo long option */
492 #ifdef GNU_COMPATIBLE
493 dash_prefix
= DD_PREFIX
;
495 } else if (*place
!= ':' && strchr(options
, *place
) != NULL
)
496 short_too
= 1; /* could be short option too */
498 optchar
= parse_long_options(nargv
, options
, long_options
,
499 idx
, short_too
, flags
);
506 if ((optchar
= (int)*place
++) == (int)':' ||
507 (optchar
== (int)'-' && *place
!= '\0') ||
508 (oli
= strchr(options
, optchar
)) == NULL
) {
510 * If the user specified "-" and '-' isn't listed in
511 * options, return -1 (non-option) as per POSIX.
512 * Otherwise, it is an unknown option character (or ':').
514 if (optchar
== (int)'-' && *place
== '\0')
518 #ifdef GNU_COMPATIBLE
520 warnx(posixly_correct
? illoptchar
: gnuoptchar
,
524 warnx(illoptchar
, optchar
);
529 if (long_options
!= NULL
&& optchar
== 'W' && oli
[1] == ';') {
531 if (*place
) /* no space */
533 else if (++optind
>= nargc
) { /* no arg */
536 warnx(recargchar
, optchar
);
539 } else /* white space */
540 place
= nargv
[optind
];
541 #ifdef GNU_COMPATIBLE
542 dash_prefix
= W_PREFIX
;
544 optchar
= parse_long_options(nargv
, options
, long_options
,
549 if (*++oli
!= ':') { /* doesn't take argument */
552 } else { /* takes (optional) argument */
554 if (*place
) /* no white space */
556 else if (oli
[1] != ':') { /* arg not optional */
557 if (++optind
>= nargc
) { /* no arg */
560 warnx(recargchar
, optchar
);
564 optarg
= nargv
[optind
];
569 /* dump back option letter */
573 #ifdef REPLACE_GETOPT
576 * Parse argc/argv argument vector.
578 * [eventually this will replace the BSD getopt]
581 getopt(int nargc
, char * const *nargv
, const char *options
)
585 * We don't pass FLAG_PERMUTE to getopt_internal() since
586 * the BSD getopt(3) (unlike GNU) has never done this.
588 * Furthermore, since many privileged programs call getopt()
589 * before dropping privileges it makes sense to keep things
590 * as simple (and bug-free) as possible.
592 return (getopt_internal(nargc
, nargv
, options
, NULL
, NULL
, 0));
594 #endif /* REPLACE_GETOPT */
598 * Parse argc/argv argument vector.
601 getopt_long(int nargc
, char * const *nargv
, const char *options
,
602 const struct option
*long_options
, int *idx
)
605 return (getopt_internal(nargc
, nargv
, options
, long_options
, idx
,
610 * getopt_long_only --
611 * Parse argc/argv argument vector.
614 getopt_long_only(int nargc
, char * const *nargv
, const char *options
,
615 const struct option
*long_options
, int *idx
)
618 return (getopt_internal(nargc
, nargv
, options
, long_options
, idx
,
619 FLAG_PERMUTE
|FLAG_LONGONLY
));