1 /* $OpenBSD: getopt_long.c,v 1.25 2011/03/05 22:10:11 guenther 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.
52 /* OPENBSD ORIGINAL: lib/libc/stdlib/getopt_long.c */
55 #if !defined(HAVE_GETOPT) || !defined(HAVE_GETOPT_OPTRESET)
58 * Some defines to make it easier to keep the code in sync with upstream.
59 * getopt opterr optind optopt optreset optarg are all in defines.h which is
60 * pulled in by includes.h.
76 /* name of long option */
79 * one of no_argument, required_argument, and optional_argument:
80 * whether option takes an argument
83 /* if not NULL, set *flag to val when option found */
85 /* if flag not NULL, value to set *flag to; else return value */
89 int opterr = 1; /* if error message should be printed */
90 int optind = 1; /* index into parent argv vector */
91 int optopt = '?'; /* character checked for validity */
92 int optreset; /* reset getopt */
93 char *optarg; /* argument associated with option */
95 #define PRINT_ERROR ((opterr) && (*options != ':'))
97 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
98 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
99 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
102 #define BADCH (int)'?'
103 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
104 #define INORDER (int)1
108 static int getopt_internal(int, char * const *, const char *,
109 const struct option *, int *, int);
110 static int parse_long_options(char * const *, const char *,
111 const struct option *, int *, int);
112 static int gcd(int, int);
113 static void permute_args(int, int, int, char * const *);
115 static char *place = EMSG; /* option letter processing */
117 /* XXX: set optreset to 1 rather than these two */
118 static int nonopt_start = -1; /* first non option argument (for permute) */
119 static int nonopt_end = -1; /* first option after non options (for permute) */
122 static const char recargchar[] = "option requires an argument -- %c";
123 static const char recargstring[] = "option requires an argument -- %s";
124 static const char ambig[] = "ambiguous option -- %.*s";
125 static const char noarg[] = "option doesn't take an argument -- %.*s";
126 static const char illoptchar[] = "unknown option -- %c";
127 static const char illoptstring[] = "unknown option -- %s";
130 * Compute the greatest common divisor of a and b.
148 * Exchange the block from nonopt_start to nonopt_end with the block
149 * from nonopt_end to opt_end (keeping the same order of arguments
153 permute_args(int panonopt_start, int panonopt_end, int opt_end,
156 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
160 * compute lengths of blocks and number and size of cycles
162 nnonopts = panonopt_end - panonopt_start;
163 nopts = opt_end - panonopt_end;
164 ncycle = gcd(nnonopts, nopts);
165 cyclelen = (opt_end - panonopt_start) / ncycle;
167 for (i = 0; i < ncycle; i++) {
168 cstart = panonopt_end+i;
170 for (j = 0; j < cyclelen; j++) {
171 if (pos >= panonopt_end)
176 /* LINTED const cast */
177 ((char **) nargv)[pos] = nargv[cstart];
178 /* LINTED const cast */
179 ((char **)nargv)[cstart] = swap;
185 * parse_long_options --
186 * Parse long options in argc/argv argument vector.
187 * Returns -1 if short_too is set and the option does not match long_options.
190 parse_long_options(char * const *nargv, const char *options,
191 const struct option *long_options, int *idx, int short_too)
193 char *current_argv, *has_equal;
194 size_t current_argv_len;
197 current_argv = place;
202 if ((has_equal = strchr(current_argv, '=')) != NULL) {
203 /* argument found (--option=arg) */
204 current_argv_len = has_equal - current_argv;
207 current_argv_len = strlen(current_argv);
209 for (i = 0; long_options[i].name; i++) {
210 /* find matching long option */
211 if (strncmp(current_argv, long_options[i].name,
215 if (strlen(long_options[i].name) == current_argv_len) {
221 * If this is a known short option, don't allow
222 * a partial match of a single character.
224 if (short_too && current_argv_len == 1)
227 if (match == -1) /* partial match */
230 /* ambiguous abbreviation */
232 warnx(ambig, (int)current_argv_len,
238 if (match != -1) { /* option found */
239 if (long_options[match].has_arg == no_argument
242 warnx(noarg, (int)current_argv_len,
245 * XXX: GNU sets optopt to val regardless of flag
247 if (long_options[match].flag == NULL)
248 optopt = long_options[match].val;
253 if (long_options[match].has_arg == required_argument ||
254 long_options[match].has_arg == optional_argument) {
257 else if (long_options[match].has_arg ==
260 * optional argument doesn't use next nargv
262 optarg = nargv[optind++];
265 if ((long_options[match].has_arg == required_argument)
266 && (optarg == NULL)) {
268 * Missing argument; leading ':' indicates no error
269 * should be generated.
275 * XXX: GNU sets optopt to val regardless of flag
277 if (long_options[match].flag == NULL)
278 optopt = long_options[match].val;
284 } else { /* unknown option */
290 warnx(illoptstring, current_argv);
296 if (long_options[match].flag) {
297 *long_options[match].flag = long_options[match].val;
300 return (long_options[match].val);
305 * Parse argc/argv argument vector. Called by user level routines.
308 getopt_internal(int nargc, char * const *nargv, const char *options,
309 const struct option *long_options, int *idx, int flags)
311 char *oli; /* option letter list index */
312 int optchar, short_too;
313 static int posixly_correct = -1;
319 * XXX Some GNU programs (like cvs) set optind to 0 instead of
320 * XXX using optreset. Work around this braindamage.
323 optind = optreset = 1;
326 * Disable GNU extensions if POSIXLY_CORRECT is set or options
327 * string begins with a '+'.
329 if (posixly_correct == -1 || optreset)
330 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
332 flags |= FLAG_ALLARGS;
333 else if (posixly_correct || *options == '+')
334 flags &= ~FLAG_PERMUTE;
335 if (*options == '+' || *options == '-')
340 nonopt_start = nonopt_end = -1;
342 if (optreset || !*place) { /* update scanning pointer */
344 if (optind >= nargc) { /* end of argument vector */
346 if (nonopt_end != -1) {
347 /* do permutation, if we have to */
348 permute_args(nonopt_start, nonopt_end,
350 optind -= nonopt_end - nonopt_start;
352 else if (nonopt_start != -1) {
354 * If we skipped non-options, set optind
355 * to the first of them.
357 optind = nonopt_start;
359 nonopt_start = nonopt_end = -1;
362 if (*(place = nargv[optind]) != '-' ||
363 (place[1] == '\0' && strchr(options, '-') == NULL)) {
364 place = EMSG; /* found non-option */
365 if (flags & FLAG_ALLARGS) {
368 * return non-option as argument to option 1
370 optarg = nargv[optind++];
373 if (!(flags & FLAG_PERMUTE)) {
375 * If no permutation wanted, stop parsing
376 * at first non-option.
381 if (nonopt_start == -1)
382 nonopt_start = optind;
383 else if (nonopt_end != -1) {
384 permute_args(nonopt_start, nonopt_end,
386 nonopt_start = optind -
387 (nonopt_end - nonopt_start);
391 /* process next argument */
394 if (nonopt_start != -1 && nonopt_end == -1)
398 * If we have "-" do nothing, if "--" we are done.
400 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
404 * We found an option (--), so if we skipped
405 * non-options, we have to permute.
407 if (nonopt_end != -1) {
408 permute_args(nonopt_start, nonopt_end,
410 optind -= nonopt_end - nonopt_start;
412 nonopt_start = nonopt_end = -1;
418 * Check long options if:
419 * 1) we were passed some
420 * 2) the arg is not just "-"
421 * 3) either the arg starts with -- we are getopt_long_only()
423 if (long_options != NULL && place != nargv[optind] &&
424 (*place == '-' || (flags & FLAG_LONGONLY))) {
427 place++; /* --foo long option */
428 else if (*place != ':' && strchr(options, *place) != NULL)
429 short_too = 1; /* could be short option too */
431 optchar = parse_long_options(nargv, options, long_options,
439 if ((optchar = (int)*place++) == (int)':' ||
440 (optchar == (int)'-' && *place != '\0') ||
441 (oli = strchr(options, optchar)) == NULL) {
443 * If the user specified "-" and '-' isn't listed in
444 * options, return -1 (non-option) as per POSIX.
445 * Otherwise, it is an unknown option character (or ':').
447 if (optchar == (int)'-' && *place == '\0')
452 warnx(illoptchar, optchar);
456 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
458 if (*place) /* no space */
460 else if (++optind >= nargc) { /* no arg */
463 warnx(recargchar, optchar);
466 } else /* white space */
467 place = nargv[optind];
468 optchar = parse_long_options(nargv, options, long_options,
473 if (*++oli != ':') { /* doesn't take argument */
476 } else { /* takes (optional) argument */
478 if (*place) /* no white space */
480 else if (oli[1] != ':') { /* arg not optional */
481 if (++optind >= nargc) { /* no arg */
484 warnx(recargchar, optchar);
488 optarg = nargv[optind];
493 /* dump back option letter */
499 * Parse argc/argv argument vector.
501 * [eventually this will replace the BSD getopt]
504 getopt(int nargc, char * const *nargv, const char *options)
508 * We don't pass FLAG_PERMUTE to getopt_internal() since
509 * the BSD getopt(3) (unlike GNU) has never done this.
511 * Furthermore, since many privileged programs call getopt()
512 * before dropping privileges it makes sense to keep things
513 * as simple (and bug-free) as possible.
515 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
521 * Parse argc/argv argument vector.
524 getopt_long(int nargc, char * const *nargv, const char *options,
525 const struct option *long_options, int *idx)
528 return (getopt_internal(nargc, nargv, options, long_options, idx,
533 * getopt_long_only --
534 * Parse argc/argv argument vector.
537 getopt_long_only(int nargc, char * const *nargv, const char *options,
538 const struct option *long_options, int *idx)
541 return (getopt_internal(nargc, nargv, options, long_options, idx,
542 FLAG_PERMUTE|FLAG_LONGONLY));
546 #endif /* !defined(HAVE_GETOPT) || !defined(HAVE_OPTRESET) */