getopt.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. /* Getopt for GNU.
  2. Copyright (C) 1987-2020 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library and is also part of gnulib.
  4. Patches to this file should be submitted to both projects.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public
  7. License as published by the Free Software Foundation; either
  8. version 3 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public
  14. License along with the GNU C Library; if not, see
  15. <https://www.gnu.org/licenses/>. */
  16. #ifndef _LIBC
  17. # include <config.h>
  18. #endif
  19. #include "getopt.h"
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. #ifdef _LIBC
  25. /* When used as part of glibc, error printing must be done differently
  26. for standards compliance. getopt is not a cancellation point, so
  27. it must not call functions that are, and it is specified by an
  28. older standard than stdio locking, so it must not refer to
  29. functions in the "user namespace" related to stdio locking.
  30. Finally, it must use glibc's internal message translation so that
  31. the messages are looked up in the proper text domain. */
  32. # include <libintl.h>
  33. # define fprintf __fxprintf_nocancel
  34. # define flockfile(fp) _IO_flockfile (fp)
  35. # define funlockfile(fp) _IO_funlockfile (fp)
  36. #else
  37. # include "gettext.h"
  38. # define _(msgid) gettext (msgid)
  39. /* When used standalone, flockfile and funlockfile might not be
  40. available. */
  41. # if (!defined _POSIX_THREAD_SAFE_FUNCTIONS \
  42. || (defined _WIN32 && ! defined __CYGWIN__))
  43. # define flockfile(fp) /* nop */
  44. # define funlockfile(fp) /* nop */
  45. # endif
  46. /* When used standalone, do not attempt to use alloca. */
  47. # define __libc_use_alloca(size) 0
  48. # undef alloca
  49. # define alloca(size) (abort (), (void *)0)
  50. #endif
  51. /* This implementation of 'getopt' has three modes for handling
  52. options interspersed with non-option arguments. It can stop
  53. scanning for options at the first non-option argument encountered,
  54. as POSIX specifies. It can continue scanning for options after the
  55. first non-option argument, but permute 'argv' as it goes so that,
  56. after 'getopt' is done, all the options precede all the non-option
  57. arguments and 'optind' points to the first non-option argument.
  58. Or, it can report non-option arguments as if they were arguments to
  59. the option character '\x01'.
  60. The default behavior of 'getopt_long' is to permute the argument list.
  61. When this implementation is used standalone, the default behavior of
  62. 'getopt' is to stop at the first non-option argument, but when it is
  63. used as part of GNU libc it also permutes the argument list. In both
  64. cases, setting the environment variable POSIXLY_CORRECT to any value
  65. disables permutation.
  66. If the first character of the OPTSTRING argument to 'getopt' or
  67. 'getopt_long' is '+', both functions will stop at the first
  68. non-option argument. If it is '-', both functions will report
  69. non-option arguments as arguments to the option character '\x01'. */
  70. #include "getopt_int.h"
  71. /* For communication from 'getopt' to the caller.
  72. When 'getopt' finds an option that takes an argument,
  73. the argument value is returned here.
  74. Also, when 'ordering' is RETURN_IN_ORDER,
  75. each non-option ARGV-element is returned here. */
  76. char *optarg;
  77. /* Index in ARGV of the next element to be scanned.
  78. This is used for communication to and from the caller
  79. and for communication between successive calls to 'getopt'.
  80. On entry to 'getopt', zero means this is the first call; initialize.
  81. When 'getopt' returns -1, this is the index of the first of the
  82. non-option elements that the caller should itself scan.
  83. Otherwise, 'optind' communicates from one call to the next
  84. how much of ARGV has been scanned so far. */
  85. /* 1003.2 says this must be 1 before any call. */
  86. int optind = 1;
  87. /* Callers store zero here to inhibit the error message
  88. for unrecognized options. */
  89. int opterr = 1;
  90. /* Set to an option character which was unrecognized.
  91. This must be initialized on some systems to avoid linking in the
  92. system's own getopt implementation. */
  93. int optopt = '?';
  94. /* Keep a global copy of all internal members of getopt_data. */
  95. static struct _getopt_data getopt_data;
  96. /* Exchange two adjacent subsequences of ARGV.
  97. One subsequence is elements [first_nonopt,last_nonopt)
  98. which contains all the non-options that have been skipped so far.
  99. The other is elements [last_nonopt,optind), which contains all
  100. the options processed since those non-options were skipped.
  101. 'first_nonopt' and 'last_nonopt' are relocated so that they describe
  102. the new indices of the non-options in ARGV after they are moved. */
  103. static void
  104. exchange (char **argv, struct _getopt_data *d)
  105. {
  106. int bottom = d->__first_nonopt;
  107. int middle = d->__last_nonopt;
  108. int top = d->optind;
  109. char *tem;
  110. /* Exchange the shorter segment with the far end of the longer segment.
  111. That puts the shorter segment into the right place.
  112. It leaves the longer segment in the right place overall,
  113. but it consists of two parts that need to be swapped next. */
  114. while (top > middle && middle > bottom)
  115. {
  116. if (top - middle > middle - bottom)
  117. {
  118. /* Bottom segment is the short one. */
  119. int len = middle - bottom;
  120. int i;
  121. /* Swap it with the top part of the top segment. */
  122. for (i = 0; i < len; i++)
  123. {
  124. tem = argv[bottom + i];
  125. argv[bottom + i] = argv[top - (middle - bottom) + i];
  126. argv[top - (middle - bottom) + i] = tem;
  127. }
  128. /* Exclude the moved bottom segment from further swapping. */
  129. top -= len;
  130. }
  131. else
  132. {
  133. /* Top segment is the short one. */
  134. int len = top - middle;
  135. int i;
  136. /* Swap it with the bottom part of the bottom segment. */
  137. for (i = 0; i < len; i++)
  138. {
  139. tem = argv[bottom + i];
  140. argv[bottom + i] = argv[middle + i];
  141. argv[middle + i] = tem;
  142. }
  143. /* Exclude the moved top segment from further swapping. */
  144. bottom += len;
  145. }
  146. }
  147. /* Update records for the slots the non-options now occupy. */
  148. d->__first_nonopt += (d->optind - d->__last_nonopt);
  149. d->__last_nonopt = d->optind;
  150. }
  151. /* Process the argument starting with d->__nextchar as a long option.
  152. d->optind should *not* have been advanced over this argument.
  153. If the value returned is -1, it was not actually a long option, the
  154. state is unchanged, and the argument should be processed as a set
  155. of short options (this can only happen when long_only is true).
  156. Otherwise, the option (and its argument, if any) have been consumed
  157. and the return value is the value to return from _getopt_internal_r. */
  158. static int
  159. process_long_option (int argc, char **argv, const char *optstring,
  160. const struct option *longopts, int *longind,
  161. int long_only, struct _getopt_data *d,
  162. int print_errors, const char *prefix)
  163. {
  164. char *nameend;
  165. size_t namelen;
  166. const struct option *p;
  167. const struct option *pfound = NULL;
  168. int n_options;
  169. int option_index;
  170. for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++)
  171. /* Do nothing. */ ;
  172. namelen = nameend - d->__nextchar;
  173. /* First look for an exact match, counting the options as a side
  174. effect. */
  175. for (p = longopts, n_options = 0; p->name; p++, n_options++)
  176. if (!strncmp (p->name, d->__nextchar, namelen)
  177. && namelen == strlen (p->name))
  178. {
  179. /* Exact match found. */
  180. pfound = p;
  181. option_index = n_options;
  182. break;
  183. }
  184. if (pfound == NULL)
  185. {
  186. /* Didn't find an exact match, so look for abbreviations. */
  187. unsigned char *ambig_set = NULL;
  188. int ambig_malloced = 0;
  189. int ambig_fallback = 0;
  190. int indfound = -1;
  191. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  192. if (!strncmp (p->name, d->__nextchar, namelen))
  193. {
  194. if (pfound == NULL)
  195. {
  196. /* First nonexact match found. */
  197. pfound = p;
  198. indfound = option_index;
  199. }
  200. else if (long_only
  201. || pfound->has_arg != p->has_arg
  202. || pfound->flag != p->flag
  203. || pfound->val != p->val)
  204. {
  205. /* Second or later nonexact match found. */
  206. if (!ambig_fallback)
  207. {
  208. if (!print_errors)
  209. /* Don't waste effort tracking the ambig set if
  210. we're not going to print it anyway. */
  211. ambig_fallback = 1;
  212. else if (!ambig_set)
  213. {
  214. if (__libc_use_alloca (n_options))
  215. ambig_set = alloca (n_options);
  216. else if ((ambig_set = malloc (n_options)) == NULL)
  217. /* Fall back to simpler error message. */
  218. ambig_fallback = 1;
  219. else
  220. ambig_malloced = 1;
  221. if (ambig_set)
  222. {
  223. memset (ambig_set, 0, n_options);
  224. ambig_set[indfound] = 1;
  225. }
  226. }
  227. if (ambig_set)
  228. ambig_set[option_index] = 1;
  229. }
  230. }
  231. }
  232. if (ambig_set || ambig_fallback)
  233. {
  234. if (print_errors)
  235. {
  236. if (ambig_fallback)
  237. fprintf (stderr, _("%s: option '%s%s' is ambiguous\n"),
  238. argv[0], prefix, d->__nextchar);
  239. else
  240. {
  241. flockfile (stderr);
  242. fprintf (stderr,
  243. _("%s: option '%s%s' is ambiguous; possibilities:"),
  244. argv[0], prefix, d->__nextchar);
  245. for (option_index = 0; option_index < n_options; option_index++)
  246. if (ambig_set[option_index])
  247. fprintf (stderr, " '%s%s'",
  248. prefix, longopts[option_index].name);
  249. /* This must use 'fprintf' even though it's only
  250. printing a single character, so that it goes through
  251. __fxprintf_nocancel when compiled as part of glibc. */
  252. fprintf (stderr, "\n");
  253. funlockfile (stderr);
  254. }
  255. }
  256. if (ambig_malloced)
  257. free (ambig_set);
  258. d->__nextchar += strlen (d->__nextchar);
  259. d->optind++;
  260. d->optopt = 0;
  261. return '?';
  262. }
  263. option_index = indfound;
  264. }
  265. if (pfound == NULL)
  266. {
  267. /* Can't find it as a long option. If this is not getopt_long_only,
  268. or the option starts with '--' or is not a valid short option,
  269. then it's an error. */
  270. if (!long_only || argv[d->optind][1] == '-'
  271. || strchr (optstring, *d->__nextchar) == NULL)
  272. {
  273. if (print_errors)
  274. fprintf (stderr, _("%s: unrecognized option '%s%s'\n"),
  275. argv[0], prefix, d->__nextchar);
  276. d->__nextchar = NULL;
  277. d->optind++;
  278. d->optopt = 0;
  279. return '?';
  280. }
  281. /* Otherwise interpret it as a short option. */
  282. return -1;
  283. }
  284. /* We have found a matching long option. Consume it. */
  285. d->optind++;
  286. d->__nextchar = NULL;
  287. if (*nameend)
  288. {
  289. /* Don't test has_arg with >, because some C compilers don't
  290. allow it to be used on enums. */
  291. if (pfound->has_arg)
  292. d->optarg = nameend + 1;
  293. else
  294. {
  295. if (print_errors)
  296. fprintf (stderr,
  297. _("%s: option '%s%s' doesn't allow an argument\n"),
  298. argv[0], prefix, pfound->name);
  299. d->optopt = pfound->val;
  300. return '?';
  301. }
  302. }
  303. else if (pfound->has_arg == 1)
  304. {
  305. if (d->optind < argc)
  306. d->optarg = argv[d->optind++];
  307. else
  308. {
  309. if (print_errors)
  310. fprintf (stderr,
  311. _("%s: option '%s%s' requires an argument\n"),
  312. argv[0], prefix, pfound->name);
  313. d->optopt = pfound->val;
  314. return optstring[0] == ':' ? ':' : '?';
  315. }
  316. }
  317. if (longind != NULL)
  318. *longind = option_index;
  319. if (pfound->flag)
  320. {
  321. *(pfound->flag) = pfound->val;
  322. return 0;
  323. }
  324. return pfound->val;
  325. }
  326. /* Initialize internal data upon the first call to getopt. */
  327. static const char *
  328. _getopt_initialize (int argc _GL_UNUSED,
  329. char **argv _GL_UNUSED, const char *optstring,
  330. struct _getopt_data *d, int posixly_correct)
  331. {
  332. /* Start processing options with ARGV-element 1 (since ARGV-element 0
  333. is the program name); the sequence of previously skipped
  334. non-option ARGV-elements is empty. */
  335. if (d->optind == 0)
  336. d->optind = 1;
  337. d->__first_nonopt = d->__last_nonopt = d->optind;
  338. d->__nextchar = NULL;
  339. /* Determine how to handle the ordering of options and nonoptions. */
  340. if (optstring[0] == '-')
  341. {
  342. d->__ordering = RETURN_IN_ORDER;
  343. ++optstring;
  344. }
  345. else if (optstring[0] == '+')
  346. {
  347. d->__ordering = REQUIRE_ORDER;
  348. ++optstring;
  349. }
  350. else if (posixly_correct || !!getenv ("POSIXLY_CORRECT"))
  351. d->__ordering = REQUIRE_ORDER;
  352. else
  353. d->__ordering = PERMUTE;
  354. d->__initialized = 1;
  355. return optstring;
  356. }
  357. /* Scan elements of ARGV (whose length is ARGC) for option characters
  358. given in OPTSTRING.
  359. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  360. then it is an option element. The characters of this element
  361. (aside from the initial '-') are option characters. If 'getopt'
  362. is called repeatedly, it returns successively each of the option characters
  363. from each of the option elements.
  364. If 'getopt' finds another option character, it returns that character,
  365. updating 'optind' and 'nextchar' so that the next call to 'getopt' can
  366. resume the scan with the following option character or ARGV-element.
  367. If there are no more option characters, 'getopt' returns -1.
  368. Then 'optind' is the index in ARGV of the first ARGV-element
  369. that is not an option. (The ARGV-elements have been permuted
  370. so that those that are not options now come last.)
  371. OPTSTRING is a string containing the legitimate option characters.
  372. If an option character is seen that is not listed in OPTSTRING,
  373. return '?' after printing an error message. If you set 'opterr' to
  374. zero, the error message is suppressed but we still return '?'.
  375. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  376. so the following text in the same ARGV-element, or the text of the following
  377. ARGV-element, is returned in 'optarg'. Two colons mean an option that
  378. wants an optional arg; if there is text in the current ARGV-element,
  379. it is returned in 'optarg', otherwise 'optarg' is set to zero.
  380. If OPTSTRING starts with '-' or '+', it requests different methods of
  381. handling the non-option ARGV-elements.
  382. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  383. Long-named options begin with '--' instead of '-'.
  384. Their names may be abbreviated as long as the abbreviation is unique
  385. or is an exact match for some defined option. If they have an
  386. argument, it follows the option name in the same ARGV-element, separated
  387. from the option name by a '=', or else the in next ARGV-element.
  388. When 'getopt' finds a long-named option, it returns 0 if that option's
  389. 'flag' field is nonzero, the value of the option's 'val' field
  390. if the 'flag' field is zero.
  391. The elements of ARGV aren't really const, because we permute them.
  392. But we pretend they're const in the prototype to be compatible
  393. with other systems.
  394. LONGOPTS is a vector of 'struct option' terminated by an
  395. element containing a name which is zero.
  396. LONGIND returns the index in LONGOPT of the long-named option found.
  397. It is only valid when a long-named option has been found by the most
  398. recent call.
  399. If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  400. long-named options. */
  401. int
  402. _getopt_internal_r (int argc, char **argv, const char *optstring,
  403. const struct option *longopts, int *longind,
  404. int long_only, struct _getopt_data *d, int posixly_correct)
  405. {
  406. int print_errors = d->opterr;
  407. if (argc < 1)
  408. return -1;
  409. d->optarg = NULL;
  410. if (d->optind == 0 || !d->__initialized)
  411. optstring = _getopt_initialize (argc, argv, optstring, d, posixly_correct);
  412. else if (optstring[0] == '-' || optstring[0] == '+')
  413. optstring++;
  414. if (optstring[0] == ':')
  415. print_errors = 0;
  416. /* Test whether ARGV[optind] points to a non-option argument. */
  417. #define NONOPTION_P (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0')
  418. if (d->__nextchar == NULL || *d->__nextchar == '\0')
  419. {
  420. /* Advance to the next ARGV-element. */
  421. /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  422. moved back by the user (who may also have changed the arguments). */
  423. if (d->__last_nonopt > d->optind)
  424. d->__last_nonopt = d->optind;
  425. if (d->__first_nonopt > d->optind)
  426. d->__first_nonopt = d->optind;
  427. if (d->__ordering == PERMUTE)
  428. {
  429. /* If we have just processed some options following some non-options,
  430. exchange them so that the options come first. */
  431. if (d->__first_nonopt != d->__last_nonopt
  432. && d->__last_nonopt != d->optind)
  433. exchange (argv, d);
  434. else if (d->__last_nonopt != d->optind)
  435. d->__first_nonopt = d->optind;
  436. /* Skip any additional non-options
  437. and extend the range of non-options previously skipped. */
  438. while (d->optind < argc && NONOPTION_P)
  439. d->optind++;
  440. d->__last_nonopt = d->optind;
  441. }
  442. /* The special ARGV-element '--' means premature end of options.
  443. Skip it like a null option,
  444. then exchange with previous non-options as if it were an option,
  445. then skip everything else like a non-option. */
  446. if (d->optind != argc && !strcmp (argv[d->optind], "--"))
  447. {
  448. d->optind++;
  449. if (d->__first_nonopt != d->__last_nonopt
  450. && d->__last_nonopt != d->optind)
  451. exchange (argv, d);
  452. else if (d->__first_nonopt == d->__last_nonopt)
  453. d->__first_nonopt = d->optind;
  454. d->__last_nonopt = argc;
  455. d->optind = argc;
  456. }
  457. /* If we have done all the ARGV-elements, stop the scan
  458. and back over any non-options that we skipped and permuted. */
  459. if (d->optind == argc)
  460. {
  461. /* Set the next-arg-index to point at the non-options
  462. that we previously skipped, so the caller will digest them. */
  463. if (d->__first_nonopt != d->__last_nonopt)
  464. d->optind = d->__first_nonopt;
  465. return -1;
  466. }
  467. /* If we have come to a non-option and did not permute it,
  468. either stop the scan or describe it to the caller and pass it by. */
  469. if (NONOPTION_P)
  470. {
  471. if (d->__ordering == REQUIRE_ORDER)
  472. return -1;
  473. d->optarg = argv[d->optind++];
  474. return 1;
  475. }
  476. /* We have found another option-ARGV-element.
  477. Check whether it might be a long option. */
  478. if (longopts)
  479. {
  480. if (argv[d->optind][1] == '-')
  481. {
  482. /* "--foo" is always a long option. The special option
  483. "--" was handled above. */
  484. d->__nextchar = argv[d->optind] + 2;
  485. return process_long_option (argc, argv, optstring, longopts,
  486. longind, long_only, d,
  487. print_errors, "--");
  488. }
  489. /* If long_only and the ARGV-element has the form "-f",
  490. where f is a valid short option, don't consider it an
  491. abbreviated form of a long option that starts with f.
  492. Otherwise there would be no way to give the -f short
  493. option.
  494. On the other hand, if there's a long option "fubar" and
  495. the ARGV-element is "-fu", do consider that an
  496. abbreviation of the long option, just like "--fu", and
  497. not "-f" with arg "u".
  498. This distinction seems to be the most useful approach. */
  499. if (long_only && (argv[d->optind][2]
  500. || !strchr (optstring, argv[d->optind][1])))
  501. {
  502. int code;
  503. d->__nextchar = argv[d->optind] + 1;
  504. code = process_long_option (argc, argv, optstring, longopts,
  505. longind, long_only, d,
  506. print_errors, "-");
  507. if (code != -1)
  508. return code;
  509. }
  510. }
  511. /* It is not a long option. Skip the initial punctuation. */
  512. d->__nextchar = argv[d->optind] + 1;
  513. }
  514. /* Look at and handle the next short option-character. */
  515. {
  516. char c = *d->__nextchar++;
  517. const char *temp = strchr (optstring, c);
  518. /* Increment 'optind' when we start to process its last character. */
  519. if (*d->__nextchar == '\0')
  520. ++d->optind;
  521. if (temp == NULL || c == ':' || c == ';')
  522. {
  523. if (print_errors)
  524. fprintf (stderr, _("%s: invalid option -- '%c'\n"), argv[0], c);
  525. d->optopt = c;
  526. return '?';
  527. }
  528. /* Convenience. Treat POSIX -W foo same as long option --foo */
  529. if (temp[0] == 'W' && temp[1] == ';' && longopts != NULL)
  530. {
  531. /* This is an option that requires an argument. */
  532. if (*d->__nextchar != '\0')
  533. d->optarg = d->__nextchar;
  534. else if (d->optind == argc)
  535. {
  536. if (print_errors)
  537. fprintf (stderr,
  538. _("%s: option requires an argument -- '%c'\n"),
  539. argv[0], c);
  540. d->optopt = c;
  541. if (optstring[0] == ':')
  542. c = ':';
  543. else
  544. c = '?';
  545. return c;
  546. }
  547. else
  548. d->optarg = argv[d->optind];
  549. d->__nextchar = d->optarg;
  550. d->optarg = NULL;
  551. return process_long_option (argc, argv, optstring, longopts, longind,
  552. 0 /* long_only */, d, print_errors, "-W ");
  553. }
  554. if (temp[1] == ':')
  555. {
  556. if (temp[2] == ':')
  557. {
  558. /* This is an option that accepts an argument optionally. */
  559. if (*d->__nextchar != '\0')
  560. {
  561. d->optarg = d->__nextchar;
  562. d->optind++;
  563. }
  564. else
  565. d->optarg = NULL;
  566. d->__nextchar = NULL;
  567. }
  568. else
  569. {
  570. /* This is an option that requires an argument. */
  571. if (*d->__nextchar != '\0')
  572. {
  573. d->optarg = d->__nextchar;
  574. /* If we end this ARGV-element by taking the rest as an arg,
  575. we must advance to the next element now. */
  576. d->optind++;
  577. }
  578. else if (d->optind == argc)
  579. {
  580. if (print_errors)
  581. fprintf (stderr,
  582. _("%s: option requires an argument -- '%c'\n"),
  583. argv[0], c);
  584. d->optopt = c;
  585. if (optstring[0] == ':')
  586. c = ':';
  587. else
  588. c = '?';
  589. }
  590. else
  591. /* We already incremented 'optind' once;
  592. increment it again when taking next ARGV-elt as argument. */
  593. d->optarg = argv[d->optind++];
  594. d->__nextchar = NULL;
  595. }
  596. }
  597. return c;
  598. }
  599. }
  600. int
  601. _getopt_internal (int argc, char **argv, const char *optstring,
  602. const struct option *longopts, int *longind, int long_only,
  603. int posixly_correct)
  604. {
  605. int result;
  606. getopt_data.optind = optind;
  607. getopt_data.opterr = opterr;
  608. result = _getopt_internal_r (argc, argv, optstring, longopts,
  609. longind, long_only, &getopt_data,
  610. posixly_correct);
  611. optind = getopt_data.optind;
  612. optarg = getopt_data.optarg;
  613. optopt = getopt_data.optopt;
  614. return result;
  615. }
  616. /* glibc gets a LSB-compliant getopt and a POSIX-complaint __posix_getopt.
  617. Standalone applications just get a POSIX-compliant getopt.
  618. POSIX and LSB both require these functions to take 'char *const *argv'
  619. even though this is incorrect (because of the permutation). */
  620. #define GETOPT_ENTRY(NAME, POSIXLY_CORRECT) \
  621. int \
  622. NAME (int argc, char *const *argv, const char *optstring) \
  623. { \
  624. return _getopt_internal (argc, (char **)argv, optstring, \
  625. 0, 0, 0, POSIXLY_CORRECT); \
  626. }
  627. #ifdef _LIBC
  628. GETOPT_ENTRY(getopt, 0)
  629. GETOPT_ENTRY(__posix_getopt, 1)
  630. #else
  631. GETOPT_ENTRY(getopt, 1)
  632. #endif
  633. #ifdef TEST
  634. /* Compile with -DTEST to make an executable for use in testing
  635. the above definition of 'getopt'. */
  636. int
  637. main (int argc, char **argv)
  638. {
  639. int c;
  640. int digit_optind = 0;
  641. while (1)
  642. {
  643. int this_option_optind = optind ? optind : 1;
  644. c = getopt (argc, argv, "abc:d:0123456789");
  645. if (c == -1)
  646. break;
  647. switch (c)
  648. {
  649. case '0':
  650. case '1':
  651. case '2':
  652. case '3':
  653. case '4':
  654. case '5':
  655. case '6':
  656. case '7':
  657. case '8':
  658. case '9':
  659. if (digit_optind != 0 && digit_optind != this_option_optind)
  660. printf ("digits occur in two different argv-elements.\n");
  661. digit_optind = this_option_optind;
  662. printf ("option %c\n", c);
  663. break;
  664. case 'a':
  665. printf ("option a\n");
  666. break;
  667. case 'b':
  668. printf ("option b\n");
  669. break;
  670. case 'c':
  671. printf ("option c with value '%s'\n", optarg);
  672. break;
  673. case '?':
  674. break;
  675. default:
  676. printf ("?? getopt returned character code 0%o ??\n", c);
  677. }
  678. }
  679. if (optind < argc)
  680. {
  681. printf ("non-option ARGV-elements: ");
  682. while (optind < argc)
  683. printf ("%s ", argv[optind++]);
  684. printf ("\n");
  685. }
  686. exit (0);
  687. }
  688. #endif /* TEST */