1 /*	$NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $	*/
2 /*	$FreeBSD: src/lib/libc/stdlib/getopt_long.c,v 1.2 2002/10/16 22:18:42 alfred 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 
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #ifdef PLATFORM_WINDOWS
45 #ifdef COMPILER_MSVC
46 #include "pbd/msvc_pbd.h"  // Defines 'GETOPT_API'
47 #endif
48 /* Windows needs warnx().  We change the definition though:
49  *  1. (another) global is defined, opterrmsg, which holds the error message
50  *  2. errors are always printed out on stderr w/o the program name
51  * Note that opterrmsg always gets set no matter what opterr is set to.  The
52  * error message will not be printed if opterr is 0 as usual.
53  */
54 
55 #include "getopt.h"
56 #include <stdio.h>
57 #include <stdarg.h>
58 
59 GETOPT_API extern char opterrmsg[128];
60 char opterrmsg[128]; /* last error message is stored here */
61 
warnx(int print_error,const char * fmt,...)62 static void warnx(int print_error, const char *fmt, ...)
63 {
64 	va_list ap;
65 	va_start(ap, fmt);
66 	if (fmt != NULL)
67 		_vsnprintf(opterrmsg, 128, fmt, ap);
68 	else
69 		opterrmsg[0]='\0';
70 	va_end(ap);
71 	if (print_error) {
72 		fprintf(stderr, opterrmsg);
73 		fprintf(stderr, "\n");
74 	}
75 }
76 
77 #endif /*PLATFORM_WINDOWS*/
78 
79 /* not part of the original file */
80 #ifndef _DIAGASSERT
81 #define _DIAGASSERT(X)
82 #endif
83 
84 #if HAVE_CONFIG_H && !HAVE_GETOPT_LONG && !HAVE_DECL_OPTIND
85 #define REPLACE_GETOPT
86 #endif
87 
88 #ifdef REPLACE_GETOPT
89 #ifdef __weak_alias
90 __weak_alias(getopt,_getopt)
91 #endif
92 int	opterr = 1;		/* if error message should be printed */
93 int	optind = 1;		/* index into parent argv vector */
94 int	optopt = '?';		/* character checked for validity */
95 int	optreset;		/* reset getopt */
96 char    *optarg;		/* argument associated with option */
97 #elif HAVE_CONFIG_H && !HAVE_DECL_OPTRESET
98 static int optreset;
99 #endif
100 
101 #ifdef __weak_alias
102 __weak_alias(getopt_long,_getopt_long)
103 #endif
104 
105 #if !HAVE_GETOPT_LONG
106 #define IGNORE_FIRST	(*options == '-' || *options == '+')
107 #define PRINT_ERROR	((opterr) && ((*options != ':') \
108 				      || (IGNORE_FIRST && options[1] != ':')))
109 #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
110 #define PERMUTE         (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
111 /* XXX: GNU ignores PC if *options == '-' */
112 #define IN_ORDER        (!IS_POSIXLY_CORRECT && *options == '-')
113 
114 /* return values */
115 #define	BADCH	(int)'?'
116 #define	BADARG		((IGNORE_FIRST && options[1] == ':') \
117 			 || (*options == ':') ? (int)':' : (int)'?')
118 #define INORDER (int)1
119 
120 #define	EMSG	""
121 
122 static int getopt_internal(int, char * const *, const char *);
123 static int gcd(int, int);
124 static void permute_args(int, int, int, char * const *);
125 
126 static char *place = EMSG; /* option letter processing */
127 
128 /* XXX: set optreset to 1 rather than these two */
129 static int nonopt_start = -1; /* first non option argument (for permute) */
130 static int nonopt_end = -1;   /* first option after non options (for permute) */
131 
132 /* Error messages */
133 static const char recargchar[] = "option requires an argument -- %c";
134 static const char recargstring[] = "option requires an argument -- %s";
135 static const char ambig[] = "ambiguous option -- %.*s";
136 static const char noarg[] = "option doesn't take an argument -- %.*s";
137 static const char illoptchar[] = "unknown option -- %c";
138 static const char illoptstring[] = "unknown option -- %s";
139 
140 
141 /*
142  * Compute the greatest common divisor of a and b.
143  */
144 static int
gcd(int a,int b)145 gcd(int a, int b)
146 {
147 	int c;
148 
149 	c = a % b;
150 	while (c != 0) {
151 		a = b;
152 		b = c;
153 		c = a % b;
154 	}
155 
156 	return b;
157 }
158 
159 /*
160  * Exchange the block from nonopt_start to nonopt_end with the block
161  * from nonopt_end to opt_end (keeping the same order of arguments
162  * in each block).
163  */
164 static void
permute_args(int panonopt_start,int panonopt_end,int opt_end,char * const * nargv)165 permute_args(int panonopt_start,
166              int panonopt_end,
167              int opt_end,
168              char * const *nargv)
169 {
170 	int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
171 	char *swap;
172 
173 	_DIAGASSERT(nargv != NULL);
174 
175 	/*
176 	 * compute lengths of blocks and number and size of cycles
177 	 */
178 	nnonopts = panonopt_end - panonopt_start;
179 	nopts = opt_end - panonopt_end;
180 	ncycle = gcd(nnonopts, nopts);
181 	cyclelen = (opt_end - panonopt_start) / ncycle;
182 
183 	for (i = 0; i < ncycle; i++) {
184 		cstart = panonopt_end+i;
185 		pos = cstart;
186 		for (j = 0; j < cyclelen; j++) {
187 			if (pos >= panonopt_end)
188 				pos -= nnonopts;
189 			else
190 				pos += nopts;
191 			swap = nargv[pos];
192 			/* LINTED const cast */
193 			((char **) nargv)[pos] = nargv[cstart];
194 			/* LINTED const cast */
195 			((char **)nargv)[cstart] = swap;
196 		}
197 	}
198 }
199 
200 /*
201  * getopt_internal --
202  *	Parse argc/argv argument vector.  Called by user level routines.
203  *  Returns -2 if -- is found (can be long option or end of options marker).
204  */
205 static int
getopt_internal(int nargc,char * const * nargv,const char * options)206 getopt_internal(int nargc,
207                 char * const *nargv,
208                 const char *options)
209 {
210 	char *oli;				/* option letter list index */
211 	int optchar;
212 
213 	_DIAGASSERT(nargv != NULL);
214 	_DIAGASSERT(options != NULL);
215 
216 	optarg = NULL;
217 
218 	/*
219 	 * XXX Some programs (like rsyncd) expect to be able to
220 	 * XXX re-initialize optind to 0 and have getopt_long(3)
221 	 * XXX properly function again.  Work around this braindamage.
222 	 */
223 	if (optind == 0)
224 		optind = 1;
225 
226 	if (optreset)
227 		nonopt_start = nonopt_end = -1;
228 start:
229 	if (optreset || !*place) {		/* update scanning pointer */
230 		optreset = 0;
231 		if (optind >= nargc) {          /* end of argument vector */
232 			place = EMSG;
233 			if (nonopt_end != -1) {
234 				/* do permutation, if we have to */
235 				permute_args(nonopt_start, nonopt_end,
236 				    optind, nargv);
237 				optind -= nonopt_end - nonopt_start;
238 			}
239 			else if (nonopt_start != -1) {
240 				/*
241 				 * If we skipped non-options, set optind
242 				 * to the first of them.
243 				 */
244 				optind = nonopt_start;
245 			}
246 			nonopt_start = nonopt_end = -1;
247 			return -1;
248 		}
249 		if ((*(place = nargv[optind]) != '-')
250 		    || (place[1] == '\0')) {    /* found non-option */
251 			place = EMSG;
252 			if (IN_ORDER) {
253 				/*
254 				 * GNU extension:
255 				 * return non-option as argument to option 1
256 				 */
257 				optarg = nargv[optind++];
258 				return INORDER;
259 			}
260 			if (!PERMUTE) {
261 				/*
262 				 * if no permutation wanted, stop parsing
263 				 * at first non-option
264 				 */
265 				return -1;
266 			}
267 			/* do permutation */
268 			if (nonopt_start == -1)
269 				nonopt_start = optind;
270 			else if (nonopt_end != -1) {
271 				permute_args(nonopt_start, nonopt_end,
272 				    optind, nargv);
273 				nonopt_start = optind -
274 				    (nonopt_end - nonopt_start);
275 				nonopt_end = -1;
276 			}
277 			optind++;
278 			/* process next argument */
279 			goto start;
280 		}
281 		if (nonopt_start != -1 && nonopt_end == -1)
282 			nonopt_end = optind;
283 		if (place[1] && *++place == '-') {	/* found "--" */
284 			place++;
285 			return -2;
286 		}
287 	}
288 	if ((optchar = (int)*place++) == (int)':' ||
289 	    (oli = (char*)strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
290 		/* option letter unknown or ':' */
291 		if (!*place)
292 			++optind;
293 #ifndef PLATFORM_WINDOWS
294 		if (PRINT_ERROR)
295 			warnx(illoptchar, optchar);
296 #else
297 			warnx(PRINT_ERROR, illoptchar, optchar);
298 #endif
299 		optopt = optchar;
300 		return BADCH;
301 	}
302 	if (optchar == 'W' && oli[1] == ';') {		/* -W long-option */
303 		/* XXX: what if no long options provided (called by getopt)? */
304 		if (*place)
305 			return -2;
306 
307 		if (++optind >= nargc) {	/* no arg */
308 			place = EMSG;
309 #ifndef PLATFORM_WINDOWS
310 			if (PRINT_ERROR)
311 				warnx(recargchar, optchar);
312 #else
313 				warnx(PRINT_ERROR, recargchar, optchar);
314 #endif
315 			optopt = optchar;
316 			return BADARG;
317 		} else				/* white space */
318 			place = nargv[optind];
319 		/*
320 		 * Handle -W arg the same as --arg (which causes getopt to
321 		 * stop parsing).
322 		 */
323 		return -2;
324 	}
325 	if (*++oli != ':') {			/* doesn't take argument */
326 		if (!*place)
327 			++optind;
328 	} else {				/* takes (optional) argument */
329 		optarg = NULL;
330 		if (*place)			/* no white space */
331 			optarg = place;
332 		/* XXX: disable test for :: if PC? (GNU doesn't) */
333 		else if (oli[1] != ':') {	/* arg not optional */
334 			if (++optind >= nargc) {	/* no arg */
335 				place = EMSG;
336 #ifndef PLATFORM_WINDOWS
337 				if (PRINT_ERROR)
338 					warnx(recargchar, optchar);
339 #else
340 					warnx(PRINT_ERROR, recargchar, optchar);
341 #endif
342 				optopt = optchar;
343 				return BADARG;
344 			} else
345 				optarg = nargv[optind];
346 		}
347 		place = EMSG;
348 		++optind;
349 	}
350 	/* dump back option letter */
351 	return optchar;
352 }
353 
354 __BEGIN_DECLS    // Added by JE - 31-01-2010
355 #ifdef REPLACE_GETOPT
356 /*
357  * getopt --
358  *	Parse argc/argv argument vector.
359  *
360  * [eventually this will replace the real getopt]
361  */
362 GETOPT_API int // 'GETOPT_API' declaration added by JE - 31-01-2010
getopt(int nargc,char * const * nargv,const char * options)363 getopt(int nargc,
364        char * const *nargv,
365        const char *options)
366 {
367 	int retval;
368 
369 	_DIAGASSERT(nargv != NULL);
370 	_DIAGASSERT(options != NULL);
371 
372 	if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
373 		++optind;
374 		/*
375 		 * We found an option (--), so if we skipped non-options,
376 		 * we have to permute.
377 		 */
378 		if (nonopt_end != -1) {
379 			permute_args(nonopt_start, nonopt_end, optind,
380 				       nargv);
381 			optind -= nonopt_end - nonopt_start;
382 		}
383 		nonopt_start = nonopt_end = -1;
384 		retval = -1;
385 	}
386 	return retval;
387 }
388 #endif
389 
390 /*
391  * getopt_long --
392  *	Parse argc/argv argument vector.
393  */
394 GETOPT_API int // 'GETOPT_API' declaration added by JE - 31-01-2010
getopt_long(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)395 getopt_long(int nargc,
396             char * const *nargv,
397             const char *options,
398             const struct option *long_options,
399             int *idx)
400 {
401 	int retval;
402 
403 	_DIAGASSERT(nargv != NULL);
404 	_DIAGASSERT(options != NULL);
405 	_DIAGASSERT(long_options != NULL);
406 	/* idx may be NULL */
407 
408 	if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
409 		char *current_argv, *has_equal;
410 		size_t current_argv_len;
411 		int i, match;
412 
413 		current_argv = place;
414 		match = -1;
415 
416 		optind++;
417 		place = EMSG;
418 
419 		if (*current_argv == '\0') {		/* found "--" */
420 			/*
421 			 * We found an option (--), so if we skipped
422 			 * non-options, we have to permute.
423 			 */
424 			if (nonopt_end != -1) {
425 				permute_args(nonopt_start, nonopt_end,
426 				    optind, nargv);
427 				optind -= nonopt_end - nonopt_start;
428 			}
429 			nonopt_start = nonopt_end = -1;
430 			return -1;
431 		}
432 		if ((has_equal = strchr(current_argv, '=')) != NULL) {
433 			/* argument found (--option=arg) */
434 			current_argv_len = has_equal - current_argv;
435 			has_equal++;
436 		} else
437 			current_argv_len = strlen(current_argv);
438 
439 		for (i = 0; long_options[i].name; i++) {
440 			/* find matching long option */
441 			if (strncmp(current_argv, long_options[i].name,
442 			    current_argv_len))
443 				continue;
444 
445 			if (strlen(long_options[i].name) ==
446 			    (unsigned)current_argv_len) {
447 				/* exact match */
448 				match = i;
449 				break;
450 			}
451 			if (match == -1)		/* partial match */
452 				match = i;
453 			else {
454 				/* ambiguous abbreviation */
455 #ifndef PLATFORM_WINDOWS
456 				if (PRINT_ERROR)
457 					warnx(ambig, (int)current_argv_len,
458 					     current_argv);
459 #else
460 					warnx(PRINT_ERROR, ambig, (int)current_argv_len,
461 					     current_argv);
462 #endif
463 				optopt = 0;
464 				return BADCH;
465 			}
466 		}
467 		if (match != -1) {			/* option found */
468 		        if (long_options[match].has_arg == no_argument
469 			    && has_equal) {
470 #ifndef PLATFORM_WINDOWS
471 				if (PRINT_ERROR)
472 					warnx(noarg, (int)current_argv_len,
473 					     current_argv);
474 #else
475 					warnx(PRINT_ERROR, noarg, (int)current_argv_len,
476 					     current_argv);
477 #endif
478 				/*
479 				 * XXX: GNU sets optopt to val regardless of
480 				 * flag
481 				 */
482 				if (long_options[match].flag == NULL)
483 					optopt = long_options[match].val;
484 				else
485 					optopt = 0;
486 				return BADARG;
487 			}
488 			if (long_options[match].has_arg == required_argument ||
489 			    long_options[match].has_arg == optional_argument) {
490 				if (has_equal)
491 					optarg = has_equal;
492 				else if (long_options[match].has_arg ==
493 				    required_argument) {
494 					/*
495 					 * optional argument doesn't use
496 					 * next nargv
497 					 */
498 					optarg = nargv[optind++];
499 				}
500 			}
501 			if ((long_options[match].has_arg == required_argument)
502 			    && (optarg == NULL)) {
503 				/*
504 				 * Missing argument; leading ':'
505 				 * indicates no error should be generated
506 				 */
507 #ifndef PLATFORM_WINDOWS
508 				if (PRINT_ERROR)
509 					warnx(recargstring, current_argv);
510 #else
511 					warnx(PRINT_ERROR, recargstring, current_argv);
512 #endif
513 				/*
514 				 * XXX: GNU sets optopt to val regardless
515 				 * of flag
516 				 */
517 				if (long_options[match].flag == NULL)
518 					optopt = long_options[match].val;
519 				else
520 					optopt = 0;
521 				--optind;
522 				return BADARG;
523 			}
524 		} else {			/* unknown option */
525 #ifndef PLATFORM_WINDOWS
526 			if (PRINT_ERROR)
527 				warnx(illoptstring, current_argv);
528 #else
529 				warnx(PRINT_ERROR, illoptstring, current_argv);
530 #endif
531 			optopt = 0;
532 			return BADCH;
533 		}
534 		if (long_options[match].flag) {
535 			*long_options[match].flag = long_options[match].val;
536 			retval = 0;
537 		} else
538 			retval = long_options[match].val;
539 		if (idx)
540 			*idx = match;
541 	}
542 	return retval;
543 }
544 __END_DECLS    // Added by JE - 31-01-2010
545 
546 #endif /* !GETOPT_LONG */
547