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