getopt.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. #ifndef __GETOPT_H__
  2. /**
  3. * DISCLAIMER
  4. * This file has no copyright assigned and is placed in the Public Domain.
  5. * This file is part of the mingw-w64 runtime package.
  6. *
  7. * The mingw-w64 runtime package and its code is distributed in the hope that it
  8. * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR
  9. * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to
  10. * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. */
  12. /*
  13. * Implementation of the `getopt', `getopt_long' and `getopt_long_only'
  14. * APIs, for inclusion in the MinGW runtime library.
  15. *
  16. * This file is part of the MinGW32 package set.
  17. *
  18. * Written by Keith Marshall <[email protected]>
  19. * Copyright (C) 2008, 2009, 2011, 2012, MinGW.org Project.
  20. *
  21. * ---------------------------------------------------------------------------
  22. *
  23. * Permission is hereby granted, free of charge, to any person obtaining a
  24. * copy of this software and associated documentation files (the "Software"),
  25. * to deal in the Software without restriction, including without limitation
  26. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  27. * and/or sell copies of the Software, and to permit persons to whom the
  28. * Software is furnished to do so, subject to the following conditions:
  29. *
  30. * The above copyright notice, this permission notice, and the following
  31. * disclaimer shall be included in all copies or substantial portions of
  32. * the Software.
  33. *
  34. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  35. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  36. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  37. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  39. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  40. * DEALINGS IN THE SOFTWARE.
  41. *
  42. * ---------------------------------------------------------------------------
  43. *
  44. */
  45. #define __GETOPT_H__
  46. /* All the headers include this file. */
  47. #include <crtdefs.h>
  48. #include <stdio.h>
  49. #include <stdlib.h>
  50. #include <stdarg.h>
  51. #ifdef __cplusplus
  52. extern "C" {
  53. #endif
  54. extern int optind; /* index of first non-option in argv */
  55. extern int optopt; /* single option character, as parsed */
  56. extern int opterr; /* flag to enable built-in diagnostics... */
  57. /* (user may set to zero, to suppress) */
  58. extern char *optarg; /* pointer to argument of current option */
  59. /* Identify how to get the calling program name, for use in messages...
  60. */
  61. #ifdef __CYGWIN__
  62. /*
  63. * CYGWIN uses this DLL reference...
  64. */
  65. # define PROGNAME __progname
  66. extern char __declspec(dllimport) *__progname;
  67. #else
  68. /*
  69. * ...while elsewhere, we simply use the first argument passed.
  70. */
  71. # define PROGNAME *argv
  72. #endif
  73. extern int getopt(int nargc, char * const *nargv, const char *options);
  74. #ifdef _BSD_SOURCE
  75. /*
  76. * BSD adds the non-standard `optreset' feature, for reinitialisation
  77. * of `getopt' parsing. We support this feature, for applications which
  78. * proclaim their BSD heritage, before including this header; however,
  79. * to maintain portability, developers are advised to avoid it.
  80. */
  81. # define optreset __mingw_optreset
  82. extern int optreset;
  83. #endif
  84. #ifdef __cplusplus
  85. }
  86. #endif
  87. /*
  88. * POSIX requires the `getopt' API to be specified in `unistd.h';
  89. * thus, `unistd.h' includes this header. However, we do not want
  90. * to expose the `getopt_long' or `getopt_long_only' APIs, when
  91. * included in this manner. Thus, close the standard __GETOPT_H__
  92. * declarations block, and open an additional __GETOPT_LONG_H__
  93. * specific block, only when *not* __UNISTD_H_SOURCED__, in which
  94. * to declare the extended API.
  95. */
  96. #endif /* !defined(__GETOPT_H__) */
  97. #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__)
  98. #define __GETOPT_LONG_H__
  99. #ifdef __cplusplus
  100. extern "C" {
  101. #endif
  102. struct option /* specification for a long form option... */
  103. {
  104. const char *name; /* option name, without leading hyphens */
  105. int has_arg; /* does it take an argument? */
  106. int *flag; /* where to save its status, or NULL */
  107. int val; /* its associated status value */
  108. };
  109. enum /* permitted values for its `has_arg' field... */
  110. {
  111. no_argument = 0, /* option never takes an argument */
  112. required_argument, /* option always requires an argument */
  113. optional_argument /* option may take an argument */
  114. };
  115. extern int getopt_long(int nargc, char * const *nargv, const char *options,
  116. const struct option *long_options, int *idx);
  117. extern int getopt_long_only(int nargc, char * const *nargv, const char *options,
  118. const struct option *long_options, int *idx);
  119. /*
  120. * Previous MinGW implementation had...
  121. */
  122. #ifndef HAVE_DECL_GETOPT
  123. /*
  124. * ...for the long form API only; keep this for compatibility.
  125. */
  126. # define HAVE_DECL_GETOPT 1
  127. #endif
  128. /* Identify how to get the calling program name, for use in messages...
  129. */
  130. #ifdef __CYGWIN__
  131. /*
  132. * CYGWIN uses this DLL reference...
  133. */
  134. # define PROGNAME __progname
  135. extern char __declspec(dllimport) *__progname;
  136. #else
  137. /*
  138. * ...while elsewhere, we simply use the first argument passed.
  139. */
  140. # define PROGNAME *argv
  141. #endif
  142. /* Initialise the public variables. */
  143. int optind = 1; /* index for first non-option arg */
  144. int opterr = 1; /* enable built-in error messages */
  145. char *optarg = NULL; /* pointer to current option argument */
  146. #define CHAR char /* argument type selector */
  147. #define getopt_switchar '-' /* option prefix character in argv */
  148. #define getopt_pluschar '+' /* prefix for POSIX mode in optstring */
  149. #define getopt_takes_argument ':' /* marker for optarg in optstring */
  150. #define getopt_arg_assign '=' /* longopt argument field separator */
  151. #define getopt_unknown '?' /* return code for unmatched option */
  152. #define getopt_ordered 1 /* return code for ordered non-option */
  153. #define getopt_all_done -1 /* return code to indicate completion */
  154. enum
  155. { /* All `getopt' API functions are implemented via calls to the
  156. * common static function `getopt_parse()'; these `mode' selectors
  157. * determine the behaviour of `getopt_parse()', to deliver the
  158. * appropriate result in each case.
  159. */
  160. getopt_mode_standard = 0, /* getopt() */
  161. getopt_mode_long, /* getopt_long() */
  162. getopt_mode_long_only /* getopt_long_only() */
  163. };
  164. enum
  165. { /* When attempting to match a command line argument to a long form option,
  166. * these indicate the status of the match.
  167. */
  168. getopt_no_match = 0, /* no successful match */
  169. getopt_abbreviated_match, /* argument is an abbreviation for an option */
  170. getopt_exact_match /* argument matches the full option name */
  171. };
  172. int optopt = getopt_unknown; /* return value for option being evaluated */
  173. /* Some BSD applications expect to be able to reinitialise `getopt' parsing
  174. * by setting a global variable called `optreset'. We provide an obfuscated
  175. * API, which allows applications to emulate this brain damage; however, any
  176. * use of this is non-portable, and is strongly discouraged.
  177. */
  178. #define optreset __mingw_optreset
  179. int optreset = 0;
  180. static
  181. int getopt_missing_arg( const CHAR *optstring )
  182. {
  183. /* Helper function to determine the appropriate return value,
  184. * for the case where a required option argument is missing.
  185. */
  186. if( (*optstring == getopt_pluschar) || (*optstring == getopt_switchar) )
  187. ++optstring;
  188. return (*optstring == getopt_takes_argument)
  189. ? getopt_takes_argument
  190. : getopt_unknown;
  191. }
  192. /* `complain' macro facilitates the generation of simple built-in
  193. * error messages, displayed on various fault conditions, provided
  194. * `opterr' is non-zero.
  195. */
  196. #define complain( MSG, ARG ) if( opterr ) \
  197. fprintf( stderr, "%s: "MSG"\n", PROGNAME, ARG )
  198. static
  199. int getopt_argerror( int mode, char *fmt, CHAR *prog, struct option *opt, int retval )
  200. {
  201. /* Helper function, to generate more complex built-in error
  202. * messages, for invalid arguments to long form options ...
  203. */
  204. if( opterr )
  205. {
  206. /* ... but, displayed only if `opterr' is non-zero.
  207. */
  208. char flag[] = "--";
  209. if( mode != getopt_mode_long )
  210. /*
  211. * only display one hyphen, for implicit long form options,
  212. * improperly resolved by `getopt_long_only()'.
  213. */
  214. flag[1] = 0;
  215. /*
  216. * always preface the program name ...
  217. */
  218. fprintf( stderr, "%s: ", prog );
  219. /*
  220. * to the appropriate, option specific message.
  221. */
  222. fprintf( stderr, fmt, flag, opt->name );
  223. }
  224. /* Whether displaying the message, or not, always set `optopt'
  225. * to identify the faulty option ...
  226. */
  227. optopt = opt->val;
  228. /*
  229. * and return the `invalid option' indicator.
  230. */
  231. return retval;
  232. }
  233. /* `getopt_conventions' establish behavioural options, to control
  234. * the operation of `getopt_parse()', e.g. to select between POSIX
  235. * and GNU style argument parsing behaviour.
  236. */
  237. #define getopt_set_conventions 0x1000
  238. #define getopt_posixly_correct 0x0010
  239. static
  240. int getopt_conventions( int flags )
  241. {
  242. static int conventions = 0;
  243. if( (conventions == 0) && ((flags & getopt_set_conventions) == 0) )
  244. {
  245. /* default conventions have not yet been established;
  246. * initialise them now!
  247. */
  248. conventions = getopt_set_conventions;
  249. if( flags == getopt_pluschar )
  250. conventions |= getopt_posixly_correct;
  251. }
  252. else if( flags & getopt_set_conventions )
  253. /*
  254. * default conventions may have already been established,
  255. * but this is a specific request to augment them.
  256. */
  257. conventions |= flags;
  258. /* in any event, return the currently established conventions.
  259. */
  260. return conventions;
  261. }
  262. static
  263. int is_switchar( CHAR flag )
  264. {
  265. /* A simple helper function, used to identify the switch character
  266. * introducing an optional command line argument.
  267. */
  268. return flag == getopt_switchar;
  269. }
  270. static
  271. const CHAR *getopt_match( CHAR lookup, const CHAR *opt_string )
  272. {
  273. /* Helper function, used to identify short form options.
  274. */
  275. if( (*opt_string == getopt_pluschar) || (*opt_string == getopt_switchar) )
  276. ++opt_string;
  277. if( *opt_string == getopt_takes_argument )
  278. ++opt_string;
  279. do if( lookup == *opt_string ) return opt_string;
  280. while( *++opt_string );
  281. return NULL;
  282. }
  283. static
  284. int getopt_match_long( const CHAR *nextchar, const CHAR *optname )
  285. {
  286. /* Helper function, used to identify potential matches for
  287. * long form options.
  288. */
  289. CHAR matchchar;
  290. while( (matchchar = *nextchar++) && (matchchar == *optname) )
  291. /*
  292. * skip over initial substring which DOES match.
  293. */
  294. ++optname;
  295. if( matchchar )
  296. {
  297. /* did NOT match the entire argument to an initial substring
  298. * of a defined option name ...
  299. */
  300. if( matchchar != getopt_arg_assign )
  301. /*
  302. * ... and didn't stop at an `=' internal field separator,
  303. * so this is NOT a possible match.
  304. */
  305. return getopt_no_match;
  306. /* DID stop at an `=' internal field separator,
  307. * so this IS a possible match, and what follows is an
  308. * argument to the possibly matched option.
  309. */
  310. optarg = (char *)(nextchar);
  311. }
  312. return *optname
  313. /*
  314. * if we DIDN'T match the ENTIRE text of the option name,
  315. * then it's a possible abbreviated match ...
  316. */
  317. ? getopt_abbreviated_match
  318. /*
  319. * but if we DID match the entire option name,
  320. * then it's a DEFINITE EXACT match.
  321. */
  322. : getopt_exact_match;
  323. }
  324. static
  325. int getopt_resolved( int mode, int argc, CHAR *const *argv, int *argind,
  326. struct option *opt, int index, int *retindex, const CHAR *optstring )
  327. {
  328. /* Helper function to establish appropriate return conditions,
  329. * on resolution of a long form option.
  330. */
  331. if( retindex != NULL )
  332. *retindex = index;
  333. /* On return, `optind' should normally refer to the argument, if any,
  334. * which follows the current one; it is convenient to set this, before
  335. * checking for the presence of any `optarg'.
  336. */
  337. optind = *argind + 1;
  338. if( optarg && (opt[index].has_arg == no_argument) )
  339. /*
  340. * it is an error for the user to specify an option specific argument
  341. * with an option which doesn't expect one!
  342. */
  343. return getopt_argerror( mode, "option `%s%s' doesn't accept an argument\n",
  344. PROGNAME, opt + index, getopt_unknown );
  345. else if( (optarg == NULL) && (opt[index].has_arg == required_argument) )
  346. {
  347. /* similarly, it is an error if no argument is specified
  348. * with an option which requires one ...
  349. */
  350. if( optind < argc )
  351. /*
  352. * ... except that the requirement may be satisfied from
  353. * the following command line argument, if any ...
  354. */
  355. optarg = argv[*argind = optind++];
  356. else
  357. /* so fail this case, only if no such argument exists!
  358. */
  359. return getopt_argerror( mode, "option `%s%s' requires an argument\n",
  360. PROGNAME, opt + index, getopt_missing_arg( optstring ) );
  361. }
  362. /* when the caller has provided a return buffer ...
  363. */
  364. if( opt[index].flag != NULL )
  365. {
  366. /* ... then we place the proper return value there,
  367. * and return a status code of zero ...
  368. */
  369. *(opt[index].flag) = opt[index].val;
  370. return 0;
  371. }
  372. /* ... otherwise, the return value becomes the status code.
  373. */
  374. return opt[index].val;
  375. }
  376. static
  377. int getopt_verify( const CHAR *nextchar, const CHAR *optstring )
  378. {
  379. /* Helper function, called by getopt_parse() when invoked
  380. * by getopt_long_only(), to verify when an unmatched or an
  381. * ambiguously matched long form option string is valid as
  382. * a short form option specification.
  383. */
  384. if( ! (nextchar && *nextchar && optstring && *optstring) )
  385. /*
  386. * There are no characters to be matched, or there are no
  387. * valid short form option characters to which they can be
  388. * matched, so this can never be valid.
  389. */
  390. return 0;
  391. while( *nextchar )
  392. {
  393. /* For each command line character in turn ...
  394. */
  395. const CHAR *test;
  396. if( (test = getopt_match( *nextchar++, optstring )) == NULL )
  397. /*
  398. * ... there is no short form option to match the current
  399. * candidate, so the entire argument fails.
  400. */
  401. return 0;
  402. if( test[1] == getopt_takes_argument )
  403. /*
  404. * The current candidate is valid, and it matches an option
  405. * which takes an argument, so this command line argument is
  406. * a valid short form option specification; accept it.
  407. */
  408. return 1;
  409. }
  410. /* If we get to here, then every character in the command line
  411. * argument was valid as a short form option; accept it.
  412. */
  413. return 1;
  414. }
  415. static
  416. #define getopt_std_args int argc, CHAR *const argv[], const CHAR *optstring
  417. int getopt_parse( int mode, getopt_std_args, ... )
  418. {
  419. /* Common core implementation for ALL `getopt' functions.
  420. */
  421. static int argind = 0;
  422. static int optbase = 0;
  423. static const CHAR *nextchar = NULL;
  424. static int optmark = 0;
  425. if( (optreset |= (optind < 1)) || (optind < optbase) )
  426. {
  427. /* POSIX does not prescribe any definitive mechanism for restarting
  428. * a `getopt' scan, but some applications may require such capability.
  429. * We will support it, by allowing the caller to adjust the value of
  430. * `optind' downwards, (nominally setting it to zero). Since POSIX
  431. * wants `optind' to have an initial value of one, but we want all
  432. * of our internal place holders to be initialised to zero, when we
  433. * are called for the first time, we will handle such a reset by
  434. * adjusting all of the internal place holders to one less than
  435. * the adjusted `optind' value, (but never to less than zero).
  436. */
  437. if( optreset )
  438. {
  439. /* User has explicitly requested reinitialisation...
  440. * We need to reset `optind' to it's normal initial value of 1,
  441. * to avoid a potential infinitely recursive loop; by doing this
  442. * up front, we also ensure that the remaining place holders
  443. * will be correctly reinitialised to no less than zero.
  444. */
  445. optind = 1;
  446. /* We also need to clear the `optreset' request...
  447. */
  448. optreset = 0;
  449. }
  450. /* Now, we may safely reinitialise the internal place holders, to
  451. * one less than `optind', without fear of making them negative.
  452. */
  453. optmark = optbase = argind = optind - 1;
  454. nextchar = NULL;
  455. }
  456. /* From a POSIX perspective, the following is `undefined behaviour';
  457. * we implement it thus, for compatibility with GNU and BSD getopt.
  458. */
  459. else if( optind > (argind + 1) )
  460. {
  461. /* Some applications expect to be able to manipulate `optind',
  462. * causing `getopt' to skip over one or more elements of `argv';
  463. * POSIX doesn't require us to support this brain-damaged concept;
  464. * (indeed, POSIX defines no particular behaviour, in the event of
  465. * such usage, so it must be considered a bug for an application
  466. * to rely on any particular outcome); nonetheless, Mac-OS-X and
  467. * BSD actually provide *documented* support for this capability,
  468. * so we ensure that our internal place holders keep track of
  469. * external `optind' increments; (`argind' must lag by one).
  470. */
  471. argind = optind - 1;
  472. /* When `optind' is misused, in this fashion, we also abandon any
  473. * residual text in the argument we had been parsing; this is done
  474. * without any further processing of such abandoned text, assuming
  475. * that the caller is equipped to handle it appropriately.
  476. */
  477. nextchar = NULL;
  478. }
  479. if( nextchar && *nextchar )
  480. {
  481. /* we are parsing a standard, or short format, option argument ...
  482. */
  483. const CHAR *optchar;
  484. if( (optchar = getopt_match( optopt = *nextchar++, optstring )) != NULL )
  485. {
  486. /* we have identified it as valid ...
  487. */
  488. if( optchar[1] == getopt_takes_argument )
  489. {
  490. /* and determined that it requires an associated argument ...
  491. */
  492. if( ! *(optarg = (char *)(nextchar)) )
  493. {
  494. /* the argument is NOT attached ...
  495. */
  496. if( optchar[2] == getopt_takes_argument )
  497. /*
  498. * but this GNU extension marks it as optional,
  499. * so we don't provide one on this occasion.
  500. */
  501. optarg = NULL;
  502. /* otherwise this option takes a mandatory argument,
  503. * so, provided there is one available ...
  504. */
  505. else if( (argc - argind) > 1 )
  506. /*
  507. * we take the following command line argument,
  508. * as the appropriate option argument.
  509. */
  510. optarg = argv[++argind];
  511. /* but if no further argument is available,
  512. * then there is nothing we can do, except for
  513. * issuing the requisite diagnostic message.
  514. */
  515. else
  516. {
  517. complain( "option requires an argument -- %c", optopt );
  518. return getopt_missing_arg( optstring );
  519. }
  520. }
  521. optind = argind + 1;
  522. nextchar = NULL;
  523. }
  524. else
  525. optarg = NULL;
  526. optind = (nextchar && *nextchar) ? argind : argind + 1;
  527. return optopt;
  528. }
  529. /* if we didn't find a valid match for the specified option character,
  530. * then we fall through to here, so take appropriate diagnostic action.
  531. */
  532. if( mode == getopt_mode_long_only )
  533. {
  534. complain( "unrecognised option `-%s'", --nextchar );
  535. nextchar = NULL;
  536. optopt = 0;
  537. }
  538. else
  539. complain( "invalid option -- %c", optopt );
  540. optind = (nextchar && *nextchar) ? argind : argind + 1;
  541. return getopt_unknown;
  542. }
  543. if( optmark > optbase )
  544. {
  545. /* This can happen, in GNU parsing mode ONLY, when we have
  546. * skipped over non-option arguments, and found a subsequent
  547. * option argument; in this case we permute the arguments.
  548. */
  549. int index;
  550. /*
  551. * `optspan' specifies the number of contiguous arguments
  552. * which are spanned by the current option, and so must be
  553. * moved together during permutation.
  554. */
  555. const int optspan = argind - optmark + 1;
  556. /*
  557. * we use `this_arg' to store these temporarily.
  558. */
  559. CHAR **this_arg = malloc(sizeof(CHAR*) * optspan);
  560. /*
  561. * we cannot manipulate `argv' directly, since the `getopt'
  562. * API prototypes it as `read-only'; this cast to `arglist'
  563. * allows us to work around that restriction.
  564. */
  565. CHAR **arglist = (char **)(argv);
  566. /* save temporary copies of the arguments which are associated
  567. * with the current option ...
  568. */
  569. for( index = 0; index < optspan; ++index )
  570. this_arg[index] = arglist[optmark + index];
  571. /* move all preceding non-option arguments to the right,
  572. * overwriting these saved arguments, while making space
  573. * to replace them in their permuted location.
  574. */
  575. for( --optmark; optmark >= optbase; --optmark )
  576. arglist[optmark + optspan] = arglist[optmark];
  577. /* restore the temporarily saved option arguments to
  578. * their permuted location.
  579. */
  580. for( index = 0; index < optspan; ++index )
  581. arglist[optbase + index] = this_arg[index];
  582. /* adjust `optbase', to account for the relocated option.
  583. */
  584. optbase += optspan;
  585. free(this_arg);
  586. }
  587. else
  588. /* no permutation occurred ...
  589. * simply adjust `optbase' for all options parsed so far.
  590. */
  591. optbase = argind + 1;
  592. /* enter main parsing loop ...
  593. */
  594. while( argc > ++argind )
  595. {
  596. /* inspect each argument in turn, identifying possible options ...
  597. */
  598. if( is_switchar( *(nextchar = argv[optmark = argind]) ) && *++nextchar )
  599. {
  600. /* we've found a candidate option argument ... */
  601. if( is_switchar( *nextchar ) )
  602. {
  603. /* it's a double hyphen argument ... */
  604. const CHAR *refchar = nextchar;
  605. if( *++refchar )
  606. {
  607. /* and it looks like a long format option ...
  608. * `getopt_long' mode must be active to accept it as such,
  609. * `getopt_long_only' also qualifies, but we must downgrade
  610. * it to force explicit handling as a long format option.
  611. */
  612. if( mode >= getopt_mode_long )
  613. {
  614. nextchar = refchar;
  615. mode = getopt_mode_long;
  616. }
  617. }
  618. else
  619. {
  620. /* this is an explicit `--' end of options marker, so wrap up now!
  621. */
  622. if( optmark > optbase )
  623. {
  624. /* permuting the argument list as necessary ...
  625. * (note use of `this_arg' and `arglist', as above).
  626. */
  627. CHAR *this_arg = argv[optmark];
  628. CHAR **arglist = (CHAR **)(argv);
  629. /* move all preceding non-option arguments to the right ...
  630. */
  631. do arglist[optmark] = arglist[optmark - 1];
  632. while( optmark-- > optbase );
  633. /* reinstate the `--' marker, in its permuted location.
  634. */
  635. arglist[optbase] = this_arg;
  636. }
  637. /* ... before finally bumping `optbase' past the `--' marker,
  638. * and returning the `all done' completion indicator.
  639. */
  640. optind = ++optbase;
  641. return getopt_all_done;
  642. }
  643. }
  644. else if( mode < getopt_mode_long_only )
  645. {
  646. /* it's not an explicit long option, and `getopt_long_only' isn't active,
  647. * so we must explicitly try to match it as a short option.
  648. */
  649. mode = getopt_mode_standard;
  650. }
  651. if( mode >= getopt_mode_long )
  652. {
  653. /* the current argument is a long form option, (either explicitly,
  654. * introduced by a double hyphen, or implicitly because we were called
  655. * by `getopt_long_only'); this is where we parse it.
  656. */
  657. int lookup;
  658. int matched = -1;
  659. /* we need to fetch the `extra' function arguments, which are
  660. * specified for the `getopt_long' APIs.
  661. */
  662. va_list refptr;
  663. struct option *longopts;
  664. int *optindex;
  665. va_start( refptr, optstring );
  666. longopts = va_arg( refptr, struct option * );
  667. optindex = va_arg( refptr, int * );
  668. va_end( refptr );
  669. /* ensuring that `optarg' does not inherit any junk, from parsing
  670. * preceding arguments ...
  671. */
  672. optarg = NULL;
  673. for( lookup = 0; longopts && longopts[lookup].name; ++lookup )
  674. {
  675. /* scan the list of defined long form options ...
  676. */
  677. switch( getopt_match_long( nextchar, longopts[lookup].name ) )
  678. {
  679. /* looking for possible matches for the current argument.
  680. */
  681. case getopt_exact_match:
  682. /*
  683. * when an exact match is found,
  684. * return it immediately, setting `nextchar' to NULL,
  685. * to ensure we don't mistakenly try to match any
  686. * subsequent characters as short form options.
  687. */
  688. nextchar = NULL;
  689. return getopt_resolved( mode, argc, argv, &argind,
  690. longopts, lookup, optindex, optstring );
  691. case getopt_abbreviated_match:
  692. /*
  693. * but, for a partial (initial substring) match ...
  694. */
  695. if( matched >= 0 )
  696. {
  697. /* if this is not the first, then we have an ambiguity ...
  698. */
  699. if( (mode == getopt_mode_long_only)
  700. /*
  701. * However, in the case of getopt_long_only(), if
  702. * the entire ambiguously matched string represents
  703. * a valid short option specification, then we may
  704. * proceed to interpret it as such.
  705. */
  706. && getopt_verify( nextchar, optstring ) )
  707. return getopt_parse( mode, argc, argv, optstring );
  708. /* If we get to here, then the ambiguously matched
  709. * partial long option isn't valid for short option
  710. * evaluation; reset parser context to resume with
  711. * the following command line argument, diagnose
  712. * ambiguity, and bail out.
  713. */
  714. optopt = 0;
  715. nextchar = NULL;
  716. optind = argind + 1;
  717. complain( "option `%s' is ambiguous", argv[argind] );
  718. return getopt_unknown;
  719. }
  720. /* otherwise just note that we've found a possible match ...
  721. */
  722. matched = lookup;
  723. }
  724. }
  725. if( matched >= 0 )
  726. {
  727. /* if we get to here, then we found exactly one partial match,
  728. * so return it, as for an exact match.
  729. */
  730. nextchar = NULL;
  731. return getopt_resolved( mode, argc, argv, &argind,
  732. longopts, matched, optindex, optstring );
  733. }
  734. /* if here, then we had what SHOULD have been a long form option,
  735. * but it is unmatched ...
  736. */
  737. if( (mode < getopt_mode_long_only)
  738. /*
  739. * ... although paradoxically, `mode == getopt_mode_long_only'
  740. * allows us to still try to match it as a short form option.
  741. */
  742. || (getopt_verify( nextchar, optstring ) == 0) )
  743. {
  744. /* When it cannot be matched, reset the parsing context to
  745. * resume from the next argument, diagnose the failed match,
  746. * and bail out.
  747. */
  748. optopt = 0;
  749. nextchar = NULL;
  750. optind = argind + 1;
  751. complain( "unrecognised option `%s'", argv[argind] );
  752. return getopt_unknown;
  753. }
  754. }
  755. /* fall through to handle standard short form options...
  756. * when the option argument format is neither explictly identified
  757. * as long, nor implicitly matched as such, and the argument isn't
  758. * just a bare hyphen, (which isn't an option), then we make one
  759. * recursive call to explicitly interpret it as short format.
  760. */
  761. if( *nextchar )
  762. return getopt_parse( mode, argc, argv, optstring );
  763. }
  764. /* if we get to here, then we've parsed a non-option argument ...
  765. * in GNU compatibility mode, we step over it, so we can permute
  766. * any subsequent option arguments, but ...
  767. */
  768. if( *optstring == getopt_switchar )
  769. {
  770. /* if `optstring' begins with a `-' character, this special
  771. * GNU specific behaviour requires us to return the non-option
  772. * arguments in strict order, as pseudo-arguments to a special
  773. * option, with return value defined as `getopt_ordered'.
  774. */
  775. nextchar = NULL;
  776. optind = argind + 1;
  777. optarg = argv[argind];
  778. return getopt_ordered;
  779. }
  780. if( getopt_conventions( *optstring ) & getopt_posixly_correct )
  781. /*
  782. * otherwise ...
  783. * for POSIXLY_CORRECT behaviour, or if `optstring' begins with
  784. * a `+' character, then we break out of the parsing loop, so that
  785. * the scan ends at the current argument, with no permutation.
  786. */
  787. break;
  788. }
  789. /* fall through when all arguments have been evaluated,
  790. */
  791. optind = optbase;
  792. return getopt_all_done;
  793. }
  794. /* All three public API entry points are trivially defined,
  795. * in terms of the internal `getopt_parse' function.
  796. */
  797. int getopt( getopt_std_args )
  798. {
  799. return getopt_parse( getopt_mode_standard, argc, argv, optstring );
  800. }
  801. int getopt_long( getopt_std_args, const struct option *opts, int *index )
  802. {
  803. return getopt_parse( getopt_mode_long, argc, argv, optstring, opts, index );
  804. }
  805. int getopt_long_only( getopt_std_args, const struct option *opts, int *index )
  806. {
  807. return getopt_parse( getopt_mode_long_only, argc, argv, optstring, opts, index );
  808. }
  809. #ifdef __weak_alias
  810. /*
  811. * These Microsnot style uglified aliases are provided for compatibility
  812. * with the previous MinGW implementation of the getopt API.
  813. */
  814. __weak_alias( getopt, _getopt )
  815. __weak_alias( getopt_long, _getopt_long )
  816. __weak_alias( getopt_long_only, _getopt_long_only )
  817. #endif
  818. #ifdef __cplusplus
  819. }
  820. #endif
  821. #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */