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