3 * @copy 2012 MinGW.org project
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
26 * Implementation of the `getopt', `getopt_long' and `getopt_long_only'
27 * APIs, for inclusion in the MinGW runtime library.
35 /* Identify how to get the calling program name, for use in messages...
39 * CYGWIN uses this DLL reference...
41 # define PROGNAME __progname
42 extern char __declspec(dllimport
) *__progname
;
45 * ...while elsewhere, we simply use the first argument passed.
47 # define PROGNAME *argv
48 # define __inline__ __inline
51 /* Initialise the public variables. */
53 int optind
= 1; /* index for first non-option arg */
54 int opterr
= 1; /* enable built-in error messages */
56 char *optarg
= NULL
; /* pointer to current option argument */
58 #define CHAR char /* argument type selector */
60 #define getopt_switchar '-' /* option prefix character in argv */
61 #define getopt_pluschar '+' /* prefix for POSIX mode in optstring */
62 #define getopt_takes_argument ':' /* marker for optarg in optstring */
63 #define getopt_arg_assign '=' /* longopt argument field separator */
64 #define getopt_unknown '?' /* return code for unmatched option */
65 #define getopt_ordered 1 /* return code for ordered non-option */
67 #define getopt_all_done -1 /* return code to indicate completion */
70 { /* All `getopt' API functions are implemented via calls to the
71 * common static function `getopt_parse()'; these `mode' selectors
72 * determine the behaviour of `getopt_parse()', to deliver the
73 * appropriate result in each case.
75 getopt_mode_standard
= 0, /* getopt() */
76 getopt_mode_long
, /* getopt_long() */
77 getopt_mode_long_only
/* getopt_long_only() */
81 { /* When attempting to match a command line argument to a long form option,
82 * these indicate the status of the match.
84 getopt_no_match
= 0, /* no successful match */
85 getopt_abbreviated_match
, /* argument is an abbreviation for an option */
86 getopt_exact_match
/* argument matches the full option name */
89 int optopt
= getopt_unknown
; /* return value for option being evaluated */
91 /* Some BSD applications expect to be able to reinitialise `getopt' parsing
92 * by setting a global variable called `optreset'. We provide an obfuscated
93 * API, which allows applications to emulate this brain damage; however, any
94 * use of this is non-portable, and is strongly discouraged.
96 #define optreset __mingw_optreset
100 int getopt_missing_arg( const CHAR
*optstring
)
102 /* Helper function to determine the appropriate return value,
103 * for the case where a required option argument is missing.
105 if( (*optstring
== getopt_pluschar
) || (*optstring
== getopt_switchar
) )
107 return (*optstring
== getopt_takes_argument
)
108 ? getopt_takes_argument
112 /* `complain' macro facilitates the generation of simple built-in
113 * error messages, displayed on various fault conditions, provided
114 * `opterr' is non-zero.
116 #define complain( MSG, ARG ) if( opterr ) \
117 fprintf( stderr, "%s: "MSG"\n", PROGNAME, ARG )
120 int getopt_argerror( int mode
, char *fmt
, CHAR
*prog
, struct option
*opt
, int retval
)
122 /* Helper function, to generate more complex built-in error
123 * messages, for invalid arguments to long form options ...
127 /* ... but, displayed only if `opterr' is non-zero.
130 if( mode
!= getopt_mode_long
)
132 * only display one hyphen, for implicit long form options,
133 * improperly resolved by `getopt_long_only()'.
137 * always preface the program name ...
139 fprintf( stderr
, "%s: ", prog
);
141 * to the appropriate, option specific message.
143 fprintf( stderr
, fmt
, flag
, opt
->name
);
145 /* Whether displaying the message, or not, always set `optopt'
146 * to identify the faulty option ...
150 * and return the `invalid option' indicator.
155 /* `getopt_conventions' establish behavioural options, to control
156 * the operation of `getopt_parse()', e.g. to select between POSIX
157 * and GNU style argument parsing behaviour.
159 #define getopt_set_conventions 0x1000
160 #define getopt_posixly_correct 0x0010
163 int getopt_conventions( int flags
)
165 static int conventions
= 0;
167 if( (conventions
== 0) && ((flags
& getopt_set_conventions
) == 0) )
169 /* default conventions have not yet been established;
170 * initialise them now!
172 conventions
= getopt_set_conventions
;
173 if( (flags
== getopt_pluschar
) || (getenv( "POSIXLY_CORRECT" ) != NULL
) )
174 conventions
|= getopt_posixly_correct
;
177 else if( flags
& getopt_set_conventions
)
179 * default conventions may have already been established,
180 * but this is a specific request to augment them.
182 conventions
|= flags
;
184 /* in any event, return the currently established conventions.
190 int is_switchar( CHAR flag
)
192 /* A simple helper function, used to identify the switch character
193 * introducing an optional command line argument.
195 return flag
== getopt_switchar
;
199 const CHAR
*getopt_match( CHAR lookup
, const CHAR
*opt_string
)
201 /* Helper function, used to identify short form options.
203 if( (*opt_string
== getopt_pluschar
) || (*opt_string
== getopt_switchar
) )
205 if( *opt_string
== getopt_takes_argument
)
207 do if( lookup
== *opt_string
) return opt_string
;
208 while( *++opt_string
);
213 int getopt_match_long( const CHAR
*nextchar
, const CHAR
*optname
)
215 /* Helper function, used to identify potential matches for
219 while( (matchchar
= *nextchar
++) && (matchchar
== *optname
) )
221 * skip over initial substring which DOES match.
227 /* did NOT match the entire argument to an initial substring
228 * of a defined option name ...
230 if( matchchar
!= getopt_arg_assign
)
232 * ... and didn't stop at an `=' internal field separator,
233 * so this is NOT a possible match.
235 return getopt_no_match
;
237 /* DID stop at an `=' internal field separator,
238 * so this IS a possible match, and what follows is an
239 * argument to the possibly matched option.
241 optarg
= (char *)(nextchar
);
245 * if we DIDN'T match the ENTIRE text of the option name,
246 * then it's a possible abbreviated match ...
248 ? getopt_abbreviated_match
250 * but if we DID match the entire option name,
251 * then it's a DEFINITE EXACT match.
253 : getopt_exact_match
;
257 int getopt_resolved( int mode
, int argc
, CHAR
*const *argv
, int *argind
,
258 struct option
*opt
, int index
, int *retindex
, const CHAR
*optstring
)
260 /* Helper function to establish appropriate return conditions,
261 * on resolution of a long form option.
263 if( retindex
!= NULL
)
266 /* On return, `optind' should normally refer to the argument, if any,
267 * which follows the current one; it is convenient to set this, before
268 * checking for the presence of any `optarg'.
270 optind
= *argind
+ 1;
272 if( optarg
&& (opt
[index
].has_arg
== no_argument
) )
274 * it is an error for the user to specify an option specific argument
275 * with an option which doesn't expect one!
277 return getopt_argerror( mode
, "option `%s%s' doesn't accept an argument\n",
278 PROGNAME
, opt
+ index
, getopt_unknown
);
280 else if( (optarg
== NULL
) && (opt
[index
].has_arg
== required_argument
) )
282 /* similarly, it is an error if no argument is specified
283 * with an option which requires one ...
287 * ... except that the requirement may be satisfied from
288 * the following command line argument, if any ...
290 optarg
= argv
[*argind
= optind
++];
293 /* so fail this case, only if no such argument exists!
295 return getopt_argerror( mode
, "option `%s%s' requires an argument\n",
296 PROGNAME
, opt
+ index
, getopt_missing_arg( optstring
) );
299 /* when the caller has provided a return buffer ...
301 if( opt
[index
].flag
!= NULL
)
303 /* ... then we place the proper return value there,
304 * and return a status code of zero ...
306 *(opt
[index
].flag
) = opt
[index
].val
;
309 /* ... otherwise, the return value becomes the status code.
311 return opt
[index
].val
;
315 int getopt_verify( const CHAR
*nextchar
, const CHAR
*optstring
)
317 /* Helper function, called by getopt_parse() when invoked
318 * by getopt_long_only(), to verify when an unmatched or an
319 * ambiguously matched long form option string is valid as
320 * a short form option specification.
322 if( ! (nextchar
&& *nextchar
&& optstring
&& *optstring
) )
324 * There are no characters to be matched, or there are no
325 * valid short form option characters to which they can be
326 * matched, so this can never be valid.
332 /* For each command line character in turn ...
335 if( (test
= getopt_match( *nextchar
++, optstring
)) == NULL
)
337 * ... there is no short form option to match the current
338 * candidate, so the entire argument fails.
342 if( test
[1] == getopt_takes_argument
)
344 * The current candidate is valid, and it matches an option
345 * which takes an argument, so this command line argument is
346 * a valid short form option specification; accept it.
350 /* If we get to here, then every character in the command line
351 * argument was valid as a short form option; accept it.
357 #define getopt_std_args int argc, CHAR *const argv[], const CHAR *optstring
358 int getopt_parse( int mode
, getopt_std_args
, ... )
360 /* Common core implementation for ALL `getopt' functions.
362 static int argind
= 0;
363 static int optbase
= 0;
364 static const CHAR
*nextchar
= NULL
;
365 static int optmark
= 0;
367 if( (optreset
|= (optind
< 1)) || (optind
< optbase
) )
369 /* POSIX does not prescribe any definitive mechanism for restarting
370 * a `getopt' scan, but some applications may require such capability.
371 * We will support it, by allowing the caller to adjust the value of
372 * `optind' downwards, (nominally setting it to zero). Since POSIX
373 * wants `optind' to have an initial value of one, but we want all
374 * of our internal place holders to be initialised to zero, when we
375 * are called for the first time, we will handle such a reset by
376 * adjusting all of the internal place holders to one less than
377 * the adjusted `optind' value, (but never to less than zero).
381 /* User has explicitly requested reinitialisation...
382 * We need to reset `optind' to it's normal initial value of 1,
383 * to avoid a potential infinitely recursive loop; by doing this
384 * up front, we also ensure that the remaining place holders
385 * will be correctly reinitialised to no less than zero.
389 /* We also need to clear the `optreset' request...
394 /* Now, we may safely reinitialise the internal place holders, to
395 * one less than `optind', without fear of making them negative.
397 optmark
= optbase
= argind
= optind
- 1;
401 /* From a POSIX perspective, the following is `undefined behaviour';
402 * we implement it thus, for compatibility with GNU and BSD getopt.
404 else if( optind
> (argind
+ 1) )
406 /* Some applications expect to be able to manipulate `optind',
407 * causing `getopt' to skip over one or more elements of `argv';
408 * POSIX doesn't require us to support this brain-damaged concept;
409 * (indeed, POSIX defines no particular behaviour, in the event of
410 * such usage, so it must be considered a bug for an application
411 * to rely on any particular outcome); nonetheless, Mac-OS-X and
412 * BSD actually provide *documented* support for this capability,
413 * so we ensure that our internal place holders keep track of
414 * external `optind' increments; (`argind' must lag by one).
418 /* When `optind' is misused, in this fashion, we also abandon any
419 * residual text in the argument we had been parsing; this is done
420 * without any further processing of such abandoned text, assuming
421 * that the caller is equipped to handle it appropriately.
426 if( nextchar
&& *nextchar
)
428 /* we are parsing a standard, or short format, option argument ...
431 if( (optchar
= getopt_match( optopt
= *nextchar
++, optstring
)) != NULL
)
433 /* we have identified it as valid ...
435 if( optchar
[1] == getopt_takes_argument
)
437 /* and determined that it requires an associated argument ...
439 if( ! *(optarg
= (char *)(nextchar
)) )
441 /* the argument is NOT attached ...
443 if( optchar
[2] == getopt_takes_argument
)
445 * but this GNU extension marks it as optional,
446 * so we don't provide one on this occasion.
450 /* otherwise this option takes a mandatory argument,
451 * so, provided there is one available ...
453 else if( (argc
- argind
) > 1 )
455 * we take the following command line argument,
456 * as the appropriate option argument.
458 optarg
= argv
[++argind
];
460 /* but if no further argument is available,
461 * then there is nothing we can do, except for
462 * issuing the requisite diagnostic message.
466 complain( "option requires an argument -- %c", optopt
);
467 return getopt_missing_arg( optstring
);
475 optind
= (nextchar
&& *nextchar
) ? argind
: argind
+ 1;
478 /* if we didn't find a valid match for the specified option character,
479 * then we fall through to here, so take appropriate diagnostic action.
481 if( mode
== getopt_mode_long_only
)
483 complain( "unrecognised option `-%s'", --nextchar
);
488 complain( "invalid option -- %c", optopt
);
489 optind
= (nextchar
&& *nextchar
) ? argind
: argind
+ 1;
490 return getopt_unknown
;
493 if( optmark
> optbase
)
495 /* This can happen, in GNU parsing mode ONLY, when we have
496 * skipped over non-option arguments, and found a subsequent
497 * option argument; in this case we permute the arguments.
501 * `optspan' specifies the number of contiguous arguments
502 * which are spanned by the current option, and so must be
503 * moved together during permutation.
505 int optspan
= argind
- optmark
+ 1;
507 * we use `this_arg' to store these temporarily.
509 CHAR
**this_arg
= (CHAR
**)malloc(optspan
* sizeof(CHAR
*));
510 if( this_arg
== NULL
)
511 return getopt_unknown
;
513 * we cannot manipulate `argv' directly, since the `getopt'
514 * API prototypes it as `read-only'; this cast to `arglist'
515 * allows us to work around that restriction.
517 CHAR
**arglist
= (char **)(argv
);
519 /* save temporary copies of the arguments which are associated
520 * with the current option ...
522 for( index
= 0; index
< optspan
; ++index
)
523 this_arg
[index
] = arglist
[optmark
+ index
];
525 /* move all preceding non-option arguments to the right,
526 * overwriting these saved arguments, while making space
527 * to replace them in their permuted location.
529 for( --optmark
; optmark
>= optbase
; --optmark
)
530 arglist
[optmark
+ optspan
] = arglist
[optmark
];
532 /* restore the temporarily saved option arguments to
533 * their permuted location.
535 for( index
= 0; index
< optspan
; ++index
)
536 arglist
[optbase
+ index
] = this_arg
[index
];
540 /* adjust `optbase', to account for the relocated option.
546 /* no permutation occurred ...
547 * simply adjust `optbase' for all options parsed so far.
549 optbase
= argind
+ 1;
551 /* enter main parsing loop ...
553 while( argc
> ++argind
)
555 /* inspect each argument in turn, identifying possible options ...
557 if( is_switchar( *(nextchar
= argv
[optmark
= argind
]) ) && *++nextchar
)
559 /* we've found a candidate option argument ... */
561 if( is_switchar( *nextchar
) )
563 /* it's a double hyphen argument ... */
565 const CHAR
*refchar
= nextchar
;
568 /* and it looks like a long format option ...
569 * `getopt_long' mode must be active to accept it as such,
570 * `getopt_long_only' also qualifies, but we must downgrade
571 * it to force explicit handling as a long format option.
573 if( mode
>= getopt_mode_long
)
576 mode
= getopt_mode_long
;
581 /* this is an explicit `--' end of options marker, so wrap up now!
583 if( optmark
> optbase
)
585 /* permuting the argument list as necessary ...
586 * (note use of `this_arg' and `arglist', as above).
588 CHAR
*this_arg
= argv
[optmark
];
589 CHAR
**arglist
= (CHAR
**)(argv
);
591 /* move all preceding non-option arguments to the right ...
593 do arglist
[optmark
] = arglist
[optmark
- 1];
594 while( optmark
-- > optbase
);
596 /* reinstate the `--' marker, in its permuted location.
598 arglist
[optbase
] = this_arg
;
600 /* ... before finally bumping `optbase' past the `--' marker,
601 * and returning the `all done' completion indicator.
604 return getopt_all_done
;
607 else if( mode
< getopt_mode_long_only
)
609 /* it's not an explicit long option, and `getopt_long_only' isn't active,
610 * so we must explicitly try to match it as a short option.
612 mode
= getopt_mode_standard
;
615 if( mode
>= getopt_mode_long
)
617 /* the current argument is a long form option, (either explicitly,
618 * introduced by a double hyphen, or implicitly because we were called
619 * by `getopt_long_only'); this is where we parse it.
624 /* we need to fetch the `extra' function arguments, which are
625 * specified for the `getopt_long' APIs.
628 va_start( refptr
, optstring
);
629 struct option
*longopts
= va_arg( refptr
, struct option
* );
630 int *optindex
= va_arg( refptr
, int * );
633 /* ensuring that `optarg' does not inherit any junk, from parsing
634 * preceding arguments ...
637 for( lookup
= 0; longopts
&& longopts
[lookup
].name
; ++lookup
)
639 /* scan the list of defined long form options ...
641 switch( getopt_match_long( nextchar
, longopts
[lookup
].name
) )
643 /* looking for possible matches for the current argument.
645 case getopt_exact_match
:
647 * when an exact match is found,
648 * return it immediately, setting `nextchar' to NULL,
649 * to ensure we don't mistakenly try to match any
650 * subsequent characters as short form options.
653 return getopt_resolved( mode
, argc
, argv
, &argind
,
654 longopts
, lookup
, optindex
, optstring
);
656 case getopt_abbreviated_match
:
658 * but, for a partial (initial substring) match ...
662 /* if this is not the first, then we have an ambiguity ...
664 if( (mode
== getopt_mode_long_only
)
666 * However, in the case of getopt_long_only(), if
667 * the entire ambiguously matched string represents
668 * a valid short option specification, then we may
669 * proceed to interpret it as such.
671 && getopt_verify( nextchar
, optstring
) )
672 return getopt_parse( mode
, argc
, argv
, optstring
);
674 /* If we get to here, then the ambiguously matched
675 * partial long option isn't valid for short option
676 * evaluation; reset parser context to resume with
677 * the following command line argument, diagnose
678 * ambiguity, and bail out.
683 complain( "option `%s' is ambiguous", argv
[argind
] );
684 return getopt_unknown
;
686 /* otherwise just note that we've found a possible match ...
693 /* if we get to here, then we found exactly one partial match,
694 * so return it, as for an exact match.
697 return getopt_resolved( mode
, argc
, argv
, &argind
,
698 longopts
, matched
, optindex
, optstring
);
700 /* if here, then we had what SHOULD have been a long form option,
701 * but it is unmatched ...
703 if( (mode
< getopt_mode_long_only
)
705 * ... although paradoxically, `mode == getopt_mode_long_only'
706 * allows us to still try to match it as a short form option.
708 || (getopt_verify( nextchar
, optstring
) == 0) )
710 /* When it cannot be matched, reset the parsing context to
711 * resume from the next argument, diagnose the failed match,
717 complain( "unrecognised option `%s'", argv
[argind
] );
718 return getopt_unknown
;
721 /* fall through to handle standard short form options...
722 * when the option argument format is neither explictly identified
723 * as long, nor implicitly matched as such, and the argument isn't
724 * just a bare hyphen, (which isn't an option), then we make one
725 * recursive call to explicitly interpret it as short format.
728 return getopt_parse( mode
, argc
, argv
, optstring
);
730 /* if we get to here, then we've parsed a non-option argument ...
731 * in GNU compatibility mode, we step over it, so we can permute
732 * any subsequent option arguments, but ...
734 if( *optstring
== getopt_switchar
)
736 /* if `optstring' begins with a `-' character, this special
737 * GNU specific behaviour requires us to return the non-option
738 * arguments in strict order, as pseudo-arguments to a special
739 * option, with return value defined as `getopt_ordered'.
743 optarg
= argv
[argind
];
744 return getopt_ordered
;
746 if( getopt_conventions( *optstring
) & getopt_posixly_correct
)
749 * for POSIXLY_CORRECT behaviour, or if `optstring' begins with
750 * a `+' character, then we break out of the parsing loop, so that
751 * the scan ends at the current argument, with no permutation.
755 /* fall through when all arguments have been evaluated,
758 return getopt_all_done
;
761 /* All three public API entry points are trivially defined,
762 * in terms of the internal `getopt_parse' function.
764 int getopt( getopt_std_args
)
766 return getopt_parse( getopt_mode_standard
, argc
, argv
, optstring
);
769 int getopt_long( getopt_std_args
, const struct option
*opts
, int *index
)
771 return getopt_parse( getopt_mode_long
, argc
, argv
, optstring
, opts
, index
);
774 int getopt_long_only( getopt_std_args
, const struct option
*opts
, int *index
)
776 return getopt_parse( getopt_mode_long_only
, argc
, argv
, optstring
, opts
, index
);
781 * These Microsnot style uglified aliases are provided for compatibility
782 * with the previous MinGW implementation of the getopt API.
784 __weak_alias( getopt
, _getopt
)
785 __weak_alias( getopt_long
, _getopt_long
)
786 __weak_alias( getopt_long_only
, _getopt_long_only
)