1 /* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl 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 #include "msvc-posix.h"
52 #include "msvc-getopt.h"
53
54 #include <errno.h>
55 #include <stdarg.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <windows.h>
60
61 int opterr = 1; /* if error message should be printed */
62 int optind = 1; /* index into parent argv vector */
63 int optopt = '?'; /* character checked for validity */
64 char* optarg; /* argument associated with option */
65
66 #define PRINT_ERROR ((opterr) && (*options != ':'))
67
68 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
69 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
70 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
71
72 /* return values */
73 #define BADCH (int)'?'
74 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
75 #define INORDER (int)1
76
77 #define __progname __argv[0]
78 #define EMSG ""
79
80 static int getopt_internal(int,
81 char* const*,
82 const char*,
83 const struct option*,
84 int*,
85 int);
86 static int parse_long_options(char* const*,
87 const char*,
88 const struct option*,
89 int*,
90 int);
91 static int gcd(int, int);
92 static void permute_args(int, int, int, char* const*);
93
94 static char* place = EMSG; /* option letter processing */
95
96 static int nonopt_start = -1; /* first non option argument (for permute) */
97 static int nonopt_end = -1; /* first option after non options (for permute) */
98
99 /* Error messages */
100 static const char recargchar[] = "option requires an argument -- %c";
101 static const char recargstring[] = "option requires an argument -- %s";
102 static const char ambig[] = "ambiguous option -- %.*s";
103 static const char noarg[] = "option doesn't take an argument -- %.*s";
104 static const char illoptchar[] = "unknown option -- %c";
105 static const char illoptstring[] = "unknown option -- %s";
106
_vwarnx(const char * fmt,va_list ap)107 static void _vwarnx(const char* fmt, va_list ap) {
108 (void)fprintf(stderr, "%s: ", __progname);
109 if (fmt != NULL)
110 (void)vfprintf(stderr, fmt, ap);
111 (void)fprintf(stderr, "\n");
112 }
113
warnx(const char * fmt,...)114 static void warnx(const char* fmt, ...) {
115 va_list ap;
116 va_start(ap, fmt);
117 _vwarnx(fmt, ap);
118 va_end(ap);
119 }
120
121 /*
122 * Compute the greatest common divisor of a and b.
123 */
gcd(int a,int b)124 static int gcd(int a, int b) {
125 int c;
126
127 c = a % b;
128 while (c != 0) {
129 a = b;
130 b = c;
131 c = a % b;
132 }
133
134 return (b);
135 }
136
137 /*
138 * Exchange the block from nonopt_start to nonopt_end with the block
139 * from nonopt_end to opt_end (keeping the same order of arguments
140 * in each block).
141 */
permute_args(int panonopt_start,int panonopt_end,int opt_end,char * const * nargv)142 static void permute_args(int panonopt_start,
143 int panonopt_end,
144 int opt_end,
145 char* const* nargv) {
146 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
147 char* swap;
148
149 /*
150 * compute lengths of blocks and number and size of cycles
151 */
152 nnonopts = panonopt_end - panonopt_start;
153 nopts = opt_end - panonopt_end;
154 ncycle = gcd(nnonopts, nopts);
155 cyclelen = (opt_end - panonopt_start) / ncycle;
156
157 for (i = 0; i < ncycle; i++) {
158 cstart = panonopt_end + i;
159 pos = cstart;
160 for (j = 0; j < cyclelen; j++) {
161 if (pos >= panonopt_end)
162 pos -= nnonopts;
163 else
164 pos += nopts;
165 swap = nargv[pos];
166 /* LINTED const cast */
167 ((char**)nargv)[pos] = nargv[cstart];
168 /* LINTED const cast */
169 ((char**)nargv)[cstart] = swap;
170 }
171 }
172 }
173
174 /*
175 * parse_long_options --
176 * Parse long options in argc/argv argument vector.
177 * Returns -1 if short_too is set and the option does not match long_options.
178 */
parse_long_options(char * const * nargv,const char * options,const struct option * long_options,int * idx,int short_too)179 static int parse_long_options(char* const* nargv,
180 const char* options,
181 const struct option* long_options,
182 int* idx,
183 int short_too) {
184 char *current_argv, *has_equal;
185 size_t current_argv_len;
186 int i, ambiguous, match;
187
188 #define IDENTICAL_INTERPRETATION(_x, _y) \
189 (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
190 long_options[(_x)].flag == long_options[(_y)].flag && \
191 long_options[(_x)].val == long_options[(_y)].val)
192
193 current_argv = place;
194 match = -1;
195 ambiguous = 0;
196
197 optind++;
198
199 if ((has_equal = strchr(current_argv, '=')) != NULL) {
200 /* argument found (--option=arg) */
201 current_argv_len = has_equal - current_argv;
202 has_equal++;
203 } else
204 current_argv_len = strlen(current_argv);
205
206 for (i = 0; long_options[i].name; i++) {
207 /* find matching long option */
208 if (strncmp(current_argv, long_options[i].name, current_argv_len))
209 continue;
210
211 if (strlen(long_options[i].name) == current_argv_len) {
212 /* exact match */
213 match = i;
214 ambiguous = 0;
215 break;
216 }
217 /*
218 * If this is a known short option, don't allow
219 * a partial match of a single character.
220 */
221 if (short_too && current_argv_len == 1)
222 continue;
223
224 if (match == -1) /* partial match */
225 match = i;
226 else if (!IDENTICAL_INTERPRETATION(i, match))
227 ambiguous = 1;
228 }
229 if (ambiguous) {
230 /* ambiguous abbreviation */
231 if (PRINT_ERROR)
232 warnx(ambig, (int)current_argv_len, current_argv);
233 optopt = 0;
234 return (BADCH);
235 }
236 if (match != -1) { /* option found */
237 if (long_options[match].has_arg == no_argument && has_equal) {
238 if (PRINT_ERROR)
239 warnx(noarg, (int)current_argv_len, current_argv);
240 /*
241 * XXX: GNU sets optopt to val regardless of flag
242 */
243 if (long_options[match].flag == NULL)
244 optopt = long_options[match].val;
245 else
246 optopt = 0;
247 return (BADARG);
248 }
249 if (long_options[match].has_arg == required_argument ||
250 long_options[match].has_arg == optional_argument) {
251 if (has_equal)
252 optarg = has_equal;
253 else if (long_options[match].has_arg == required_argument) {
254 /*
255 * optional argument doesn't use next nargv
256 */
257 optarg = nargv[optind++];
258 }
259 }
260 if ((long_options[match].has_arg == required_argument) &&
261 (optarg == NULL)) {
262 /*
263 * Missing argument; leading ':' indicates no error
264 * should be generated.
265 */
266 if (PRINT_ERROR)
267 warnx(recargstring, current_argv);
268 /*
269 * XXX: GNU sets optopt to val regardless of flag
270 */
271 if (long_options[match].flag == NULL)
272 optopt = long_options[match].val;
273 else
274 optopt = 0;
275 --optind;
276 return (BADARG);
277 }
278 } else { /* unknown option */
279 if (short_too) {
280 --optind;
281 return (-1);
282 }
283 if (PRINT_ERROR)
284 warnx(illoptstring, current_argv);
285 optopt = 0;
286 return (BADCH);
287 }
288 if (idx)
289 *idx = match;
290 if (long_options[match].flag) {
291 *long_options[match].flag = long_options[match].val;
292 return (0);
293 } else
294 return (long_options[match].val);
295 #undef IDENTICAL_INTERPRETATION
296 }
297
298 /*
299 * getopt_internal --
300 * Parse argc/argv argument vector. Called by user level routines.
301 */
getopt_internal(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx,int flags)302 static int getopt_internal(int nargc,
303 char* const* nargv,
304 const char* options,
305 const struct option* long_options,
306 int* idx,
307 int flags) {
308 char* oli; /* option letter list index */
309 int optchar, short_too;
310 static int posixly_correct = -1;
311
312 if (options == NULL)
313 return (-1);
314
315 if (optind == 0)
316 optind = 1;
317
318 /*
319 * Disable GNU extensions if POSIXLY_CORRECT is set or options
320 * string begins with a '+'.
321 *
322 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
323 * optreset != 0 for GNU compatibility.
324 */
325 if (posixly_correct == -1)
326 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
327 if (*options == '-')
328 flags |= FLAG_ALLARGS;
329 else if (posixly_correct || *options == '+')
330 flags &= ~FLAG_PERMUTE;
331 if (*options == '+' || *options == '-')
332 options++;
333
334 optarg = NULL;
335 start:
336 if (!*place) { /* update scanning pointer */
337 if (optind >= nargc) { /* end of argument vector */
338 place = EMSG;
339 if (nonopt_end != -1) {
340 /* do permutation, if we have to */
341 permute_args(nonopt_start, nonopt_end, optind, nargv);
342 optind -= nonopt_end - nonopt_start;
343 } else if (nonopt_start != -1) {
344 /*
345 * If we skipped non-options, set optind
346 * to the first of them.
347 */
348 optind = nonopt_start;
349 }
350 nonopt_start = nonopt_end = -1;
351 return (-1);
352 }
353 if (*(place = nargv[optind]) != '-' ||
354 (place[1] == '\0' && strchr(options, '-') == NULL)) {
355 place = EMSG; /* found non-option */
356 if (flags & FLAG_ALLARGS) {
357 /*
358 * GNU extension:
359 * return non-option as argument to option 1
360 */
361 optarg = nargv[optind++];
362 return (INORDER);
363 }
364 if (!(flags & FLAG_PERMUTE)) {
365 /*
366 * If no permutation wanted, stop parsing
367 * at first non-option.
368 */
369 return (-1);
370 }
371 /* do permutation */
372 if (nonopt_start == -1)
373 nonopt_start = optind;
374 else if (nonopt_end != -1) {
375 permute_args(nonopt_start, nonopt_end, optind, nargv);
376 nonopt_start = optind - (nonopt_end - nonopt_start);
377 nonopt_end = -1;
378 }
379 optind++;
380 /* process next argument */
381 goto start;
382 }
383 if (nonopt_start != -1 && nonopt_end == -1)
384 nonopt_end = optind;
385
386 /*
387 * If we have "-" do nothing, if "--" we are done.
388 */
389 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
390 optind++;
391 place = EMSG;
392 /*
393 * We found an option (--), so if we skipped
394 * non-options, we have to permute.
395 */
396 if (nonopt_end != -1) {
397 permute_args(nonopt_start, nonopt_end, optind, nargv);
398 optind -= nonopt_end - nonopt_start;
399 }
400 nonopt_start = nonopt_end = -1;
401 return (-1);
402 }
403 }
404
405 /*
406 * Check long options if:
407 * 1) we were passed some
408 * 2) the arg is not just "-"
409 * 3) either the arg starts with -- we are getopt_long_only()
410 */
411 if (long_options != NULL && place != nargv[optind] &&
412 (*place == '-' || (flags & FLAG_LONGONLY))) {
413 short_too = 0;
414 if (*place == '-')
415 place++; /* --foo long option */
416 else if (*place != ':' && strchr(options, *place) != NULL)
417 short_too = 1; /* could be short option too */
418
419 optchar = parse_long_options(nargv, options, long_options, idx,
420 short_too);
421 if (optchar != -1) {
422 place = EMSG;
423 return (optchar);
424 }
425 }
426
427 if ((optchar = (int)*place++) == (int)':' ||
428 (optchar == (int)'-' && *place != '\0') ||
429 (oli = strchr(options, optchar)) == NULL) {
430 /*
431 * If the user specified "-" and '-' isn't listed in
432 * options, return -1 (non-option) as per POSIX.
433 * Otherwise, it is an unknown option character (or ':').
434 */
435 if (optchar == (int)'-' && *place == '\0')
436 return (-1);
437 if (!*place)
438 ++optind;
439 if (PRINT_ERROR)
440 warnx(illoptchar, optchar);
441 optopt = optchar;
442 return (BADCH);
443 }
444 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
445 /* -W long-option */
446 if (*place) /* no space */
447 /* NOTHING */;
448 else if (++optind >= nargc) { /* no arg */
449 place = EMSG;
450 if (PRINT_ERROR)
451 warnx(recargchar, optchar);
452 optopt = optchar;
453 return (BADARG);
454 } else /* white space */
455 place = nargv[optind];
456 optchar = parse_long_options(nargv, options, long_options, idx, 0);
457 place = EMSG;
458 return (optchar);
459 }
460 if (*++oli != ':') { /* doesn't take argument */
461 if (!*place)
462 ++optind;
463 } else { /* takes (optional) argument */
464 optarg = NULL;
465 if (*place) /* no white space */
466 optarg = place;
467 else if (oli[1] != ':') { /* arg not optional */
468 if (++optind >= nargc) { /* no arg */
469 place = EMSG;
470 if (PRINT_ERROR)
471 warnx(recargchar, optchar);
472 optopt = optchar;
473 return (BADARG);
474 } else
475 optarg = nargv[optind];
476 }
477 place = EMSG;
478 ++optind;
479 }
480 /* dump back option letter */
481 return (optchar);
482 }
483
484 /*
485 * getopt --
486 * Parse argc/argv argument vector.
487 *
488 * [eventually this will replace the BSD getopt]
489 */
getopt(int nargc,char * const * nargv,const char * options)490 int getopt(int nargc, char* const* nargv, const char* options) {
491 /*
492 * We don't pass FLAG_PERMUTE to getopt_internal() since
493 * the BSD getopt(3) (unlike GNU) has never done this.
494 *
495 * Furthermore, since many privileged programs call getopt()
496 * before dropping privileges it makes sense to keep things
497 * as simple (and bug-free) as possible.
498 */
499 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
500 }
501
502 /*
503 * getopt_long --
504 * Parse argc/argv argument vector.
505 */
getopt_long(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)506 int getopt_long(int nargc,
507 char* const* nargv,
508 const char* options,
509 const struct option* long_options,
510 int* idx) {
511 return (getopt_internal(nargc, nargv, options, long_options, idx,
512 FLAG_PERMUTE));
513 }
514
515 /*
516 * getopt_long_only --
517 * Parse argc/argv argument vector.
518 */
getopt_long_only(int nargc,char * const * nargv,const char * options,const struct option * long_options,int * idx)519 int getopt_long_only(int nargc,
520 char* const* nargv,
521 const char* options,
522 const struct option* long_options,
523 int* idx) {
524 return (getopt_internal(nargc, nargv, options, long_options, idx,
525 FLAG_PERMUTE | FLAG_LONGONLY));
526 }
527