Home | History | Annotate | Line # | Download | only in stdlib
getopt_long.c revision 1.14
      1 /*	$NetBSD: getopt_long.c,v 1.14 2002/01/29 10:20:30 tv 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 #include <sys/cdefs.h>
     40 #if defined(LIBC_SCCS) && !defined(lint)
     41 __RCSID("$NetBSD: getopt_long.c,v 1.14 2002/01/29 10:20:30 tv Exp $");
     42 #endif /* LIBC_SCCS and not lint */
     43 
     44 #include "namespace.h"
     45 
     46 #include <assert.h>
     47 #include <errno.h>
     48 #include <stdlib.h>
     49 #include <string.h>
     50 #include <getopt.h>
     51 
     52 #if HAVE_ERR_H || !HAVE_CONFIG_H
     53 #include <err.h>
     54 #endif
     55 
     56 #ifdef REPLACE_GETOPT
     57 #ifdef __weak_alias
     58 __weak_alias(getopt,_getopt)
     59 #endif
     60 int	opterr = 1;		/* if error message should be printed */
     61 int	optind = 1;		/* index into parent argv vector */
     62 int	optopt = '?';		/* character checked for validity */
     63 int	optreset;		/* reset getopt */
     64 char    *optarg;		/* argument associated with option */
     65 #elif HAVE_CONFIG_H
     66 static int optreset;
     67 #endif
     68 
     69 #ifdef __weak_alias
     70 __weak_alias(getopt_long,_getopt_long)
     71 #endif
     72 
     73 
     74 #define IGNORE_FIRST	(*options == '-' || *options == '+')
     75 #define PRINT_ERROR	((opterr) && ((*options != ':') \
     76 				      || (IGNORE_FIRST && options[1] != ':')))
     77 #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
     78 #define PERMUTE         (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
     79 /* XXX: GNU ignores PC if *options == '-' */
     80 #define IN_ORDER        (!IS_POSIXLY_CORRECT && *options == '-')
     81 
     82 /* return values */
     83 #define	BADCH	(int)'?'
     84 #define	BADARG		((IGNORE_FIRST && options[1] == ':') \
     85 			 || (*options == ':') ? (int)':' : (int)'?')
     86 #define INORDER (int)1
     87 
     88 #define	EMSG	""
     89 
     90 static int getopt_internal __P((int, char * const *, const char *));
     91 static int gcd __P((int, int));
     92 static void permute_args __P((int, int, int, char * const *));
     93 
     94 static char *place = EMSG; /* option letter processing */
     95 
     96 /* XXX: set optreset to 1 rather than these two */
     97 static int nonopt_start = -1; /* first non option argument (for permute) */
     98 static int nonopt_end = -1;   /* first option after non options (for permute) */
     99 
    100 /* Error messages */
    101 static const char recargchar[] = "option requires an argument -- %c";
    102 static const char recargstring[] = "option requires an argument -- %s";
    103 static const char ambig[] = "ambiguous option -- %.*s";
    104 static const char noarg[] = "option doesn't take an argument -- %.*s";
    105 static const char illoptchar[] = "unknown option -- %c";
    106 static const char illoptstring[] = "unknown option -- %s";
    107 
    108 
    109 /*
    110  * Compute the greatest common divisor of a and b.
    111  */
    112 static int
    113 gcd(a, b)
    114 	int a;
    115 	int b;
    116 {
    117 	int c;
    118 
    119 	c = a % b;
    120 	while (c != 0) {
    121 		a = b;
    122 		b = c;
    123 		c = a % b;
    124 	}
    125 
    126 	return b;
    127 }
    128 
    129 /*
    130  * Exchange the block from nonopt_start to nonopt_end with the block
    131  * from nonopt_end to opt_end (keeping the same order of arguments
    132  * in each block).
    133  */
    134 static void
    135 permute_args(panonopt_start, panonopt_end, opt_end, nargv)
    136 	int panonopt_start;
    137 	int panonopt_end;
    138 	int opt_end;
    139 	char * const *nargv;
    140 {
    141 	int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
    142 	char *swap;
    143 
    144 	_DIAGASSERT(nargv != NULL);
    145 
    146 	/*
    147 	 * compute lengths of blocks and number and size of cycles
    148 	 */
    149 	nnonopts = panonopt_end - panonopt_start;
    150 	nopts = opt_end - panonopt_end;
    151 	ncycle = gcd(nnonopts, nopts);
    152 	cyclelen = (opt_end - panonopt_start) / ncycle;
    153 
    154 	for (i = 0; i < ncycle; i++) {
    155 		cstart = panonopt_end+i;
    156 		pos = cstart;
    157 		for (j = 0; j < cyclelen; j++) {
    158 			if (pos >= panonopt_end)
    159 				pos -= nnonopts;
    160 			else
    161 				pos += nopts;
    162 			swap = nargv[pos];
    163 			/* LINTED const cast */
    164 			((char **) nargv)[pos] = nargv[cstart];
    165 			/* LINTED const cast */
    166 			((char **)nargv)[cstart] = swap;
    167 		}
    168 	}
    169 }
    170 
    171 /*
    172  * getopt_internal --
    173  *	Parse argc/argv argument vector.  Called by user level routines.
    174  *  Returns -2 if -- is found (can be long option or end of options marker).
    175  */
    176 static int
    177 getopt_internal(nargc, nargv, options)
    178 	int nargc;
    179 	char * const *nargv;
    180 	const char *options;
    181 {
    182 	char *oli;				/* option letter list index */
    183 	int optchar;
    184 
    185 	_DIAGASSERT(nargv != NULL);
    186 	_DIAGASSERT(options != NULL);
    187 
    188 	optarg = NULL;
    189 
    190 	/*
    191 	 * XXX Some programs (like rsyncd) expect to be able to
    192 	 * XXX re-initialize optind to 0 and have getopt_long(3)
    193 	 * XXX properly function again.  Work around this braindamage.
    194 	 */
    195 	if (optind == 0)
    196 		optind = 1;
    197 
    198 	if (optreset)
    199 		nonopt_start = nonopt_end = -1;
    200 start:
    201 	if (optreset || !*place) {		/* update scanning pointer */
    202 		optreset = 0;
    203 		if (optind >= nargc) {          /* end of argument vector */
    204 			place = EMSG;
    205 			if (nonopt_end != -1) {
    206 				/* do permutation, if we have to */
    207 				permute_args(nonopt_start, nonopt_end,
    208 				    optind, nargv);
    209 				optind -= nonopt_end - nonopt_start;
    210 			}
    211 			else if (nonopt_start != -1) {
    212 				/*
    213 				 * If we skipped non-options, set optind
    214 				 * to the first of them.
    215 				 */
    216 				optind = nonopt_start;
    217 			}
    218 			nonopt_start = nonopt_end = -1;
    219 			return -1;
    220 		}
    221 		if ((*(place = nargv[optind]) != '-')
    222 		    || (place[1] == '\0')) {    /* found non-option */
    223 			place = EMSG;
    224 			if (IN_ORDER) {
    225 				/*
    226 				 * GNU extension:
    227 				 * return non-option as argument to option 1
    228 				 */
    229 				optarg = nargv[optind++];
    230 				return INORDER;
    231 			}
    232 			if (!PERMUTE) {
    233 				/*
    234 				 * if no permutation wanted, stop parsing
    235 				 * at first non-option
    236 				 */
    237 				return -1;
    238 			}
    239 			/* do permutation */
    240 			if (nonopt_start == -1)
    241 				nonopt_start = optind;
    242 			else if (nonopt_end != -1) {
    243 				permute_args(nonopt_start, nonopt_end,
    244 				    optind, nargv);
    245 				nonopt_start = optind -
    246 				    (nonopt_end - nonopt_start);
    247 				nonopt_end = -1;
    248 			}
    249 			optind++;
    250 			/* process next argument */
    251 			goto start;
    252 		}
    253 		if (nonopt_start != -1 && nonopt_end == -1)
    254 			nonopt_end = optind;
    255 		if (place[1] && *++place == '-') {	/* found "--" */
    256 			place++;
    257 			return -2;
    258 		}
    259 	}
    260 	if ((optchar = (int)*place++) == (int)':' ||
    261 	    (oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
    262 		/* option letter unknown or ':' */
    263 		if (!*place)
    264 			++optind;
    265 		if (PRINT_ERROR)
    266 			warnx(illoptchar, optchar);
    267 		optopt = optchar;
    268 		return BADCH;
    269 	}
    270 	if (optchar == 'W' && oli[1] == ';') {		/* -W long-option */
    271 		/* XXX: what if no long options provided (called by getopt)? */
    272 		if (*place)
    273 			return -2;
    274 
    275 		if (++optind >= nargc) {	/* no arg */
    276 			place = EMSG;
    277 			if (PRINT_ERROR)
    278 				warnx(recargchar, optchar);
    279 			optopt = optchar;
    280 			return BADARG;
    281 		} else				/* white space */
    282 			place = nargv[optind];
    283 		/*
    284 		 * Handle -W arg the same as --arg (which causes getopt to
    285 		 * stop parsing).
    286 		 */
    287 		return -2;
    288 	}
    289 	if (*++oli != ':') {			/* doesn't take argument */
    290 		if (!*place)
    291 			++optind;
    292 	} else {				/* takes (optional) argument */
    293 		optarg = NULL;
    294 		if (*place)			/* no white space */
    295 			optarg = place;
    296 		/* XXX: disable test for :: if PC? (GNU doesn't) */
    297 		else if (oli[1] != ':') {	/* arg not optional */
    298 			if (++optind >= nargc) {	/* no arg */
    299 				place = EMSG;
    300 				if (PRINT_ERROR)
    301 					warnx(recargchar, optchar);
    302 				optopt = optchar;
    303 				return BADARG;
    304 			} else
    305 				optarg = nargv[optind];
    306 		}
    307 		place = EMSG;
    308 		++optind;
    309 	}
    310 	/* dump back option letter */
    311 	return optchar;
    312 }
    313 
    314 #ifdef REPLACE_GETOPT
    315 /*
    316  * getopt --
    317  *	Parse argc/argv argument vector.
    318  *
    319  * [eventually this will replace the real getopt]
    320  */
    321 int
    322 getopt(nargc, nargv, options)
    323 	int nargc;
    324 	char * const *nargv;
    325 	const char *options;
    326 {
    327 	int retval;
    328 
    329 	_DIAGASSERT(nargv != NULL);
    330 	_DIAGASSERT(options != NULL);
    331 
    332 	if ((retval = getopt_internal(nargc, nargv, options)) == -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 	_DIAGASSERT(nargv != NULL);
    365 	_DIAGASSERT(options != NULL);
    366 	_DIAGASSERT(long_options != NULL);
    367 	/* idx may be NULL */
    368 
    369 	if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
    370 		char *current_argv, *has_equal;
    371 		size_t current_argv_len;
    372 		int i, match;
    373 
    374 		current_argv = place;
    375 		match = -1;
    376 
    377 		optind++;
    378 		place = EMSG;
    379 
    380 		if (*current_argv == '\0') {		/* found "--" */
    381 			/*
    382 			 * We found an option (--), so if we skipped
    383 			 * non-options, we have to permute.
    384 			 */
    385 			if (nonopt_end != -1) {
    386 				permute_args(nonopt_start, nonopt_end,
    387 				    optind, nargv);
    388 				optind -= nonopt_end - nonopt_start;
    389 			}
    390 			nonopt_start = nonopt_end = -1;
    391 			return -1;
    392 		}
    393 		if ((has_equal = strchr(current_argv, '=')) != NULL) {
    394 			/* argument found (--option=arg) */
    395 			current_argv_len = has_equal - current_argv;
    396 			has_equal++;
    397 		} else
    398 			current_argv_len = strlen(current_argv);
    399 
    400 		for (i = 0; long_options[i].name; i++) {
    401 			/* find matching long option */
    402 			if (strncmp(current_argv, long_options[i].name,
    403 			    current_argv_len))
    404 				continue;
    405 
    406 			if (strlen(long_options[i].name) ==
    407 			    (unsigned)current_argv_len) {
    408 				/* exact match */
    409 				match = i;
    410 				break;
    411 			}
    412 			if (match == -1)		/* partial match */
    413 				match = i;
    414 			else {
    415 				/* ambiguous abbreviation */
    416 				if (PRINT_ERROR)
    417 					warnx(ambig, (int)current_argv_len,
    418 					     current_argv);
    419 				optopt = 0;
    420 				return BADCH;
    421 			}
    422 		}
    423 		if (match != -1) {			/* option found */
    424 		        if (long_options[match].has_arg == no_argument
    425 			    && has_equal) {
    426 				if (PRINT_ERROR)
    427 					warnx(noarg, (int)current_argv_len,
    428 					     current_argv);
    429 				/*
    430 				 * XXX: GNU sets optopt to val regardless of
    431 				 * flag
    432 				 */
    433 				if (long_options[match].flag == NULL)
    434 					optopt = long_options[match].val;
    435 				else
    436 					optopt = 0;
    437 				return BADARG;
    438 			}
    439 			if (long_options[match].has_arg == required_argument ||
    440 			    long_options[match].has_arg == optional_argument) {
    441 				if (has_equal)
    442 					optarg = has_equal;
    443 				else if (long_options[match].has_arg ==
    444 				    required_argument) {
    445 					/*
    446 					 * optional argument doesn't use
    447 					 * next nargv
    448 					 */
    449 					optarg = nargv[optind++];
    450 				}
    451 			}
    452 			if ((long_options[match].has_arg == required_argument)
    453 			    && (optarg == NULL)) {
    454 				/*
    455 				 * Missing argument; leading ':'
    456 				 * indicates no error should be generated
    457 				 */
    458 				if (PRINT_ERROR)
    459 					warnx(recargstring, current_argv);
    460 				/*
    461 				 * XXX: GNU sets optopt to val regardless
    462 				 * of flag
    463 				 */
    464 				if (long_options[match].flag == NULL)
    465 					optopt = long_options[match].val;
    466 				else
    467 					optopt = 0;
    468 				--optind;
    469 				return BADARG;
    470 			}
    471 		} else {			/* unknown option */
    472 			if (PRINT_ERROR)
    473 				warnx(illoptstring, current_argv);
    474 			optopt = 0;
    475 			return BADCH;
    476 		}
    477 		if (long_options[match].flag) {
    478 			*long_options[match].flag = long_options[match].val;
    479 			retval = 0;
    480 		} else
    481 			retval = long_options[match].val;
    482 		if (idx)
    483 			*idx = match;
    484 	}
    485 	return retval;
    486 }
    487