Home | History | Annotate | Line # | Download | only in stdlib
getopt_long.c revision 1.24
      1 /*	$NetBSD: getopt_long.c,v 1.24 2007/11/09 03:29:20 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Dieter Baron and Thomas Klausner.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #if HAVE_NBTOOL_CONFIG_H
     33 #include "nbtool_config.h"
     34 #endif
     35 
     36 #include <sys/cdefs.h>
     37 #if defined(LIBC_SCCS) && !defined(lint)
     38 __RCSID("$NetBSD: getopt_long.c,v 1.24 2007/11/09 03:29:20 christos Exp $");
     39 #endif /* LIBC_SCCS and not lint */
     40 
     41 #include "namespace.h"
     42 
     43 #include <assert.h>
     44 #include <err.h>
     45 #include <errno.h>
     46 #if HAVE_NBTOOL_CONFIG_H
     47 #include "compat_getopt.h"
     48 #else
     49 #include <getopt.h>
     50 #endif
     51 #include <stdlib.h>
     52 #include <string.h>
     53 
     54 #if HAVE_NBTOOL_CONFIG_H && !HAVE_GETOPT_LONG && !HAVE_DECL_OPTIND
     55 #define REPLACE_GETOPT
     56 #endif
     57 
     58 #ifdef REPLACE_GETOPT
     59 #ifdef __weak_alias
     60 __weak_alias(getopt,_getopt)
     61 #endif
     62 int	opterr = 1;		/* if error message should be printed */
     63 int	optind = 1;		/* index into parent argv vector */
     64 int	optopt = '?';		/* character checked for validity */
     65 int	optreset;		/* reset getopt */
     66 char    *optarg;		/* argument associated with option */
     67 #elif HAVE_NBTOOL_CONFIG_H && !HAVE_DECL_OPTRESET
     68 static int optreset;
     69 #endif
     70 
     71 #ifdef __weak_alias
     72 __weak_alias(getopt_long,_getopt_long)
     73 #endif
     74 
     75 #define IGNORE_FIRST	(*options == '-' || *options == '+')
     76 #define PRINT_ERROR	((opterr) && ((*options != ':') \
     77 				      || (IGNORE_FIRST && options[1] != ':')))
     78 #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
     79 #define PERMUTE         (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
     80 /* XXX: GNU ignores PC if *options == '-' */
     81 #define IN_ORDER        (!IS_POSIXLY_CORRECT && *options == '-')
     82 
     83 /* return values */
     84 #define	BADCH	(int)'?'
     85 #define	BADARG		((IGNORE_FIRST && options[1] == ':') \
     86 			 || (*options == ':') ? (int)':' : (int)'?')
     87 #define INORDER (int)1
     88 
     89 #define	EMSG	""
     90 
     91 static int getopt_internal __P((int, char **, const char *));
     92 static int gcd __P((int, int));
     93 static void permute_args __P((int, int, int, char **));
     94 
     95 static const char *place = EMSG; /* option letter processing */
     96 
     97 /* XXX: set optreset to 1 rather than these two */
     98 static int nonopt_start = -1; /* first non option argument (for permute) */
     99 static int nonopt_end = -1;   /* first option after non options (for permute) */
    100 
    101 /* Error messages */
    102 static const char recargchar[] = "option requires an argument -- %c";
    103 static const char recargstring[] = "option requires an argument -- %s";
    104 static const char ambig[] = "ambiguous option -- %.*s";
    105 static const char noarg[] = "option doesn't take an argument -- %.*s";
    106 static const char illoptchar[] = "unknown option -- %c";
    107 static const char illoptstring[] = "unknown option -- %s";
    108 
    109 
    110 /*
    111  * Compute the greatest common divisor of a and b.
    112  */
    113 static int
    114 gcd(a, b)
    115 	int a;
    116 	int b;
    117 {
    118 	int c;
    119 
    120 	c = a % b;
    121 	while (c != 0) {
    122 		a = b;
    123 		b = c;
    124 		c = a % b;
    125 	}
    126 
    127 	return b;
    128 }
    129 
    130 /*
    131  * Exchange the block from nonopt_start to nonopt_end with the block
    132  * from nonopt_end to opt_end (keeping the same order of arguments
    133  * in each block).
    134  */
    135 static void
    136 permute_args(panonopt_start, panonopt_end, opt_end, nargv)
    137 	int panonopt_start;
    138 	int panonopt_end;
    139 	int opt_end;
    140 	char **nargv;
    141 {
    142 	int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
    143 	char *swap;
    144 
    145 	_DIAGASSERT(nargv != NULL);
    146 
    147 	/*
    148 	 * compute lengths of blocks and number and size of cycles
    149 	 */
    150 	nnonopts = panonopt_end - panonopt_start;
    151 	nopts = opt_end - panonopt_end;
    152 	ncycle = gcd(nnonopts, nopts);
    153 	cyclelen = (opt_end - panonopt_start) / ncycle;
    154 
    155 	for (i = 0; i < ncycle; i++) {
    156 		cstart = panonopt_end+i;
    157 		pos = cstart;
    158 		for (j = 0; j < cyclelen; j++) {
    159 			if (pos >= panonopt_end)
    160 				pos -= nnonopts;
    161 			else
    162 				pos += nopts;
    163 			swap = nargv[pos];
    164 			nargv[pos] = nargv[cstart];
    165 			nargv[cstart] = swap;
    166 		}
    167 	}
    168 }
    169 
    170 /*
    171  * getopt_internal --
    172  *	Parse argc/argv argument vector.  Called by user level routines.
    173  *  Returns -2 if -- is found (can be long option or end of options marker).
    174  */
    175 static int
    176 getopt_internal(nargc, nargv, options)
    177 	int nargc;
    178 	char **nargv;
    179 	const char *options;
    180 {
    181 	char *oli;				/* option letter list index */
    182 	int optchar;
    183 
    184 	_DIAGASSERT(nargv != NULL);
    185 	_DIAGASSERT(options != NULL);
    186 
    187 	optarg = NULL;
    188 
    189 	/*
    190 	 * XXX Some programs (like rsyncd) expect to be able to
    191 	 * XXX re-initialize optind to 0 and have getopt_long(3)
    192 	 * XXX properly function again.  Work around this braindamage.
    193 	 */
    194 	if (optind == 0)
    195 		optind = 1;
    196 
    197 	if (optreset)
    198 		nonopt_start = nonopt_end = -1;
    199 start:
    200 	if (optreset || !*place) {		/* update scanning pointer */
    201 		optreset = 0;
    202 		if (optind >= nargc) {          /* end of argument vector */
    203 			place = EMSG;
    204 			if (nonopt_end != -1) {
    205 				/* do permutation, if we have to */
    206 				permute_args(nonopt_start, nonopt_end,
    207 				    optind, nargv);
    208 				optind -= nonopt_end - nonopt_start;
    209 			}
    210 			else if (nonopt_start != -1) {
    211 				/*
    212 				 * If we skipped non-options, set optind
    213 				 * to the first of them.
    214 				 */
    215 				optind = nonopt_start;
    216 			}
    217 			nonopt_start = nonopt_end = -1;
    218 			return -1;
    219 		}
    220 		if ((*(place = nargv[optind]) != '-')
    221 		    || (place[1] == '\0')) {    /* found non-option */
    222 			place = EMSG;
    223 			if (IN_ORDER) {
    224 				/*
    225 				 * GNU extension:
    226 				 * return non-option as argument to option 1
    227 				 */
    228 				optarg = nargv[optind++];
    229 				return INORDER;
    230 			}
    231 			if (!PERMUTE) {
    232 				/*
    233 				 * if no permutation wanted, stop parsing
    234 				 * at first non-option
    235 				 */
    236 				return -1;
    237 			}
    238 			/* do permutation */
    239 			if (nonopt_start == -1)
    240 				nonopt_start = optind;
    241 			else if (nonopt_end != -1) {
    242 				permute_args(nonopt_start, nonopt_end,
    243 				    optind, nargv);
    244 				nonopt_start = optind -
    245 				    (nonopt_end - nonopt_start);
    246 				nonopt_end = -1;
    247 			}
    248 			optind++;
    249 			/* process next argument */
    250 			goto start;
    251 		}
    252 		if (nonopt_start != -1 && nonopt_end == -1)
    253 			nonopt_end = optind;
    254 		if (place[1] && *++place == '-') {	/* found "--" */
    255 			place++;
    256 			return -2;
    257 		}
    258 	}
    259 	if ((optchar = (int)*place++) == (int)':' ||
    260 	    (oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
    261 		/* option letter unknown or ':' */
    262 		if (!*place)
    263 			++optind;
    264 		if (PRINT_ERROR)
    265 			warnx(illoptchar, optchar);
    266 		optopt = optchar;
    267 		return BADCH;
    268 	}
    269 	if (optchar == 'W' && oli[1] == ';') {		/* -W long-option */
    270 		/* XXX: what if no long options provided (called by getopt)? */
    271 		if (*place)
    272 			return -2;
    273 
    274 		if (++optind >= nargc) {	/* no arg */
    275 			place = EMSG;
    276 			if (PRINT_ERROR)
    277 				warnx(recargchar, optchar);
    278 			optopt = optchar;
    279 			return BADARG;
    280 		} else				/* white space */
    281 			place = nargv[optind];
    282 		/*
    283 		 * Handle -W arg the same as --arg (which causes getopt to
    284 		 * stop parsing).
    285 		 */
    286 		return -2;
    287 	}
    288 	if (*++oli != ':') {			/* doesn't take argument */
    289 		if (!*place)
    290 			++optind;
    291 	} else {				/* takes (optional) argument */
    292 		optarg = NULL;
    293 		if (*place)			/* no white space */
    294 			optarg = __UNCONST(place);
    295 		/* XXX: disable test for :: if PC? (GNU doesn't) */
    296 		else if (oli[1] != ':') {	/* arg not optional */
    297 			if (++optind >= nargc) {	/* no arg */
    298 				place = EMSG;
    299 				if (PRINT_ERROR)
    300 					warnx(recargchar, optchar);
    301 				optopt = optchar;
    302 				return BADARG;
    303 			} else
    304 				optarg = nargv[optind];
    305 		}
    306 		place = EMSG;
    307 		++optind;
    308 	}
    309 	/* dump back option letter */
    310 	return optchar;
    311 }
    312 
    313 #ifdef REPLACE_GETOPT
    314 /*
    315  * getopt --
    316  *	Parse argc/argv argument vector.
    317  *
    318  * [eventually this will replace the real getopt]
    319  */
    320 int
    321 getopt(nargc, nargv, options)
    322 	int nargc;
    323 	char * const *nargv;
    324 	const char *options;
    325 {
    326 	int retval;
    327 
    328 	_DIAGASSERT(nargv != NULL);
    329 	_DIAGASSERT(options != NULL);
    330 
    331 	retval = getopt_internal(nargc, __UNCONST(nargv), options);
    332 	if (retval == -2) {
    333 		++optind;
    334 		/*
    335 		 * We found an option (--), so if we skipped non-options,
    336 		 * we have to permute.
    337 		 */
    338 		if (nonopt_end != -1) {
    339 			permute_args(nonopt_start, nonopt_end, optind,
    340 				       nargv);
    341 			optind -= nonopt_end - nonopt_start;
    342 		}
    343 		nonopt_start = nonopt_end = -1;
    344 		retval = -1;
    345 	}
    346 	return retval;
    347 }
    348 #endif
    349 
    350 /*
    351  * getopt_long --
    352  *	Parse argc/argv argument vector.
    353  */
    354 int
    355 getopt_long(nargc, nargv, options, long_options, idx)
    356 	int nargc;
    357 	char * const *nargv;
    358 	const char *options;
    359 	const struct option *long_options;
    360 	int *idx;
    361 {
    362 	int retval;
    363 
    364 #define IDENTICAL_INTERPRETATION(_x, _y)				\
    365 	(long_options[(_x)].has_arg == long_options[(_y)].has_arg &&	\
    366 	 long_options[(_x)].flag == long_options[(_y)].flag &&		\
    367 	 long_options[(_x)].val == long_options[(_y)].val)
    368 
    369 	_DIAGASSERT(nargv != NULL);
    370 	_DIAGASSERT(options != NULL);
    371 	_DIAGASSERT(long_options != NULL);
    372 	/* idx may be NULL */
    373 
    374 	retval = getopt_internal(nargc, __UNCONST(nargv), options);
    375 	if (retval == -2) {
    376 		char *current_argv, *has_equal;
    377 		size_t current_argv_len;
    378 		int i, ambiguous, match;
    379 
    380 		current_argv = __UNCONST(place);
    381 		match = -1;
    382 		ambiguous = 0;
    383 
    384 		optind++;
    385 		place = EMSG;
    386 
    387 		if (*current_argv == '\0') {		/* found "--" */
    388 			/*
    389 			 * We found an option (--), so if we skipped
    390 			 * non-options, we have to permute.
    391 			 */
    392 			if (nonopt_end != -1) {
    393 				permute_args(nonopt_start, nonopt_end,
    394 				    optind, __UNCONST(nargv));
    395 				optind -= nonopt_end - nonopt_start;
    396 			}
    397 			nonopt_start = nonopt_end = -1;
    398 			return -1;
    399 		}
    400 		if ((has_equal = strchr(current_argv, '=')) != NULL) {
    401 			/* argument found (--option=arg) */
    402 			current_argv_len = has_equal - current_argv;
    403 			has_equal++;
    404 		} else
    405 			current_argv_len = strlen(current_argv);
    406 
    407 		for (i = 0; long_options[i].name; i++) {
    408 			/* find matching long option */
    409 			if (strncmp(current_argv, long_options[i].name,
    410 			    current_argv_len))
    411 				continue;
    412 
    413 			if (strlen(long_options[i].name) ==
    414 			    (unsigned)current_argv_len) {
    415 				/* exact match */
    416 				match = i;
    417 				ambiguous = 0;
    418 				break;
    419 			}
    420 			if (match == -1)		/* partial match */
    421 				match = i;
    422 			else if (!IDENTICAL_INTERPRETATION(i, match))
    423 				ambiguous = 1;
    424 		}
    425 		if (ambiguous) {
    426 			/* ambiguous abbreviation */
    427 			if (PRINT_ERROR)
    428 				warnx(ambig, (int)current_argv_len,
    429 				     current_argv);
    430 			optopt = 0;
    431 			return BADCH;
    432 		}
    433 		if (match != -1) {			/* option found */
    434 		        if (long_options[match].has_arg == no_argument
    435 			    && has_equal) {
    436 				if (PRINT_ERROR)
    437 					warnx(noarg, (int)current_argv_len,
    438 					     current_argv);
    439 				/*
    440 				 * XXX: GNU sets optopt to val regardless of
    441 				 * flag
    442 				 */
    443 				if (long_options[match].flag == NULL)
    444 					optopt = long_options[match].val;
    445 				else
    446 					optopt = 0;
    447 				return BADARG;
    448 			}
    449 			if (long_options[match].has_arg == required_argument ||
    450 			    long_options[match].has_arg == optional_argument) {
    451 				if (has_equal)
    452 					optarg = has_equal;
    453 				else if (long_options[match].has_arg ==
    454 				    required_argument) {
    455 					/*
    456 					 * optional argument doesn't use
    457 					 * next nargv
    458 					 */
    459 					optarg = nargv[optind++];
    460 				}
    461 			}
    462 			if ((long_options[match].has_arg == required_argument)
    463 			    && (optarg == NULL)) {
    464 				/*
    465 				 * Missing argument; leading ':'
    466 				 * indicates no error should be generated
    467 				 */
    468 				if (PRINT_ERROR)
    469 					warnx(recargstring, current_argv);
    470 				/*
    471 				 * XXX: GNU sets optopt to val regardless
    472 				 * of flag
    473 				 */
    474 				if (long_options[match].flag == NULL)
    475 					optopt = long_options[match].val;
    476 				else
    477 					optopt = 0;
    478 				--optind;
    479 				return BADARG;
    480 			}
    481 		} else {			/* unknown option */
    482 			if (PRINT_ERROR)
    483 				warnx(illoptstring, current_argv);
    484 			optopt = 0;
    485 			return BADCH;
    486 		}
    487 		if (long_options[match].flag) {
    488 			*long_options[match].flag = long_options[match].val;
    489 			retval = 0;
    490 		} else
    491 			retval = long_options[match].val;
    492 		if (idx)
    493 			*idx = match;
    494 	}
    495 	return retval;
    496 #undef IDENTICAL_INTERPRETATION
    497 }
    498