1 /* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl 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>
6 * Copyright (c) 2008 coresystems GmbH
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 * Sponsored in part by the Defense Advanced Research Projects
21 * Agency (DARPA) and Air Force Research Laboratory, Air Force
22 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
25 * Copyright (c) 2000 The NetBSD Foundation, Inc.
26 * All rights reserved.
28 * This code is derived from software contributed to The NetBSD Foundation
29 * by Dieter Baron and Thomas Klausner.
31 * Redistribution and use in source and binary forms, with or without
32 * modification, are permitted provided that the following conditions
34 * 1. Redistributions of source code must retain the above copyright
35 * notice, this list of conditions and the following disclaimer.
36 * 2. Redistributions in binary form must reproduce the above copyright
37 * notice, this list of conditions and the following disclaimer in the
38 * documentation and/or other materials provided with the distribution.
40 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
41 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
42 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
44 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
48 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
50 * POSSIBILITY OF SUCH DAMAGE.
57 #include <libpayload.h>
59 #define warnx(x...) printf(x)
64 #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
67 int opterr = 1; /* if error message should be printed */
68 int optind = 1; /* index into parent argv vector */
69 int optopt = '?'; /* character checked for validity */
70 int optreset; /* reset getopt */
71 char *optarg; /* argument associated with option */
73 int posixly_correct = 0;
76 #define PRINT_ERROR ((opterr) && (*options != ':'))
78 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
79 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
80 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
83 #define BADCH (int)'?'
84 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
85 #define INORDER (int)1
89 static int getopt_internal(int, char * const *, const char *,
90 const struct option *, int *, int);
91 static int parse_long_options(char * const *, const char *,
92 const struct option *, int *, int);
93 static int gcd(int, int);
94 static void permute_args(int, int, int, char * const *);
96 static char *place = EMSG; /* option letter processing */
98 /* XXX: set optreset to 1 rather than these two */
99 static int nonopt_start = -1; /* first non option argument (for permute) */
100 static int nonopt_end = -1; /* first option after non options (for permute) */
103 static const char recargchar[] = "option requires an argument -- %c";
104 static const char recargstring[] = "option requires an argument -- %s";
105 static const char ambig[] = "ambiguous option -- %.*s";
106 static const char noarg[] = "option doesn't take an argument -- %.*s";
107 static const char illoptchar[] = "unknown option -- %c";
108 static const char illoptstring[] = "unknown option -- %s";
111 * Compute the greatest common divisor of a and b.
129 * Exchange the block from nonopt_start to nonopt_end with the block
130 * from nonopt_end to opt_end (keeping the same order of arguments
134 permute_args(int panonopt_start, int panonopt_end, int opt_end,
137 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
141 * compute lengths of blocks and number and size of cycles
143 nnonopts = panonopt_end - panonopt_start;
144 nopts = opt_end - panonopt_end;
145 ncycle = gcd(nnonopts, nopts);
146 cyclelen = (opt_end - panonopt_start) / ncycle;
148 for (i = 0; i < ncycle; i++) {
149 cstart = panonopt_end+i;
151 for (j = 0; j < cyclelen; j++) {
152 if (pos >= panonopt_end)
157 /* LINTED const cast */
158 ((char **) nargv)[pos] = nargv[cstart];
159 /* LINTED const cast */
160 ((char **)nargv)[cstart] = swap;
166 * parse_long_options --
167 * Parse long options in argc/argv argument vector.
168 * Returns -1 if short_too is set and the option does not match long_options.
171 parse_long_options(char * const *nargv, const char *options,
172 const struct option *long_options, int *idx, int short_too)
174 char *current_argv, *has_equal;
175 size_t current_argv_len;
178 current_argv = place;
183 if ((has_equal = strchr(current_argv, '=')) != NULL) {
184 /* argument found (--option=arg) */
185 current_argv_len = has_equal - current_argv;
188 current_argv_len = strlen(current_argv);
190 for (i = 0; long_options[i].name; i++) {
191 /* find matching long option */
192 if (strncmp(current_argv, long_options[i].name,
196 if (strlen(long_options[i].name) == current_argv_len) {
202 * If this is a known short option, don't allow
203 * a partial match of a single character.
205 if (short_too && current_argv_len == 1)
208 if (match == -1) /* partial match */
211 /* ambiguous abbreviation */
213 warnx(ambig, (int)current_argv_len,
219 if (match != -1) { /* option found */
220 if (long_options[match].has_arg == no_argument
223 warnx(noarg, (int)current_argv_len,
226 * XXX: GNU sets optopt to val regardless of flag
228 if (long_options[match].flag == NULL)
229 optopt = long_options[match].val;
234 if (long_options[match].has_arg == required_argument ||
235 long_options[match].has_arg == optional_argument) {
238 else if (long_options[match].has_arg ==
241 * optional argument doesn't use next nargv
243 optarg = nargv[optind++];
246 if ((long_options[match].has_arg == required_argument)
247 && (optarg == NULL)) {
249 * Missing argument; leading ':' indicates no error
250 * should be generated.
256 * XXX: GNU sets optopt to val regardless of flag
258 if (long_options[match].flag == NULL)
259 optopt = long_options[match].val;
265 } else { /* unknown option */
271 warnx(illoptstring, current_argv);
277 if (long_options[match].flag) {
278 *long_options[match].flag = long_options[match].val;
281 return (long_options[match].val);
286 * Parse argc/argv argument vector. Called by user level routines.
289 getopt_internal(int nargc, char * const *nargv, const char *options,
290 const struct option *long_options, int *idx, int flags)
292 char *oli; /* option letter list index */
293 int optchar, short_too;
299 * Disable GNU extensions if posixly_correct is set or options
300 * string begins with a '+'.
302 if (posixly_correct || *options == '+')
303 flags &= ~FLAG_PERMUTE;
304 else if (*options == '-')
305 flags |= FLAG_ALLARGS;
306 if (*options == '+' || *options == '-')
310 * XXX Some GNU programs (like cvs) set optind to 0 instead of
311 * XXX using optreset. Work around this braindamage.
314 optind = optreset = 1;
318 nonopt_start = nonopt_end = -1;
320 if (optreset || !*place) { /* update scanning pointer */
322 if (optind >= nargc) { /* end of argument vector */
324 if (nonopt_end != -1) {
325 /* do permutation, if we have to */
326 permute_args(nonopt_start, nonopt_end,
328 optind -= nonopt_end - nonopt_start;
330 else if (nonopt_start != -1) {
332 * If we skipped non-options, set optind
333 * to the first of them.
335 optind = nonopt_start;
337 nonopt_start = nonopt_end = -1;
340 if (*(place = nargv[optind]) != '-' ||
341 (place[1] == '\0' && strchr(options, '-') == NULL)) {
342 place = EMSG; /* found non-option */
343 if (flags & FLAG_ALLARGS) {
346 * return non-option as argument to option 1
348 optarg = nargv[optind++];
351 if (!(flags & FLAG_PERMUTE)) {
353 * If no permutation wanted, stop parsing
354 * at first non-option.
359 if (nonopt_start == -1)
360 nonopt_start = optind;
361 else if (nonopt_end != -1) {
362 permute_args(nonopt_start, nonopt_end,
364 nonopt_start = optind -
365 (nonopt_end - nonopt_start);
369 /* process next argument */
372 if (nonopt_start != -1 && nonopt_end == -1)
376 * If we have "-" do nothing, if "--" we are done.
378 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
382 * We found an option (--), so if we skipped
383 * non-options, we have to permute.
385 if (nonopt_end != -1) {
386 permute_args(nonopt_start, nonopt_end,
388 optind -= nonopt_end - nonopt_start;
390 nonopt_start = nonopt_end = -1;
396 * Check long options if:
397 * 1) we were passed some
398 * 2) the arg is not just "-"
399 * 3) either the arg starts with -- we are getopt_long_only()
401 if (long_options != NULL && place != nargv[optind] &&
402 (*place == '-' || (flags & FLAG_LONGONLY))) {
405 place++; /* --foo long option */
406 else if (*place != ':' && strchr(options, *place) != NULL)
407 short_too = 1; /* could be short option too */
409 optchar = parse_long_options(nargv, options, long_options,
417 if ((optchar = (int)*place++) == (int)':' ||
418 (optchar == (int)'-' && *place != '\0') ||
419 (oli = strchr(options, optchar)) == NULL) {
421 * If the user specified "-" and '-' isn't listed in
422 * options, return -1 (non-option) as per POSIX.
423 * Otherwise, it is an unknown option character (or ':').
425 if (optchar == (int)'-' && *place == '\0')
430 warnx(illoptchar, optchar);
434 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
436 if (*place) /* no space */
438 else if (++optind >= nargc) { /* no arg */
441 warnx(recargchar, optchar);
444 } else /* white space */
445 place = nargv[optind];
446 optchar = parse_long_options(nargv, options, long_options,
451 if (*++oli != ':') { /* doesn't take argument */
454 } else { /* takes (optional) argument */
456 if (*place) /* no white space */
458 else if (oli[1] != ':') { /* arg not optional */
459 if (++optind >= nargc) { /* no arg */
462 warnx(recargchar, optchar);
466 optarg = nargv[optind];
471 /* dump back option letter */
475 #ifdef REPLACE_GETOPT
478 * Parse argc/argv argument vector.
480 * [eventually this will replace the BSD getopt]
483 getopt(int nargc, char * const *nargv, const char *options)
487 * We don't pass FLAG_PERMUTE to getopt_internal() since
488 * the BSD getopt(3) (unlike GNU) has never done this.
490 * Furthermore, since many privileged programs call getopt()
491 * before dropping privileges it makes sense to keep things
492 * as simple (and bug-free) as possible.
494 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
496 #endif /* REPLACE_GETOPT */
500 * Parse argc/argv argument vector.
503 getopt_long(int nargc, char * const *nargv, const char *options,
504 const struct option *long_options, int *idx)
507 return (getopt_internal(nargc, nargv, options, long_options, idx,
512 * getopt_long_only --
513 * Parse argc/argv argument vector.
516 getopt_long_only(int nargc, char * const *nargv, const char *options,
517 const struct option *long_options, int *idx)
520 return (getopt_internal(nargc, nargv, options, long_options, idx,
521 FLAG_PERMUTE|FLAG_LONGONLY));