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