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