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