xref: /dpdk/lib/eal/windows/getopt.c (revision 7917b0d38e92e8b9ec5a870415b791420e10f11a)
1 /* SPDX-License-Identifier: ISC AND BSD-2-Clause
2  * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Sponsored in part by the Defense Advanced Research Projects
5  * Agency (DARPA) and Air Force Research Laboratory, Air Force
6  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
7  */
8 /*
9  * Copyright (c) 2000 The NetBSD Foundation, Inc.
10  * All rights reserved.
11  *
12  * This code is derived from software contributed to The NetBSD Foundation
13  * by Dieter Baron and Thomas Klausner.
14  */
15 
16 #include <getopt.h>
17 
18 #ifdef NEED_USUAL_GETOPT
19 
20 #include <string.h>
21 #include <stdlib.h>
22 
23 const char    *optarg;		/* argument associated with option */
24 int	opterr = 1;		/* if error message should be printed */
25 int	optind = 1;		/* index into parent argv vector */
26 int	optopt = '?';		/* character checked for validity */
27 
28 static void pass(const char *a) {(void) a; }
29 #define warnx(a, ...) pass(a)
30 
31 #define PRINT_ERROR	((opterr) && (*options != ':'))
32 
33 #define FLAG_PERMUTE	0x01	/* permute non-options to the end of argv */
34 #define FLAG_ALLARGS	0x02	/* treat non-options as args to option "-1" */
35 #define FLAG_LONGONLY	0x04	/* operate as getopt_long_only */
36 
37 /* return values */
38 #define	BADCH		((int)'?')
39 #define	BADARG		((*options == ':') ? (int)':' : (int)'?')
40 #define	INORDER		1
41 
42 #define	EMSG		""
43 
44 static const char *place = EMSG; /* option letter processing */
45 
46 /* XXX: set optreset to 1 rather than these two */
47 static int nonopt_start = -1; /* first non option argument (for permute) */
48 static int nonopt_end = -1;   /* first option after non options (for permute) */
49 
50 /* Error messages */
51 static const char recargchar[] = "option requires an argument -- %c";
52 static const char recargstring[] = "option requires an argument -- %s";
53 static const char ambig[] = "ambiguous option -- %.*s";
54 static const char noarg[] = "option doesn't take an argument -- %.*s";
55 static const char illoptchar[] = "unknown option -- %c";
56 static const char illoptstring[] = "unknown option -- %s";
57 
58 /*
59  * Compute the greatest common divisor of a and b.
60  */
61 static int
62 gcd(int a, int b)
63 {
64 	int c;
65 
66 	c = a % b;
67 	while (c != 0) {
68 		a = b;
69 		b = c;
70 		c = a % b;
71 	}
72 
73 	return (b);
74 }
75 
76 /*
77  * Exchange the block from nonopt_start to nonopt_end with the block
78  * from nonopt_end to opt_end (keeping the same order of arguments
79  * in each block).
80  */
81 static void
82 permute_args(int panonopt_start, int panonopt_end, int opt_end,
83 	char **nargv)
84 {
85 	int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
86 	char *swap;
87 
88 	/*
89 	 * compute lengths of blocks and number and size of cycles
90 	 */
91 	nnonopts = panonopt_end - panonopt_start;
92 	nopts = opt_end - panonopt_end;
93 	ncycle = gcd(nnonopts, nopts);
94 	cyclelen = (opt_end - panonopt_start) / ncycle;
95 
96 	for (i = 0; i < ncycle; i++) {
97 		cstart = panonopt_end+i;
98 		pos = cstart;
99 		for (j = 0; j < cyclelen; j++) {
100 			if (pos >= panonopt_end)
101 				pos -= nnonopts;
102 			else
103 				pos += nopts;
104 			swap = nargv[pos];
105 			/* LINTED const cast */
106 			((char **) nargv)[pos] = nargv[cstart];
107 			/* LINTED const cast */
108 			((char **)nargv)[cstart] = swap;
109 		}
110 	}
111 }
112 
113 /*
114  * parse_long_options --
115  *	Parse long options in argc/argv argument vector.
116  * Returns -1 if short_too is set and the option does not match long_options.
117  */
118 static int
119 parse_long_options(char **nargv, const char *options,
120 	const struct option *long_options, int *idx, int short_too)
121 {
122 	const char *current_argv;
123 	char *has_equal;
124 	size_t current_argv_len;
125 	int i, match;
126 
127 	current_argv = place;
128 	match = -1;
129 
130 	optind++;
131 
132 	has_equal = strchr(current_argv, '=');
133 	if (has_equal != NULL) {
134 		/* argument found (--option=arg) */
135 		current_argv_len = has_equal - current_argv;
136 		has_equal++;
137 	} else
138 		current_argv_len = strlen(current_argv);
139 
140 	for (i = 0; long_options[i].name; i++) {
141 		/* find matching long option */
142 		if (strncmp(current_argv, long_options[i].name,
143 		    current_argv_len))
144 			continue;
145 
146 		if (strlen(long_options[i].name) == current_argv_len) {
147 			/* exact match */
148 			match = i;
149 			break;
150 		}
151 		/*
152 		 * If this is a known short option, don't allow
153 		 * a partial match of a single character.
154 		 */
155 		if (short_too && current_argv_len == 1)
156 			continue;
157 
158 		if (match == -1)	/* partial match */
159 			match = i;
160 		else {
161 			/* ambiguous abbreviation */
162 			if (PRINT_ERROR)
163 				warnx(ambig, (int)current_argv_len,
164 				     current_argv);
165 			optopt = 0;
166 			return BADCH;
167 		}
168 	}
169 	if (match != -1) {		/* option found */
170 		if (long_options[match].has_arg == no_argument
171 		    && has_equal) {
172 			if (PRINT_ERROR)
173 				warnx(noarg, (int)current_argv_len,
174 				     current_argv);
175 			/*
176 			 * XXX: GNU sets optopt to val regardless of flag
177 			 */
178 			if (long_options[match].flag == NULL)
179 				optopt = long_options[match].val;
180 			else
181 				optopt = 0;
182 			return BADARG;
183 		}
184 		if (long_options[match].has_arg == required_argument ||
185 		    long_options[match].has_arg == optional_argument) {
186 			if (has_equal)
187 				optarg = has_equal;
188 			else if (long_options[match].has_arg ==
189 			    required_argument) {
190 				/*
191 				 * optional argument doesn't use next nargv
192 				 */
193 				optarg = nargv[optind++];
194 			}
195 		}
196 		if ((long_options[match].has_arg == required_argument)
197 		    && (optarg == NULL)) {
198 			/*
199 			 * Missing argument; leading ':' indicates no error
200 			 * should be generated.
201 			 */
202 			if (PRINT_ERROR)
203 				warnx(recargstring,
204 				    current_argv);
205 			/*
206 			 * XXX: GNU sets optopt to val regardless of flag
207 			 */
208 			if (long_options[match].flag == NULL)
209 				optopt = long_options[match].val;
210 			else
211 				optopt = 0;
212 			--optind;
213 			return BADARG;
214 		}
215 	} else {			/* unknown option */
216 		if (short_too) {
217 			--optind;
218 			return (-1);
219 		}
220 		if (PRINT_ERROR)
221 			warnx(illoptstring, current_argv);
222 		optopt = 0;
223 		return BADCH;
224 	}
225 	if (idx)
226 		*idx = match;
227 	if (long_options[match].flag) {
228 		*long_options[match].flag = long_options[match].val;
229 		return 0;
230 	} else
231 		return (long_options[match].val);
232 }
233 
234 /*
235  * getopt_internal --
236  *	Parse argc/argv argument vector.  Called by user level routines.
237  */
238 static int
239 getopt_internal(int nargc, char **nargv, const char *options,
240 	const struct option *long_options, int *idx, int flags)
241 {
242 	char *oli;				/* option letter list index */
243 	int optchar, short_too;
244 	static int posixly_correct = -1;
245 	size_t len;
246 	int optreset = 0;
247 
248 	if (options == NULL)
249 		return (-1);
250 
251 	/*
252 	 * Disable GNU extensions if POSIXLY_CORRECT is set or options
253 	 * string begins with a '+'.
254 	 */
255 	if (posixly_correct == -1) {
256 		errno_t err = _wgetenv_s(&len, NULL, 0, L"POSIXLY_CORRECT");
257 		posixly_correct = (err == 0) && (len > 0);
258 	}
259 	if (!posixly_correct || *options == '+')
260 		flags &= ~FLAG_PERMUTE;
261 	else if (*options == '-')
262 		flags |= FLAG_ALLARGS;
263 	if (*options == '+' || *options == '-')
264 		options++;
265 	/*
266 	 * reset if requested
267 	 */
268 	if (optind == 0)
269 		optind = optreset = 1;
270 
271 	optarg = NULL;
272 	if (optreset)
273 		nonopt_start = nonopt_end = -1;
274 start:
275 	if (optreset || !*place) {		/* update scanning pointer */
276 		optreset = 0;
277 		if (optind >= nargc) {          /* end of argument vector */
278 			place = EMSG;
279 			if (nonopt_end != -1) {
280 				/* do permutation, if we have to */
281 				permute_args(nonopt_start, nonopt_end,
282 				    optind, nargv);
283 				optind -= nonopt_end - nonopt_start;
284 			} else if (nonopt_start != -1) {
285 				/*
286 				 * If we skipped non-options, set optind
287 				 * to the first of them.
288 				 */
289 				optind = nonopt_start;
290 			}
291 			nonopt_start = nonopt_end = -1;
292 			return (-1);
293 		}
294 		place = nargv[optind];
295 		if (*place != '-' ||
296 		    (place[1] == '\0' && strchr(options, '-') == NULL)) {
297 			place = EMSG;		/* found non-option */
298 			if (flags & FLAG_ALLARGS) {
299 				/*
300 				 * GNU extension:
301 				 * return non-option as argument to option 1
302 				 */
303 				optarg = nargv[optind++];
304 				return INORDER;
305 			}
306 			if (!(flags & FLAG_PERMUTE)) {
307 				/*
308 				 * If no permutation wanted, stop parsing
309 				 * at first non-option.
310 				 */
311 				return (-1);
312 			}
313 			/* do permutation */
314 			if (nonopt_start == -1)
315 				nonopt_start = optind;
316 			else if (nonopt_end != -1) {
317 				permute_args(nonopt_start, nonopt_end,
318 				    optind, nargv);
319 				nonopt_start = optind -
320 				    (nonopt_end - nonopt_start);
321 				nonopt_end = -1;
322 			}
323 			optind++;
324 			/* process next argument */
325 			goto start;
326 		}
327 		if (nonopt_start != -1 && nonopt_end == -1)
328 			nonopt_end = optind;
329 
330 		/*
331 		 * If we have "-" do nothing, if "--" we are done.
332 		 */
333 		if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
334 			optind++;
335 			place = EMSG;
336 			/*
337 			 * We found an option (--), so if we skipped
338 			 * non-options, we have to permute.
339 			 */
340 			if (nonopt_end != -1) {
341 				permute_args(nonopt_start, nonopt_end,
342 				    optind, nargv);
343 				optind -= nonopt_end - nonopt_start;
344 			}
345 			nonopt_start = nonopt_end = -1;
346 			return (-1);
347 		}
348 	}
349 
350 	/*
351 	 * Check long options if:
352 	 *  1) we were passed some
353 	 *  2) the arg is not just "-"
354 	 *  3) either the arg starts with -- we are getopt_long_only()
355 	 */
356 	if (long_options != NULL && place != nargv[optind] &&
357 	    (*place == '-' || (flags & FLAG_LONGONLY))) {
358 		short_too = 0;
359 		if (*place == '-')
360 			place++;		/* --foo long option */
361 		else if (*place != ':' && strchr(options, *place) != NULL)
362 			short_too = 1;		/* could be short option too */
363 
364 		optchar = parse_long_options(nargv, options, long_options,
365 		    idx, short_too);
366 		if (optchar != -1) {
367 			place = EMSG;
368 			return optchar;
369 		}
370 	}
371 
372 	optchar = (int)*place++;
373 	oli = strchr(options, optchar);
374 	if (optchar == (int)':' ||
375 	    (optchar == (int)'-' && *place != '\0') ||
376 	    oli == NULL) {
377 		/*
378 		 * If the user specified "-" and  '-' isn't listed in
379 		 * options, return -1 (non-option) as per POSIX.
380 		 * Otherwise, it is an unknown option character (or ':').
381 		 */
382 		if (optchar == (int)'-' && *place == '\0')
383 			return (-1);
384 		if (!*place)
385 			++optind;
386 		if (PRINT_ERROR)
387 			warnx(illoptchar, optchar);
388 		optopt = optchar;
389 		return BADCH;
390 	}
391 	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
392 		/* -W long-option */
393 		if (*place)
394 			;
395 		else if (++optind >= nargc) {	/* no arg */
396 			place = EMSG;
397 			if (PRINT_ERROR)
398 				warnx(recargchar, optchar);
399 			optopt = optchar;
400 			return BADARG;
401 		}				/* white space */
402 		place = nargv[optind];
403 		optchar = parse_long_options(nargv, options, long_options,
404 		    idx, 0);
405 		place = EMSG;
406 		return optchar;
407 	}
408 	if (*++oli != ':') {			/* doesn't take argument */
409 		if (!*place)
410 			++optind;
411 	} else {				/* takes (optional) argument */
412 		optarg = NULL;
413 		if (*place)			/* no white space */
414 			optarg = place;
415 		else if (oli[1] != ':') {	/* arg not optional */
416 			if (++optind >= nargc) {	/* no arg */
417 				place = EMSG;
418 				if (PRINT_ERROR)
419 					warnx(recargchar, optchar);
420 				optopt = optchar;
421 				return BADARG;
422 			}
423 			optarg = nargv[optind];
424 		}
425 		place = EMSG;
426 		++optind;
427 	}
428 	/* dump back option letter */
429 	return optchar;
430 }
431 
432 /*
433  * getopt --
434  *	Parse argc/argv argument vector.
435  */
436 int
437 getopt(int nargc, char *nargv[], const char *options)
438 {
439 	return getopt_internal(nargc, nargv, options, NULL, NULL,
440 			       FLAG_PERMUTE);
441 }
442 
443 /*
444  * getopt_long --
445  *	Parse argc/argv argument vector.
446  */
447 int
448 getopt_long(int nargc, char *nargv[], const char *options,
449 	const struct option *long_options, int *idx)
450 {
451 
452 	return (getopt_internal(nargc, nargv, options, long_options, idx,
453 	    FLAG_PERMUTE));
454 }
455 
456 /*
457  * getopt_long_only --
458  *	Parse argc/argv argument vector.
459  */
460 int
461 getopt_long_only(int nargc, char *nargv[], const char *options,
462 	const struct option *long_options, int *idx)
463 {
464 
465 	return (getopt_internal(nargc, nargv, options, long_options, idx,
466 	    FLAG_PERMUTE|FLAG_LONGONLY));
467 }
468 
469 #endif /* NEED_USUAL_GETOPT */
470