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 	}
372 #endif
373 	if (*options == '+' || *options == '-') {
374 		options++;
375 	}
376 
377 	/*
378 	 * XXX Some GNU programs (like cvs) set optind to 0 instead of
379 	 * XXX using optreset.  Work around this braindamage.
380 	 */
381 	if (state->optind == 0) {
382 		state->optind = state->optreset = 1;
383 	}
384 
385 	state->optarg = NULL;
386 	if (state->optreset) {
387 		state->nonopt_start = state->nonopt_end = -1;
388 	}
389 start:
390 	if (state->optreset || !*(state->place)) {/* update scanning pointer */
391 		state->optreset = 0;
392 		if (state->optind >= nargc) {          /* end of argument vector */
393 			state->place = EMSG;
394 			if (state->nonopt_end != -1) {
395 				/* do permutation, if we have to */
396 				permute_args(state->nonopt_start,
397 					     state->nonopt_end,
398 					     state->optind, nargv);
399 				state->optind -= state->nonopt_end -
400 						state->nonopt_start;
401 			} else if (state->nonopt_start != -1) {
402 				/*
403 				 * If we skipped non-options, set optind
404 				 * to the first of them.
405 				 */
406 				state->optind = state->nonopt_start;
407 			}
408 			state->nonopt_start = state->nonopt_end = -1;
409 			return -1;
410 		}
411 		state->place = nargv[state->optind];
412 		if (*(state->place) != '-' ||
413 #ifdef GNU_COMPATIBLE
414 		    state->place[1] == '\0') {
415 #else
416 		    (state->place[1] == '\0' && strchr(options, '-') == NULL)) {
417 #endif
418 			state->place = EMSG;		/* found non-option */
419 			if (flags & FLAG_ALLARGS) {
420 				/*
421 				 * GNU extension:
422 				 * return non-option as argument to option 1
423 				 */
424 				state->optarg = nargv[state->optind++];
425 				return INORDER;
426 			}
427 			if (!(flags & FLAG_PERMUTE)) {
428 				/*
429 				 * If no permutation wanted, stop parsing
430 				 * at first non-option.
431 				 */
432 				return -1;
433 			}
434 			/* do permutation */
435 			if (state->nonopt_start == -1) {
436 				state->nonopt_start = state->optind;
437 			} else if (state->nonopt_end != -1) {
438 				permute_args(state->nonopt_start,
439 					     state->nonopt_end,
440 					     state->optind,
441 					     nargv);
442 				state->nonopt_start = state->optind -
443 				    (state->nonopt_end - state->nonopt_start);
444 				state->nonopt_end = -1;
445 			}
446 			state->optind++;
447 			/* process next argument */
448 			goto start;
449 		}
450 		if (state->nonopt_start != -1 && state->nonopt_end == -1) {
451 			state->nonopt_end = state->optind;
452 		}
453 
454 		/*
455 		 * If we have "-" do nothing, if "--" we are done.
456 		 */
457 		if (state->place[1] != '\0' && *++(state->place) == '-' &&
458 		    state->place[1] == '\0') {
459 			state->optind++;
460 			state->place = EMSG;
461 			/*
462 			 * We found an option (--), so if we skipped
463 			 * non-options, we have to permute.
464 			 */
465 			if (state->nonopt_end != -1) {
466 				permute_args(state->nonopt_start,
467 					     state->nonopt_end,
468 					     state->optind,
469 					     nargv);
470 				state->optind -= state->nonopt_end -
471 						 state->nonopt_start;
472 			}
473 			state->nonopt_start = state->nonopt_end = -1;
474 			return -1;
475 		}
476 	}
477 
478 	/*
479 	 * Check long options if:
480 	 *  1) we were passed some
481 	 *  2) the arg is not just "-"
482 	 *  3) either the arg starts with -- we are getopt_long_only()
483 	 */
484 	if (long_options != NULL && state->place != nargv[state->optind] &&
485 	    (*(state->place) == '-' || (flags & FLAG_LONGONLY))) {
486 		short_too = 0;
487 #ifdef GNU_COMPATIBLE
488 		dash_prefix = D_PREFIX;
489 #endif
490 		if (*(state->place) == '-') {
491 			state->place++;		/* --foo long option */
492 #ifdef GNU_COMPATIBLE
493 			dash_prefix = DD_PREFIX;
494 #endif
495 		} else if (*(state->place) != ':' && strchr(options, *(state->place)) != NULL) {
496 			short_too = 1;		/* could be short option too */
497 		}
498 
499 		optchar = parse_long_options(state, nargv, options,
500 					     long_options, idx, short_too,
501 					     flags);
502 		if (optchar != -1) {
503 			state->place = EMSG;
504 			return optchar;
505 		}
506 	}
507 	optchar = (int)*(state->place)++;
508 	oli = strchr(options, optchar);
509 	if (optchar == (int)':' ||
510 	    (optchar == (int)'-' && *(state->place) != '\0') ||
511 	    oli == NULL) {
512 		/*
513 		 * If the user specified "-" and  '-' isn't listed in
514 		 * options, return -1 (non-option) as per POSIX.
515 		 * Otherwise, it is an unknown option character (or ':').
516 		 */
517 		if (optchar == (int)'-' && *(state->place) == '\0') {
518 			return -1;
519 		}
520 		if (!*(state->place)) {
521 			++state->optind;
522 		}
523 #ifdef GNU_COMPATIBLE
524 		if (PRINT_ERROR) {
525 			LOG_WRN(GNUOPTCHAR, optchar);
526 		}
527 #else
528 		if (PRINT_ERROR) {
529 			LOG_WRN(ILLOPTCHAR, optchar);
530 		}
531 #endif
532 		state->optopt = optchar;
533 		return BADCH;
534 	}
535 	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
536 		/* -W long-option */
537 		if (*(state->place)) {		/* no space */
538 			; /* NOTHING */
539 		} else if (++(state->optind) >= nargc) {	/* no arg */
540 			state->place = EMSG;
541 			if (PRINT_ERROR) {
542 				LOG_WRN(RECARGCHAR, optchar);
543 			}
544 			state->optopt = optchar;
545 			return BADARG;
546 		} else if ((state->optind) < nargc) {
547 			state->place = nargv[state->optind];
548 		}
549 #ifdef GNU_COMPATIBLE
550 		dash_prefix = W_PREFIX;
551 #endif
552 		optchar = parse_long_options(state, nargv, options,
553 					     long_options, idx, 0, flags);
554 		state->place = EMSG;
555 		return optchar;
556 	}
557 	if (*++oli != ':') {			/* doesn't take argument */
558 		if (!*(state->place)) {
559 			++state->optind;
560 		}
561 	} else {				/* takes (optional) argument */
562 		state->optarg = NULL;
563 		if (*(state->place)) {			/* no white space */
564 			state->optarg = state->place;
565 		} else if (oli[1] != ':') {	/* arg not optional */
566 			if (++state->optind >= nargc) {	/* no arg */
567 				state->place = EMSG;
568 				if (PRINT_ERROR) {
569 					LOG_WRN(RECARGCHAR, optchar);
570 				}
571 				state->optopt = optchar;
572 				return BADARG;
573 			}
574 			state->optarg = nargv[state->optind];
575 		}
576 		state->place = EMSG;
577 		++state->optind;
578 	}
579 	/* dump back option letter */
580 	return optchar;
581 }
582 
583 /*
584  * getopt_long --
585  *	Parse argc/argv argument vector.
586  */
587 int
588 getopt_long(int nargc, char *const *nargv,
589 	    const char *options, const struct option *long_options,
590 	    int *idx)
591 {
592 	struct getopt_state *state;
593 	int ret;
594 
595 	/* Get state of the current thread */
596 	state = getopt_state_get();
597 
598 	ret = getopt_internal(state, nargc, nargv, options, long_options, idx,
599 			      FLAG_PERMUTE);
600 
601 	z_getopt_global_state_update(state);
602 
603 	return ret;
604 }
605 
606 /*
607  * getopt_long_only --
608  *	Parse argc/argv argument vector.
609  */
610 int
611 getopt_long_only(int nargc, char *const *nargv,
612 		 const char *options, const struct option *long_options,
613 		 int *idx)
614 {
615 	struct getopt_state *state;
616 	int ret;
617 
618 	/* Get state of the current thread */
619 	state = getopt_state_get();
620 
621 	ret = getopt_internal(state, nargc, nargv, options, long_options, idx,
622 			      FLAG_PERMUTE|FLAG_LONGONLY);
623 
624 	z_getopt_global_state_update(state);
625 
626 	return ret;
627 }
628