getopt.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. /* Getopt for GNU.
  2. NOTE: getopt is part of the C library, so if you don't know what
  3. "Keep this file name-space clean" means, talk to drepper@gnu.org
  4. before changing it!
  5. Copyright (C) 1987-1996, 1998-2004, 2006, 2008-2013 Free Software
  6. Foundation, Inc.
  7. This file is part of the GNU C Library.
  8. This program is free software: you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 3 of the License, or
  11. (at your option) any later version.
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. GNU General Public License for more details.
  16. You should have received a copy of the GNU General Public License
  17. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  18. #ifndef _LIBC
  19. # include <config.h>
  20. #endif
  21. #include "getopt.h"
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <unistd.h>
  26. #ifdef _LIBC
  27. # include <libintl.h>
  28. #else
  29. # include "gettext.h"
  30. # define _(msgid) gettext (msgid)
  31. #endif
  32. #if defined _LIBC && defined USE_IN_LIBIO
  33. # include <wchar.h>
  34. #endif
  35. /* This version of 'getopt' appears to the caller like standard Unix 'getopt'
  36. but it behaves differently for the user, since it allows the user
  37. to intersperse the options with the other arguments.
  38. As 'getopt_long' works, it permutes the elements of ARGV so that,
  39. when it is done, all the options precede everything else. Thus
  40. all application programs are extended to handle flexible argument order.
  41. Using 'getopt' or setting the environment variable POSIXLY_CORRECT
  42. disables permutation.
  43. Then the behavior is completely standard.
  44. GNU application programs can use a third alternative mode in which
  45. they can distinguish the relative order of options and other arguments. */
  46. #include "getopt_int.h"
  47. /* For communication from 'getopt' to the caller.
  48. When 'getopt' finds an option that takes an argument,
  49. the argument value is returned here.
  50. Also, when 'ordering' is RETURN_IN_ORDER,
  51. each non-option ARGV-element is returned here. */
  52. char *optarg;
  53. /* Index in ARGV of the next element to be scanned.
  54. This is used for communication to and from the caller
  55. and for communication between successive calls to 'getopt'.
  56. On entry to 'getopt', zero means this is the first call; initialize.
  57. When 'getopt' returns -1, this is the index of the first of the
  58. non-option elements that the caller should itself scan.
  59. Otherwise, 'optind' communicates from one call to the next
  60. how much of ARGV has been scanned so far. */
  61. /* 1003.2 says this must be 1 before any call. */
  62. int optind = 1;
  63. /* Callers store zero here to inhibit the error message
  64. for unrecognized options. */
  65. int opterr = 1;
  66. /* Set to an option character which was unrecognized.
  67. This must be initialized on some systems to avoid linking in the
  68. system's own getopt implementation. */
  69. int optopt = '?';
  70. /* Keep a global copy of all internal members of getopt_data. */
  71. static struct _getopt_data getopt_data;
  72. #if defined HAVE_DECL_GETENV && !HAVE_DECL_GETENV
  73. extern char *getenv ();
  74. #endif
  75. #ifdef _LIBC
  76. /* Stored original parameters.
  77. XXX This is no good solution. We should rather copy the args so
  78. that we can compare them later. But we must not use malloc(3). */
  79. extern int __libc_argc;
  80. extern char **__libc_argv;
  81. /* Bash 2.0 gives us an environment variable containing flags
  82. indicating ARGV elements that should not be considered arguments. */
  83. # ifdef USE_NONOPTION_FLAGS
  84. /* Defined in getopt_init.c */
  85. extern char *__getopt_nonoption_flags;
  86. # endif
  87. # ifdef USE_NONOPTION_FLAGS
  88. # define SWAP_FLAGS(ch1, ch2) \
  89. if (d->__nonoption_flags_len > 0) \
  90. { \
  91. char __tmp = __getopt_nonoption_flags[ch1]; \
  92. __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
  93. __getopt_nonoption_flags[ch2] = __tmp; \
  94. }
  95. # else
  96. # define SWAP_FLAGS(ch1, ch2)
  97. # endif
  98. #else /* !_LIBC */
  99. # define SWAP_FLAGS(ch1, ch2)
  100. #endif /* _LIBC */
  101. /* Exchange two adjacent subsequences of ARGV.
  102. One subsequence is elements [first_nonopt,last_nonopt)
  103. which contains all the non-options that have been skipped so far.
  104. The other is elements [last_nonopt,optind), which contains all
  105. the options processed since those non-options were skipped.
  106. 'first_nonopt' and 'last_nonopt' are relocated so that they describe
  107. the new indices of the non-options in ARGV after they are moved. */
  108. static void
  109. exchange (char **argv, struct _getopt_data *d)
  110. {
  111. int bottom = d->__first_nonopt;
  112. int middle = d->__last_nonopt;
  113. int top = d->optind;
  114. char *tem;
  115. /* Exchange the shorter segment with the far end of the longer segment.
  116. That puts the shorter segment into the right place.
  117. It leaves the longer segment in the right place overall,
  118. but it consists of two parts that need to be swapped next. */
  119. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  120. /* First make sure the handling of the '__getopt_nonoption_flags'
  121. string can work normally. Our top argument must be in the range
  122. of the string. */
  123. if (d->__nonoption_flags_len > 0 && top >= d->__nonoption_flags_max_len)
  124. {
  125. /* We must extend the array. The user plays games with us and
  126. presents new arguments. */
  127. char *new_str = malloc (top + 1);
  128. if (new_str == NULL)
  129. d->__nonoption_flags_len = d->__nonoption_flags_max_len = 0;
  130. else
  131. {
  132. memset (__mempcpy (new_str, __getopt_nonoption_flags,
  133. d->__nonoption_flags_max_len),
  134. '\0', top + 1 - d->__nonoption_flags_max_len);
  135. d->__nonoption_flags_max_len = top + 1;
  136. __getopt_nonoption_flags = new_str;
  137. }
  138. }
  139. #endif
  140. while (top > middle && middle > bottom)
  141. {
  142. if (top - middle > middle - bottom)
  143. {
  144. /* Bottom segment is the short one. */
  145. int len = middle - bottom;
  146. int i;
  147. /* Swap it with the top part of the top segment. */
  148. for (i = 0; i < len; i++)
  149. {
  150. tem = argv[bottom + i];
  151. argv[bottom + i] = argv[top - (middle - bottom) + i];
  152. argv[top - (middle - bottom) + i] = tem;
  153. SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  154. }
  155. /* Exclude the moved bottom segment from further swapping. */
  156. top -= len;
  157. }
  158. else
  159. {
  160. /* Top segment is the short one. */
  161. int len = top - middle;
  162. int i;
  163. /* Swap it with the bottom part of the bottom segment. */
  164. for (i = 0; i < len; i++)
  165. {
  166. tem = argv[bottom + i];
  167. argv[bottom + i] = argv[middle + i];
  168. argv[middle + i] = tem;
  169. SWAP_FLAGS (bottom + i, middle + i);
  170. }
  171. /* Exclude the moved top segment from further swapping. */
  172. bottom += len;
  173. }
  174. }
  175. /* Update records for the slots the non-options now occupy. */
  176. d->__first_nonopt += (d->optind - d->__last_nonopt);
  177. d->__last_nonopt = d->optind;
  178. }
  179. /* Initialize the internal data when the first call is made. */
  180. static const char *
  181. _getopt_initialize (int argc _GL_UNUSED,
  182. char **argv _GL_UNUSED, const char *optstring,
  183. struct _getopt_data *d, int posixly_correct)
  184. {
  185. /* Start processing options with ARGV-element 1 (since ARGV-element 0
  186. is the program name); the sequence of previously skipped
  187. non-option ARGV-elements is empty. */
  188. d->__first_nonopt = d->__last_nonopt = d->optind;
  189. d->__nextchar = NULL;
  190. d->__posixly_correct = posixly_correct || !!getenv ("POSIXLY_CORRECT");
  191. /* Determine how to handle the ordering of options and nonoptions. */
  192. if (optstring[0] == '-')
  193. {
  194. d->__ordering = RETURN_IN_ORDER;
  195. ++optstring;
  196. }
  197. else if (optstring[0] == '+')
  198. {
  199. d->__ordering = REQUIRE_ORDER;
  200. ++optstring;
  201. }
  202. else if (d->__posixly_correct)
  203. d->__ordering = REQUIRE_ORDER;
  204. else
  205. d->__ordering = PERMUTE;
  206. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  207. if (!d->__posixly_correct
  208. && argc == __libc_argc && argv == __libc_argv)
  209. {
  210. if (d->__nonoption_flags_max_len == 0)
  211. {
  212. if (__getopt_nonoption_flags == NULL
  213. || __getopt_nonoption_flags[0] == '\0')
  214. d->__nonoption_flags_max_len = -1;
  215. else
  216. {
  217. const char *orig_str = __getopt_nonoption_flags;
  218. int len = d->__nonoption_flags_max_len = strlen (orig_str);
  219. if (d->__nonoption_flags_max_len < argc)
  220. d->__nonoption_flags_max_len = argc;
  221. __getopt_nonoption_flags =
  222. (char *) malloc (d->__nonoption_flags_max_len);
  223. if (__getopt_nonoption_flags == NULL)
  224. d->__nonoption_flags_max_len = -1;
  225. else
  226. memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
  227. '\0', d->__nonoption_flags_max_len - len);
  228. }
  229. }
  230. d->__nonoption_flags_len = d->__nonoption_flags_max_len;
  231. }
  232. else
  233. d->__nonoption_flags_len = 0;
  234. #endif
  235. return optstring;
  236. }
  237. /* Scan elements of ARGV (whose length is ARGC) for option characters
  238. given in OPTSTRING.
  239. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  240. then it is an option element. The characters of this element
  241. (aside from the initial '-') are option characters. If 'getopt'
  242. is called repeatedly, it returns successively each of the option characters
  243. from each of the option elements.
  244. If 'getopt' finds another option character, it returns that character,
  245. updating 'optind' and 'nextchar' so that the next call to 'getopt' can
  246. resume the scan with the following option character or ARGV-element.
  247. If there are no more option characters, 'getopt' returns -1.
  248. Then 'optind' is the index in ARGV of the first ARGV-element
  249. that is not an option. (The ARGV-elements have been permuted
  250. so that those that are not options now come last.)
  251. OPTSTRING is a string containing the legitimate option characters.
  252. If an option character is seen that is not listed in OPTSTRING,
  253. return '?' after printing an error message. If you set 'opterr' to
  254. zero, the error message is suppressed but we still return '?'.
  255. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  256. so the following text in the same ARGV-element, or the text of the following
  257. ARGV-element, is returned in 'optarg'. Two colons mean an option that
  258. wants an optional arg; if there is text in the current ARGV-element,
  259. it is returned in 'optarg', otherwise 'optarg' is set to zero.
  260. If OPTSTRING starts with '-' or '+', it requests different methods of
  261. handling the non-option ARGV-elements.
  262. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  263. Long-named options begin with '--' instead of '-'.
  264. Their names may be abbreviated as long as the abbreviation is unique
  265. or is an exact match for some defined option. If they have an
  266. argument, it follows the option name in the same ARGV-element, separated
  267. from the option name by a '=', or else the in next ARGV-element.
  268. When 'getopt' finds a long-named option, it returns 0 if that option's
  269. 'flag' field is nonzero, the value of the option's 'val' field
  270. if the 'flag' field is zero.
  271. The elements of ARGV aren't really const, because we permute them.
  272. But we pretend they're const in the prototype to be compatible
  273. with other systems.
  274. LONGOPTS is a vector of 'struct option' terminated by an
  275. element containing a name which is zero.
  276. LONGIND returns the index in LONGOPT of the long-named option found.
  277. It is only valid when a long-named option has been found by the most
  278. recent call.
  279. If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  280. long-named options. */
  281. int
  282. _getopt_internal_r (int argc, char **argv, const char *optstring,
  283. const struct option *longopts, int *longind,
  284. int long_only, struct _getopt_data *d, int posixly_correct)
  285. {
  286. int print_errors = d->opterr;
  287. if (argc < 1)
  288. return -1;
  289. d->optarg = NULL;
  290. if (d->optind == 0 || !d->__initialized)
  291. {
  292. if (d->optind == 0)
  293. d->optind = 1; /* Don't scan ARGV[0], the program name. */
  294. optstring = _getopt_initialize (argc, argv, optstring, d,
  295. posixly_correct);
  296. d->__initialized = 1;
  297. }
  298. else if (optstring[0] == '-' || optstring[0] == '+')
  299. optstring++;
  300. if (optstring[0] == ':')
  301. print_errors = 0;
  302. /* Test whether ARGV[optind] points to a non-option argument.
  303. Either it does not have option syntax, or there is an environment flag
  304. from the shell indicating it is not an option. The later information
  305. is only used when the used in the GNU libc. */
  306. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  307. # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0' \
  308. || (d->optind < d->__nonoption_flags_len \
  309. && __getopt_nonoption_flags[d->optind] == '1'))
  310. #else
  311. # define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
  312. #endif
  313. if (d->__nextchar == NULL || *d->__nextchar == '\0')
  314. {
  315. /* Advance to the next ARGV-element. */
  316. /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  317. moved back by the user (who may also have changed the arguments). */
  318. if (d->__last_nonopt > d->optind)
  319. d->__last_nonopt = d->optind;
  320. if (d->__first_nonopt > d->optind)
  321. d->__first_nonopt = d->optind;
  322. if (d->__ordering == PERMUTE)
  323. {
  324. /* If we have just processed some options following some non-options,
  325. exchange them so that the options come first. */
  326. if (d->__first_nonopt != d->__last_nonopt
  327. && d->__last_nonopt != d->optind)
  328. exchange ((char **) argv, d);
  329. else if (d->__last_nonopt != d->optind)
  330. d->__first_nonopt = d->optind;
  331. /* Skip any additional non-options
  332. and extend the range of non-options previously skipped. */
  333. while (d->optind < argc && NONOPTION_P)
  334. d->optind++;
  335. d->__last_nonopt = d->optind;
  336. }
  337. /* The special ARGV-element '--' means premature end of options.
  338. Skip it like a null option,
  339. then exchange with previous non-options as if it were an option,
  340. then skip everything else like a non-option. */
  341. if (d->optind != argc && !strcmp (argv[d->optind], "--"))
  342. {
  343. d->optind++;
  344. if (d->__first_nonopt != d->__last_nonopt
  345. && d->__last_nonopt != d->optind)
  346. exchange ((char **) argv, d);
  347. else if (d->__first_nonopt == d->__last_nonopt)
  348. d->__first_nonopt = d->optind;
  349. d->__last_nonopt = argc;
  350. d->optind = argc;
  351. }
  352. /* If we have done all the ARGV-elements, stop the scan
  353. and back over any non-options that we skipped and permuted. */
  354. if (d->optind == argc)
  355. {
  356. /* Set the next-arg-index to point at the non-options
  357. that we previously skipped, so the caller will digest them. */
  358. if (d->__first_nonopt != d->__last_nonopt)
  359. d->optind = d->__first_nonopt;
  360. return -1;
  361. }
  362. /* If we have come to a non-option and did not permute it,
  363. either stop the scan or describe it to the caller and pass it by. */
  364. if (NONOPTION_P)
  365. {
  366. if (d->__ordering == REQUIRE_ORDER)
  367. return -1;
  368. d->optarg = argv[d->optind++];
  369. return 1;
  370. }
  371. /* We have found another option-ARGV-element.
  372. Skip the initial punctuation. */
  373. d->__nextchar = (argv[d->optind] + 1
  374. + (longopts != NULL && argv[d->optind][1] == '-'));
  375. }
  376. /* Decode the current option-ARGV-element. */
  377. /* Check whether the ARGV-element is a long option.
  378. If long_only and the ARGV-element has the form "-f", where f is
  379. a valid short option, don't consider it an abbreviated form of
  380. a long option that starts with f. Otherwise there would be no
  381. way to give the -f short option.
  382. On the other hand, if there's a long option "fubar" and
  383. the ARGV-element is "-fu", do consider that an abbreviation of
  384. the long option, just like "--fu", and not "-f" with arg "u".
  385. This distinction seems to be the most useful approach. */
  386. if (longopts != NULL
  387. && (argv[d->optind][1] == '-'
  388. || (long_only && (argv[d->optind][2]
  389. || !strchr (optstring, argv[d->optind][1])))))
  390. {
  391. char *nameend;
  392. unsigned int namelen;
  393. const struct option *p;
  394. const struct option *pfound = NULL;
  395. struct option_list
  396. {
  397. const struct option *p;
  398. struct option_list *next;
  399. } *ambig_list = NULL;
  400. int exact = 0;
  401. int indfound = -1;
  402. int option_index;
  403. for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
  404. /* Do nothing. */ ;
  405. namelen = nameend - d->__nextchar;
  406. /* Test all long options for either exact match
  407. or abbreviated matches. */
  408. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  409. if (!strncmp (p->name, d->__nextchar, namelen))
  410. {
  411. if (namelen == (unsigned int) strlen (p->name))
  412. {
  413. /* Exact match found. */
  414. pfound = p;
  415. indfound = option_index;
  416. exact = 1;
  417. break;
  418. }
  419. else if (pfound == NULL)
  420. {
  421. /* First nonexact match found. */
  422. pfound = p;
  423. indfound = option_index;
  424. }
  425. else if (long_only
  426. || pfound->has_arg != p->has_arg
  427. || pfound->flag != p->flag
  428. || pfound->val != p->val)
  429. {
  430. /* Second or later nonexact match found. */
  431. struct option_list *newp = malloc (sizeof (*newp));
  432. newp->p = p;
  433. newp->next = ambig_list;
  434. ambig_list = newp;
  435. }
  436. }
  437. if (ambig_list != NULL && !exact)
  438. {
  439. if (print_errors)
  440. {
  441. struct option_list first;
  442. first.p = pfound;
  443. first.next = ambig_list;
  444. ambig_list = &first;
  445. #if defined _LIBC && defined USE_IN_LIBIO
  446. char *buf = NULL;
  447. size_t buflen = 0;
  448. FILE *fp = open_memstream (&buf, &buflen);
  449. if (fp != NULL)
  450. {
  451. fprintf (fp,
  452. _("%s: option '%s' is ambiguous; possibilities:"),
  453. argv[0], argv[d->optind]);
  454. do
  455. {
  456. fprintf (fp, " '--%s'", ambig_list->p->name);
  457. ambig_list = ambig_list->next;
  458. }
  459. while (ambig_list != NULL);
  460. fputc_unlocked ('\n', fp);
  461. if (__builtin_expect (fclose (fp) != EOF, 1))
  462. {
  463. _IO_flockfile (stderr);
  464. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  465. ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
  466. __fxprintf (NULL, "%s", buf);
  467. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  468. _IO_funlockfile (stderr);
  469. free (buf);
  470. }
  471. }
  472. #else
  473. fprintf (stderr,
  474. _("%s: option '%s' is ambiguous; possibilities:"),
  475. argv[0], argv[d->optind]);
  476. do
  477. {
  478. fprintf (stderr, " '--%s'", ambig_list->p->name);
  479. ambig_list = ambig_list->next;
  480. }
  481. while (ambig_list != NULL);
  482. fputc ('\n', stderr);
  483. #endif
  484. }
  485. d->__nextchar += strlen (d->__nextchar);
  486. d->optind++;
  487. d->optopt = 0;
  488. return '?';
  489. }
  490. while (ambig_list != NULL)
  491. {
  492. struct option_list *pn = ambig_list->next;
  493. free (ambig_list);
  494. ambig_list = pn;
  495. }
  496. if (pfound != NULL)
  497. {
  498. option_index = indfound;
  499. d->optind++;
  500. if (*nameend)
  501. {
  502. /* Don't test has_arg with >, because some C compilers don't
  503. allow it to be used on enums. */
  504. if (pfound->has_arg)
  505. d->optarg = nameend + 1;
  506. else
  507. {
  508. if (print_errors)
  509. {
  510. #if defined _LIBC && defined USE_IN_LIBIO
  511. char *buf;
  512. int n;
  513. #endif
  514. if (argv[d->optind - 1][1] == '-')
  515. {
  516. /* --option */
  517. #if defined _LIBC && defined USE_IN_LIBIO
  518. n = __asprintf (&buf, _("\
  519. %s: option '--%s' doesn't allow an argument\n"),
  520. argv[0], pfound->name);
  521. #else
  522. fprintf (stderr, _("\
  523. %s: option '--%s' doesn't allow an argument\n"),
  524. argv[0], pfound->name);
  525. #endif
  526. }
  527. else
  528. {
  529. /* +option or -option */
  530. #if defined _LIBC && defined USE_IN_LIBIO
  531. n = __asprintf (&buf, _("\
  532. %s: option '%c%s' doesn't allow an argument\n"),
  533. argv[0], argv[d->optind - 1][0],
  534. pfound->name);
  535. #else
  536. fprintf (stderr, _("\
  537. %s: option '%c%s' doesn't allow an argument\n"),
  538. argv[0], argv[d->optind - 1][0],
  539. pfound->name);
  540. #endif
  541. }
  542. #if defined _LIBC && defined USE_IN_LIBIO
  543. if (n >= 0)
  544. {
  545. _IO_flockfile (stderr);
  546. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  547. ((_IO_FILE *) stderr)->_flags2
  548. |= _IO_FLAGS2_NOTCANCEL;
  549. __fxprintf (NULL, "%s", buf);
  550. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  551. _IO_funlockfile (stderr);
  552. free (buf);
  553. }
  554. #endif
  555. }
  556. d->__nextchar += strlen (d->__nextchar);
  557. d->optopt = pfound->val;
  558. return '?';
  559. }
  560. }
  561. else if (pfound->has_arg == 1)
  562. {
  563. if (d->optind < argc)
  564. d->optarg = argv[d->optind++];
  565. else
  566. {
  567. if (print_errors)
  568. {
  569. #if defined _LIBC && defined USE_IN_LIBIO
  570. char *buf;
  571. if (__asprintf (&buf, _("\
  572. %s: option '--%s' requires an argument\n"),
  573. argv[0], pfound->name) >= 0)
  574. {
  575. _IO_flockfile (stderr);
  576. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  577. ((_IO_FILE *) stderr)->_flags2
  578. |= _IO_FLAGS2_NOTCANCEL;
  579. __fxprintf (NULL, "%s", buf);
  580. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  581. _IO_funlockfile (stderr);
  582. free (buf);
  583. }
  584. #else
  585. fprintf (stderr,
  586. _("%s: option '--%s' requires an argument\n"),
  587. argv[0], pfound->name);
  588. #endif
  589. }
  590. d->__nextchar += strlen (d->__nextchar);
  591. d->optopt = pfound->val;
  592. return optstring[0] == ':' ? ':' : '?';
  593. }
  594. }
  595. d->__nextchar += strlen (d->__nextchar);
  596. if (longind != NULL)
  597. *longind = option_index;
  598. if (pfound->flag)
  599. {
  600. *(pfound->flag) = pfound->val;
  601. return 0;
  602. }
  603. return pfound->val;
  604. }
  605. /* Can't find it as a long option. If this is not getopt_long_only,
  606. or the option starts with '--' or is not a valid short
  607. option, then it's an error.
  608. Otherwise interpret it as a short option. */
  609. if (!long_only || argv[d->optind][1] == '-'
  610. || strchr (optstring, *d->__nextchar) == NULL)
  611. {
  612. if (print_errors)
  613. {
  614. #if defined _LIBC && defined USE_IN_LIBIO
  615. char *buf;
  616. int n;
  617. #endif
  618. if (argv[d->optind][1] == '-')
  619. {
  620. /* --option */
  621. #if defined _LIBC && defined USE_IN_LIBIO
  622. n = __asprintf (&buf, _("%s: unrecognized option '--%s'\n"),
  623. argv[0], d->__nextchar);
  624. #else
  625. fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
  626. argv[0], d->__nextchar);
  627. #endif
  628. }
  629. else
  630. {
  631. /* +option or -option */
  632. #if defined _LIBC && defined USE_IN_LIBIO
  633. n = __asprintf (&buf, _("%s: unrecognized option '%c%s'\n"),
  634. argv[0], argv[d->optind][0], d->__nextchar);
  635. #else
  636. fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
  637. argv[0], argv[d->optind][0], d->__nextchar);
  638. #endif
  639. }
  640. #if defined _LIBC && defined USE_IN_LIBIO
  641. if (n >= 0)
  642. {
  643. _IO_flockfile (stderr);
  644. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  645. ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
  646. __fxprintf (NULL, "%s", buf);
  647. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  648. _IO_funlockfile (stderr);
  649. free (buf);
  650. }
  651. #endif
  652. }
  653. d->__nextchar = (char *) "";
  654. d->optind++;
  655. d->optopt = 0;
  656. return '?';
  657. }
  658. }
  659. /* Look at and handle the next short option-character. */
  660. {
  661. char c = *d->__nextchar++;
  662. const char *temp = strchr (optstring, c);
  663. /* Increment 'optind' when we start to process its last character. */
  664. if (*d->__nextchar == '\0')
  665. ++d->optind;
  666. if (temp == NULL || c == ':' || c == ';')
  667. {
  668. if (print_errors)
  669. {
  670. #if defined _LIBC && defined USE_IN_LIBIO
  671. char *buf;
  672. int n;
  673. #endif
  674. #if defined _LIBC && defined USE_IN_LIBIO
  675. n = __asprintf (&buf, _("%s: invalid option -- '%c'\n"),
  676. argv[0], c);
  677. #else
  678. fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
  679. #endif
  680. #if defined _LIBC && defined USE_IN_LIBIO
  681. if (n >= 0)
  682. {
  683. _IO_flockfile (stderr);
  684. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  685. ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
  686. __fxprintf (NULL, "%s", buf);
  687. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  688. _IO_funlockfile (stderr);
  689. free (buf);
  690. }
  691. #endif
  692. }
  693. d->optopt = c;
  694. return '?';
  695. }
  696. /* Convenience. Treat POSIX -W foo same as long option --foo */
  697. if (temp[0] == 'W' && temp[1] == ';')
  698. {
  699. char *nameend;
  700. const struct option *p;
  701. const struct option *pfound = NULL;
  702. int exact = 0;
  703. int ambig = 0;
  704. int indfound = 0;
  705. int option_index;
  706. if (longopts == NULL)
  707. goto no_longs;
  708. /* This is an option that requires an argument. */
  709. if (*d->__nextchar != '\0')
  710. {
  711. d->optarg = d->__nextchar;
  712. /* If we end this ARGV-element by taking the rest as an arg,
  713. we must advance to the next element now. */
  714. d->optind++;
  715. }
  716. else if (d->optind == argc)
  717. {
  718. if (print_errors)
  719. {
  720. #if defined _LIBC && defined USE_IN_LIBIO
  721. char *buf;
  722. if (__asprintf (&buf,
  723. _("%s: option requires an argument -- '%c'\n"),
  724. argv[0], c) >= 0)
  725. {
  726. _IO_flockfile (stderr);
  727. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  728. ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
  729. __fxprintf (NULL, "%s", buf);
  730. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  731. _IO_funlockfile (stderr);
  732. free (buf);
  733. }
  734. #else
  735. fprintf (stderr,
  736. _("%s: option requires an argument -- '%c'\n"),
  737. argv[0], c);
  738. #endif
  739. }
  740. d->optopt = c;
  741. if (optstring[0] == ':')
  742. c = ':';
  743. else
  744. c = '?';
  745. return c;
  746. }
  747. else
  748. /* We already incremented 'd->optind' once;
  749. increment it again when taking next ARGV-elt as argument. */
  750. d->optarg = argv[d->optind++];
  751. /* optarg is now the argument, see if it's in the
  752. table of longopts. */
  753. for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '=';
  754. nameend++)
  755. /* Do nothing. */ ;
  756. /* Test all long options for either exact match
  757. or abbreviated matches. */
  758. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  759. if (!strncmp (p->name, d->__nextchar, nameend - d->__nextchar))
  760. {
  761. if ((unsigned int) (nameend - d->__nextchar) == strlen (p->name))
  762. {
  763. /* Exact match found. */
  764. pfound = p;
  765. indfound = option_index;
  766. exact = 1;
  767. break;
  768. }
  769. else if (pfound == NULL)
  770. {
  771. /* First nonexact match found. */
  772. pfound = p;
  773. indfound = option_index;
  774. }
  775. else if (long_only
  776. || pfound->has_arg != p->has_arg
  777. || pfound->flag != p->flag
  778. || pfound->val != p->val)
  779. /* Second or later nonexact match found. */
  780. ambig = 1;
  781. }
  782. if (ambig && !exact)
  783. {
  784. if (print_errors)
  785. {
  786. #if defined _LIBC && defined USE_IN_LIBIO
  787. char *buf;
  788. if (__asprintf (&buf, _("%s: option '-W %s' is ambiguous\n"),
  789. argv[0], d->optarg) >= 0)
  790. {
  791. _IO_flockfile (stderr);
  792. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  793. ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
  794. __fxprintf (NULL, "%s", buf);
  795. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  796. _IO_funlockfile (stderr);
  797. free (buf);
  798. }
  799. #else
  800. fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
  801. argv[0], d->optarg);
  802. #endif
  803. }
  804. d->__nextchar += strlen (d->__nextchar);
  805. d->optind++;
  806. return '?';
  807. }
  808. if (pfound != NULL)
  809. {
  810. option_index = indfound;
  811. if (*nameend)
  812. {
  813. /* Don't test has_arg with >, because some C compilers don't
  814. allow it to be used on enums. */
  815. if (pfound->has_arg)
  816. d->optarg = nameend + 1;
  817. else
  818. {
  819. if (print_errors)
  820. {
  821. #if defined _LIBC && defined USE_IN_LIBIO
  822. char *buf;
  823. if (__asprintf (&buf, _("\
  824. %s: option '-W %s' doesn't allow an argument\n"),
  825. argv[0], pfound->name) >= 0)
  826. {
  827. _IO_flockfile (stderr);
  828. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  829. ((_IO_FILE *) stderr)->_flags2
  830. |= _IO_FLAGS2_NOTCANCEL;
  831. __fxprintf (NULL, "%s", buf);
  832. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  833. _IO_funlockfile (stderr);
  834. free (buf);
  835. }
  836. #else
  837. fprintf (stderr, _("\
  838. %s: option '-W %s' doesn't allow an argument\n"),
  839. argv[0], pfound->name);
  840. #endif
  841. }
  842. d->__nextchar += strlen (d->__nextchar);
  843. return '?';
  844. }
  845. }
  846. else if (pfound->has_arg == 1)
  847. {
  848. if (d->optind < argc)
  849. d->optarg = argv[d->optind++];
  850. else
  851. {
  852. if (print_errors)
  853. {
  854. #if defined _LIBC && defined USE_IN_LIBIO
  855. char *buf;
  856. if (__asprintf (&buf, _("\
  857. %s: option '-W %s' requires an argument\n"),
  858. argv[0], pfound->name) >= 0)
  859. {
  860. _IO_flockfile (stderr);
  861. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  862. ((_IO_FILE *) stderr)->_flags2
  863. |= _IO_FLAGS2_NOTCANCEL;
  864. __fxprintf (NULL, "%s", buf);
  865. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  866. _IO_funlockfile (stderr);
  867. free (buf);
  868. }
  869. #else
  870. fprintf (stderr, _("\
  871. %s: option '-W %s' requires an argument\n"),
  872. argv[0], pfound->name);
  873. #endif
  874. }
  875. d->__nextchar += strlen (d->__nextchar);
  876. return optstring[0] == ':' ? ':' : '?';
  877. }
  878. }
  879. else
  880. d->optarg = NULL;
  881. d->__nextchar += strlen (d->__nextchar);
  882. if (longind != NULL)
  883. *longind = option_index;
  884. if (pfound->flag)
  885. {
  886. *(pfound->flag) = pfound->val;
  887. return 0;
  888. }
  889. return pfound->val;
  890. }
  891. no_longs:
  892. d->__nextchar = NULL;
  893. return 'W'; /* Let the application handle it. */
  894. }
  895. if (temp[1] == ':')
  896. {
  897. if (temp[2] == ':')
  898. {
  899. /* This is an option that accepts an argument optionally. */
  900. if (*d->__nextchar != '\0')
  901. {
  902. d->optarg = d->__nextchar;
  903. d->optind++;
  904. }
  905. else
  906. d->optarg = NULL;
  907. d->__nextchar = NULL;
  908. }
  909. else
  910. {
  911. /* This is an option that requires an argument. */
  912. if (*d->__nextchar != '\0')
  913. {
  914. d->optarg = d->__nextchar;
  915. /* If we end this ARGV-element by taking the rest as an arg,
  916. we must advance to the next element now. */
  917. d->optind++;
  918. }
  919. else if (d->optind == argc)
  920. {
  921. if (print_errors)
  922. {
  923. #if defined _LIBC && defined USE_IN_LIBIO
  924. char *buf;
  925. if (__asprintf (&buf, _("\
  926. %s: option requires an argument -- '%c'\n"),
  927. argv[0], c) >= 0)
  928. {
  929. _IO_flockfile (stderr);
  930. int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
  931. ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
  932. __fxprintf (NULL, "%s", buf);
  933. ((_IO_FILE *) stderr)->_flags2 = old_flags2;
  934. _IO_funlockfile (stderr);
  935. free (buf);
  936. }
  937. #else
  938. fprintf (stderr,
  939. _("%s: option requires an argument -- '%c'\n"),
  940. argv[0], c);
  941. #endif
  942. }
  943. d->optopt = c;
  944. if (optstring[0] == ':')
  945. c = ':';
  946. else
  947. c = '?';
  948. }
  949. else
  950. /* We already incremented 'optind' once;
  951. increment it again when taking next ARGV-elt as argument. */
  952. d->optarg = argv[d->optind++];
  953. d->__nextchar = NULL;
  954. }
  955. }
  956. return c;
  957. }
  958. }
  959. int
  960. _getopt_internal (int argc, char **argv, const char *optstring,
  961. const struct option *longopts, int *longind, int long_only,
  962. int posixly_correct)
  963. {
  964. int result;
  965. getopt_data.optind = optind;
  966. getopt_data.opterr = opterr;
  967. result = _getopt_internal_r (argc, argv, optstring, longopts,
  968. longind, long_only, &getopt_data,
  969. posixly_correct);
  970. optind = getopt_data.optind;
  971. optarg = getopt_data.optarg;
  972. optopt = getopt_data.optopt;
  973. return result;
  974. }
  975. /* glibc gets a LSB-compliant getopt.
  976. Standalone applications get a POSIX-compliant getopt. */
  977. #if _LIBC
  978. enum { POSIXLY_CORRECT = 0 };
  979. #else
  980. enum { POSIXLY_CORRECT = 1 };
  981. #endif
  982. int
  983. getopt (int argc, char *const *argv, const char *optstring)
  984. {
  985. return _getopt_internal (argc, (char **) argv, optstring,
  986. (const struct option *) 0,
  987. (int *) 0,
  988. 0, POSIXLY_CORRECT);
  989. }
  990. #ifdef _LIBC
  991. int
  992. __posix_getopt (int argc, char *const *argv, const char *optstring)
  993. {
  994. return _getopt_internal (argc, argv, optstring,
  995. (const struct option *) 0,
  996. (int *) 0,
  997. 0, 1);
  998. }
  999. #endif
  1000. #ifdef TEST
  1001. /* Compile with -DTEST to make an executable for use in testing
  1002. the above definition of 'getopt'. */
  1003. int
  1004. main (int argc, char **argv)
  1005. {
  1006. int c;
  1007. int digit_optind = 0;
  1008. while (1)
  1009. {
  1010. int this_option_optind = optind ? optind : 1;
  1011. c = getopt (argc, argv, "abc:d:0123456789");
  1012. if (c == -1)
  1013. break;
  1014. switch (c)
  1015. {
  1016. case '0':
  1017. case '1':
  1018. case '2':
  1019. case '3':
  1020. case '4':
  1021. case '5':
  1022. case '6':
  1023. case '7':
  1024. case '8':
  1025. case '9':
  1026. if (digit_optind != 0 && digit_optind != this_option_optind)
  1027. printf ("digits occur in two different argv-elements.\n");
  1028. digit_optind = this_option_optind;
  1029. printf ("option %c\n", c);
  1030. break;
  1031. case 'a':
  1032. printf ("option a\n");
  1033. break;
  1034. case 'b':
  1035. printf ("option b\n");
  1036. break;
  1037. case 'c':
  1038. printf ("option c with value '%s'\n", optarg);
  1039. break;
  1040. case '?':
  1041. break;
  1042. default:
  1043. printf ("?? getopt returned character code 0%o ??\n", c);
  1044. }
  1045. }
  1046. if (optind < argc)
  1047. {
  1048. printf ("non-option ARGV-elements: ");
  1049. while (optind < argc)
  1050. printf ("%s ", argv[optind++]);
  1051. printf ("\n");
  1052. }
  1053. exit (0);
  1054. }
  1055. #endif /* TEST */