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