4 * This file is part of the mingw-w64 runtime package.
6 * The mingw-w64 runtime package and its code is distributed in the hope that it
7 * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR
8 * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to
9 * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
14 * Permission to use, copy, modify, and distribute this software for any
15 * purpose with or without fee is hereby granted, provided that the above
16 * copyright notice and this permission notice appear in all copies.
18 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
19 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
20 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
21 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
22 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
23 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
24 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 * Sponsored in part by the Defense Advanced Research Projects
27 * Agency (DARPA) and Air Force Research Laboratory, Air Force
28 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
31 * Copyright (c) 2000 The NetBSD Foundation, Inc.
32 * All rights reserved.
34 * This code is derived from software contributed to The NetBSD Foundation
35 * by Dieter Baron and Thomas Klausner.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
46 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
47 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
48 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
49 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
50 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
56 * POSSIBILITY OF SUCH DAMAGE.
59 #pragma warning(disable:4996)
63 /* All the headers include this file. */
76 #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
79 int opterr = 1; /* if error message should be printed */
80 int optind = 1; /* index into parent argv vector */
81 int optopt = '?'; /* character checked for validity */
82 #undef optreset /* see getopt.h */
83 #define optreset __mingw_optreset
84 int optreset; /* reset getopt */
85 char *optarg; /* argument associated with option */
88 //extern int optind; /* index of first non-option in argv */
89 //extern int optopt; /* single option character, as parsed */
90 //extern int opterr; /* flag to enable built-in diagnostics... */
91 // /* (user may set to zero, to suppress) */
93 //extern char *optarg; /* pointer to argument of current option */
95 #define PRINT_ERROR ((opterr) && (*options != ':'))
97 #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
98 #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
99 #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
102 #define BADCH (int)'?'
103 #define BADARG ((*options == ':') ? (int)':' : (int)'?')
104 #define INORDER (int)1
107 #define __progname __argv[0]
109 extern char __declspec(dllimport) *__progname;
113 static char EMSG[] = "";
118 static int getopt_internal(int, char * const *, const char *,
119 const struct option *, int *, int);
120 static int parse_long_options(char * const *, const char *,
121 const struct option *, int *, int);
122 static int gcd(int, int);
123 static void permute_args(int, int, int, char * const *);
125 static char *place = EMSG; /* option letter processing */
127 /* XXX: set optreset to 1 rather than these two */
128 static int nonopt_start = -1; /* first non option argument (for permute) */
129 static int nonopt_end = -1; /* first option after non options (for permute) */
132 static const char recargchar[] = "option requires an argument -- %c";
133 static const char recargstring[] = "option requires an argument -- %s";
134 static const char ambig[] = "ambiguous option -- %.*s";
135 static const char noarg[] = "option doesn't take an argument -- %.*s";
136 static const char illoptchar[] = "unknown option -- %c";
137 static const char illoptstring[] = "unknown option -- %s";
140 _vwarnx(const char *fmt,va_list ap)
142 (void)fprintf(stderr,"%s: ",__progname);
144 (void)vfprintf(stderr,fmt,ap);
145 (void)fprintf(stderr,"\n");
149 warnx(const char *fmt,...)
158 * Compute the greatest common divisor of a and b.
176 * Exchange the block from nonopt_start to nonopt_end with the block
177 * from nonopt_end to opt_end (keeping the same order of arguments
181 permute_args(int panonopt_start, int panonopt_end, int opt_end,
184 int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
188 * compute lengths of blocks and number and size of cycles
190 nnonopts = panonopt_end - panonopt_start;
191 nopts = opt_end - panonopt_end;
192 ncycle = gcd(nnonopts, nopts);
193 cyclelen = (opt_end - panonopt_start) / ncycle;
195 for (i = 0; i < ncycle; i++) {
196 cstart = panonopt_end+i;
198 for (j = 0; j < cyclelen; j++) {
199 if (pos >= panonopt_end)
204 /* LINTED const cast */
205 ((char **) nargv)[pos] = nargv[cstart];
206 /* LINTED const cast */
207 ((char **)nargv)[cstart] = swap;
212 #ifdef REPLACE_GETOPT
215 * Parse argc/argv argument vector.
217 * [eventually this will replace the BSD getopt]
220 getopt(int nargc, char * const *nargv, const char *options)
224 * We don't pass FLAG_PERMUTE to getopt_internal() since
225 * the BSD getopt(3) (unlike GNU) has never done this.
227 * Furthermore, since many privileged programs call getopt()
228 * before dropping privileges it makes sense to keep things
229 * as simple (and bug-free) as possible.
231 return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
233 #endif /* REPLACE_GETOPT */
235 //extern int getopt(int nargc, char * const *nargv, const char *options);
239 * BSD adds the non-standard `optreset' feature, for reinitialisation
240 * of `getopt' parsing. We support this feature, for applications which
241 * proclaim their BSD heritage, before including this header; however,
242 * to maintain portability, developers are advised to avoid it.
244 # define optreset __mingw_optreset
251 * POSIX requires the `getopt' API to be specified in `unistd.h';
252 * thus, `unistd.h' includes this header. However, we do not want
253 * to expose the `getopt_long' or `getopt_long_only' APIs, when
254 * included in this manner. Thus, close the standard __GETOPT_H__
255 * declarations block, and open an additional __GETOPT_LONG_H__
256 * specific block, only when *not* __UNISTD_H_SOURCED__, in which
257 * to declare the extended API.
259 #endif /* !defined(__GETOPT_H__) */
261 #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__)
262 #define __GETOPT_LONG_H__
268 struct option /* specification for a long form option... */
270 const char *name; /* option name, without leading hyphens */
271 int has_arg; /* does it take an argument? */
272 int *flag; /* where to save its status, or NULL */
273 int val; /* its associated status value */
276 enum /* permitted values for its `has_arg' field... */
278 no_argument = 0, /* option never takes an argument */
279 required_argument, /* option always requires an argument */
280 optional_argument /* option may take an argument */
284 * parse_long_options --
285 * Parse long options in argc/argv argument vector.
286 * Returns -1 if short_too is set and the option does not match long_options.
289 parse_long_options(char * const *nargv, const char *options,
290 const struct option *long_options, int *idx, int short_too)
292 char *current_argv, *has_equal;
293 size_t current_argv_len;
294 int i, ambiguous, match;
296 #define IDENTICAL_INTERPRETATION(_x, _y) \
297 (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
298 long_options[(_x)].flag == long_options[(_y)].flag && \
299 long_options[(_x)].val == long_options[(_y)].val)
301 current_argv = place;
307 if ((has_equal = strchr(current_argv, '=')) != NULL) {
308 /* argument found (--option=arg) */
309 current_argv_len = has_equal - current_argv;
312 current_argv_len = strlen(current_argv);
314 for (i = 0; long_options[i].name; i++) {
315 /* find matching long option */
316 if (strncmp(current_argv, long_options[i].name,
320 if (strlen(long_options[i].name) == current_argv_len) {
327 * If this is a known short option, don't allow
328 * a partial match of a single character.
330 if (short_too && current_argv_len == 1)
333 if (match == -1) /* partial match */
335 else if (!IDENTICAL_INTERPRETATION(i, match))
339 /* ambiguous abbreviation */
341 warnx(ambig, (int)current_argv_len,
346 if (match != -1) { /* option found */
347 if (long_options[match].has_arg == no_argument
350 warnx(noarg, (int)current_argv_len,
353 * XXX: GNU sets optopt to val regardless of flag
355 if (long_options[match].flag == NULL)
356 optopt = long_options[match].val;
361 if (long_options[match].has_arg == required_argument ||
362 long_options[match].has_arg == optional_argument) {
365 else if (long_options[match].has_arg ==
368 * optional argument doesn't use next nargv
370 optarg = nargv[optind++];
373 if ((long_options[match].has_arg == required_argument)
374 && (optarg == NULL)) {
376 * Missing argument; leading ':' indicates no error
377 * should be generated.
383 * XXX: GNU sets optopt to val regardless of flag
385 if (long_options[match].flag == NULL)
386 optopt = long_options[match].val;
392 } else { /* unknown option */
398 warnx(illoptstring, current_argv);
404 if (long_options[match].flag) {
405 *long_options[match].flag = long_options[match].val;
408 return (long_options[match].val);
409 #undef IDENTICAL_INTERPRETATION
414 * Parse argc/argv argument vector. Called by user level routines.
417 getopt_internal(int nargc, char * const *nargv, const char *options,
418 const struct option *long_options, int *idx, int flags)
420 char *oli; /* option letter list index */
421 int optchar, short_too;
422 static int posixly_correct = -1;
428 * XXX Some GNU programs (like cvs) set optind to 0 instead of
429 * XXX using optreset. Work around this braindamage.
432 optind = optreset = 1;
435 * Disable GNU extensions if POSIXLY_CORRECT is set or options
436 * string begins with a '+'.
438 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
439 * optreset != 0 for GNU compatibility.
441 if (posixly_correct == -1 || optreset != 0)
442 posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
444 flags |= FLAG_ALLARGS;
445 else if (posixly_correct || *options == '+')
446 flags &= ~FLAG_PERMUTE;
447 if (*options == '+' || *options == '-')
452 nonopt_start = nonopt_end = -1;
454 if (optreset || !*place) { /* update scanning pointer */
456 if (optind >= nargc) { /* end of argument vector */
458 if (nonopt_end != -1) {
459 /* do permutation, if we have to */
460 permute_args(nonopt_start, nonopt_end,
462 optind -= nonopt_end - nonopt_start;
464 else if (nonopt_start != -1) {
466 * If we skipped non-options, set optind
467 * to the first of them.
469 optind = nonopt_start;
471 nonopt_start = nonopt_end = -1;
474 if (*(place = nargv[optind]) != '-' ||
475 (place[1] == '\0' && strchr(options, '-') == NULL)) {
476 place = EMSG; /* found non-option */
477 if (flags & FLAG_ALLARGS) {
480 * return non-option as argument to option 1
482 optarg = nargv[optind++];
485 if (!(flags & FLAG_PERMUTE)) {
487 * If no permutation wanted, stop parsing
488 * at first non-option.
493 if (nonopt_start == -1)
494 nonopt_start = optind;
495 else if (nonopt_end != -1) {
496 permute_args(nonopt_start, nonopt_end,
498 nonopt_start = optind -
499 (nonopt_end - nonopt_start);
503 /* process next argument */
506 if (nonopt_start != -1 && nonopt_end == -1)
510 * If we have "-" do nothing, if "--" we are done.
512 if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
516 * We found an option (--), so if we skipped
517 * non-options, we have to permute.
519 if (nonopt_end != -1) {
520 permute_args(nonopt_start, nonopt_end,
522 optind -= nonopt_end - nonopt_start;
524 nonopt_start = nonopt_end = -1;
530 * Check long options if:
531 * 1) we were passed some
532 * 2) the arg is not just "-"
533 * 3) either the arg starts with -- we are getopt_long_only()
535 if (long_options != NULL && place != nargv[optind] &&
536 (*place == '-' || (flags & FLAG_LONGONLY))) {
539 place++; /* --foo long option */
540 else if (*place != ':' && strchr(options, *place) != NULL)
541 short_too = 1; /* could be short option too */
543 optchar = parse_long_options(nargv, options, long_options,
551 if ((optchar = (int)*place++) == (int)':' ||
552 (optchar == (int)'-' && *place != '\0') ||
553 (oli = (char*)strchr(options, optchar)) == NULL) {
555 * If the user specified "-" and '-' isn't listed in
556 * options, return -1 (non-option) as per POSIX.
557 * Otherwise, it is an unknown option character (or ':').
559 if (optchar == (int)'-' && *place == '\0')
564 warnx(illoptchar, optchar);
568 if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
570 if (*place) /* no space */
572 else if (++optind >= nargc) { /* no arg */
575 warnx(recargchar, optchar);
578 } else /* white space */
579 place = nargv[optind];
580 optchar = parse_long_options(nargv, options, long_options,
585 if (*++oli != ':') { /* doesn't take argument */
588 } else { /* takes (optional) argument */
590 if (*place) /* no white space */
592 else if (oli[1] != ':') { /* arg not optional */
593 if (++optind >= nargc) { /* no arg */
596 warnx(recargchar, optchar);
600 optarg = nargv[optind];
605 /* dump back option letter */
611 * Parse argc/argv argument vector.
614 getopt_long(int nargc, char * const *nargv, const char *options,
615 const struct option *long_options, int *idx)
618 return (getopt_internal(nargc, nargv, options, long_options, idx,
623 * getopt_long_only --
624 * Parse argc/argv argument vector.
627 getopt_long_only(int nargc, char * const *nargv, const char *options,
628 const struct option *long_options, int *idx)
631 return (getopt_internal(nargc, nargv, options, long_options, idx,
632 FLAG_PERMUTE|FLAG_LONGONLY));
635 //extern int getopt_long(int nargc, char * const *nargv, const char *options,
636 // const struct option *long_options, int *idx);
637 //extern int getopt_long_only(int nargc, char * const *nargv, const char *options,
638 // const struct option *long_options, int *idx);
640 * Previous MinGW implementation had...
642 #ifndef HAVE_DECL_GETOPT
644 * ...for the long form API only; keep this for compatibility.
646 # define HAVE_DECL_GETOPT 1
653 #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */