1 /*	$OpenBSD: getopt_long.c,v 1.22 2006/10/04 21:29:04 jmc Exp $	*/
2 /*	$NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $	*/
3 
4 /*
5  * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  *
19  * Sponsored in part by the Defense Advanced Research Projects
20  * Agency (DARPA) and Air Force Research Laboratory, Air Force
21  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
22  */
23 /*
24  * Copyright (c) 2000 The NetBSD Foundation, Inc.
25  * All rights reserved.
26  *
27  * This code is derived from software contributed to The NetBSD Foundation
28  * by Dieter Baron and Thomas Klausner.
29  *
30  * Redistribution and use in source and binary forms, with or without
31  * modification, are permitted provided that the following conditions
32  * are met:
33  * 1. Redistributions of source code must retain the above copyright
34  *    notice, this list of conditions and the following disclaimer.
35  * 2. Redistributions in binary form must reproduce the above copyright
36  *    notice, this list of conditions and the following disclaimer in the
37  *    documentation and/or other materials provided with the distribution.
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
40  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
41  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
43  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
47  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49  * POSSIBILITY OF SUCH DAMAGE.
50  */
51 
52 #include <string.h>
53 #include "getopt.h"
54 #include "getopt_common.h"
55 
56 #include <zephyr/logging/log.h>
57 LOG_MODULE_DECLARE(getopt);
58 
59 #define GNU_COMPATIBLE		/* Be more compatible, configure's use us! */
60 
61 #define PRINT_ERROR	((state->opterr) && (*options != ':'))
62 
63 #define FLAG_PERMUTE	0x01	/* permute non-options to the end of argv */
64 #define FLAG_ALLARGS	0x02	/* treat non-options as args to option "-1" */
65 #define FLAG_LONGONLY	0x04	/* operate as getopt_long_only */
66 
67 /* return values */
68 #define	BADCH		(int)'?'
69 #define	BADARG		((*options == ':') ? (int)':' : (int)'?')
70 #define	INORDER	1
71 
72 #define	EMSG		""
73 
74 #ifdef GNU_COMPATIBLE
75 #define NO_PREFIX	(-1)
76 #define D_PREFIX	0
77 #define DD_PREFIX	1
78 #define W_PREFIX	2
79 #endif
80 
81 static int getopt_internal(struct getopt_state *, int, char * const *,
82 			   const char *, const struct option *, int *, int);
83 static int parse_long_options(struct getopt_state *, char * const *,
84 			      const char *, const struct option *, int *, int,
85 			      int);
86 static int gcd(int, int);
87 static void permute_args(int, int, int, char *const *);
88 
89 /* Error messages */
90 #define RECARGCHAR "option requires an argument -- %c"
91 #define ILLOPTCHAR "illegal option -- %c" /* From P1003.2 */
92 #ifdef GNU_COMPATIBLE
93 static int dash_prefix = NO_PREFIX;
94 #define GNUOPTCHAR "invalid option -- %c"
95 
96 #define RECARGSTRING "option `%s%s' requires an argument"
97 #define AMBIG "option `%s%.*s' is ambiguous"
98 #define NOARG "option `%s%.*s' doesn't allow an argument"
99 #define ILLOPTSTRING "unrecognized option `%s%s'"
100 #else
101 #define RECARGSTRING "option requires an argument -- %s"
102 #define AMBIG "ambiguous option -- %.*s"
103 #define NOARG "option doesn't take an argument -- %.*s"
104 #define ILLOPTSTRING "unknown option -- %s"
105 #endif
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 	/*
138 	 * compute lengths of blocks and number and size of cycles
139 	 */
140 	nnonopts = panonopt_end - panonopt_start;
141 	nopts = opt_end - panonopt_end;
142 	ncycle = gcd(nnonopts, nopts);
143 	cyclelen = (opt_end - panonopt_start) / ncycle;
144 
145 	for (i = 0; i < ncycle; i++) {
146 		cstart = panonopt_end+i;
147 		pos = cstart;
148 		for (j = 0; j < cyclelen; j++) {
149 			if (pos >= panonopt_end) {
150 				pos -= nnonopts;
151 			} else {
152 				pos += nopts;
153 			}
154 			swap = nargv[pos];
155 			/* LINTED const cast */
156 			((char **) nargv)[pos] = nargv[cstart];
157 			/* LINTED const cast */
158 			((char **)nargv)[cstart] = swap;
159 		}
160 	}
161 }
162 
163 /*
164  * parse_long_options --
165  *	Parse long options in argc/argv argument vector.
166  * Returns -1 if short_too is set and the option does not match long_options.
167  */
168 static int
parse_long_options(struct getopt_state * state,char * const * nargv,const char * options,const struct option * long_options,int * idx,int short_too,int flags)169 parse_long_options(struct getopt_state *state, char * const *nargv,
170 		   const char *options,	const struct option *long_options,
171 		   int *idx, int short_too, int flags)
172 {
173 	char *current_argv, *has_equal;
174 #ifdef GNU_COMPATIBLE
175 	char *current_dash = "";
176 #endif
177 	size_t current_argv_len;
178 	int i, match, exact_match, second_partial_match;
179 
180 	current_argv = state->place;
181 #ifdef GNU_COMPATIBLE
182 	if (PRINT_ERROR) {
183 		switch (dash_prefix) {
184 		case D_PREFIX:
185 			current_dash = "-";
186 			break;
187 		case DD_PREFIX:
188 			current_dash = "--";
189 			break;
190 		case W_PREFIX:
191 			current_dash = "-W ";
192 			break;
193 		default:
194 			break;
195 		}
196 	}
197 #endif
198 	match = -1;
199 	exact_match = 0;
200 	second_partial_match = 0;
201 
202 	state->optind++;
203 
204 	has_equal = strchr(current_argv, '=');
205 	if (has_equal != NULL) {
206 		/* argument found (--option=arg) */
207 		current_argv_len = has_equal - current_argv;
208 		has_equal++;
209 	} else {
210 		current_argv_len = strlen(current_argv);
211 	}
212 
213 	for (i = 0; long_options[i].name; i++) {
214 		/* find matching long option */
215 		if (strncmp(current_argv, long_options[i].name, current_argv_len)) {
216 			continue;
217 		}
218 
219 		if (strlen(long_options[i].name) == current_argv_len) {
220 			/* exact match */
221 			match = i;
222 			exact_match = 1;
223 			break;
224 		}
225 		/*
226 		 * If this is a known short option, don't allow
227 		 * a partial match of a single character.
228 		 */
229 		if (short_too && current_argv_len == 1) {
230 			continue;
231 		}
232 
233 		if (match == -1) { /* first partial match */
234 			match = i;
235 		} else if ((flags & FLAG_LONGONLY) ||
236 			   long_options[i].has_arg != long_options[match].has_arg ||
237 			   long_options[i].flag != long_options[match].flag ||
238 			   long_options[i].val != long_options[match].val) {
239 			second_partial_match = 1;
240 		}
241 	}
242 	if (!exact_match && second_partial_match) {
243 		/* ambiguous abbreviation */
244 		if (PRINT_ERROR) {
245 			LOG_WRN(AMBIG,
246 #ifdef GNU_COMPATIBLE
247 			     current_dash,
248 #endif
249 			     (int)current_argv_len,
250 			     current_argv);
251 		}
252 		state->optopt = 0;
253 		return BADCH;
254 	}
255 	if (match != -1) {		/* option found */
256 		if (long_options[match].has_arg == no_argument
257 		    && has_equal) {
258 			if (PRINT_ERROR) {
259 				LOG_WRN(NOARG,
260 #ifdef GNU_COMPATIBLE
261 				     current_dash,
262 #endif
263 				     (int)current_argv_len,
264 				     current_argv);
265 			}
266 			/*
267 			 * XXX: GNU sets optopt to val regardless of flag
268 			 */
269 			if (long_options[match].flag == NULL) {
270 				state->optopt = long_options[match].val;
271 			} else {
272 				state->optopt = 0;
273 			}
274 #ifdef GNU_COMPATIBLE
275 			return BADCH;
276 #else
277 			return BADARG;
278 #endif
279 		}
280 		if (long_options[match].has_arg == required_argument ||
281 		    long_options[match].has_arg == optional_argument) {
282 			if (has_equal) {
283 				state->optarg = has_equal;
284 			} else if (long_options[match].has_arg == required_argument) {
285 				/*
286 				 * optional argument doesn't use next nargv
287 				 */
288 				state->optarg = nargv[state->optind++];
289 			}
290 		}
291 		if ((long_options[match].has_arg == required_argument)
292 		    && (state->optarg == NULL)) {
293 			/*
294 			 * Missing argument; leading ':' indicates no error
295 			 * should be generated.
296 			 */
297 			if (PRINT_ERROR) {
298 				LOG_WRN(RECARGSTRING,
299 #ifdef GNU_COMPATIBLE
300 				    current_dash,
301 #endif
302 				    current_argv);
303 			}
304 			/*
305 			 * XXX: GNU sets optopt to val regardless of flag
306 			 */
307 			if (long_options[match].flag == NULL) {
308 				state->optopt = long_options[match].val;
309 			} else {
310 				state->optopt = 0;
311 			}
312 			--state->optind;
313 			return BADARG;
314 		}
315 	} else {			/* unknown option */
316 		if (short_too) {
317 			--state->optind;
318 			return -1;
319 		}
320 		if (PRINT_ERROR) {
321 			LOG_WRN(ILLOPTSTRING,
322 #ifdef GNU_COMPATIBLE
323 			      current_dash,
324 #endif
325 			      current_argv);
326 		}
327 		state->optopt = 0;
328 		return BADCH;
329 	}
330 	if (idx) {
331 		*idx = match;
332 	}
333 	if (long_options[match].flag) {
334 		*long_options[match].flag = long_options[match].val;
335 		return 0;
336 	} else {
337 		return long_options[match].val;
338 	}
339 }
340 
341 /*
342  * getopt_internal --
343  *	Parse argc/argv argument vector.  Called by user level routines.
344  */
345 static int
getopt_internal(struct getopt_state * state,int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx,int flags)346 getopt_internal(struct getopt_state *state, int nargc, char * const *nargv,
347 		const char *options, const struct option *long_options,
348 		int *idx, int flags)
349 {
350 	char *oli;				/* option letter list index */
351 	int optchar, short_too;
352 
353 	if (options == NULL) {
354 		return -1;
355 	}
356 
357 	/*
358 	 * Disable GNU extensions if options string begins with a '+'.
359 	 */
360 #ifdef GNU_COMPATIBLE
361 	if (*options == '-') {
362 		flags |= FLAG_ALLARGS;
363 	} else if (*options == '+') {
364 		flags &= ~FLAG_PERMUTE;
365 	}
366 #else
367 	if (*options == '+')
368 		flags &= ~FLAG_PERMUTE;
369 	else if (*options == '-')
370 		flags |= FLAG_ALLARGS;
371 #endif
372 	if (*options == '+' || *options == '-') {
373 		options++;
374 	}
375 
376 	/*
377 	 * XXX Some GNU programs (like cvs) set optind to 0 instead of
378 	 * XXX using optreset.  Work around this braindamage.
379 	 */
380 	if (state->optind == 0) {
381 		state->optind = state->optreset = 1;
382 	}
383 
384 	state->optarg = NULL;
385 	if (state->optreset) {
386 		state->nonopt_start = state->nonopt_end = -1;
387 	}
388 start:
389 	if (state->optreset || !*(state->place)) {/* update scanning pointer */
390 		state->optreset = 0;
391 		if (state->optind >= nargc) {          /* end of argument vector */
392 			state->place = EMSG;
393 			if (state->nonopt_end != -1) {
394 				/* do permutation, if we have to */
395 				permute_args(state->nonopt_start,
396 					     state->nonopt_end,
397 					     state->optind, nargv);
398 				state->optind -= state->nonopt_end -
399 						state->nonopt_start;
400 			} else if (state->nonopt_start != -1) {
401 				/*
402 				 * If we skipped non-options, set optind
403 				 * to the first of them.
404 				 */
405 				state->optind = state->nonopt_start;
406 			}
407 			state->nonopt_start = state->nonopt_end = -1;
408 			return -1;
409 		}
410 		state->place = nargv[state->optind];
411 		if (*(state->place) != '-' ||
412 #ifdef GNU_COMPATIBLE
413 		    state->place[1] == '\0') {
414 #else
415 		    (state->place[1] == '\0' && strchr(options, '-') == NULL)) {
416 #endif
417 			state->place = EMSG;		/* found non-option */
418 			if (flags & FLAG_ALLARGS) {
419 				/*
420 				 * GNU extension:
421 				 * return non-option as argument to option 1
422 				 */
423 				state->optarg = nargv[state->optind++];
424 				return INORDER;
425 			}
426 			if (!(flags & FLAG_PERMUTE)) {
427 				/*
428 				 * If no permutation wanted, stop parsing
429 				 * at first non-option.
430 				 */
431 				return -1;
432 			}
433 			/* do permutation */
434 			if (state->nonopt_start == -1) {
435 				state->nonopt_start = state->optind;
436 			} else if (state->nonopt_end != -1) {
437 				permute_args(state->nonopt_start,
438 					     state->nonopt_end,
439 					     state->optind,
440 					     nargv);
441 				state->nonopt_start = state->optind -
442 				    (state->nonopt_end - state->nonopt_start);
443 				state->nonopt_end = -1;
444 			}
445 			state->optind++;
446 			/* process next argument */
447 			goto start;
448 		}
449 		if (state->nonopt_start != -1 && state->nonopt_end == -1) {
450 			state->nonopt_end = state->optind;
451 		}
452 
453 		/*
454 		 * If we have "-" do nothing, if "--" we are done.
455 		 */
456 		if (state->place[1] != '\0' && *++(state->place) == '-' &&
457 		    state->place[1] == '\0') {
458 			state->optind++;
459 			state->place = EMSG;
460 			/*
461 			 * We found an option (--), so if we skipped
462 			 * non-options, we have to permute.
463 			 */
464 			if (state->nonopt_end != -1) {
465 				permute_args(state->nonopt_start,
466 					     state->nonopt_end,
467 					     state->optind,
468 					     nargv);
469 				state->optind -= state->nonopt_end -
470 						 state->nonopt_start;
471 			}
472 			state->nonopt_start = state->nonopt_end = -1;
473 			return -1;
474 		}
475 	}
476 
477 	/*
478 	 * Check long options if:
479 	 *  1) we were passed some
480 	 *  2) the arg is not just "-"
481 	 *  3) either the arg starts with -- we are getopt_long_only()
482 	 */
483 	if (long_options != NULL && state->place != nargv[state->optind] &&
484 	    (*(state->place) == '-' || (flags & FLAG_LONGONLY))) {
485 		short_too = 0;
486 #ifdef GNU_COMPATIBLE
487 		dash_prefix = D_PREFIX;
488 #endif
489 		if (*(state->place) == '-') {
490 			state->place++;		/* --foo long option */
491 #ifdef GNU_COMPATIBLE
492 			dash_prefix = DD_PREFIX;
493 #endif
494 		} else if (*(state->place) != ':' && strchr(options, *(state->place)) != NULL) {
495 			short_too = 1;		/* could be short option too */
496 		}
497 
498 		optchar = parse_long_options(state, nargv, options,
499 					     long_options, idx, short_too,
500 					     flags);
501 		if (optchar != -1) {
502 			state->place = EMSG;
503 			return optchar;
504 		}
505 	}
506 	optchar = (int)*(state->place)++;
507 	oli = strchr(options, optchar);
508 	if (optchar == (int)':' ||
509 	    (optchar == (int)'-' && *(state->place) != '\0') ||
510 	    oli == NULL) {
511 		/*
512 		 * If the user specified "-" and  '-' isn't listed in
513 		 * options, return -1 (non-option) as per POSIX.
514 		 * Otherwise, it is an unknown option character (or ':').
515 		 */
516 		if (optchar == (int)'-' && *(state->place) == '\0') {
517 			return -1;
518 		}
519 		if (!*(state->place)) {
520 			++state->optind;
521 		}
522 #ifdef GNU_COMPATIBLE
523 		if (PRINT_ERROR) {
524 			LOG_WRN(GNUOPTCHAR, optchar);
525 		}
526 #else
527 		if (PRINT_ERROR) {
528 			LOG_WRN(ILLOPTCHAR, optchar);
529 		}
530 #endif
531 		state->optopt = optchar;
532 		return BADCH;
533 	}
534 	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
535 		/* -W long-option */
536 		if (*(state->place)) {		/* no space */
537 			; /* NOTHING */
538 		} else if (++(state->optind) >= nargc) {	/* no arg */
539 			state->place = EMSG;
540 			if (PRINT_ERROR) {
541 				LOG_WRN(RECARGCHAR, optchar);
542 			}
543 			state->optopt = optchar;
544 			return BADARG;
545 		} else if ((state->optind) < nargc) {
546 			state->place = nargv[state->optind];
547 		}
548 #ifdef GNU_COMPATIBLE
549 		dash_prefix = W_PREFIX;
550 #endif
551 		optchar = parse_long_options(state, nargv, options,
552 					     long_options, idx, 0, flags);
553 		state->place = EMSG;
554 		return optchar;
555 	}
556 	if (*++oli != ':') {			/* doesn't take argument */
557 		if (!*(state->place)) {
558 			++state->optind;
559 		}
560 	} else {				/* takes (optional) argument */
561 		state->optarg = NULL;
562 		if (*(state->place)) {			/* no white space */
563 			state->optarg = state->place;
564 		} else if (oli[1] != ':') {	/* arg not optional */
565 			if (++state->optind >= nargc) {	/* no arg */
566 				state->place = EMSG;
567 				if (PRINT_ERROR) {
568 					LOG_WRN(RECARGCHAR, optchar);
569 				}
570 				state->optopt = optchar;
571 				return BADARG;
572 			}
573 			state->optarg = nargv[state->optind];
574 		}
575 		state->place = EMSG;
576 		++state->optind;
577 	}
578 	/* dump back option letter */
579 	return optchar;
580 }
581 
582 /*
583  * getopt_long --
584  *	Parse argc/argv argument vector.
585  */
586 int
587 getopt_long(int nargc, char *const *nargv,
588 	    const char *options, const struct option *long_options,
589 	    int *idx)
590 {
591 	struct getopt_state *state;
592 	int ret;
593 
594 	/* Get state of the current thread */
595 	state = getopt_state_get();
596 
597 	ret = getopt_internal(state, nargc, nargv, options, long_options, idx,
598 			      FLAG_PERMUTE);
599 
600 	z_getopt_global_state_update(state);
601 
602 	return ret;
603 }
604 
605 /*
606  * getopt_long_only --
607  *	Parse argc/argv argument vector.
608  */
609 int
610 getopt_long_only(int nargc, char *const *nargv,
611 		 const char *options, const struct option *long_options,
612 		 int *idx)
613 {
614 	struct getopt_state *state;
615 	int ret;
616 
617 	/* Get state of the current thread */
618 	state = getopt_state_get();
619 
620 	ret = getopt_internal(state, nargc, nargv, options, long_options, idx,
621 			      FLAG_PERMUTE|FLAG_LONGONLY);
622 
623 	z_getopt_global_state_update(state);
624 
625 	return ret;
626 }
627